import sys
from streamlit import cli as stcli

from folium.plugins import HeatMap
import folium
from streamlit_folium import folium_static

import tempfile

import streamlit as st
import pandas as pd
import numpy as np
from PIL import Image
import time
import os
import json

import torch
import cv2

from stqdm import stqdm

import tkinter as tk
from tkinter import filedialog

@st.cache()
def load_model(path='models/best.pt'):
    detection_model = torch.hub.load('ultralytics/yolov5', 'custom', path=path)
    return detection_model

def detect_image(image, model):
    pred = model(image)
    pred_df = pred.pandas().xyxy[0].sort_values('confidence', ascending=False)
    pred_image = pred.render()[0]
    if pred_df.shape[0] > 0:
        if pred_df.confidence.iloc[0] > 0.5:
            return pred_image, pred_df.name.iloc[0]
        else:
            return pred_image, 'Неизвестное животное'
    else:
        return image, 'Нет животного'

def plot_map():
    map_df = pd.read_csv('lisa_tracking.csv')
    map_heatmap = folium.Map(location=[map_df.latitude.mean(), map_df.longitude.mean()], zoom_start=11)
    # Filter the DF for columns, then remove NaNs
    heat_df = map_df[["latitude", "longitude"]]
    heat_df = heat_df.dropna(axis=0, subset=["latitude", "longitude"])
    # List comprehension to make list of lists
    heat_data = [
        [row["latitude"], row["longitude"]] for index, row in heat_df.iterrows()
    ]
    # Plot it on the map
    HeatMap(heat_data).add_to(map_heatmap)
    # Display the map using the community component
    folium_static(map_heatmap)

def process_video(cap, model, save=True, path_to_save='temp.mp4'):
    frame_width = int(cap.get(3))
    frame_height = int(cap.get(4))
    stframe = st.empty()
    preds = []
    if save:
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        out = cv2.VideoWriter(path_to_save, fourcc, 25.0, (frame_width, frame_height))
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            print("Can't receive frame (stream end?). Exiting ...")
            break
        frame, pred = detect_image(frame, model)
        #st.write(pred)
        if pred != 'Неизвестное животное' and pred != 'Нет животного':
            if save:
                out.write(frame)
            stframe.image(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
            preds.append(pred)
        elif pred == 'Неизвестное животное':
            preds.append(pred)
    cap.release()
    if save:
        out.release()
    if len(preds) > 0:
        return pd.DataFrame(preds).reset_index().groupby(0).count().sort_values('index').index[-1]
    else:
        return 'Нет животного'

def main():

    st.title('Обработка данных из фотоловушек')

    model = load_model('best.pt')

    data_type = st.radio(
        "Выберите тип данных",
        ('Директория с фото', 'Директория с видео',
         'Фото', 'Видео'))

    if data_type == 'Директория с фото':

        st.header('Обработка директории с фотографиями')
        root = tk.Tk()
        root.withdraw()
        root.wm_attributes('-topmost', 1)

        st.write('Выберите папку с фотографиями:')
        clicked = st.button('Выбор папки')

        if clicked:
        # Создать папки, в которых будут лежать обработанные фотографии

            dirname = st.text_input('Выбранная папка:', filedialog.askdirectory(master=root))
            #directory = "ProcessedImages"
            path = './ProcessedImages' #os.path.join(dirname, directory)
            try:
                os.mkdir(path)
            except:
                st.write('WARNING: Папка ProcessedImages уже существует.')

            for i in ['Bear', 'Deer', 'Lynx', 'Fox', 'Tiger', 'Leopard', 'Wolf', 'Eagle', 'Boar', 'Saiga', 'Squirrel', 'Raccoon', 'Man','Weasel', 'Unknown_Animal', 'No_Animal']:
                os.mkdir(os.path.join(path, i))
            # Загрузка модели
            labels = {}
            for img_path in stqdm([dirname + '\\' + x for x in os.listdir(dirname)]):
                try:
                    image = np.array(Image.open(img_path))
                    image, prediction = detect_image(image, model)
                except :
                    continue

                image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
                labels[img_path.split('\\')[-1]]=[prediction]

                with open('labels.json', 'w') as outfile:
                    json.dump(labels, outfile)

                for i, p in zip(['Медведь', 'Олень', 'Рысь', 'Лиса', 'Тигр', 'Леопард', 'Волк', 'Орёл', 'Кабан', 'Сайгак', 'Белка', 'Енот', 'Человек', 'Ласка', 'Неизвестное животное', 'Нет животного'],
                ['Bear', 'Deer', 'Lynx', 'Fox', 'Tiger', 'Leopard', 'Wolf', 'Eagle', 'Boar', 'Saiga', 'Squirrel', 'Raccoon', 'Man','Weasel', 'Unknown_Animal', 'No_Animal']):
                    if prediction == i:
                        path_init = os.path.join(path, p)
                        path_to_save = os.path.join(path_init, img_path.split('\\')[-1])
                        cv2.imwrite(path_to_save, np.array(image))
                        break

            st.write('Фотографии обработаны')

    elif data_type == 'Директория с видео':
        st.header('Обработка директории с видео')
        root = tk.Tk()
        root.withdraw()
        root.wm_attributes('-topmost', 1)

        st.write('Выберите папку с видео:')
        clicked = st.button('Выбор папки')

        if clicked:
        # Создать папки, в которых будут лежать обработанные фотографии

            dirname = st.text_input('Выбранная папка:', filedialog.askdirectory(master=root))
            #directory = "ProcessedImages"
            path = './ProcessedVideos' #os.path.join(dirname, directory)
            try:
                os.mkdir(path)
            except:
                st.write('WARNING: Папка ProcessedVideos уже существует.')

            labels_video = {}
            for video_path in stqdm([dirname + '\\' + x for x in os.listdir(dirname)]):
                cap = cv2.VideoCapture(video_path)

                prediction = process_video(cap, model, save=True, path_to_save='./ProcessedVideos/'+video_path.split('\\')[-1].split('.')[0] + '.mp4')
                st.write(prediction)

                labels_video[video_path.split('\\')[-1]]=[prediction]

                with open('labels_video.json', 'w') as outfile:
                    json.dump(labels_video, outfile)

            st.write('Видео обработаны')

    elif data_type == 'Фото':
        st.header('Обработка фото')
        file = st.file_uploader('Загрузите изображение')
        if file:
            image = np.array(Image.open(file))
            image, pred = detect_image(image, model)
            st.header('Результаты распознавания')
            st.metric('Вид', pred)
            st.image(image)
            if pred == 'Лиса':
                plot_or_not = st.checkbox('Показать карту активности вида - {}'.format(pred))
                if plot_or_not:
                    plot_map()

    elif data_type == 'Видео':
        st.header('Обработка видео')
        file = st.file_uploader('Загрузите изображение')
        if file:
            st.header('Результаты распознавания')
            tfile = tempfile.NamedTemporaryFile(delete=False)
            tfile.write(file.read())
            cap = cv2.VideoCapture(tfile.name)
            pred = process_video(cap, model)
            st.text('Видео обработано')
            st.metric('Вид', pred)
            if pred == 'Лиса':
                plot_or_not = st.checkbox('Показать карту активности вида - {}'.format(pred))
                if plot_or_not:
                    plot_map()

if __name__ == '__main__':
    if st._is_running_with_streamlit:
        main()
    else:
        sys.argv = ["streamlit", "run", sys.argv[0]]
        sys.exit(stcli.main())


from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect, Http404
from intranet.decorators import role_required
from .models import *
from django.urls import reverse
from django.contrib import messages
import csv
from .forms import *
from .filters import answers_filter

# Create your views here.
@login_required(login_url="/login/")

def index(request):
    context = {}
    placement = Placements.objects.all()
    context['title'] = 'Companies'
    context['placement'] = placement
    return render(request, 'control/placead.html', context)

@login_required(login_url="/login/")
def details(request, id=None):
    if request.method == "GET":
        try:
            placement = Placements.objects.get(id=id)
        except:
            raise Http404
        form =ans_form()
        context = {}
        context['placement'] = placement
        context['form'] = form
        return render(request, 'student/detail.html', context)
    if request.method == "POST":
        user_id = request.user
        form = ans_form(request.POST)
    if form.is_valid():
        post = form.save()
        post.save()
        messages.success(request, "Successful")

def answer(request, id=None):
    if request.method == "GET":
        placement = Placements.objects.get(id=id)
        answer = Answer.objects.all()
        myFilter = answers_filter(request.GET, queryset=answer)
        answer = myFilter.qs
        context ={}
        context['myfilter'] = myFilter
        context['answer'] = answer
        context['user'] = request.user
        return render(request, 'control/answer.html', context)

def answer_backup(request):
    if request.method == "POST":
        response = HttpResponse(content_type='text/csv')
    writer = csv.writer(response)
    writer.writerow(['Usernumber', 'URN', 'First Name', 'Last Name', 'Company'])
    for ans in Answer.objects.all().values_list('placement','user','username', 'firstname', 'lastname'):
        writer.writerow(ans)
    response['Content-Disposition'] = 'attachment; filename="student_names.csv"'
    return response

@login_required(login_url="/login/")
def single_choice(request, id=None):
    if request.method == 'POST':
        form = ans_form(request.POST)
        if form.is_valid():
            post = form.save()
            post.save()
            return HttpResponseRedirect(reverse('placement'))
    else:
        form = ans_form()
    return render(request, 'student/detail.html', {'form': form})

@login_required(login_url="/login/")
@role_required(allowed_roles = "Admin")
def add_placement(request):
    return render(request, 'control/add.html')

@login_required(login_url="/login/")
@role_required(allowed_roles = "Admin")
def create_placement(request):
    title = request.POST["title"]
    info = request.POST["info"]
    creator = request.user
    start_date = request.POST["start_date"]
    end_date = request.POST["end_date"]
    start_time = request.POST["start_time"]
    end_time = request.POST["end_time"]

    placement_info = Placements(title=title, information=info, created_by=creator,
    start_date=start_date, end_date=end_date, start_time=start_time, end_time=end_time)
    placement_info.save()
    messages.success(request, "Successful")
    return render(request, 'control/add.html')

@login_required(login_url="/login/")
@role_required(allowed_roles = "Admin")
def placement_delete(request, id=None):
    placement = Placements.objects.get(id=id)

    if request.method == 'POST':
        placement.delete()
        messages.success(request, "Successful")
        return HttpResponseRedirect(reverse('placement'))
    else:
        context = {}
        context['placement'] = placement
        return render(request, 'control/delete.html', context)

def add_choice(request):
    if request.method == 'POST':
        form = choice_form(request.POST)
        if form.is_valid():
            post = form.save()
            post.save()
            return HttpResponseRedirect(reverse('add_choice'))
    else:
        form = choice_form()
    return render(request, 'control/add_choice.html', {'form': form})


import numpy as np
import re
import time
import utils
from bpe import BPE

bpe = BPE()
bpe.load('data/words.bpe')
endToken = bpe.str_to_token['\n']
numTokens = len(bpe.str_to_token)

raw_data = utils.get_dataset(low_it=True)

SAVE_NAME = 'data/train_data_bpe_edition.npz'

DATA_TO_PROCESS = int(input('data to process, {} max? '.format(len(raw_data))))
BATCH_SIZE = int(input('batch size? '))

if DATA_TO_PROCESS > len(raw_data):
	DATA_TO_PROCESS = len(raw_data)

vocab = utils.vocab

xi, xp, y = utils.encodeData(raw_data[:DATA_TO_PROCESS], bpe, endToken)

print ('to start processing {} of data, press any key'.format(len(xi)))
input()
print ('{:=^40}'.format(' starting '))

start = time.time()

x1_shape, x2_shape, y_shape = utils.encoded2xy(xi[:1], xp[:1], y[:1], endToken, numTokens)

Xp = np.zeros(x1_shape.shape, dtype=np.float32)
Xu = np.zeros(x2_shape.shape, dtype=np.float32)
Y = np.zeros(y_shape.shape, dtype=np.float32)

while len(xi) > 0:
	X_past_on_batch, X_user_on_batch, Y_on_batch = utils.encoded2xy(xi[:BATCH_SIZE], xp[:BATCH_SIZE], y[:BATCH_SIZE], endToken, numTokens)

	#print (X.shape, X_on_batch.shape)

	Xp = np.concatenate((Xp, X_past_on_batch), axis=0)
	Xu = np.concatenate((Xu, X_user_on_batch), axis=0)
	Y = np.concatenate((Y, Y_on_batch), axis=0)

	#print (X, Y)
	print ('data loaded:', Xp[1:].shape, Xu[1:].shape, Y[1:].shape)
	print ('data available:', len(xi), len(xp), len(y))
	xi = xi[BATCH_SIZE:]
	xp = xp[BATCH_SIZE:]
	y = y[BATCH_SIZE:]

utils.save_train_data2(SAVE_NAME, Xp[1:], Xu[1:], Y[1:])
print ('{:=^40}'.format(' data saved '))

print ('data saved:', Xp[1:].shape, Xu[1:].shape, Y[1:].shape)
print ('data left:', len(xi), len(xp), len(y))

print ('total time: {:.4f}s'.format(time.time()-start))

print ('(っ・ω・）っ≡≡≡≡≡≡☆')


# -*- coding: utf-8 -*-
import scrapy
from ..items import CodeItem

class JpointSpider(scrapy.Spider):
    name = 'jpoint'
    allowed_domains = ['www.javatpoint.com']
    start_urls = ['https://www.javatpoint.com/operators-in-java']

    def parse(self, response):
       # tk=response.css('.codeblock')
       # dess=response.css('p::text').extract()
        #titlelist=dict()
        title=response.css('#h1::text,.h1 ::text')[0].extract()
        language=response.xpath('//*[@id="smoothmenu1"]/ul/li[5]/a/text()').extract_first()
        subtitles=response.xpath('//h2[not(contains(.,"Javatpoint Services") or contains(.,"Training For College Campus") or contains(.,"Please Share") or contains(.,"Learn Latest Tutorials"))]/text()').extract()
        count = 1
        for t in subtitles:
            #code = t.css('.java::text').extract_first()
            description = response.xpath('//p[count(preceding-sibling::h2)=' + str(count) + ']/text()').extract()

            #print(code)
            Item=CodeItem()
            Item['Title']=title + ' - ' + t

            Item['Code']= response.xpath('//div[count(preceding-sibling::h2)=' + str(count) + ']/textarea[@class="java"]/text()').extract()
            Item['Language']=language
            Item['Description']=description
            Item['URL']= response.request.url
            count+=1
            yield Item

        NextLinkSelector= response.xpath('//*[@id="bottomnextup"]/a[1]/@href')
        if NextLinkSelector:
           NextLink=NextLinkSelector.extract_first()
           yield scrapy.Request(url=response.urljoin(NextLink))


#! /usr/bin/env python

import sys
import os
import pygame
from pygame.locals import *

sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir))

import game_lib

'''
def load_image(image_path):

    from PIL import Image
    from PIL import ImageDraw
    image = Image.open(image_path)
    draw = ImageDraw.Draw(image)
    mode = image.mode
    size = image.size
    data = image.tobytes()
    return pygame.image.fromstring(data, size, mode)
'''

pygame.init()

FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()

# set up the window
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Animation')

WHITE = (255, 255, 255)

#catImg = pygame.image.load('cat.png')
catImg = game_lib.load_image('cat.png')
catx = 10
caty = 10
direction = 'right'

while True: # the main game loop
    DISPLAYSURF.fill(WHITE)

    if direction == 'right':
        catx += 5
        if catx == 280:
            direction = 'down'
    elif direction == 'down':
        caty += 5
        if caty == 220:
            direction = 'left'
    elif direction == 'left':
        catx -= 5
        if catx == 10:
            direction = 'up'
    elif direction == 'up':
        caty -= 5
        if caty == 10:
            direction = 'right'

    DISPLAYSURF.blit(catImg, (catx, caty))

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

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


from django.shortcuts import render, redirect
from .models import tournament as t_db
from .models import registration
from .models import tournamentMatch
from .forms import NewTournamentForm
from users.models import Profile
from django.contrib import messages
from underscore import _
from django.core import serializers
import json

# Create your views here.

def updateScore(request, id=0):
    match = tournamentMatch.objects.get(pk=id)
    if request.method == 'POST':
        if match.tourn_id.completed:
            messages.warning(request, 'This tournament is already completed!')
            return redirect('tournamentView', tid=match.tourn_id.id)
        win_id = int(request.POST.get('winner'))
        win = registration.objects.get(pk=win_id)
        match.winner = win
        match.save()
        if match.nextGame:
            next = tournamentMatch.objects.get(tourn_id=match.tourn_id, bracketNo=match.nextGame)
            if next.p1 is None:
                next.p1 = win
            elif next.p2 is None:
                next.p2 = win
            else:
                messages.warning(request, 'Winners already selected!')
                return redirect('tournamentView', tid=match.tourn_id.id)
            next.save()
        else:
            match.tourn_id.winner = win.player
            match.tourn_id.completed = True
            match.tourn_id.save()
        return redirect('tournamentView', tid=match.tourn_id.id)

    context = {
        'match': match,
    }
    return render(request, 'tournament/updateScore.html', context)

def tournament(request, tid=0):
    tm = t_db.objects.get(id=tid)
    regs = registration.objects.filter(tournament=tid)
    matches = tournamentMatch.objects.filter(tourn_id=tid)
    if request.method == 'POST' and 'register' in request.POST:
        reg = registration(player=request.user, tournament=tm)
        reg.save()

    if request.method == "POST" and 'start' in request.POST:
        if regs.count() != tm.no_of_players:
            messages.warning(request, 'Incorrect number of players registered!')
            return redirect(str(tid))
        tm.started = True
        tm.save()
        startBracket(regs, tm.no_of_players, tm)

    jsons = serializers.serialize('json', matches)

    users = {}

    for reg in regs:
        users[reg.id] = reg.player.username

    users = json.dumps(users)

    print(users)

    context = {
        'tournament': tm,
        'regs': regs,
        'matches': jsons,
        'users': users
    }

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

def new(request):
    if request.method == 'POST':
        tournament = t_db(creator=request.user)
        form = NewTournamentForm(request.POST, instance=tournament)
        if form.is_valid():
            form.save()
            messages.success(request, 'You have successfully created a new tournament!')
            return redirect('dashboard')
    else:
        form = NewTournamentForm()
    context = {
        'form': form
    }
    return render(request, 'tournament/new.html', context)

def startBracket(regs, base, tm):
    knownBrackets = [2, 4, 8, 16, 32]
    bracketCount = 0
    teams = _.shuffle(list(regs))
    closest = _.find(knownBrackets, lambda k, *a: k >= base)
    byes = closest - base

    if byes > 0:
        base = closest

    brackets = []
    rounds = 1
    baseT = base / 2
    baseC = base / 2
    teamMark = 0
    nextInc = base / 2

    print(teams[1])

    for i in range(1, base):
        print(teamMark)
        baseR = i / baseT
        isBye = False

        if byes > 0 and (i % 2 != 0 or byes >= baseT - i):
            isBye = True
            byes - 1
        last = _.map(_.filter(brackets, lambda b, *a: b['nextGame'] == i), lambda c, *a: { 'game': c['bracketNo']})
        brackets.append({
            'lastGames': None if rounds == 1 else [last[0]['game'], last[1]['game']],
            'nextGame': None if nextInc + i > base - 1 else nextInc + i,
            'p1': teams[teamMark] if rounds == 1 else None,
            'p2': teams[teamMark + 1] if rounds == 1 else None,
            'bracketNo': i,
            'roundNo': rounds,
            'bye': isBye,
        })

        teamMark += 2
        if i % 2 != 0:
            nextInc -= 1

        while baseR >= 1:
            rounds += 1
            baseC /= 2
            baseT = baseT + baseC
            baseR = i / baseT

    for match in brackets:
        match = tournamentMatch(tourn_id=tm, p1=match['p1'], p2=match['p2'], roundNo=match['roundNo'], bye=match['bye'], lastGames=match['lastGames'], nextGame=match['nextGame'], bracketNo=match['bracketNo'])
        match.save()
    return brackets


import discord
from discord.ext import commands, tasks
from discord import Embed
import api
import database as db
from util import checks, log
import logging
from datetime import datetime, timezone, timedelta
from dateutil import parser
import pytz

logger = logging.getLogger('__name__')
logger.setLevel(logging.INFO)
handler = logging.FileHandler(
    filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter(
    '%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

class Diamond(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.diamond_check.start()

    @commands.group(aliases=['d'], hidden=True)
    async def diamond(self, ctx):
        if ctx.invoked_subcommand is None:

            pass

    @diamond.command()
    @checks.is_owner()
    async def setup(self, ctx, channel: discord.TextChannel, role: discord.Role):
        try:
            await db.add_diamond_role(ctx.guild.id, role.id)
            await db.add_diamond_channel(ctx.guild.id, channel.id)
            await db.update_timestamp(ctx.guild.id, datetime.utcnow())
            await ctx.send("Succesfully added the channel and role")
        except Exception as e:
            await ctx.send(e)
            raise e

    @diamond.command()
    @checks.is_owner()
    async def toggle(self, ctx, boolean: bool):
        try:
            await db.enable_diamond_ping(ctx.guild.id, boolean)
            await ctx.send(f"Diamond pings have been set to: {boolean}")
        except Exception as e:
            await ctx.send(e)
            raise e

    @diamond.command()
    @checks.is_owner()
    async def config(self, ctx):

        config = await db.server_config(ctx.guild.id)
        print(config)
        ID, ping_bool, role, channel, timestamp = config[0]
        embed = Embed(title="Server Config",
                      description=f"ID: {ID}\nDiamond Ping: {ping_bool}\nPinged Role: {ctx.guild.get_role(role)}\nChannel: {ctx.guild.get_channel(channel)}")
        await ctx.send(embed=embed)

    @tasks.loop(minutes=1, reconnect=True)
    async def diamond_check(self):
        # print('starting diamond check')
        cheap_diamonds = False
        more_than_200 = False
        string = ""
        listings = await api.diamond_market()
        allservers = await db.all_servers()
        # listings = [{"price_per_diamond": 1, "diamonds_remaining": 5}]

        # Servers who have premium and have a properly configured diamond pings
        filtered = [
            x for x in allservers if x.premium and x.diamond_ping and x.diamond_role is not None and x.diamond_channel is not None]

        for server in filtered:
            diamond = [x for x in listings if x['price_per_diamond']
                       < server.diamond_amount]

            if diamond is not []:
                embed = Embed(title="Cheap Diamonds!!!")
                string = ""
                for list in diamond:
                    string += f"There are {list['diamonds_remaining']} diamonds left at {list['price_per_diamond']:,} each.\n"

                embed.description = string
                guild = self.bot.get_guild(server.serverid)
                if guild is None:
                    continue
                chan = self.bot.get_channel(server.diamond_channel)
                role = guild.get_role(server.diamond_role)

                if chan is None or role is None:
                    embed = Embed(title="Diamond Config is missing role or channel",
                                  description=f"Role: {role}\nChannel: {chan}")
                    await log.server_log_embed(self.bot, server.serverid, embed)
                    continue
                if server.last_pinged is None:
                    await db.update_timestamp(server.serverid, datetime.now(timezone.utc))
                    continue
                plus30min = server.last_pinged + timedelta(minutes=29)
                plus30min = pytz.utc.localize(plus30min)

                if plus30min < datetime.now(timezone.utc):
                    await chan.send(f'{role.mention}', embed=embed)
                    await db.update_timestamp(server.serverid, datetime.now(timezone.utc))

    @diamond_check.before_loop
    async def before_diamodn_check(self):
        await self.bot.wait_until_ready()

def setup(bot):
    bot.add_cog(Diamond(bot))
    print("Diamond Cog Loaded")


import logging

import numpy as np
from timeit import default_timer as timer

import alphai_crocubot_oracle.crocubot.evaluate as crocubot_eval
import pandas as pd
from alphai_crocubot_oracle.oracle import CrocubotOracle
from alphai_feature_generation.transformation import GymDataTransformation
from copy import deepcopy

from alphai_metacrocubot_oracle.result import FeatureSensitivity, OraclePrediction

class MetaCrocubotOracle(CrocubotOracle):

    def _init_data_transformation(self):
        data_trans_conf = self.config['data_transformation']
        data_trans_conf[GymDataTransformation.KEY_EXCHANGE] = self.calendar_name
        data_trans_conf["features_start_market_minute"] = self.scheduling['training_frequency']['minutes_offset']
        data_trans_conf["prediction_market_minute"] = self.scheduling['prediction_frequency']['minutes_offset']
        data_trans_conf["target_delta"] = self.prediction_horizon
        data_trans_conf["target_market_minute"] = self.scheduling['prediction_frequency']['minutes_offset']
        data_trans_conf["n_classification_bins"] = self.config['model']["n_classification_bins"]
        data_trans_conf["classify_per_series"] = self.config['model']["classify_per_series"]
        data_trans_conf["normalise_per_series"] = self.config['model']["normalise_per_series"]
        data_trans_conf["n_assets"] = self.config['model']["n_assets"]

        self._data_transformation = GymDataTransformation(data_trans_conf)

        self._target_feature = self._data_transformation.get_target_feature()
        self._n_features = len(self._data_transformation.features)

    def _sanity_check(self):
        pass

    def _init_universe_provider(self):
        pass

    def get_universe(self, data):
        return None

    def _preprocess_outputs(self, train_y_dict):

        train_y = list(train_y_dict.values())[0]
        train_y = np.swapaxes(train_y, axis1=1, axis2=2)

        if self._tensorflow_flags.predict_single_shares:
            n_feat_y = train_y.shape[3]
            train_y = np.reshape(train_y, [-1, 1, 1, n_feat_y])

        if self.network == 'dropout':
            train_y = np.squeeze(train_y)

        self.verify_y_data(train_y)

        return train_y.astype(np.float32)

    def _filter_universe_from_data_for_prediction(self, data, *args):
        return data

    def verify_pricing_data(self, predict_data):
        pass

    def predict(self, data, current_timestamp, *args, **kwargs):
        """
             Main method that gives us a prediction after the training phase is done

             :param data: The dict of dataframes to be used for prediction
             :type data: dict
             :param current_timestamp: The timestamp of the time when the prediction is executed
             :type current_timestamp: datetime.datetime
             :return: Mean vector or covariance matrix together with the timestamp of the prediction
             :rtype: PredictionResult
             """

        if self._topology is None:
            logging.warning('Not ready for prediction - safer to run train first')

        logging.info('Crocubot Oracle prediction on {}.'.format(current_timestamp))

        self.verify_pricing_data(data)
        latest_train_file = self._train_file_manager.latest_train_filename(current_timestamp)
        predict_x, symbols, prediction_timestamp, target_timestamp = self._data_transformation.create_predict_data(data)

        feature_list = list(predict_x.keys())

        predict_x = self._preprocess_inputs(predict_x)

        logging.info('Executing Main Prediction')
        prediction_result = self._do_single_prediction(
            predict_x,
            latest_train_file,
            symbols,
            current_timestamp,
            target_timestamp
        )

        for i in range(predict_x.shape[3]):
            feature_name = feature_list[i]
            perturbed_x = deepcopy(predict_x)
            perturbed_x[:, :, :, i] = 0

            try:
                logging.info('Executing sensitivity prediction for feature {}'.format(feature_name))
                perturbed_result = self._do_single_prediction(
                    perturbed_x,
                    latest_train_file,
                    symbols,
                    current_timestamp,
                    target_timestamp
                )

                perturbation = perturbed_result.mean_vector - prediction_result.mean_vector

                logging.info("Calculated sensitivity for feature [{}]".format(feature_name))

                prediction_result.add_feature_sensitivity(FeatureSensitivity(feature_name, perturbation))
            except Exception as e:
                logging.error("Error calculating sensitivy for feature [{}]. Reason: {}".format(
                    feature_name, e
                ))
        return prediction_result

    def _do_single_prediction(self, predict_x, latest_train_file, symbols, current_timestamp,
                              target_timestamp):

        start_time = timer()

        if self._topology is None:
            n_timesteps = predict_x.shape[2]
            self.initialise_topology(n_timesteps)

        network_input_shape = self._topology.get_network_input_shape()
        data_input_shape = predict_x.shape[-3:]

        if data_input_shape != network_input_shape:
            err_msg = 'Data shape' + str(data_input_shape) + " doesnt match network input " + str(
                network_input_shape)
            raise ValueError(err_msg)

        predict_y = crocubot_eval.eval_neural_net(
            predict_x, self._topology,
            self._tensorflow_flags,
            latest_train_file
        )

        end_time = timer()
        eval_time = end_time - start_time
        logging.info("Network evaluation took: {} seconds".format(eval_time))

        means, conf_low, conf_high = self._data_transformation.inverse_transform_multi_predict_y(predict_y, symbols)
        self.log_validity_of_predictions(means, conf_low, conf_high)

        means_series = pd.Series(np.squeeze(means), index=symbols)
        conf_low_series = pd.Series(np.squeeze(conf_low), index=symbols)
        conf_high_series = pd.Series(np.squeeze(conf_high), index=symbols)

        return OraclePrediction(means_series, conf_low_series, conf_high_series, current_timestamp, target_timestamp)

    @staticmethod
    def log_validity_of_predictions(means, conf_low, conf_high):
        """ Checks that the network outputs are sensible. """

        if not (np.isfinite(conf_low).all() and np.isfinite(conf_high).all()):
            logging.warning('Confidence interval contains non-finite values.')

        if not np.isfinite(means).all():
            logging.warning('Means found to contain non-finite values.')

        logging.debug('Samples from predicted means: {}'.format(means.flatten()[0:10]))


# raise - lançando exceções (erros)
# https://docs.python.org/pt-br/3/library/exceptions.html#built-in-exceptions

def nao_aceito_zero(divisor):
        if divisor == 0:
            raise ZeroDivisionError('Voce esta tentando dividir por zero')
        return True

def deve_ser_int_ou_float(numero):
       tipo_numero = type(numero)
       if not isinstance(numero, (float, int)):
            raise TypeError(
                  f'"{numero}" deve ser int ou float.'
                  f'"{tipo_numero.__name__}" enviado.'
            )
       return True

def divide(numero, divisor):
    deve_ser_int_ou_float(numero)
    deve_ser_int_ou_float(divisor)
    nao_aceito_zero(divisor)
    return numero / divisor

print(divide(8, 'l'))


"""File containing tests specific for the djWasabi/container.py file."""

import sys
import os
import requests
import pytest

currentPath = os.path.dirname(os.path.realpath(__file__))
rootPath = os.path.join(currentPath, "..")
libraryDir = os.path.join(rootPath, "lib")
sys.path.append(libraryDir)
from djWasabi import djWasabi

def test_validateDockerRunning():
    """Test if Docker is running.
    :returns:
    """
    assert djWasabi.container.validateDockerRunning()

def test_container_getValueArg_owner():
    """Test the to execute command to do an ls
    :return:
    """
    value = "owner"
    owner = "dj-wasabi"
    repository = "dj-wasabi-release"
    output = djWasabi.container.getValueArg(
        value=value,
        owner=owner,
        repository=repository
    )
    assert output == "dj-wasabi"

def test_container_getValueArg_repository():
    """Test the to execute command to do an ls
    :return:
    """
    value = "repository"
    owner = "dj-wasabi"
    repository = "dj-wasabi-release"
    output = djWasabi.container.getValueArg(
        value=value,
        owner=owner,
        repository=repository
    )
    assert output == "dj-wasabi-release"

def test_container_getValueArg_none():
    """Test the to execute command to do an ls
    :return:
    """
    value = "notexisting"
    owner = "dj-wasabi"
    repository = "dj-wasabi-release"
    output = djWasabi.container.getValueArg(
        value=value,
        owner=owner,
        repository=repository
    )
    assert output is None

def test_container_getValueArg_version():
    """Test the to execute command to do an ls
    :return:
    """
    value = "version"
    owner = "dj-wasabi"
    repository = "dj-wasabi-release"
    version = "1.2.3"
    output = djWasabi.container.getValueArg(
        value=value,
        owner=owner,
        repository=repository,
        version=version
    )
    assert output == "1.2.3"

def test_container_createContainerCommand():
    """Test the docker run with only Docker image.
    :return:
    """
    configuration = {
        "image": "dj-wasabi/consul"
    }
    owner = "dj-wasabi"
    repository = "dj-wasabi-release"
    container = djWasabi.container.createContainerCommand(
        configuration=configuration,
        owner=owner,
        repository=repository
    )
    output = djWasabi.generic.getString(data=container)
    assert output == "docker run --rm dj-wasabi/consul"

def test_container_createContainerCommand_environment():
    """Test the docker run with only Docker image.
    :return:
    """
    configuration = {
        "image": "dj-wasabi/consul",
        "environment": ["DJWASABI"]

    }
    owner = "dj-wasabi"
    repository = "dj-wasabi-release"
    container = djWasabi.container.createContainerCommand(
        configuration=configuration,
        owner=owner,
        repository=repository
    )
    output = djWasabi.generic.getString(data=container)
    assert output == "docker run --rm -e DJWASABI=test dj-wasabi/consul"

def test_container_createContainerCommand_volumes():
    """Test the docker run with only Docker image.
    :return:
    """

    configuration = {
        "image": "dj-wasabi/consul",
        "volumes": {
            "PWD": "/data",
            "/data": "/data"
        }

    }
    owner = "dj-wasabi"
    repository = "dj-wasabi-release"
    container = djWasabi.container.createContainerCommand(
        configuration=configuration,
        owner=owner,
        repository=repository
    )
    output = djWasabi.generic.getString(data=container)
    value = "docker run --rm -v {v}:/data -v /data:/data dj-wasabi/consul".format(v=os.getcwd())
    assert output == value

def test_container_createContainerCommand_noImage():
    """Test the _delete function without providing url.
    :return:
    """
    configuration = {
        "volumes": {
            "PWD": "/data",
            "/data": "/data"
        }

    }
    owner = "dj-wasabi"
    repository = "dj-wasabi-release"
    with pytest.raises(ValueError, match="Please provide the Docker image."):
        djWasabi.container.createContainerCommand(
            configuration=configuration,
            owner=owner,
            repository=repository
        )

def test_container_createContainerCommand_arguments():
    """Test the docker run with provided arguments.
    :return:
    """

    configuration = {
        "image": "dj-wasabi/consul",
        "arguments": {
            "repository": "-p"
        }

    }
    owner = "dj-wasabi"
    repository = "dj-wasabi-release"
    container = djWasabi.container.createContainerCommand(
        configuration=configuration,
        owner=owner,
        repository=repository
    )
    output = djWasabi.generic.getString(data=container)
    value = "docker run --rm dj-wasabi/consul -p {r}".format(r=repository)
    assert output == value


import discord
import sys
import foods
import dice
import scores
from game_logic import is_over, play_game

MAX_RANGE = 1000
intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

playing = False

@client.event
async def on_ready():

    print(f'We have logged in as {client.user}')
    # Load the list of foods from the file
    foods.load_foods()
    scores.load_scores()

@client.event
async def on_message(message):
    global MAX_RANGE
    global playing

    if message.author == client.user:
        return

    # Handle the "foods" and "food" commands
    if message.content.lower().startswith('$foods') or message.content.lower().startswith('$food'):
        await message.channel.send(f'Pierre should eat {foods.get_random_food()}.')

    elif message.content.lower().startswith('$addfood'):
        await message.channel.send(f'```Please enter the name of the food you would like to add to the list or type $cancel to cancel adding a food to the list```')
        message = await client.wait_for('message')
        if message.content.lower().startswith('$cancel'):
            return
        while message.author == client.user:
            message = await client.wait_for('message')
        food = message.content
        foods.add_food(food)
        await message.channel.send(f'```Added {food} to the list```')
        food.load_foods()

    elif message.content.lower().startswith('$reload'):
        foods.load_foods()
        await message.channel.send("```Food list has been reloaded```")

    elif message.content.lower().startswith('$d20'):
      await message.channel.send(f'```{str(message.author).split("#")[0]} {dice.roll_d20()}```')

    elif message.content.lower().startswith('$scores'):
        await message.channel.send(scores.print_scores())

#edit to make sure game aint going
    if message.content.lower() =='$stop' and is_over() == True:
        await message.channel.send(f'```Shutting down.```')
        sys.exit(0)
    elif message.content.lower() =='$stop':
        await message.channel.send(f'```There is currently a game going on, please wait.```')
    if message.content.lower().startswith('$start'):
        scores_dict = scores.get_scores()
        print(scores_dict)
        await play_game(message, client, scores_dict)

    if message.content.lower().startswith('$help'):
      await message.channel.send(f'```Commands:\n$foods or $food: Return a random food for Pierre to eat.\n$addfood: Add a new food to the list.\n$reload: Reload the list of foods.\n$scores: Get the current scores.\n$d20: Roll a d20.\n$start: Start the random number game.```')

#token here
client.run('')


def supply(inventory):
    item = input("Sure, what do you want to add to my stock? ").lower()
    if item in inventory.keys():
        amt = int(input(f"How many {item}s do you want"+
                        "to add to my stock? "))
        while amt < 1:
            amt = int(input(f"How many {item}s do you want "+
                            "to add to my stock? "))
        inventory[item][2] += amt
    else:
        desc = input(f"What is {item}'s description? ").lower()
        price = float(input(f"What is {item}'s price? "))
        amt = int(input(f"How many {item}s do you want "+
                        "to add to my stock? "))
        inventory[item] = [desc,price,amt]

def retrieve(inventory):
    item = input("Sure, what do you want to retrieve from my stock? ").lower()
    if item not in inventory.keys():
        print(f"Sorry, {item} is currently not in my stock.")
    else:
        amt = int(input(f"How many {item}s do you want "+
                        "to remove from my inventory? "))
        while amt < 1:
            amt = int(input(f"How many {item}s do you want "+
                            "to remove from my inventory? "))
        if inventory[item][2] <= amt:
            print(f"I only have {inventory[item][2]} of those. I'm returning"+
                  "all of them to you.")
        inventory[item][2] -= amt
        if inventory[item][2] <= 0:
            inventory.pop(item)
            print(f"I have no {item}s left. I removed it from my inventory.")
        else:
            print(f"I have {inventory[item][2]} {item}s left.")
def check(inventory):
    print("This is a list of what I currently have:")
    for item in inventory.items():
        print(f"{item[0]}: {item[1][0]}. ${item[1][1]:.2f},"+
              f"available: {item[1][2]}")

def main():
    shop = {"rusty sword": ["a rusted sword", 100.00, 10],
            "molten sand": ["a bucket of molten sand",51.93, 3],
            "empty can": ["an empty can of soda", 0.75, 20],
            "inflatable rubber duck": ["hope you have strong lungs", 150.00, 5],
            "planetary ring": ["taken from a distant planet", 1000000.00, 1]}

    supplying = True

    print("Welcome, supplier!")

    while supplying:
        answer = input("What do you want to do today? (supply, retrieve, "+\
                       "check, leave): ").lower()
        if answer == "supply":
            supply(shop)
        elif answer == "retrieve":
            retrieve(shop)
        elif answer == "check":
            check(shop)
        elif answer == "leave":
            supplying = False

    print("Thanks for stopping by, supplier!")

if __name__ == "__main__":
    main()


"""
the general training framework
"""

from __future__ import print_function

import os
import argparse
import socket
import time

import tensorboard_logger as tb_logger
import torch
import torch.optim as optim
import torch.nn as nn
import torch.backends.cudnn as cudnn

from models import model_dict
from models.util import FeatTrans
from models.util import Connector, Translator, Paraphraser

from dataset.cifar100 import get_cifar100_dataloaders, get_cifar100_dataloaders_sample

from helper.util import adjust_learning_rate

from distiller_zoo import DistillKL, HintLoss, Attention, Similarity, Correlation, VIDLoss, RKDLoss
from distiller_zoo import PKT, ABLoss, FactorTransfer, KDSVD, FSP, NSTLoss
from crd.criterion import CRDLoss

from helper.loops import train_sftn as train, validate
from helper.pretrain import init

def parse_option():

    hostname = socket.gethostname()

    parser = argparse.ArgumentParser('argument for training')

    parser.add_argument('--print_freq', type=int, default=100, help='print frequency')
    parser.add_argument('--tb_freq', type=int, default=500, help='tb frequency')
    parser.add_argument('--save_freq', type=int, default=40, help='save frequency')
    parser.add_argument('--batch_size', type=int, default=64, help='batch_size')
    parser.add_argument('--num_workers', type=int, default=8, help='num of workers to use')
    parser.add_argument('--epochs', type=int, default=240, help='number of training epochs')
    parser.add_argument('--init_epochs', type=int, default=30, help='init training for two-stage methods')

    # optimization
    parser.add_argument('--learning_rate', type=float, default=0.05, help='learning rate')
    parser.add_argument('--lr_decay_epochs', type=str, default='150,180,210', help='where to decay lr, can be a list')
    parser.add_argument('--lr_decay_rate', type=float, default=0.1, help='decay rate for learning rate')
    parser.add_argument('--weight_decay', type=float, default=5e-4, help='weight decay')
    parser.add_argument('--momentum', type=float, default=0.9, help='momentum')

    # dataset
    parser.add_argument('--dataset', type=str, default='cifar100', choices=['cifar100'], help='dataset')

    # model
    parser.add_argument('--model_s', type=str, default='resnet110',
                        choices=['resnet8', 'resnet14', 'resnet20', 'resnet32', 'resnet44', 'resnet56', 'resnet110',
                                 'resnet8x4', 'resnet32x4', 'wrn_16_1', 'wrn_16_2', 'wrn_40_1', 'wrn_40_2',
                                 'vgg8', 'vgg11', 'vgg13', 'vgg16', 'vgg19',
                                 'MobileNetV2', 'ShuffleV1', 'ShuffleV2', ])
    parser.add_argument('--model_t', type=str, default=None, help='teacher model snapshot')
    parser.add_argument('--trial', type=str, default='1', help='trial id')

    parser.add_argument('-r', '--gamma', type=float, default=1, help='weight for teacher classification')
    parser.add_argument('-a', '--alpha', type=float, default=3, help='weight balance for KD between teacher and student logit')
    parser.add_argument('-b', '--beta', type=float, default=1, help='weight for student classification')

    # KL distillation
    parser.add_argument('--kd_T', type=float, default=1, help='temperature for student aware training')

    # hint layer
    parser.add_argument('--hint_layer', default=2, type=int, choices=[0, 1, 2, 3, 4])

    # gpu configuration
    parser.add_argument('--gpu_idx', default="0", type=str)

    opt = parser.parse_args()

    # set the path according to the environment
    opt.model_path = './save/sftn'
    opt.tb_path = './save/sftn_tensorboards'

    iterations = opt.lr_decay_epochs.split(',')
    opt.lr_decay_epochs = list([])
    for it in iterations:
        opt.lr_decay_epochs.append(int(it))

    opt.model_name = 'S:{}_T:{}_sftn_{}_r:{}_a:{}_b:{}_{}'.format(opt.model_s, opt.model_t, opt.dataset,
                                                                opt.gamma, opt.alpha, opt.beta, opt.trial)

    opt.tb_folder = os.path.join(opt.tb_path, opt.model_name)
    if not os.path.isdir(opt.tb_folder):
        os.makedirs(opt.tb_folder)

    opt.save_folder = os.path.join(opt.model_path, opt.model_name)
    if not os.path.isdir(opt.save_folder):
        os.makedirs(opt.save_folder)

    return opt

def main():
    best_acc = 0

    opt = parse_option()
    os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
    os.environ["CUDA_VISIBLE_DEVICES"] = opt.gpu_idx

    # tensorboard logger
    logger = tb_logger.Logger(logdir=opt.tb_folder, flush_secs=2)

    # dataloader
    if opt.dataset == 'cifar100':
        train_loader, val_loader, n_data = get_cifar100_dataloaders(batch_size=opt.batch_size,
                                                                    num_workers=opt.num_workers,
                                                                    is_instance=True)
        n_cls = 100
    else:
        raise NotImplementedError(opt.dataset)

    # teacher model
    model_t = model_dict[opt.model_t](num_classes=n_cls) # random init t model

    # student branches
    branch1, branch2 = model_dict[opt.model_s+"_branches"](num_classes=n_cls)

    # feature transform layer
    model_s = model_dict[opt.model_s](num_classes=n_cls)

    data = torch.randn(2, 3, 32, 32)
    model_t.eval()
    model_s.eval()
    feat_t, _ = model_t(data, is_feat=True)
    feat_s, _ = model_s(data, is_feat=True)
    transform1 = FeatTrans(feat_s[1].shape, feat_t[1].shape)
    transform2 = FeatTrans(feat_s[2].shape, feat_t[2].shape)

    module_list = nn.ModuleList([])
    module_list.append(model_t)
    module_list.append(branch1)
    module_list.append(branch2)
    module_list.append(transform1)
    module_list.append(transform2)

    trainable_list = nn.ModuleList([])
    trainable_list.append(model_t)
    trainable_list.append(branch1)
    trainable_list.append(branch2)
    trainable_list.append(transform1)
    trainable_list.append(transform2)

    criterion_T_CE = nn.CrossEntropyLoss()
    criterion_S_KL = DistillKL(opt.kd_T)
    criterion_S_CE = nn.CrossEntropyLoss()

    criterion_list = nn.ModuleList([])
    criterion_list.append(criterion_T_CE)    # classification loss
    criterion_list.append(criterion_S_KL)    # KL divergence loss, original knowledge distillation
    criterion_list.append(criterion_S_CE)     # other knowledge distillation loss

    # optimizer
    optimizer = optim.SGD(trainable_list.parameters(),
                          lr=opt.learning_rate,
                          momentum=opt.momentum,
                          weight_decay=opt.weight_decay)

    if torch.cuda.is_available():
        module_list.cuda()
        criterion_list.cuda()
        cudnn.benchmark = True

    # routine
    for epoch in range(1, opt.epochs + 1):

        adjust_learning_rate(epoch, opt, optimizer)
        print("==> training...")

        time1 = time.time()
        train_acc, train_loss = train(epoch, train_loader, module_list, criterion_list, optimizer, opt)
        time2 = time.time()
        print('epoch {}, total time {:.2f}'.format(epoch, time2 - time1))

        logger.log_value('train_acc', train_acc, epoch)
        logger.log_value('train_loss', train_loss, epoch)

        test_acc, tect_acc_top5, test_loss = validate(val_loader, model_t, criterion_T_CE, opt)

        logger.log_value('test_acc', test_acc, epoch)
        logger.log_value('test_loss', test_loss, epoch)
        logger.log_value('test_acc_top5', tect_acc_top5, epoch)

        # save the best model
        if test_acc > best_acc:
            best_acc = test_acc
            state = {
                'epoch': epoch,
                'model': model_t.state_dict(),
                'best_acc': best_acc,
            }
            save_file = os.path.join(opt.save_folder, '{}_best.pth'.format(opt.model_s))
            print('saving the best model!')
            torch.save(state, save_file)

        # regular saving
        if epoch % opt.save_freq == 0:
            print('==> Saving...')
            state = {
                'epoch': epoch,
                'model': model_t.state_dict(),
                'accuracy': test_acc,
            }
            save_file = os.path.join(opt.save_folder, 'ckpt_epoch_{epoch}.pth'.format(epoch=epoch))
            torch.save(state, save_file)

    # This best accuracy is only for printing purpose.
    # The results reported in the paper/README is from the last epoch.
    print('best accuracy:', best_acc)

    # save model
    state = {
        'opt': opt,
        'model': model_t.state_dict(),
    }
    save_file = os.path.join(opt.save_folder, '{}_last.pth'.format(opt.model_s))
    torch.save(state, save_file)

if __name__ == '__main__':
    main()


from omegaconf import OmegaConf
import torch

import logging
from agent.polybeast.models.base import BaseNet, RandomNet, HalfCheetahAgent
from nle.env.base import DUNGEON_SHAPE
from envs.skills_all import HalfCheetah
from agent.common.envs import tasks
from agent.polybeast.models import BaseNet

def create_basenet(flags, device):
    model_string = flags.model
    logging.critical(flags.model)
    if model_string == "baseline":
        model_cls = BaseNet
    elif model_string == "baseline_c":
        model_cls = HalfCheetahAgent
    elif model_string == "cnn" or model_string == "transformer":
        raise RuntimeError(
            "model=%s deprecated, use model=baseline crop_model=%s instead"
            % (model_string, model_string)
        )
    else:
        raise NotImplementedError("model=%s" % model_string)

    if flags.model in ["baseline_c","hks_c"]:
        logging.critical(flags.model)
        print(flags.model)
        env = HalfCheetah()()#have a functor, first brackets is constructor and second is a function call
        model = model_cls(env.observation_space,env.action_space,flags,device)
    else:
        num_actions = len(
            tasks.ENVS[flags.env](savedir=None, archivefile=None).actions
        )
        model = model_cls(DUNGEON_SHAPE, num_actions, flags, device)

    model.to(device=device)
    return model

def load_model(env, pretrained_path, pretrained_config_path, device):
    flags = OmegaConf.load(pretrained_config_path)
    flags["env"] = env
    model = create_basenet(flags, device)

    checkpoint_states = torch.load(pretrained_path, map_location=device)

    model.load_state_dict(checkpoint_states["model_state_dict"])
    # model.training = False

    hidden = model.initial_state(batch_size=1)
    return model, hidden


# 47. Permutations II
# backtrack

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        res = []
        path = []
        used = [False] * len(nums)
        nums.sort()

        def backtrack():
            if len(path) == len(nums):
                res.append(path.copy())
                return

            for i in range(len(nums)):
                if used[i]:
                    continue
                if i > 0 and nums[i] == nums[i-1] and not used[i-1]:
                    continue
                path.append(nums[i])
                used[i] = True
                backtrack()
                path.pop()
                used[i] = False

        backtrack()
        return res


from tkinter import *
from PIL import ImageTk, Image

import t
import callfunction
#from tqdm import tqdm
class MyWindow:
    data=[]
    def __init__(self, win):

        #replace data with values of list
        ima=Image.open('hevo1.png')
        pho=ImageTk.PhotoImage(ima)
        i4=Label(win,bg='black')
        i4.config(image=pho)
        i4.img=pho
        i4.place(x=150,y=5)
        #canvas.create_image(20,20, anchor=NW, image=img)
        self.lab = Label( text="HevoValYou",font="-weight bold")
        self.lab.config(font=("Courier", 48))
        self.lab.config(fg='white')
        self.lab.config(bg='black')
        self.lb = Listbox(win,width=80, height=20, selectmode='multiple')
        data=[]
        for num in data:
            self.lb.insert(END,num)
        self.btn1 = Button(win, text='Select All')
        self.btn2 = Button(win, text='Search the web')
        self.lab.place(x=250, y=5)
        self.lb.place(x=150, y=100)
        self.b1=Button(win, text='    Select All    ',command=self.selectall)
        self.b2=Button(win, text='Search the Web', command=self.search)
        self.b3=Button(win, text='      Load        ', command=self.load)
        self.b3.place(x=200, y=450)
        self.b1.place(x=350, y=450)
        self.b2.place(x=500, y=450)
    def selectall(self):
        callfunction.callfunction(self.data)
    def load(self):
        self.data=[]
        self.lb.delete(0,'end')
        self.data=t.check()
        for num in self.data:
            self.lb.insert(END,num)
    def search(self):
        selection = self.lb.curselection()
        selection=list(selection)
        print(selection)
        l=[]
        for x in range(len(selection)):
            l.append(self.data[selection[x]])
        callfunction.callfunction(l)

window=Tk()
mywin=MyWindow(window)
window.title('HevoValYou')
window.geometry("800x500+10+10")
window.configure(bg="#000000")
p1 = PhotoImage(file = 'hevo1.png')
window.iconphoto(False, p1)
window.mainloop()


from random import sample
from itertools import chain
from typing import List

from colour import Color
import numpy as np
from tqdm.auto import tqdm
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_distances as pairwise_cos_dist

class Avance():

    def __init__(self, liste_txt : List[str], *args, nb_pivots : float = 50, **kwargs) -> None:
        self.liste_txt = liste_txt
        self.nb_pivots = nb_pivots

        tqdm.write("\nDédoublonage avancé")

        with tqdm(total=2, desc = "Calcul des vecteurs BoW") as pbar:
            docspivots = sample(list(enumerate(liste_txt)), nb_pivots)
            textespivots = {e for _, e in docspivots}
            #On crée les vecteurs pour les textes (coordonnée n = occurences du mot de position n dans la liste de vocabulaire)
            vocab = set(' '.join(textespivots).lower().split())
            vectorizer = TfidfVectorizer(stop_words = ("english"), vocabulary = vocab)
            pbar.update()
            tf = vectorizer.fit_transform(liste_txt)
            pbar.update()
            self.arrtf = tf.toarray()
            self.pivots = docspivots

    def process(self, *args, taillegroupe : int = 1000, sensibilite : float = 0.00001, **kwargs) -> None:
        index_doublons , liste_doublons= [], []
        liste_txt = self.liste_txt
        self.taillegroupe = taillegroupe
        avg = np.mean([len(e) for e in liste_txt])
        tupliste = [(txt, i) for i, txt in enumerate(liste_txt)]
        tupliste = sorted(tupliste, key=lambda tupliste: len(tupliste))

        #On sépare les textes en groupes de même taille, en fonction de leur longueur
        nbgroupes = 1 + (len(tupliste) // taillegroupe)
        groupes = [tupliste[i*taillegroupe:(i+1)*taillegroupe] for i in range(nbgroupes)]

        colors = [Color("blue")] +list(Color("blue").range_to(Color("green"),nbgroupes))

        manualpbar = tqdm(groupes, desc="Calcul des vecteurs seconds / supression")
        for i, groupe in enumerate(manualpbar):
            manualpbar.colour = colors[i].hex_l
            #Array de tous les vecteurs 2, un texte par ligne comparé a chaque pivot par colonne
            vect1_pivot = np.array([self.arrtf [i] * (avg / len(e)) for i, e in self.pivots], dtype = np.half)
            vect1_non_pivot = np.array([self.arrtf [i] * (avg / len(e)) for i, e in enumerate(groupe)], dtype = np.half)
            array_vecteurs = pairwise_cos_dist(vect1_non_pivot, vect1_pivot)
            del vect1_non_pivot, vect1_pivot

            #Matrice de la distance cosinus entre chaque texte du corpus, chaque intersection [x,y] donnant
            #la distance entre les textes de rang x et y
            matrice_cosine = pairwise_cos_dist(array_vecteurs)
            del array_vecteurs

            #Permet de faire abstraction de la distance nulle du texte n avec lui-même et ne pas le remonter comme doublon
            for i in range(np.shape(matrice_cosine)[0]):
                matrice_cosine[i,i] = 1
            #Liste de toutes les distances faibles --> Doublons
            lst_doublons = np.transpose(np.nonzero(matrice_cosine < sensibilite)).tolist()

            del matrice_cosine
            for e in lst_doublons:
                lst_doublons.remove([e[1], e[0]])
            #Nous permet de supprimer directement les doublons par l'index vu que l'élement reste a sa place (seuls ceux qui suivent ont étés supprimés)
            doublons = sorted(list(set(e[1] for e in lst_doublons)), reverse = True)
            del lst_doublons

            for db in doublons:
                x = (groupe.pop(db))
                liste_doublons.append(x[0])
                index_doublons.append(x[1])

            del doublons

        self.liste_propre = list(chain.from_iterable(groupes))
        self.index_doublons = sorted(index_doublons)
        self.liste_doublons = sorted(liste_doublons, key=lambda liste_doublons: len(liste_doublons))
        tqdm.write(f"Dédoublonage avancé : Il reste désormais {len(liste_txt)} articles.")


# encoding=utf-8
from selenium import webdriver
import random,time,os
import urllib.request
import base64

from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
import selenium.webdriver.support.expected_conditions as EC
import selenium.webdriver.support.ui as ui

class FBUserlogoDownload:

    def __init__(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(10)

    def is_visible(slef,locator, timeout=10):
        try:
            ui.WebDriverWait(slef.driver, timeout).until(EC.visibility_of_element_located((By.XPATH, locator)))
            return True
        except TimeoutException:
            return False

    def is_not_visible(slef,locator, timeout=10):
        try:
            ui.WebDriverWait(slef.driver, timeout).until_not(EC.visibility_of_element_located((By.XPATH, locator)))
            return True
        except TimeoutException:
            return False

    def scroll2Bottom(self,browser, maxCount=None):
        allBodyPre = browser.page_source
        iCount = 0
        while True:
            browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            iCount += 1
            time.sleep(random.randint(4, 5))
            print("%sth time Scroll to the bottom to fetch more information" % iCount)

            if maxCount is not None:
                if iCount > maxCount:
                    break
            allBodySrolled = browser.page_source
            if len(allBodySrolled) == len(allBodyPre):
                print("no more information can be found!")
                break
            else:
                allBodyPre = allBodySrolled

    def base64tofile(self,base64src,localUrl):
        ori_image_data = base64.b64decode(base64src)
        with open(localUrl,'wb') as f:
            f.write(ori_image_data)

    def loginFB(self,usr,pwd):
        self.driver.get('https://www.facebook.com/')
        time.sleep(random.randint(3,5))
        xp_iu= "//input[@id='email']"
        xp_ip = "//input[@id='pass']"
        xp_login = "//input[@data-testid='royal_login_button']"
        if self.is_visible(xp_iu) and self.is_visible(xp_ip):
            e_usr = self.driver.find_element_by_xpath(xp_iu)
            e_pas = self.driver.find_element_by_xpath(xp_ip)
            e_login = self.driver.find_element_by_xpath(xp_login)
            e_usr.clear()
            e_pas.clear()
            e_usr.send_keys(usr)
            e_pas.send_keys(pwd)
            e_login.click()
            time.sleep(random.randint(5,10))

        else:
            print('input not visible')

        if self.is_visible(By.XPATH,"//input[@class='_1frb']"):
            return True
        return False

    def loadMemberByURL(self,surl):
        try:
            loginFlag = self.loginFB('leena201818@gmail.com','1qaz@WSX3edc')
            if not loginFlag:
                print("login failed!")
                return

            #surl = 'https://www.facebook.com/groups/8578301243/members/'
            self.driver.get(surl)
            time.sleep(random.randint(5,10))

            self.scroll2Bottom(self.driver)

            xp_seemore = "//a[@class='pam uiBoxLightblue uiMorePagerPrimary']"

            while self.is_visible(xp_seemore):
                btn_seemore = self.driver.find_element_by_xpath(xp_seemore)
                btn_seemore.click()
                time.sleep(random.randint(1, 4))
                self.scroll2Bottom(self.driver)

        except Exception as e:
            print(e)
            return False

    def savePages(self,targetfile):
        #all images are displayed
        title = self.driver.title
        print(title)
        os.system(r'd:\saveas.exe "{0}" {1}'.format(title,targetfile))
        print('save ok:{0}'.format(targetfile))

        # all images are displayed

        images = self.driver.find_elements_by_xpath("//img[@class='rg_ic rg_i']")
        for img in images:
            src = img.get_attribute('src')
            name = img.get_attribute('name').replace(':', '')
            dir = os.path.splitext(targetfile)[0]+'_files'
            localfile = os.path.join(dir, name + '.jpeg')

            print(src)

            if src is not None and src.startswith('data'):
                print('data')
                src = src.split(',')
                base64src = src[1]
                self.base64tofile(base64src, localfile)
                print('download base64 img:{0}'.format(localfile))
            else:
                print('{0} is not acceptable'.format(src))

if __name__ == '__main__':
    surl = 'https://www.facebook.com/groups/117245955585344/members/'
    ndaurl = 'https://www.facebook.com/groups/1615742195336598/members/'
    fu = FBUserlogoDownload()

    fu.loginFB('leena201818@gmail.com', '1qaz@WSX3edc')

    # fu.loadMemberByURL(surl)
    # targetfile = r'd:\img\samples\normal\117245955585344.htm'
    # fu.savePages(targetfile)


import numpy
import itertools
import functools

def evaluate_test_data(self, test_data):
    test_res = [(numpy.argmax(self.compute(x)), numpy.argmax(exp)) for (x, exp) in test_data]
    return sum([int(idx_got == idx_exp) for (idx_got, idx_exp) in test_res])

def evaluate_test_mnist_data(self, test_data):
    test_res = [(numpy.argmax(self.compute(x)), y) for (x, y) in test_data]
    return sum(int(x == y) for (x, y) in test_res)

##test flower

refTable = ["daisy", "dandelion", "rose", "sunflower", "tulip"]

#display percentage evaluation among the different species of flower
def evaluate_test_flower_verbose(self, test_data):
    ##
    percentage = {
        "daisy": (0, 0),
        "dandelion": (0, 0),
        "rose": (0, 0),
        "sunflower": (0, 0),
        "tulip": (0, 0),
    }
    for (x, y) in test_data:
        got_idx = numpy.argmax(self.compute(x))
        expec_idx  = numpy.argmax(y)
        # print(f"expec = {expec_idx}")
        # print(f"got = {got_idx}")
        key = refTable[expec_idx]
        if got_idx == expec_idx:
            percentage[key] = (percentage[key][0] + 1, percentage[key][1])
        percentage[key] = (percentage[key][0], percentage[key][1] + 1)

    print("### verbose evaluation ###")
    for key, val in percentage.items(): print(f"{key} = {val[0]}/{val[1]} ", end="")

    print("")

    total = functools.reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), list(percentage.values()), (0, 0))
    print(f"total = {total[0]}/{total[1]}")
    print("###########################")
    return total[0]


import matplotlib.pyplot as plt
import numpy as np

N = 3

ind = np.arange(N)  # the x locations for the groups
width = 0.25       # the width of the bars

fig, ax = plt.subplots()

pos_bar = (0.36, 0.32, 0.28)
neg_bar = (0.54, 0.41, 0.34)
neu_bar = (0.08, 0.26, 0.38)
no_bar = (0.02, 0.01, 0.00)

rects1 = ax.bar(ind+.2, pos_bar, width, color='b' )
rects2 = ax.bar(ind+.2 + width*1, neg_bar, width, color='r')
rects3 = ax.bar(ind+.2 + width*2, neu_bar, width, color='y')
rects4 = ax.bar(ind+.2 + width*3, no_bar, width, color='g')
# add some text for labels, title and axes ticks
ax.set_ylabel('Percentage')
ax.set_title('Quinnipiac Polling Result, Aug 12th, 2015')
ax.set_xticks(ind + width)
ax.set_xticklabels(('Donanld Trump', 'Jeb Bush', 'Ted Cruz'))

ax.legend((rects1[0], rects2[0], rects3[0], rects4[0]), ('Favorable', 'Unfavorable', 'Never heard', 'No opinion'))

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                height,
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
autolabel(rects4)

axes = plt.gca()

axes.set_ylim([0.0,1.0])

plt.show()


from collections import deque

with open('input.txt', 'r') as f:
    n, m = map(int, f.readline().split())
    b = []
    for i in range(n):
        b.append(int(f.readline()))

print(b)

feed = []
i = 0
type = None
add_later = deque([])
while i < n:
    if b[i] != type:
        feed.append(i)
        type = b[i]
    else:
        for j in range(len(add_later)):
            if type != b[add_later[j]]:
                feed.append(add_later[j])
                del add_later[j]
                break
        add_later.append(i)
    i += 1

print(feed)

# def value(i, j):
#     return 2**(-i) * 2**(-j)
#
# def printknapSack(W, wt, n):
#     K = [[0 for w in range(W + 1)]
#             for i in range(n + 1)]
#
#     # Build table K[][] in bottom
#     # up manner
#     for i in range(n + 1):
#         for w in range(W + 1):
#             if i == 0 or w == 0:
#                 K[i][w] = 0
#             elif wt[i - 1] <= w:
#                 K[i][w] = max(value(i-1, w-1)
#                   + K[i - 1][w - wt[i - 1]],
#                                K[i - 1][w])
#             else:
#                 K[i][w] = K[i - 1][w]
#
#
#
#     res = K[n][W]
#     print(res)
#
#     w = W
#     for i in range(n, 0, -1):
#         if res <= 0:
#             break
#         # either the result comes from the
#         # top (K[i-1][w]) or from (val[i-1]
#         # + K[i-1] [w-wt[i-1]]) as in Knapsack
#         # table. If it comes from the latter
#         # one/ it means the item is included.
#         if res == K[i - 1][w]:
#             continue
#         else:
#
#             # This item is included.
#             print(w)
#
#             # Since this weight is included
#             # its value is deducted
#             res = res - value(i,w)
#             w = w - wt[i - 1]
#
# # Driver code
# wt = [ 1 for i in range(n) ]
# W = n
#
# printknapSack(W, wt, n)


from __future__ import print_function, division
from keras.models import Model
from keras.layers import Concatenate, Add, Average, Input, Dense, Flatten, BatchNormalization, Activation, LeakyReLU
from keras.layers.convolutional import Convolution2D, MaxPooling2D, UpSampling2D, Convolution2DTranspose
from keras import backend as K
from keras.utils.np_utils import to_categorical
import keras.callbacks as callbacks
import keras.optimizers as optimizers
from advanced import HistoryCheckpoint, SubPixelUpscaling, non_local_block, TensorBoardBatch
import img_utils
import numpy as np
import os
import time
import warnings

try:
    import cv2
    _cv2_available = True
except:
    warnings.warn('Could not load opencv properly. This may affect the quality of output images.')
    _cv2_available = False

train_path = img_utils.output_path
validation_path = img_utils.validation_output_path
path_X = img_utils.output_path + "X/"
path_Y = img_utils.output_path + "y/"

def PSNRLoss(y_true, y_pred):

    return -10. * K.log(K.mean(K.square(y_pred - y_true))) / K.log(10.)

def psnr(y_true, y_pred):
    assert y_true.shape == y_pred.shape, "Cannot calculate PSNR. Input shapes not same." \
                                         " y_true shape = %s, y_pred shape = %s" % (str(y_true.shape),
                                                                                str(y_pred.shape))

    return -10. * np.log10(np.mean(np.square(y_pred - y_true)))

class BaseSuperResolutionModel(object):

    def __init__(self, model_name, scale_factor):

        self.model = None # type: Model
        self.model_name = model_name
        self.scale_factor = scale_factor
        self.weight_path = None

        self.type_scale_type = "norm" # Default = "norm" = 1. / 255
        self.type_requires_divisible_shape = False
        self.type_true_upscaling = False

        self.evaluation_func = None
        self.uses_learning_phase = False

    def create_model(self, height=32, width=32, channels=3, load_weights=False, batch_size=128) -> Model:

        if self.type_requires_divisible_shape and height is not None and width is not None:
            assert height * img_utils._image_scale_multiplier % 4 == 0, "Height of the image must be divisible by 4"
            assert width * img_utils._image_scale_multiplier % 4 == 0, "Width of the image must be divisible by 4"

        if K.image_dim_ordering() == "th":
            if width is not None and height is not None:
                shape = (channels, width * img_utils._image_scale_multiplier, height * img_utils._image_scale_multiplier)
            else:
                shape = (channels, None, None)
        else:
            if width is not None and height is not None:
                shape = (width * img_utils._image_scale_multiplier, height * img_utils._image_scale_multiplier, channels)
            else:
                shape = (None, None, channels)

        init = Input(shape=shape)

        return init

    def fit(self, batch_size=128, nb_epochs=100, save_history=True, history_fn="Model History.txt") -> Model:

        samples_per_epoch = img_utils.image_count()
        val_count = img_utils.val_image_count()
        if self.model == None: self.create_model(batch_size=batch_size)

        callback_list = [callbacks.ModelCheckpoint(self.weight_path, monitor='val_PSNRLoss', save_best_only=True,
                                                   mode='max', save_weights_only=True, verbose=2)]
        if save_history:
            callback_list.append(HistoryCheckpoint(history_fn))

            if K.backend() == 'tensorflow':
                log_dir = './%s_logs/' % self.model_name
                tensorboard = TensorBoardBatch(log_dir, batch_size=batch_size)
                callback_list.append(tensorboard)

        print("Training model : %s" % (self.__class__.__name__))
        self.model.fit_generator(img_utils.image_generator(train_path, scale_factor=self.scale_factor,
                                                           small_train_images=self.type_true_upscaling,
                                                           batch_size=batch_size),
                                 steps_per_epoch=samples_per_epoch // batch_size + 1,
                                 epochs=nb_epochs, callbacks=callback_list,
                                 validation_data=img_utils.image_generator(validation_path,
                                                                           scale_factor=self.scale_factor,
                                                                           small_train_images=self.type_true_upscaling,
                                                                           batch_size=batch_size),
                                 validation_steps=val_count // batch_size + 1)

        return self.model

    def upscale(self, img_path, save_intermediate=False, return_image=False, suffix="scaled",
                patch_size=8, mode="patch", verbose=True):

        import os
        from scipy.misc import imread, imresize, imsave

        # Destination path
        path = os.path.splitext(img_path)
        #print(path[0])
        filename = path[0] + "_" + suffix + "(%dx)" % (self.scale_factor) + path[1]

        # Read image
        scale_factor = int(self.scale_factor)
        true_img = imread(img_path, mode='RGB')
        init_dim_1, init_dim_2 = true_img.shape[0], true_img.shape[1]
        if verbose: print("Old Size : ", true_img.shape)
        if verbose: print("New Size : (%d, %d, 3)" % (init_dim_1 * scale_factor, init_dim_2 * scale_factor))

        img_dim_1, img_dim_2 = 0, 0

        if mode == "patch" and self.type_true_upscaling:
            # Overriding mode for True Upscaling models
            mode = 'fast'
            print("Patch mode does not work with True Upscaling models yet. Defaulting to mode='fast'")

        if mode == 'patch':
            # Create patches
            if self.type_requires_divisible_shape:
                if patch_size % 4 != 0:
                    print("Deep Denoise requires patch size which is multiple of 4.\nSetting patch_size = 8.")
                    patch_size = 8

            images = img_utils.make_patches(true_img, scale_factor, patch_size, verbose)

            nb_images = images.shape[0]
            img_dim_1, img_dim_2 = images.shape[1], images.shape[2]
            print("Number of patches = %d, Patch Shape = (%d, %d)" % (nb_images, img_dim_2, img_dim_1))
        else:
            # Use full image for super resolution
            img_dim_1, img_dim_2 = self.__match_autoencoder_size(img_dim_1, img_dim_2, init_dim_1, init_dim_2,
                                                                 scale_factor)

            images = imresize(true_img, (img_dim_1, img_dim_2))
            images = np.expand_dims(images, axis=0)
            print("Image is reshaped to : (%d, %d, %d)" % (images.shape[1], images.shape[2], images.shape[3]))

        # Save intermediate bilinear scaled image is needed for comparison.
        # intermediate_img = None
        # if save_intermediate:
        #     if verbose: print("Saving intermediate image.")
        #     fn = path[0] + "_intermediate_" + path[1]
        #     intermediate_img = imresize(true_img, (init_dim_1 * scale_factor, init_dim_2 * scale_factor))
        #     imsave(fn, intermediate_img)

        # Transpose and Process images
        if K.image_dim_ordering() == "th":
            img_conv = images.transpose((0, 3, 1, 2)).astype(np.float32) / 255.
        else:
            img_conv = images.astype(np.float32) / 255.

        model = self.create_model(img_dim_2, img_dim_1, load_weights=True)
        if verbose: print("Model loaded.")

        # Create prediction for image patches
        result = model.predict(img_conv, batch_size=128, verbose=verbose)

        if verbose: print("De-processing images.")

         # Deprocess patches
        if K.image_dim_ordering() == "th":
            result = result.transpose((0, 2, 3, 1)).astype(np.float32) * 255.
        else:
            result = result.astype(np.float32) * 255.

        # Output shape is (original_width * scale, original_height * scale, nb_channels)
        if mode == 'patch':
            out_shape = (init_dim_1 * scale_factor, init_dim_2 * scale_factor, 3)
            result = img_utils.combine_patches(result, out_shape, scale_factor)
        else:
            result = result[0, :, :, :] # Access the 3 Dimensional image vector

        result = np.clip(result, 0, 255).astype('uint8')

        if _cv2_available:
            # used to remove noisy edges
            result = cv2.pyrUp(result)
            result = cv2.medianBlur(result, 3)
            result = cv2.pyrDown(result)

        if verbose: print("\nCompleted De-processing image.")

        if return_image:
            # Return the image without saving. Useful for testing images.
            return result

        if verbose: print("Saving image.")
        imsave(filename, result)

    def __match_autoencoder_size(self, img_dim_1, img_dim_2, init_dim_1, init_dim_2, scale_factor):
        if self.type_requires_divisible_shape:
            if not self.type_true_upscaling:
                # AE model but not true upsampling
                if ((init_dim_2 * scale_factor) % 4 != 0) or ((init_dim_1 * scale_factor) % 4 != 0) or \
                        (init_dim_2 % 2 != 0) or (init_dim_1 % 2 != 0):

                    print("AE models requires image size which is multiple of 4.")
                    img_dim_2 = ((init_dim_2 * scale_factor) // 4) * 4
                    img_dim_1 = ((init_dim_1 * scale_factor) // 4) * 4

                else:
                    # No change required
                    img_dim_2, img_dim_1 = init_dim_2 * scale_factor, init_dim_1 * scale_factor
            else:
                # AE model and true upsampling
                if ((init_dim_2) % 4 != 0) or ((init_dim_1) % 4 != 0) or \
                        (init_dim_2 % 2 != 0) or (init_dim_1 % 2 != 0):

                    print("AE models requires image size which is multiple of 4.")
                    img_dim_2 = ((init_dim_2) // 4) * 4
                    img_dim_1 = ((init_dim_1) // 4) * 4

                else:
                    # No change required
                    img_dim_2, img_dim_1 = init_dim_2, init_dim_1
        else:
            # Not AE but true upsampling
            if self.type_true_upscaling:
                img_dim_2, img_dim_1 = init_dim_2, init_dim_1
            else:
                # Not AE and not true upsampling
                img_dim_2, img_dim_1 = init_dim_2 * scale_factor, init_dim_1 * scale_factor

        return img_dim_1, img_dim_2,

class DistilledResNetSR(BaseSuperResolutionModel):

    def __init__(self, scale_factor):
        super(DistilledResNetSR, self).__init__("DistilledResNetSR", scale_factor)

        # Treat this model as a denoising auto encoder
        # Force the fit, evaluate and upscale methods to take special care about image shape
        self.type_requires_divisible_shape = True
        self.uses_learning_phase = False

        self.n = 32
        self.mode = 2

        self.weight_path = "weights/DistilledResNetSR %dX.h5" % (self.scale_factor)
        self.type_true_upscaling = True

    def create_model(self, height=32, width=32, channels=3, load_weights=False, batch_size=128):
        init =  super(DistilledResNetSR, self).create_model(height, width, channels, load_weights, batch_size)

        x0 = Convolution2D(self.n, (3, 3), activation='relu', padding='same', name='student_sr_res_conv1')(init)

        x = self._residual_block(x0, 1)

        x = Add(name='student_residual')([x, x0])
        x = self._upscale_block(x, 1)

        x = Convolution2D(3, (3, 3), activation="linear", padding='same', name='student_sr_res_conv_final')(x)

        model = Model(init, x)
        # dont compile yet
        if load_weights: model.load_weights(self.weight_path, by_name=True)

        self.model = model
        return model

    def _residual_block(self, ip, id):
        mode = False if self.mode == 2 else None
        channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
        init = ip

        x = Convolution2D(self.n, (3, 3), activation='linear', padding='same',
                          name='student_sr_res_conv_' + str(id) + '_1')(ip)
        x = BatchNormalization(axis=channel_axis, name="student_sr_res_batchnorm_" + str(id) + "_1")(x, training=mode)

        x = Activation('relu', name="student_sr_res_activation_" + str(id) + "_1")(x)

        x = Convolution2D(self.n, (3, 3), activation='linear', padding='same',
                          name='student_sr_res_conv_' + str(id) + '_2')(x)
        x = BatchNormalization(axis=channel_axis, name="student_sr_res_batchnorm_" + str(id) + "_2")(x, training=mode)

        m = Add(name="student_sr_res_merge_" + str(id))([x, init])

        return m

    def _upscale_block(self, ip, id):
        init = ip

        channel_dim = 1 if K.image_data_format() == 'channels_first' else -1
        channels = init._keras_shape[channel_dim]

        x = UpSampling2D(name='student_upsampling_%d' % id)(init)
        x = Convolution2D(self.n * 2, (3, 3), activation="relu", padding='same', name='student_sr_res_filter1_%d' % id)(x)

        return x

    def fit(self, batch_size=128, nb_epochs=100, save_history=True, history_fn="Distilled ResNetSR History.txt"):
        super(DistilledResNetSR, self).fit(batch_size, nb_epochs, save_history, history_fn)


import sys
sys.setrecursionlimit(100000)

def dfs(x, y, h):
    visited[x][y]
    for m in range(4):
        nx = x + dx[m]
        ny = y + dy[m]

        if (0 <= nx < n) and (0 <= ny < n) and not visited[nx][ny]:
            if graph[nx][ny] > h:
                visited[nx][ny] = True
                dfs(nx, ny, h)

dx = [1,-1,0,0]
dy = [0,0,1,-1]

n = int(input())
graph = [list(map(int, input().split())) for _ in range(n)]
ans = 1
max_height = max(map(max, graph))

for k in range(max_height):
    visited = [[False] * n for _ in range(n)]
    cnt = 0
    for i in range(n):
        for j in range(n):
            if not visited[i][j] and graph[i][j] > k:
                cnt += 1

                dfs(i,j,k)
    ans = max(ans, cnt)
print(ans)


import os
import sys
import time
import unittest
import uuid

from ament_index_python.packages import get_package_share_directory

from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.actions import IncludeLaunchDescription

import launch
import launch_ros
import launch_ros.actions
import launch_testing.actions
import launch_testing_ros

import pytest

import rclpy

import std_msgs.msg

@pytest.mark.rostest
def generate_test_description():
  # Normally, talker publishes on the 'chatter' topic and listener listens on the
  # 'chatter' topic, but we want to show how to use remappings to munge the data so we
  # will remap these topics when we launch the nodes and insert our own node that can
  # change the data as it passes through
  path_to_test = os.path.dirname(__file__)
  package_prefix = get_package_share_directory('perception')
  perception_node = launch_ros.actions.Node(
      executable=sys.executable,
      arguments=[os.path.join(
          path_to_test, '../perception/perception_node.py')],
      additional_env={'PYTHONUNBUFFERED': '1'},
      remappings=[('topic', 'topic2')]
  )

  # return launch.LaunchDescription([
  #     IncludeLaunchDescription(
  #         PythonLaunchDescriptionSource(
  #             [package_prefix, '/launch/perception.launch.py'])
  #     ),
  #     launch_testing.actions.ReadyToTest()
  # ])
  return (
      launch.LaunchDescription([
          perception_node,
          # Start tests right away - no need to wait for anything
          launch_testing.actions.ReadyToTest(),
      ]),
      {
          'perception': perception_node,
      }
  )

class TestTalkerListenerLink(unittest.TestCase):

  @classmethod
  def setUpClass(cls):
    # Initialize the ROS context for the test node
    rclpy.init()

  @classmethod
  def tearDownClass(cls):
    # Shutdown the ROS context
    rclpy.shutdown()

  def setUp(self):
    # Create a ROS node for tests
    self.node = rclpy.create_node('test_talker_listener_link')

  def tearDown(self):
    self.node.destroy_node()

  def test_perception_transmits(self, launch_service, perception, proc_output):
    # Expect the talker to publish strings on '/talker_chatter' and also write to stdout
    msgs_rx = []

    sub = self.node.create_subscription(
        std_msgs.msg.String,
        'topic2',
        lambda msg: msgs_rx.append(msg),
        10
    )
    try:
      # Wait until the talker transmits two messages over the ROS topic
      end_time = time.time() + 20
      while time.time() < end_time:
        rclpy.spin_once(self.node, timeout_sec=0.1)
        if len(msgs_rx) > 2:
          break

      self.assertGreater(len(msgs_rx), 2)

      # Make sure the talker also output the same data via stdout
      for msg in msgs_rx:
        proc_output.assertWaitFor(
            expected_output=msg.data, process=perception
        )
    finally:
      self.node.destroy_subscription(sub)


from typing import Optional
from datetime import datetime
from uuid import UUID

class User:
    def __init__(
        self,
        id: str,
        display_name: str,
        email: str,
        created_at: int,
    ) -> None:
        self.id = id
        self.email = email
        self.created_at = created_at
        self.display_name = display_name

class Entry:
    def __init__(
        self,
        id: UUID,
        campaign_id: str,
        title: str,
        entry_text_rich: str,
        entry_text_raw: str,
        created_at: datetime,
        last_modified_at: datetime,
        created_by: str,
        last_modified_by: str,
        entry_text_summary: Optional[str],
        category_id: Optional[str],
    ) -> None:
        self.id = id
        self.campaign_id = campaign_id
        self.title = title
        self.entry_text_rich = entry_text_rich
        self.entry_text_raw = entry_text_raw
        self.created_at = created_at
        self.last_modified_at = last_modified_at
        self.created_by = created_by
        self.last_modified_by = last_modified_by
        self.entry_text_summary = entry_text_summary
        self.category_id = category_id

class EntryMetadata:
    def __init__(
        self,
        id: str,
        campaign_id: str,
        title: str,
        created_at: datetime,
        created_by: str,
        last_modified_at: datetime,
        last_modified_by: str,
        category_id: Optional[str],
    ) -> None:
        self.id = id
        self.campaign_id = campaign_id
        self.title = title
        self.created_at = created_at
        self.created_by = created_by
        self.last_modified_at = last_modified_at
        self.last_modified_by = last_modified_by
        self.category_id = category_id

class Campaign:
    def __init__(
        self, id: UUID, title: str, created_at: datetime, created_by: str
    ) -> None:
        self.id = id
        self.title = title
        self.created_at = created_at
        self.created_by = created_by

class CampaignMember:
    def __init__(self, campaign_id: str, user_id: str, is_dm: bool) -> None:
        self.campaign_id = campaign_id
        self.user_id = user_id
        self.is_dm = is_dm

class Category:
    def __init__(
        self,
        id: UUID,
        campaign_id: UUID,
        title: str,
        created_at: datetime,
        parent_id: Optional[UUID],
    ) -> None:
        self.id = id
        self.campaign_id = campaign_id
        self.title = title
        self.created_at = created_at
        self.parent_id = parent_id


N = int(input())
expression = input()
number = [int(input()) for n in range(N)]

OPERATOR = {'+': lambda a, b: a + b
          , '-': lambda a, b: a - b
          , '*': lambda a, b: a * b
          , '/': lambda a, b: a / b}

stack = []
for oper in expression:
    if oper.isalpha():
        stack.append(number[ord(oper) - 65])
    else:
        a = stack.pop();
        b = stack.pop();
        stack.append(OPERATOR[oper](b, a))

print("{:.2f}".format(stack[-1]))


"""
This file is part of the tractor library.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.

Created on Jan 06, 2012.
"""

from StringIO import StringIO
from datetime import datetime
from tractor.attachment import AttachmentWrapper
from tractor.attachment import Base64Converter
from tractor.tests.base import BaseTestCase
from xmlrpclib import Binary
import zipfile

class Base64ConverterTestCase(BaseTestCase):

    def test_encode_string(self):
        test_str = 'This is a string for base64 conversion testing.'
        exp_conv = Binary(test_str)
        self.assert_equal(Base64Converter.encode_string(test_str), exp_conv)

    def test_encode_stream(self):
        test_stream = StringIO('This is a stream for base64 conversion testing.')
        exp_conv = Binary(test_stream.read())
        self.assert_equal(Base64Converter.encode_stream(test_stream), exp_conv)
        test_stream.close()

    def test_encode_zip_stream(self):
        zip_stream = StringIO()
        archive = zipfile.ZipFile(zip_stream, 'a', zipfile.ZIP_DEFLATED, False)
        archive.writestr('file1', 'test stream 1')
        archive.writestr('file2', 'test stream 2')
        for zfile in archive.filelist: zfile.create_system = 0
        archive.close()
        zip_stream.seek(0)
        exp_conv = Binary(zip_stream.getvalue())
        self.assert_equal(Base64Converter.encode_zip_stream(zip_stream),
                          exp_conv)
        zip_stream.close()

    def test_decode_string(self):
        test_str = 'This is a string for base64 conversion testing.'
        conv = Base64Converter.encode_string(test_str)
        self.assert_equal(Base64Converter.decode_to_string(conv), test_str)

    def test_decode_stream(self):
        test_stream = StringIO('This is a stream for base64 conversion testing.')
        conv = Base64Converter.encode_stream(test_stream)
        decoded_conv = Base64Converter.decode_to_stream(conv)
        decoded_cont = decoded_conv.read()
        test_stream.seek(0)
        exp_cont = test_stream.read()
        self.assert_equal(decoded_cont, exp_cont)

    def test_decode_zip_file_data(self):
        zip_stream = StringIO()
        archive = zipfile.ZipFile(zip_stream, 'a', zipfile.ZIP_DEFLATED, False)
        archive.writestr('file1', 'test stream 1')
        archive.writestr('file2', 'test stream 2')
        for zfile in archive.filelist: zfile.create_system = 0
        archive.close()
        zip_stream.seek(0)
        conv = Base64Converter.encode_zip_stream(zip_stream)
        decoded_conv = Base64Converter.decode_to_stream(conv)
        ret_archive = zipfile.ZipFile(decoded_conv, 'a', zipfile.ZIP_DEFLATED,
                                      False)
        content1 = None
        content2 = None
        self.assert_equal(len(ret_archive.namelist()), 2)
        for file_name in ret_archive.namelist():
            if file_name == 'file1':
                content1 = ret_archive.read(file_name)
                self.assert_equal(content1, 'test stream 1')
                self.assert_not_equal(content2, 'test stream 2')
            else:
                content2 = ret_archive.read(file_name)
                self.assert_equal(content2, 'test stream 2')
                self.assert_not_equal(content2, 'test stream 1')

class AttachmentTestCase(BaseTestCase):

    def set_up(self):
        BaseTestCase.set_up(self)
        self.init_data = dict(content='Important attachment content.',
                              file_name='test_file1.txt',
                              description='A test file.',
                              size=14,
                              author='user1',
                              time=None)

    def test_init(self):
        att = AttachmentWrapper(**self.init_data)
        for attr_name, exp_value in self.init_data.iteritems():
            self.assert_equal(getattr(att, attr_name), exp_value)

    def test_create_from_trac_data(self):
        file_name = 'test_file1.txt'
        description = 'A test file.'
        size = len(file_name)
        time = datetime
        author = 'user1'
        trac_data = (file_name, description, size, time, author)
        att = AttachmentWrapper.create_from_trac_data(trac_data)
        self.init_data['content'] = None
        self.init_data['time'] = time
        for attr_name, exp_value in self.init_data.iteritems():
            self.assert_equal(getattr(att, attr_name), exp_value)

    def test_get_base64_data_for_upload(self):
        # Test string
        test_str = 'This is a string for base64 conversion testing.'
        self.init_data['content'] = test_str
        exp_conv = Base64Converter.encode_string(test_str)
        att = AttachmentWrapper(**self.init_data)
        self.assert_equal(att.get_base64_data_for_upload(), exp_conv)
        # Test stream
        test_stream = StringIO('This is a stream for base64 conversion testing.')
        exp_conv = Base64Converter.encode_stream(test_stream)
        self.init_data['content'] = test_stream
        att = AttachmentWrapper(**self.init_data)
        self.assert_equal(att.get_base64_data_for_upload(), exp_conv)
        # Test file map
        file_map = dict(file1='test stream 1', file2='test stream 2')
        zip_stream = StringIO()
        archive = zipfile.ZipFile(zip_stream, 'a', zipfile.ZIP_DEFLATED, False)
        for fn, content in file_map.iteritems(): archive.writestr(fn, content)
        for zfile in archive.filelist: zfile.create_system = 0
        archive.close()
        zip_stream.seek(0)
        exp_conv = Base64Converter.encode_zip_stream(zip_stream)
        self.init_data['content'] = file_map
        att = AttachmentWrapper(**self.init_data)
        self.assert_equal(att.get_base64_data_for_upload(), exp_conv)
        # Test error raising
        self.init_data['content'] = 1
        att = AttachmentWrapper(**self.init_data)
        self.assert_raises(TypeError, att.get_base64_data_for_upload)


from collections import OrderedDict
from typing import List

import pandas as pd

class TaskField:
    def __init__(self, name: str = None):
        if name is None:
            self.name = type(self).__name__
        else:
            self.name = name

    def get(self, task_id: int):
        return task_id

class TaskFieldList(List[TaskField]):
    """List of Field types"""

    def get_names(self):
        return [field.name for field in self]

    def to_data(self, task_ids: list[int]) -> pd.DataFrame:
        """
        Given a list of task_ids, calls all the TaskFields to get the data for each task_id
        and returns a dataframe with the data
        """
        task_list = [Task(task_id, self) for task_id in task_ids]
        data = []
        for i, task in enumerate(task_list):
            print("working on", i, "out of", len(task_list))
            task.append_to_data(data)
        return pd.DataFrame(data)

    def append_to_data(self, data: pd.DataFrame):
        """ Creates a new dataframe from the triallist and appends it to the supplied dataframe
        This is used to add new columns (fields) to an existing dataframe"""
        # get first column
        new_data = []
        task_ids = data[data.columns[0]]
        task_list = [Task(task_id, self) for task_id in task_ids]
        for i, task in enumerate(task_list):
            print("working on", i, "out of", len(task_list))
            task.append_to_data(new_data)

        new_df = pd.DataFrame(new_data, columns=self.get_names())
        data = pd.concat([data, new_df], axis=1)
        return data

class Task:
    def __init__(self, task_id: int, fields: TaskFieldList):
        self.task_id = task_id
        self.fields = fields

    def append_to_data(self, data):
        field_values = [field.get(self.task_id) for field in self.fields]
        names = self.fields.get_names()
        new_row = OrderedDict(zip(names, field_values))
        data.append(new_row)

def get_data_from_tasks(fields: TaskFieldList, task_ids: list[int]) -> pd.DataFrame:
    task_list = [Task(task_id, fields) for task_id in task_ids]
    data = []
    for i, task in enumerate(task_list):
        print("working on", i, "out of", len(task_list))
        task.append_to_data(data)
    return pd.DataFrame(data)