import os
from random import randint
from itertools import cycle
import json

import pygame as pg

from .. import tools, prepare
from ..components.angles import get_distance
from ..components.animation import Animation
from ..components.labels import Label, Blinker, Button, ButtonGroup

class ScreenSprite(pg.sprite.Sprite):
    def __init__(self,center, image, *groups):
        super(ScreenSprite, self).__init__(*groups)
        self.image = image
        self.rect = self.image.get_rect(center=center)

class GridUI(object):
    def __init__(self, grid):
        topleft = (grid.rect.left - 1, grid.rect.bottom + 9)
        self.bonus_bar = BonusBar(topleft, grid.bonus, grid.max_bonus)
        self.high_scores_table = HighScoresTable(pg.Rect(904, 128, prepare.SCREEN_RECT.right - 904, 500), grid.score)
        self.make_labels(grid)
        self.quit = False
        self.buttons = ButtonGroup()
        img = prepare.GFX["icon-close"]
        Button({"topright": (prepare.SCREEN_RECT.right -10, 10)},
                    self.buttons, idle_image=img, button_size=img.get_size(),
                    call=self.quit_game)
        self.volume_slider = VolumeSlider((910, 20))

    def quit_game(self, *args):
        self.quit = True

    def make_labels(self, grid):
        self.labels = pg.sprite.Group()
        self.level_label = Label("Level {}".format(grid.level),
                    {"midtop": (182, 16)}, self.labels, font_size=64)
        self.score_label = Label("{}".format(grid.score),
                    {"midtop": (182, 64)}, self.labels, font_size=48)
        target = grid.level_targets[grid.level]
        self.next_level_label = Label("Next Level {}".format(target),
                    {"midtop": (182, 128)}, self.labels, font_size=24)

    def get_event(self, event):
        self.buttons.get_event(event)
        self.volume_slider.get_event(event)

    def update(self, dt, grid):
        self.buttons.update(pg.mouse.get_pos())
        level = "Level {}".format(grid.level)
        score = "{}".format(grid.score)
        next_level = "Next Level {}".format(grid.level_targets[grid.level])
        if self.level_label.text != level:
            self.level_label.set_text(level)
        if self.score_label.text != score:
            self.score_label.set_text(score)
        if self.next_level_label.text != next_level:
            self.next_level_label.set_text(next_level)
        self.bonus_bar.update(dt, grid.bonus)
        self.high_scores_table.update(dt, grid.score)
        self.volume_slider.update()

    def draw(self, surface):
        self.labels.draw(surface)
        self.buttons.draw(surface)
        self.bonus_bar.draw(surface)
        self.high_scores_table.draw(surface)
        self.volume_slider.draw(surface)

class HighScoresTable(pg.sprite.Sprite):
    def __init__(self, rect, player_score, *groups):
        super(HighScoresTable, self).__init__(*groups)
        self.rect = rect
        self.image = pg.Surface(self.rect.size).convert_alpha()
        self.title = Label("High Scores",
                    {"midtop": (self.rect.centerx, self.rect.top + 8)},
                    font_size=48, font_path=prepare.FONTS["vipond_octic"])
        self.player_score = self.last_score = player_score
        self.saved_scores = self.load_saved_scores()
        self.make_high_score_labels(self.saved_scores)

    def load_saved_scores(self):
        p = os.path.join("resources", "high_scores.json")
        try:
            with open(p, "r") as f:
                scores = json.load(f)
        except IOError:
            scores = []
        ranked = sorted(scores, reverse=True)
        return ranked

    def update_scores(self, player_score):
        self.player_score = player_score

        if self.player_score != self.last_score:
            ranked = self.saved_scores[:]
            if len(self.saved_scores) < 10 or self.player_score >= ranked[-1]:
                ranked.append(self.player_score)
            ranked = sorted(ranked, reverse=True)[:10]
            self.make_high_score_labels(ranked)
        self.last_score = self.player_score

    def make_high_score_labels(self, scores):
        self.score_labels = pg.sprite.Group()
        top = self.rect.top + 60
        right = self.rect.right - 16
        current = None
        for score in scores:
            if score == self.player_score and current is None:
                Blinker("{}".format(score), {"topright": (right, top)}, 500,
                            self.score_labels, font_size=40)
                current = True
            else:
                Label("{}".format(score), {"topright": (right, top)},
                            self.score_labels, font_size=40)
            top += 35

    def update(self, dt, score):
        self.score_labels.update(dt)
        self.update_scores(score)

    def draw(self, surface):
        self.title.draw(surface)
        self.score_labels.draw(surface)

class BonusBar(pg.sprite.Sprite):
    def __init__(self, topleft, value, max_value):
        self.animations = pg.sprite.Group()
        self.value = value
        self.max_value = max_value
        self.rect = pg.Rect(topleft, (514, 18))
        self.bg_color = "gray20"
        colors= [(0, 227, 255), (236, 230, 255),
                    (255, 120, 255), (236, 230, 255)]
        self.colors = cycle(colors)
        self.color_change_duration = 1000
        self.color = self.draw_color = next(self.colors)
        self.next_color = next(self.colors)
        self.change_color()
        self.image = pg.Surface(self.rect.size)
        self.bar_image = pg.Surface(self.rect.size)
        self.bar_image.set_colorkey((0, 0, 0))
        self.make_image()
        self.warning_sounds = {
                    x: prepare.SFX["jewel-warning{}".format(x)]
                    for x in range(1, 5)}
        self.warning_sound_num = None

    def stop(self):
        for sound in self.warning_sounds.values():
            sound.stop()

    def change_color(self):
        self.color = self.next_color
        self.next_color = next(self.colors)
        self.lerp_val = 0
        ani = Animation(lerp_val=1, duration=self.color_change_duration)
        ani.start(self)
        ani.callback = self.change_color
        self.animations.add(ani)

    def make_image(self):
        self.image.fill((0, 0, 0))
        w = int((self.value / float(self.max_value)) * self.rect.w)
        self.bar_image.fill((0, 0, 0))
        pg.draw.rect(self.bar_image, pg.Color(*self.draw_color),
                    (0, 0, w, self.rect.h))

    def update(self, dt, value):
        self.animations.update(dt)
        self.draw_color = tools.lerp(self.color,
                    self.next_color, self.lerp_val)
        self.value = value
        self.make_image()
        val = self.value / float(self.max_value)
        if val >= .2:
            self.stop()
            self.warning_sound_num = None
        else:
            new_num = None
            if val < .05:
                if self.warning_sound_num != 4:
                    new_num = 4
            elif val < .1:
                if self.warning_sound_num != 3:
                    new_num = 3
            elif val < .15:
                if self.warning_sound_num != 2:
                    new_num = 2
            elif self.warning_sound_num != 1:
                new_num = 1
            if new_num is not None:
                self.stop()
                self.warning_sound_num = new_num
                self.warning_sounds[self.warning_sound_num].play(-1)

    def draw(self, surface):
        surface.blit(self.bar_image, self.rect)

class VolumeSlider(pg.sprite.Sprite):
    def __init__(self, topleft, *groups):
        self.muted = False
        self.sounds = {x: prepare.SFX["jewel-{}note".format(x)]
                    for x in range(3, 9)}
        self.icon = prepare.GFX["icon-speaker"]
        self.muted_icon = prepare.GFX["icon-muted"]
        self.icon_rect = self.icon.get_rect(topleft=topleft)
        self.slider_image = prepare.GFX["slider"]
        self.slider_box = pg.Rect(self.icon_rect.right + 8, 0, 256, 16)
        self.slider_box.centery =  self.icon_rect.centery
        self.slider_rect = self.slider_image.get_rect(
                    center=self.slider_box.center)
        self.volume = 0.
        self.set_volume()
        self.grabbed = False
        self.grab_point = None

    def get_event(self, event):
        if event.type == pg.MOUSEBUTTONDOWN:
            if self.slider_rect.collidepoint(event.pos):
                self.grabbed = True
                self.grab_point = (event.pos[0] - self.slider_rect.left,
                            event.pos[1] - self.slider_rect.top)
        elif event.type == pg.MOUSEBUTTONUP:
            self.grabbed = False
            if self.icon_rect.collidepoint(event.pos):
                self.muted = not self.muted

    def set_volume(self):
        rect, box = self.slider_rect, self.slider_box
        volume = (rect.left - box.left) / float(box.w - rect.w)
        if self.muted:
            volume = 0
        if volume != self.volume:
            for s in prepare.SFX.values():
                s.set_volume(volume)
            self.volume = volume

    def update(self):
        if self.grabbed:
            mx, my = pg.mouse.get_pos()
            left = mx -  self.grab_point[0]
            self.slider_rect.left = min(max(self.slider_box.left, left),
                        self.slider_box.right - self.slider_rect.w)
        self.set_volume()

    def draw(self, surface):
        icon = self.icon
        if self.muted:
            icon = self.muted_icon
        surface.blit(icon, self.icon_rect)
        pg.draw.line(surface, pg.Color("white"), self.slider_box.midleft,
                    self.slider_box.midright, 2)
        surface.blit(self.slider_image, self.slider_rect)

class ScreenBackground(object):
    def __init__(self, image, rects):
        self.image = image
        self.images = [(image.subsurface(rect), pg.Rect(rect))
                    for rect in rects]

    def clear(self, surface):
        surface.blit(self.image, (0, 0))

    def draw(self, surface):
        for image, rect in self.images:
            surface.blit(image, rect)

class BouncingBackground(pg.sprite.Sprite):
    def __init__(self, topleft, view_size, image, speed, *groups):
        super(BouncingBackground, self).__init__(*groups)
        self.speed = speed
        self.base_image = image.convert_alpha()
        self.base_rect = self.base_image.get_rect()
        self.rect = pg.Rect(topleft, view_size)
        self.bounce_rect = self.rect.copy()
        self.bounce_rect.center = self.base_rect.center
        self.image = self.base_image.subsurface(self.bounce_rect)
        self.animations = pg.sprite.Group()

    def update(self, dt):
        self.animations.update(dt)
        clamped = self.bounce_rect.clamp(self.base_rect)
        if clamped != self.bounce_rect or not self.animations:
            self.bounce_rect = clamped
            self.random_destination()
        self.image = self.base_image.subsurface(self.bounce_rect)

    def random_destination(self):
        self.animations.empty()
        x = randint(0, self.base_rect.w - self.rect.w)
        y = randint(0, self.base_rect.h - self.rect.h)
        dist = get_distance(self.bounce_rect.topleft, (x, y))
        ani = Animation(left=x, top=y, duration=dist*self.speed)
        ani.start(self.bounce_rect)
        self.animations.add(ani)

    def draw(self, surface):
        surface.blit(self.image, self.rect)

class StainedGlass(pg.sprite.Sprite):
    def __init__(self, center, image, cover_image, colors, alpha,
                color_change_duration, *groups):
        super(StainedGlass, self).__init__(*groups)
        self.animations = pg.sprite.Group()
        self.frame = image
        self.rect = self.frame.get_rect(center=center)
        self.image = pg.Surface(self.rect.size).convert_alpha()
        self.cover = cover_image
        self.surf = pg.Surface(self.rect.size)
        self.surf.set_colorkey((0, 0 ,0, 255))
        self.alpha = alpha
        self.surf.set_alpha(self.alpha)
        self.colors = cycle(colors)
        self.color_change_duration = color_change_duration
        self.color = next(self.colors)
        self.next_color = next(self.colors)
        self.last_draw_color = None
        self.change_color()

    def change_color(self):
        self.color = self.next_color
        self.next_color = next(self.colors)
        self.lerp_val = 0
        ani = Animation(lerp_val=1, duration=self.color_change_duration)
        ani.start(self)
        ani.callback = self.change_color
        self.animations.add(ani)

    def make_image(self, draw_color):
        self.surf.fill(draw_color)
        self.surf.blit(self.cover, (0, 0))
        self.surf.set_alpha(self.alpha)
        self.image.fill((0,0,0,0))
        self.image.blit(self.surf, (0, 0))
        self.image.blit(self.frame, (0, 0))

    def update(self, dt):
        self.animations.update(dt)
        draw_color = tools.lerp(self.color, self.next_color, self.lerp_val)
        if draw_color != self.last_draw_color:
            self.make_image(draw_color)
            self.last_draw_color = draw_color

    def draw(self, surface):
        surface.blit(self.image, self.rect)


#!/usr/bin/env python3
"""Calculate the difference between geocodes and some truth data in a csv.

The input consistss of a truth csv (without a header) of imageId,lat,lng and some geocode_results.
The script checks to see how many of calculated lat, lngs are corrected in comparision to the
truth csv. Incorrect image ids get saved to a csv and correct image ids get printed to stderr.

Geocodes
    - Missing a location
    - Have a location where there should be none
    - Location is far (>250m?) from true location. Bullseye = within 25m?
    - Not Geocodable. geocode.py did not find any lat, lng.
"""
import argparse
import csv
import json
import sys

from calculate_metrics import diff_geocode

def check_against_truth_data(geocodes, truth):
    correct = []
    incorrect = []
    for row in truth:
        image_id = row['image_id']
        geocode_result = geocodes.get(image_id)
        if geocode_result:
            geocode_lat = geocode_result['lat']
            geocode_lng = geocode_result['lng']
            is_same, error_reason = diff_geocode((float(row['lng']), float(row['lat'])),
                                                 (geocode_lng, geocode_lat))
            if is_same:
                correct.append(image_id)
            else:
                incorrect.append((image_id, error_reason))
        else:
            incorrect.append((image_id, 'Not Geocodable'))
    return correct, incorrect

def main(geocodes_json_path, truth_csv_path, incorrect_file):
    geocodes = json.load(open(geocodes_json_path))
    with open(truth_csv_path) as csv_file:
        truth = csv.DictReader(csv_file, ['image_id', 'lat', 'lng'])
        corrected_ids, incorrect_geocodes = check_against_truth_data(geocodes, truth)
        with open(incorrect_file, 'w') as csv_file:
            writer = csv.writer(csv_file)
            for incorrect in incorrect_geocodes:
                writer.writerow(incorrect)
        for correct in corrected_ids:
            sys.stderr.write(f'{correct}\n')
        sys.stderr.write('\n\n\n\n\n')
        total_ids = len(corrected_ids) + len(incorrect_geocodes)
        sys.stderr.write(f'corrected ids: {len(corrected_ids)} / {total_ids}\n')
        sys.stderr.write(f'inncorrect ids: {len(incorrect_geocodes)} / {total_ids}\n')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        'Check lat, lngs against a csv of truth data, print out matches.')
    parser.add_argument('--geocodes', type=str,
                        help='file calculated by geocode.results',
                        default='data/corrections.geocode_results.json')
    parser.add_argument('--truth_data', type=str,
                        help='CSV file (without a header line) of imageId,lat,lng',
                        default='data/corrections.csv')
    parser.add_argument('--incorrect_file', type=str,
                        help='file to write a csv of image_id,error_reason',
                        default='data/incorrect.csv')
    args = parser.parse_args()

    main(args.geocodes, args.truth_data, args.incorrect_file)


import torch

def get_square_distance(query_pos, all_pos):
    """
    query_pos.shape = (b, sample, 3)
    all_pos.shape = (b, n, 3)
    return shape = (b, sample, n)
    """
    res = ((query_pos.unsqueeze(dim=2) - all_pos.unsqueeze(dim=1)) ** 2).sum(dim=-1)
    return res

b, n, sample = 1, 1, 1
torch.manual_seed(1)
query = torch.randn((b, sample, 3), device='cuda:1')
all_pos = torch.randn((b, n, 3), device='cuda:1')

# res = get_square_distance(query, all_pos)
res = torch.cdist(query, all_pos)
print(res)


# https://leetcode.com/problems/sum-of-digits-in-base-k/description/

class Solution:
    def sumBase(self, n: int, k: int) -> int:
        """
        Logic: Divmod

        Time: O(n)
        Space: O(1)
        """
        total = 0

        while n:
            n, x = divmod(n, k)
            total += x

        return total


import random
import urllib
from hello.domains import myRandom, memberlist
from quiz00 import Quiz00
import random

from bs4 import BeautifulSoup
from urllib.request import urlopen
import  pandas as pd

class Quiz20:

    def quiz20list(self) -> str: return None

    def quiz21tuple(self) -> str: return None

    def quiz22dict(self) -> str: return None

    def quiz23listcom(self) -> str:
        print('---legacy---')
        a=[]
        for i in range(5):
            a.append(i)
        print(a)

        print('---comprehension---')
        a2=[i for i in range(5)]
        print(a2)
        return None

    def quiz24bugs_zip(self) -> {}:
        url = 'https://music.bugs.co.kr/chart/track/realtime/total'
        html_doc = urlopen(url)
        soup = BeautifulSoup(html_doc, 'lxml')  # html.parser vs lxml

        # self.print_music_list(soup) # 아티스트와 타이틀을 분리해서 출력하기
        # self.find_rank(soup) # 랭킹보기
        # a = [i for i in cls_names]
        # print(soup.prettify())
        ls1 = self.find_bugs_music(soup, 'title')
        ls2 = self.find_bugs_music(soup, 'artist')
        a = [i if i == 0 or i == 0 else i for i in range(1)]
        b = [i for i in []]
        c = [(i, j) for i, j in enumerate([])]
        d = {i: j for i, j in zip(ls1, ls2)}
        dict = {i:j for i, j in zip(ls1,ls2)}
        l = [ i + j for i, j in zip(ls1,ls2)]
        l2 = list(zip(ls1,ls2))
        #d1 = dict(zip(ls1,ls2))
        # self.dict1(ls1, ls2)
        # self.dict2(ls1, ls2)
        # self.dict3(ls1, ls2)
        dict = {}
        for i, j in zip(ls1, ls2):
            dict[i] = j
            print(dict)
        return dict

    def print_bugs_list(self, soup) -> None:
        artists = soup.find_all('p', {'class': 'artist'})
        # print(type(artists)) # <class 'bs4.element.ResultSet'>
        artists = [i.get_text() for i in artists]
        # print(type(artists))
        print(''.join(i for i in artists))
        titles = soup.find_all('p', {'class': 'title'})
        titles = [i.get_text() for i in titles]
        print(''.join(i for i in titles))

    def find_bugs_rank(self, soup):
        for i, j in enumerate(['artist', 'title']):
            for i, j in enumerate(self.find_bugs_music(soup, j)):
                print(f'{i}위 : {j}')
                print('#' * 100)

    @staticmethod
    def find_bugs_music(soup, cls_nm) -> []:
        ls = soup.find_all('p', {'class': cls_nm})
        return [i.get_text() for i in ls]

    @staticmethod
    def dict3(ls1,ls2):
        dict = {}
        for i, j in zip(ls1, ls2):
            dict[i] = j
            print(dict)
        return dict

    @staticmethod
    def dict2(ls1,ls2):
        dict = {}
        for i, j in enumerate(ls1):
            dict[j] = ls2[i]
        print(dict)

    @staticmethod
    def dict1(ls1,ls2) -> None:
        dict = {}
        for i in range(len(ls1)):
            dict[ls1[i]] = ls2[i]
        print(dict)

    @staticmethod
    def quiz25dictcom()-> str:
        a = Quiz00
        #1명인데 5명 추출 0~100사이 랜덤
        b = set([a.quiz06memberChoice() for i in range(5)])
        print(b)
        while len(b) !=5:
            b.add(a.quiz06memberChoice())

        scores = [myRandom(0,101)for i in range(5)]
        students = list(b)
        aa={i : j for i , j in zip (students,scores)}

        print(aa)

    def quiz26map(self) -> str: return None

    def quiz27melon_zip(self) -> {}:

        headers = {'User-Agent': 'Mozilla/5.0'}
        url = 'https://www.melon.com/chart/index.htm?dayTime=2022030816'
        req = urllib.request.Request(url, headers=headers)
        soup = BeautifulSoup(urlopen(req).read(), 'lxml')
        ls1 = self.find_melon_music(soup,'ellipsis rank01')
        ls2 = self.find_melon_artist(soup, 'checkEllipsis')
        dict = {}
        for i, j in zip(ls1, ls2):
            dict[i] = j
        print(dict)
        return dict

        # artists = soup.find_all('span',{'class' : 'checkEllipsis'})
        # artists = [i.get_text() for i in artists]
        # print('\n'.join(i for i in artists))
        #title = soup.find_all('div', {'class': 'ellipsis rank01'})
        #title = [i.get_text() for i in title]
        #print(''.join(i for i in title))
        # print(soup)

    def print_melon_list(self, soup) -> None:
        for i, j in enumerate(['ellipsis rank01', 'checkEllipsis']):
            print(''.join(i for i in [i for i in self.find_melon(soup, j)]))
            print('*' * 100)

    def find_melon_rank(self, soup) -> None:
        for i, j in enumerate(['ellipsis rank01', 'checkEllipsis']):
            for i, j in enumerate(self.find_melon(soup, j)):
                print(f'{i}위 : {j}')
            print('*' * 100)

    @staticmethod
    def find_melon_music(soup, music) -> []:
        ls = soup.find_all('div', {'class':  music})
        return [i.get_text() for i in ls]

    @staticmethod
    def find_melon_artist(soup, artist) -> []:
        ls = soup.find_all('span', {'class': artist})
        return [i.get_text() for i in ls]

    def quiz28dataframe(self) -> None:
        dict = self.quiz24bugs_zip()
        df = pd.DataFrame.from_dict(dict, orient='index')
        soup = BeautifulSoup()
        print(df)
        df.to_csv('./save/bugs.csv', sep=',', na_rep='NaN')

        dict1 = self.quiz27melon_zip()
        ds = pd.DataFrame.from_dict(dict1, orient= 'index')
        soup = BeautifulSoup()
        print(ds)
        ds.to_csv('./save/melon.csv', sep=',', na_rep='NaN')
    '''
    다음 결과 출력
        a   b   c
     1  1   3   5
     2  2   4   6

    '''
    def quiz29_pandas_(self) -> object:
        d2 = {"1": [1, 3, 5], "2": [2, 4, 6]}
        d3 = {"1": [1, 3, 5]}
        d4 = {"2": [2, 4, 6]}
        '''
        *방법1
        df2 = pd.DataFrame.from_dict(d2, orient='index', columns=['a', 'b', 'c'])
        print(df2)
        ---------------------------------------
        *방법2
        d = {'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}
        df1 = pd.DataFrame(d, index=[1, 2])
        print(df1)
        '''
        evens = []
        odds = []
        [evens.append(i) if i % 2 == 0 else odds.append(i) for i in range(1,7)]
        #print(j)
        #print(h)

        jh = [odds,evens]
        #print(jh)
        ind = ['1','2']
        c_zip = {i:j for i, j in zip(ind, jh)}
        #print(c_zip)
        c = [chr(i) for i in range(97, 100)]
        df3 = pd.DataFrame.from_dict(c_zip, orient='index', columns=c)
        print(df3)
        '''
           0  1  2
        1  1  3  5
        2  2  4  6
        '''
        df4 = pd.DataFrame.from_dict(c_zip, orient='index')
        #print(df4)

        #frame = pd.DataFrame(d1, index=[1,2])
        #print(frame)

        return None


class Record:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)  # создаем словарь в локальных атрибутах
        self.__total_attrs = len(kwargs)  # вспом. аттр - кол-во элементов слоавря
        self.__attrs = tuple(self.__dict__.keys())  # ключи словаря

    def __check_indx(self, indx):
        if type(indx) != int or not (-self.__total_attrs <= indx <= self.__total_attrs):
            raise IndexError('неверный индекс поля')

    def __getitem__(self, item):
        self.__check_indx(item)
        return getattr(self, self.__attrs[item])

    def __setitem__(self, key, value):
        self.__check_indx(key)
        setattr(self, self.__attrs[key], value)

r = Record(pk=1, title='Python ООП', author='Балакирев')
r[0] = 2 # доступ к полю pk
r[1] = 'Супер курс по ООП' # доступ к полю title
r[2] = 'Балакирев С.М.' # доступ к полю author
print(r[1]) # Супер курс по ООП
r[3] # генерируется исключение IndexError


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 11 15:52:17 2022

@author: sylvain
"""

import numpy as np
from calendar import monthrange
import pandas as pd

# Hypotheses
eta_pp = 0.7      # Average efficiency of the plunger pumps
eta_surpr = 0.4   # average efficiency of the "surpresseur" pumps
C_day = 250       # average daily water consumption in m³
depth = 70        # Depth of the wells
p_nom = 5e5       # nominal absolute pressure of the water distribution
V_dot_nom = C_day/10   # nominal flow rate of the pumps in m³/h
n_days=150            # number of days in the year where the 250m³ are needed

# Average daily consumption:
C_joules = 1000 * 9.81 * depth * C_day / eta_pp + C_day * (p_nom - 1E5)/eta_surpr
# in kWh:
C_kwh = C_joules/3.6e6
print('daily electricity consumption for water pumping:' + str(C_kwh) + ' kWh')
print('monthly electricity consumption for water pumping:' + str(30*C_kwh) + ' kWh')
print('yearly electricity consumption for water pumping:' + str(150*C_kwh) + ' kWh')

# Nominal electricity consumption of the pumps:
V_dot_nom_m3s = V_dot_nom/3600
W_dot_nom = (1000 * 9.81 * depth * V_dot_nom_m3s / eta_pp + V_dot_nom_m3s * (p_nom - 1E5)/eta_pp )/1000
print('Nominal power of the pumps: ' + str(W_dot_nom) + ' kW')

# Ratio between water consumption and electricity consumption:
water_elec_cost = C_kwh/C_day
print('Specific electricity of water: ' + str(water_elec_cost) + ' kWh/m³')

daily_profiles = pd.read_csv('PV_casamance - daily profiles.csv',index_col=0)
daily_profiles.plot()

profile = pd.DataFrame(index=pd.date_range(start='2015-01-01 00:00',end='2015-12-31 23:59',freq='1h'))
water = pd.Series(index=pd.date_range(start='2015-01-01 00:00',end='2015-12-31 23:59',freq='1h'))
conso = pd.Series(index=range(1,13),data=[8580, 10316, 7429, 16165, 10114, 5089, 2851, 2108, 2138, 3463, 6492, 8500])

profile['Lighting and others'] = 0
profile['Plunger Pump'] = 0
profile['Plunger Pump day'] = 0
profile['Surpresseurs'] = 0

profile_flat = profile

conso_base = 2100

for m in range(1,13):
    n_days = monthrange(2015, m)[1]
    conso_pp = conso[m] - conso_base
    idx_month = (profile.index.month == m)
    conso_w_month = conso_pp/water_elec_cost
    print('Water consumption for month ' + str(m) + ': ' + str(conso_w_month) + ' m³')
    conso_w_day = conso_w_month/n_days
    n_hours_pumping = conso_w_day/V_dot_nom
    conso_left = conso_w_day
    daily_cons = np.zeros(24)
    hh = 0
    while conso_left>0:
        if conso_left > 2 * V_dot_nom:
            daily_cons[-hh] = V_dot_nom
            daily_cons[1+hh] = V_dot_nom
            conso_left -= 2 * V_dot_nom
        else:
            daily_cons[-hh] = conso_left/2
            daily_cons[1+hh] = conso_left/2
            conso_left = 0
        hh += 1

    # loop through each day
    for n in range(1,n_days+1):
        idx = (profile.index.month == m) & (profile.index.day==n)
        profile.loc[idx,'Lighting and others'] = daily_profiles['Lighting & other'].values
        if m<6 or m >10:
            water[idx] = daily_profiles['Water cons wet season'].values
        else:
            water[idx] = daily_profiles['Water cons dry season'].values

        profile.loc[idx,'Plunger Pump'] = daily_cons * 1000 * 9.81 * depth / eta_pp / 3.6E6
        profile.loc[idx,'Plunger Pump day'] = daily_cons[range(-12,12)] * 1000 * 9.81 * depth / eta_pp / 3.6E6

    water[idx_month] =  water[idx_month] * conso_w_month/water[idx_month].sum()
    profile.loc[idx_month,'Surpresseurs'] = water[idx_month].values * (p_nom - 1E5)/eta_surpr/3.6E6
    profile.loc[idx_month,'Lighting and others'] =  profile.loc[idx_month,'Lighting and others'] * conso_base/profile.loc[idx_month,'Lighting and others'].sum()

demand_night = profile['Lighting and others'] + profile['Plunger Pump'] + profile['Surpresseurs']
demand_day = profile['Lighting and others'] + profile['Plunger Pump day'] + profile['Surpresseurs']

profile.to_csv('PV_casamance - yearly profiles.csv')

PV Casamance/PV_casamance - generate_profiles.py


#Connect to the dq database as the user dq.
#Write a SQL query that creates a table called users in the dq database, with the following columns and data types:
#id -- integer data type, and is a primary key.
#email -- text data type.
#name -- text data type.
#address -- text data type.
#Execute the query using the execute method.
#Use the commit method on the Connection object to apply the changes in the transaction to the database.
#Close the Connection.

import psycopg2
conn = psycopg2.connect("dbname = dq user = dq")
cur = conn.cursor()
cur.execute("CREATE TABLE users(id integer PRIMARY KEY, email text, name text, address text)")
conn.commit()
conn.close()


#!/usr/bin/python3
"""
0. N queens
"""
import sys
BOARD_SIZE = sys.argv[1]

def under_attack(col, queens):
    """
    [check if a queen is under attack]
    """
    return col in queens or any(abs(col - x) == len(queens) - i
                                for i, x in enumerate(queens))

def solve(BOARD_SIZE):
    """
    [FIND SOLUTION]
    """
    if not len(sys.argv) == 2:
        print("Usage: nqueens N")
        exit(1)
    if not (sys.argv[1]).isdigit():
        print("N must be a number")
        exit(1)
    BOARD_SIZE = int(sys.argv[1])
    if BOARD_SIZE < 4:
        print("N must be at least 4")
        exit(1)
    solutions = [[]]
    for row in range(BOARD_SIZE):
        solutions = [solution+[i]
                     for solution in solutions
                     for i in range(BOARD_SIZE)
                     if not under_attack(i, solution)]
    return solutions

for answer in solve(BOARD_SIZE):
    print(list(enumerate(answer)))


import scrapy
import csv
import json
import re
from html.parser import HTMLParser

def remove_non_ascii(text):
    return ''.join([i if ord(i) < 128 else '' for i in text])

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.strict = False
        self.convert_charrefs= True
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return '|'.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

class HCVID175_www_storyltd_com_Spider(scrapy.Spider):
    name = "HCVID175.www.storyltd.com"
    products_seen = []
    jsonData = []

    def closed(self, reason):
        toWrite = {'data' : HCVID175_www_storyltd_com_Spider.jsonData}
        with open('./json/HCVID175.www.storyltd.com.json', 'w+') as outfile:
            json.dump(toWrite, outfile, ensure_ascii=False)

    def start_requests(self):
        url = "https://www.storyltd.com/"
        yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        x = response.css('div#top_navigation_navigationListHolder ul#top_navigation_top_menus_list > li')
        for columns in x:
            head_category = columns.css('a::text').extract_first()
            if head_category != 'Artists' and head_category != 'Auctions':
                list_items = columns.css('div.block1:first-child ul li')
                for item in list_items:
                    page = item.css('a::attr(href)').extract_first()
                    sub_category = item.css('a::text').extract_first()
                    if page is not None:
                        print(page)
                        request = scrapy.Request(url=page, callback = self.parsePage)
                        request.meta['category'] = str(head_category) + '|' + str(sub_category)
                        yield request

    def parsePage(self, response):
        scripts = response.css('script[type=text\/javascript]').extract()
        for script in scripts:
            if 'var urlBase' in script and 'var pageIndex' in script:
                link = 'https://www.storyltd.com' + re.search('var urlBase = \'(.*?)\';', script).group(1) + '&pageSize=60&pageIndex=1'
                request = scrapy.Request(url=link, callback=self.parseOthers)
                request.meta['category'] = response.meta['category']
                request.meta['pagenum'] = 1
                yield request

    def parseOthers(self, response):
        products = response.css('body > li')
        if not products:
            return
        else:
            for product in products:
                product_link = product.css('a::attr(href)').extract_first()
                product_image = product.css('a img::attr(data-original)').extract_first()
                request = scrapy.Request(url=product_link, callback=self.parseProduct)
                request.meta['product_link'] = product_link
                request.meta['product_image'] = product_image
                request.meta['product_category'] = response.meta['category']
                yield request
            nextpage = response.meta['pagenum'] + 1
            product_link = response.request.url[:response.request.url.index('&pageIndex')] + '&pageIndex=' + str(nextpage)
            request = scrapy.Request(url=product_link, callback=self.parseOthers)
            request.meta['category'] = response.meta['category']
            request.meta['pagenum'] = nextpage
            yield request

    def parseProduct(self, response):
        productLink = response.meta['product_link']
        productCategory = response.meta['product_category']
        productImage = response.meta['product_image']
        productMerchant = 'NA'
        productPrice = response.css('li#ContentPlaceHolder1_primary_price::text').extract_first().replace('Rs','').strip()

        productName = response.css('div.author-details h1::text').extract_first()
        if productName:
            productName += ' by '
            productName += response.css('div.author-details h2::text').extract_first()
        else:
            productName = response.css('div.author-details h2::text').extract_first()

        productDesc = response.css('div#ContentPlaceHolder1_itemdetails').extract_first()
        if not productDesc:
            productDesc = 'NA'
        else:
            productDesc = strip_tags(productDesc)

        productSku = ''
        texts = response.css('div#ContentPlaceHolder1_itemdetails::text').extract()
        for text in texts:
            if 'StoryLTD Ref No:' in text:
                productSku = text.replace('StoryLTD Ref No:','').strip()
        if not productSku:
            productSku = 'SKU-NA'

        productCategory = productCategory.replace('"','``')
        productDesc = re.sub('\n' ,'|',productDesc)
        productDesc = re.sub('\t','',productDesc)
        productDesc = re.sub('\r','',productDesc)
        productDesc = re.sub('[ ]+',' ',productDesc)
        productDesc = re.sub('(\| )+','|',productDesc)
        productDesc = re.sub('\|+','|',productDesc)
        productDesc = productDesc.strip('|')
        productDesc = productDesc.replace('"','``')
        productName = productName.replace('"','``')

        productDesc = remove_non_ascii(productDesc)
        productCategory = remove_non_ascii(productCategory)
        productName = remove_non_ascii(productName)

        with open('HCVID175.www.storyltd.com.csv', 'a', newline='') as csvfile:
            fieldnames = ['Title', 'Category', 'URL', 'IMG_SRC', 'Merchant', 'Price', 'SKU', 'Description']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writerow({'Title': '"'+str(productName)+'"', 'IMG_SRC': '"'+str(productImage)+'"', 'Description': '"'+str(productDesc)+'"','Price': '"'+str(productPrice)+'"', 'URL': '"'+str(productLink)+'"', 'Category': '"'+str(productCategory)+'"', 'SKU': '"'+str(productSku)+'"', 'Merchant': '"'+str(productMerchant)+'"'})

        HCVID175_www_storyltd_com_Spider.jsonData.append({'Title': productName, 'Description': productDesc, 'IMG_SRC': productImage, 'Price': productPrice, 'SKU': productSku, 'Category': productCategory, 'URL': productLink, 'Merchant': productMerchant})


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 27 15:18:20 2020
@author: jlee
"""

import time
start_time = time.time()

import numpy as np
import glob, os
import copy
import sys
from astropy.io import fits
from astropy.convolution import Gaussian2DKernel
from astropy.convolution import convolve
from scipy import ndimage
from tqdm import trange
import init_cfg as ic
import warnings
warnings.filterwarnings("error")

# ----- Directories ----- #
current_dir = os.getcwd()
working_dir = ic.dir_cmb
split_dir = ic.dir_cmb+"split/"
os.chdir(working_dir)
os.system('rm -rfv '+split_dir)
os.system('mkdir '+split_dir)

# ----- Making the split 2D images for spatial alignment ----- #
kernel = Gaussian2DKernel(2)
p = np.genfromtxt(current_dir+"/count_max.txt", dtype=None, encoding=None,
	              names=("cb","val"))
count_max = p['val'].max()

# Making the split images
for i in np.arange(len(ic.cube_list)):
	hd0 = fits.getheader(ic.cube_list[i], ext=0)
	d_sci, h_sci = fits.getdata(ic.cube_list[i], ext=1, header=True)
	d_var, h_var = fits.getdata(ic.cube_list[i], ext=2, header=True)

	wav = np.linspace(start=h_sci['CRVAL3']+(1-h_sci['CRPIX3'])*h_sci['CD3_3'],
                      stop=h_sci['CRVAL3']+(h_sci['NAXIS3']-h_sci['CRPIX3'])*h_sci['CD3_3'],
                      num=h_sci['NAXIS3'], endpoint=True)

	# Wavelength cut
	spx_start = np.abs(wav-ic.wav_range[0]).argmin()
	spx_end = spx_start + ic.nw_cut

	d_sci_cut = d_sci[spx_start:spx_end,:,:]
	d_var_cut = d_var[spx_start:spx_end,:,:]

	assert (p['cb'][i] == ic.cube_name[i])

	os.chdir(split_dir)
	print('Working on '+ic.cube_name[i])
	for j in trange(np.shape(d_sci_cut)[0]):
		d_sci_cut2 = d_sci_cut[j,:,:]
		d_var_cut2 = d_var_cut[j,:,:]

		d_sci_cut2[d_sci_cut2 > count_max] = np.nan
		d_sci_cut2[d_sci_cut2 < -count_max] = 0.0

		try:
			conv = convolve(d_sci_cut2, kernel)
			d_sci_cut2[np.isnan(d_sci_cut2)] = conv[np.isnan(d_sci_cut2)]
		except:
			try:
				conv2 = convolve(d_sci_cut2, Gaussian2DKernel(4))
				d_sci_cut2[np.isnan(d_sci_cut2)] = conv2[np.isnan(d_sci_cut2)]
			except:
				d_sci_cut2[np.isnan(d_sci_cut2)] = 0.5*(count_max + np.nanmedian(d_sci_cut2))

		fits.writeto(ic.cube_name[i]+f"_SCI_{j+1:04d}.fits", d_sci_cut2, h_sci, overwrite=True)
		fits.writeto(ic.cube_name[i]+f"_VAR_{j+1:04d}.fits", d_var_cut2, h_var, overwrite=True)
	os.chdir(working_dir)
print('----- Split images were created. -----\n')

# ----- Shifting cubes with offset.txt ----- #
os.chdir(split_dir)
offset_X, offset_Y = np.loadtxt(ic.dir_cmb+"offset.txt").T
for j in trange(d_sci_cut.shape[0]):
	for k in np.arange(len(ic.cube_name)):
		ds, hs = fits.getdata(ic.cube_name[k]+f"_SCI_{j+1:04d}.fits", header=True)
		ds_shifted = ndimage.shift(ds, shift=(-offset_Y[k], -offset_X[k]), mode='nearest')
		fits.writeto("al1_"+ic.cube_name[k]+f"_SCI_{j+1:04d}.fits", ds_shifted, hs, overwrite=True)

		dv, hv = fits.getdata(ic.cube_name[k]+f"_VAR_{j+1:04d}.fits", header=True)
		dv_shifted = ndimage.shift(dv, shift=(-offset_Y[k], -offset_X[k]), mode='nearest')
		fits.writeto("al1_"+ic.cube_name[k]+f"_VAR_{j+1:04d}.fits", dv_shifted, hv, overwrite=True)

os.chdir(working_dir)
print('----- Shift images were created. -----\n')

# ----- Saving new cubes ([SCI, VAR]) ----- #
os.system("rm -rfv "+working_dir+"cube1")
os.system("mkdir "+working_dir+"cube1")

for i in np.arange(len(ic.cube_list)):
	hd0 = fits.getheader(ic.cube_list[i], ext=0)
	d_sci, h_sci = fits.getdata(ic.cube_list[i], ext=1, header=True)
	d_var, h_var = fits.getdata(ic.cube_list[i], ext=2, header=True)

	# assert (p['cb'][i] == ic.cube_name[i])
	# count_max = p['val'].max()
	# d_sci[d_sci > count_max] = 0.0

	wav = np.linspace(start=h_sci['CRVAL3']+(1-h_sci['CRPIX3'])*h_sci['CD3_3'],
                      stop=h_sci['CRVAL3']+(h_sci['NAXIS3']-h_sci['CRPIX3'])*h_sci['CD3_3'],
                      num=h_sci['NAXIS3'], endpoint=True)

	spx_start = np.abs(wav-ic.wav_range[0]).argmin()
	spx_end = spx_start + ic.nw_cut

	d_sci_cut = d_sci[spx_start:spx_end,:,:]
	d_var_cut = d_var[spx_start:spx_end,:,:]

	al1_d_sci = np.zeros((np.shape(d_sci_cut)[0], np.shape(d_sci_cut)[1], np.shape(d_sci_cut)[2]))
	al1_d_var = np.zeros((np.shape(d_sci_cut)[0], np.shape(d_sci_cut)[1], np.shape(d_sci_cut)[2]))

	for j in np.arange(np.shape(d_sci_cut)[0]):
		d_sci2 = fits.getdata(split_dir+"al1_"+ic.cube_name[i]+f"_SCI_{j+1:04d}.fits")
		al1_d_sci[j,:,:] = d_sci2
		d_var2 = fits.getdata(split_dir+"al1_"+ic.cube_name[i]+f"_VAR_{j+1:04d}.fits")
		al1_d_var[j,:,:] = d_var2

	os.chdir(working_dir+"cube1")

	nhd0 = fits.PrimaryHDU()
	nhd1 = fits.ImageHDU()
	nhd2 = fits.ImageHDU()

	nhd0.header = hd0

	nhd1.data = al1_d_sci
	nhd1.header = h_sci
	nhd1.header['CRPIX3'] = 1.
	nhd1.header['CRVAL3'] = wav[spx_start]

	nhd2.data = al1_d_var
	nhd2.header = h_var
	nhd2.header['CRPIX3'] = 1.
	nhd2.header['CRVAL3'] = wav[spx_start]

	cb_hdu = fits.HDUList([nhd0, nhd1, nhd2])
	cb_hdu.writeto("al1_"+ic.cube_name[i]+"_3D.fits", overwrite=True)

	print("Written: al1_"+ic.cube_name[i]+"_3D.fits")

	os.chdir(working_dir)

os.chdir(current_dir)

# Printing the running time
print('--- %.4f seconds ---' %(time.time()-start_time))


from framework.logger.providers import get_logger
from framework.rest.blueprints.meta import MetaBlueprint
from services.carrier_service import CarrierService

logger = get_logger(__name__)
carrier_bp = MetaBlueprint('carrier_bp', __name__)

@carrier_bp.configure('/api/carriers', methods=['GET'], auth_scheme='read')
async def get_carriers(container):
    carrier_service: CarrierService = container.resolve(
        CarrierService)

    response = await carrier_service.get_carriers()
    return {'carriers': response}

@carrier_bp.configure('/api/carriers/balances', methods=['GET'], auth_scheme='read')
async def get_balances(container):
    carrier_service: CarrierService = container.resolve(
        CarrierService)

    response = await carrier_service.get_balances()
    return response

@carrier_bp.configure('/api/carriers/services', methods=['GET'], auth_scheme='read')
async def get_service_codes(container):
    carrier_service: CarrierService = container.resolve(
        CarrierService)

    response = await carrier_service.get_service_codes()
    return response


"""
author - N@vindu
Input - voice files from (https://drive.google.com/drive/folders/1HdE6trrwraLuS7pvPTrTg9aiBzSlJb-4?usp=sharing) save in to root file
"""

import librosa
import librosa.display
import pandas as pd
import numpy as np
from tqdm import tqdm
from os import walk
import pickle

mypath1="./voice/HEALTHY_SPEECH_COUNTING"
mypath2="./voice/POSITIVE_SPEECH_COUNTING"
mypath3="./voice/HEALTHY_COUGH"
mypath4="./voice/POSITIVE_COUGH"
mypath5="./voice/HEALTHY_SPEECH_VOWELS"
mypath6="./voice/POSITIVE_SPEECH_VOWELS"
mypath7="./voice/BREATHING_HEALTHY"
mypath8="./voice/BREATHING_POSITIVE"
mypath9="./voice/input"

# mypath1,mypath2,mypath3,mypath4,mypath5,mypath6,mypath7,mypath8
# if type of voices are high number of time will increases

x=[mypath1,mypath2,mypath3,mypath4,mypath5,mypath6,mypath7,mypath8]
f = []
for i in x:
    for (dirpath, dirnames, filenames) in walk(i):
        f.extend(filenames)
        break

print(f)

d={}
label=''
path=""
file=""

'''
Labeling the voice files according to voice type and save the file path into dictionary. Please change path according to files where saved.
Read instructions for labeling methodes
'''

for i in f:
    if 'HSCN' in i:
        label=1
        path="./voice/HEALTHY_SPEECH_COUNTING"
        file=path+'/'+i
        d[i]=file,label
    elif 'HSCF' in i:
        label = 1
        path = "./voice/HEALTHY_SPEECH_COUNTING"
        file = path + '/' + i
        d[i] = file, label
    elif 'PSCN' in i:
        label = 2
        path = "./voice/POSITIVE_SPEECH_COUNTING"
        file = path + '/' + i
        d[i] = file, label
    elif 'PSCF' in i:
        label = 2
        path = "./voice/POSITIVE_SPEECH_COUNTING"
        file = path + '/' + i
        d[i] = file, label
    if 'HCH' in i:
        label = 1
        path = "./voice/HEALTHY_COUGH"
        file = path + '/' + i
        d[i] = file, label
    elif 'HCS' in i:
        label = 1
        path = "./voice/HEALTHY_COUGH"
        file = path + '/' + i
        d[i] = file, label
    elif 'PCH' in i:
        label = 2
        path = "./voice/POSITIVE_COUGH"
        file = path + '/' + i
        d[i] = file, label
    elif 'PCS' in i:
        label = 2
        path = "./voice/POSITIVE_COUGH"
        file = path + '/' + i
        d[i] = file, label
    elif 'HSVA' in i:
        label = 1
        path = "./voice/HEALTHY_SPEECH_VOWELS"
        file = path + '/' + i
        d[i] = file, label
    elif 'HSVE' in i:
        label = 2
        path = "./voice/HEALTHY_SPEECH_VOWELS"
        file = path + '/' + i
        d[i] = file, label
    elif 'HSVO' in i:
        label = 3
        path = "./voice/HEALTHY_SPEECH_VOWELS"
        file = path + '/' + i
        d[i] = file, label
    elif 'PSVA' in i:
        label = 4
        path = "./voice/POSITIVE_SPEECH_VOWELS"
        file = path + '/' + i
        d[i] = file, label
    elif 'PSVE' in i:
        label = 5
        path = "./voice/POSITIVE_SPEECH_VOWELS"
        file = path + '/' + i
        d[i] = file, label
    elif 'PSVO' in i:
        label = 6
        path = "./voice/POSITIVE_SPEECH_VOWELS"
        file = path + '/' + i
        d[i] = file, label
    if 'HBD' in i:
        label = 1
        path = "./voice/BREATHING_HEALTHY"
        file = path + '/' + i
        d[i] = file, label
    elif 'HBS' in i:
        label = 2
        path = "./voice/BREATHING_HEALTHY"
        file = path + '/' + i
        d[i] = file, label
    elif 'PBD' in i:
        label = 2
        path = "./voice/BREATHING_POSITIVE"
        file = path + '/' + i
        d[i] = file, label
    elif 'PBS' in i:
        label = 4
        path = "./voice/BREATHING_POSITIVE"
        file = path + '/' + i
        d[i] = file, label

df=pd.DataFrame.from_dict(d,orient='index',columns=['relative_path', 'classID'])

print(df)

from scipy.io import wavfile
import noisereduce as nr

def noice_reduce(file):

    # load data
    rate, data = wavfile.read(file_name)
    # perform noise reduction
    reduced_noise = nr.reduce_noise(y=data, sr=rate)
    return reduced_noise

def features_extractor(file):
    #load the file (audio)
    audio, sample_rate = librosa.load(file_name, res_type='kaiser_fast')

    #we extract mfcc
    mfccs_features = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=80)
    #in order to find out scaled feature we do mean of transpose of value
    mfccs_scaled_features = np.mean(mfccs_features.T,axis=0)
    return mfccs_scaled_features

#Now we ned to extract the featured from all the audio files so we use tqdm

### Now we iterate through every audio file and extract features
### using Mel-Frequency Cepstral Coefficients
i=1
extracted_features=[]
for index_num,row in tqdm(df.iterrows()):
    file_name = str(row["relative_path"])
    final_class_labels=row["classID"]
    # print(file_name)
    newdata=noice_reduce(file_name)
    data=features_extractor(newdata)
    extracted_features.append([data,final_class_labels])

### converting extracted_features to Pandas dataframe
extracted_features_df=pd.DataFrame(extracted_features,columns=['feature','class'])
print(extracted_features_df.head())
# extracted_features_df.to_excel('features.xlsx')

### Split the dataset into independent and dependent dataset
X=np.array(extracted_features_df['feature'].tolist())
with open('x_breath_nr_q','wb') as f:
    pickle.dump(X, f)

y=np.array(extracted_features_df['class'].tolist())
with open('y_breath_nr_q','wb') as f:
    pickle.dump(y, f)

### Label Encoding -> Label Encoder

from tensorflow.python.keras.utils.np_utils import to_categorical
from sklearn.preprocessing import LabelEncoder

labelencoder=LabelEncoder()
y=to_categorical(labelencoder.fit_transform(y))

### Train Test Split
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=0)

from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense,Dropout,Activation,Flatten

### No of classes
num_labels=y.shape[1]

model=Sequential()
###first layer
model.add(Dense(100,input_shape=(80,)))
model.add(Activation('relu'))
model.add(Dropout(0.5))
###second layer
model.add(Dense(200))
model.add(Activation('relu'))
model.add(Dropout(0.5))
###third layer
model.add(Dense(100))
model.add(Activation('relu'))
model.add(Dropout(0.5))
###final layer
model.add(Dense(num_labels))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')

## Trianing model
from tensorflow.python.keras.callbacks import ModelCheckpoint
from datetime import datetime
num_epochs = 1000
num_batch_size = 16
checkpointer = ModelCheckpoint(filepath='./audio_classification.hdf5',
                               verbose=1, save_best_only=True)
start = datetime.now()
model.fit(X_train, y_train, batch_size=num_batch_size, epochs=num_epochs, validation_data=(X_test, y_test), callbacks=[checkpointer], verbose=1)
duration = datetime.now() - start
print("Training completed in time: ", duration)

test_accuracy=model.evaluate(X_test,y_test,verbose=0)
print(test_accuracy[1])

import tensorflow as tf
filename = 'model_breath_nr_q.h5'
tf.keras.models.save_model(model, filename)
#model.predict_classes(X_test)

predict_x=model.predict(X_test)
classes_x=np.argmax(predict_x,axis=1)
print(classes_x)


import getmac
import netifaces

def get_router_mac():
    gateways = netifaces.gateways()
    default_gateway = gateways['default'][netifaces.AF_INET][0]
    mac = getmac.get_mac_address(ip=default_gateway, network_request=True)

    return mac


import re
import sh

from aibench.proto import base_pb2
from aibench.python.utils import sh_commands
from aibench.python.device.device import Device
from aibench.python.device.device import YAMLKeyword

class AdbDevice(Device):

    def __init__(self, adb):
        self.address = adb[0]
        prop = self.get_props()
        Device.__init__(self, {
            YAMLKeyword.device_name: adb[1],
            YAMLKeyword.target_abis:
                prop['ro.product.cpu.abilist'].split(','),
            YAMLKeyword.target_socs: prop['ro.board.platform'],
            YAMLKeyword.models: prop['ro.product.model'],
            YAMLKeyword.address: adb[0],
        })

    def get_shell_prefix(self):
        return "adb -s %s shell" % self.address

    def exec_command(self, command, *args, **kwargs):
        return sh.adb('-s', self.address, 'shell',
                      command, *args, **kwargs)

    def push(self, src_path, dst_path, silent=False):
        sh_commands.adb_push(src_path, dst_path, self.address, silent)

    def pull(self, src_path, dst_path='.'):
        sh_commands.adb_pull(src_path, dst_path, self.address)

    def get_props(self):
        outputs = sh.adb("-s", self.address, "shell", "getprop")
        raw_props = sh_commands.split_stdout(outputs)
        props = {}
        p = re.compile(r'\[(.+)\]: \[(.+)\]')
        for raw_prop in raw_props:
            m = p.match(raw_prop)
            if m:
                props[m.group(1)] = m.group(2)
        return props

    def get_available_device_types(self, device_types, abi, executor):
        avail_device_types = Device.get_available_device_types(
            self, device_types, abi, executor)
        if base_pb2.GPU in device_types:
            avail_device_types.append(base_pb2.GPU)
        return avail_device_types

    def get_bench_path(self):
        return "/data/local/tmp/aibench"


import copy

edges = [ e.split('-') for e in open('input.txt').read().splitlines() ]

reverse = [ [a,b] for b,a in edges]

edges = edges + reverse

edges = [ [a,b] for a,b in edges if b != 'start' ]

start = [ e for e in edges if e[0] == 'start' ]

paths = []

def find_path(edge, path, cave):
  a, b = edge
  if b > 'a' and b in path:
    cave = b
  path.append(b)
  next = [ e for e in edges if e[0] == edge[1] ]
  if b == 'end':
    paths.append(path)
    return
  if len(next) == 0:
    return
  for n in next:
    if n[1][0] < 'a' or cave == '' or n[1] not in path:
      find_path(n, copy.deepcopy(path), cave)

for e in start:
  find_path(e, [e[0]], '')

print(len(paths))


#!/usr/bin/python
"""
diagManager.py: version 0.1.0

History:
2017/01/29: coding style phase1:
            reformat to python-guide.org code style
            http://docs.python-guide.org/en/latest/writing/style/
            which uses PEP 8 as a base: http://pep8.org/.
2017/01/09: Initial version converted to a class
"""

import numpy as np
import cv2
import math
from p5lib.cameraCal import CameraCal
from p5lib.imageFilters import ImageFilters
from p5lib.projectionManager import ProjectionManager
from p5lib.line import Line

class DiagManager():
    # Initialize ImageFilter

    def __init__(self, roadManager):
        self.rMgr = roadManager
        self.pMgr = self.rMgr.projMgr

    ########################################################
    # Apply Textural Diagnostics
    ########################################################
    def textOverlay(self, diagScreen, offset, color=(64, 64, 0)):
        roadMgr = self.rMgr
        projMgr = self.pMgr
        imgFtr = self.rMgr.curImgFtr
        font = cv2.FONT_HERSHEY_COMPLEX

        # output image stats
        y = 30 + offset
        text = '%-28s%-28s%-28sBalance: %f' % (
            imgFtr.skyText, imgFtr.skyImageQ,
            imgFtr.roadImageQ, imgFtr.roadbalance)
        cv2.putText(diagScreen, text, (30, y), font, 1, color, 2)

        # output projection stats in the next two lines
        y += 30
        if imgFtr.horizonFound:
            text = 'Projection Last Top: %d'
            text += '   Road Horizon: %d'
            text += '   Vanishing Point: %d'
            text = text % (roadMgr.lastTop, imgFtr.roadhorizon,
                           projMgr.lane_info[7][1])
            cv2.putText(diagScreen, text, (30, y), font, 1, color, 2)
        else:
            text = 'Projection Last Top: %d   Horizon: NOT FOUND!'
            cv2.putText(diagScreen, text % (
                roadMgr.lastTop), (30, y), font, 1, color, 2)
        y += 30
        text = 'Road Backoff at: %d   Gap: %d   Visibility: %6.2fm'
        cv2.putText(diagScreen, text % (
            projMgr.curGradient,
            projMgr.curGradient - projMgr.gradient0,
            imgFtr.throwDistance), (30, y), font, 1, color, 2)

        # output restart stats
        y += 30
        text = 'Restart Count: %d   Projection Reset Count: %d' % (
            roadMgr.restartCount, roadMgr.resetProjectionCount)
        cv2.putText(diagScreen, text, (30, y), font, 1, color, 2)

        # output vehicle stats
        y += 30
        text = 'Vehicle Count: %d' % (
            len(roadMgr.vehicles))
        cv2.putText(diagScreen, text, (30, y), font, 1, color, 2)

        return diagScreen

    ########################################################
    # Full diagnostics of the RoadManager
    ########################################################
    def fullDiag(self, color=(128, 128, 0)):
        roadMgr = self.rMgr
        projMgr = self.pMgr
        imgFtr = self.rMgr.curImgFtr
        font = cv2.FONT_HERSHEY_COMPLEX

        diag2 = projMgr.diag2.astype(np.uint8)
        imgFtr.drawHorizon(diag2)
        middlepanel = np.zeros((120, 1280, 3), dtype=np.uint8)

        # curvature output
        if roadMgr.roadStraight:
            text = 'Estimated lane curvature: road nearly straight'
            cv2.putText(middlepanel, text,
                        (30, 60), font, 1, color, 2)
        elif roadMgr.radiusOfCurvature > 0.0:
            text = 'Estimated lane curvature: center is %fm to the right'
            cv2.putText(middlepanel, text % (
                roadMgr.radiusOfCurvature), (30, 60), font, 1, color, 2)
        else:
            text = 'Estimated lane curvature: center is %fm to the left'
            cv2.putText(middlepanel, text % (-roadMgr.radiusOfCurvature),
                        (30, 60), font, 1, color, 2)

        # center of road output
        if roadMgr.lineBasePos < 0.0:
            text = 'Estimated left of center: %5.2fcm'
            cv2.putText(middlepanel, text % (-roadMgr.lineBasePos * 1000),
                        (30, 90), font, 1, color, 2)
        elif roadMgr.lineBasePos > 0.0:
            text = 'Estimated right of center: %5.2fcm'
            cv2.putText(middlepanel, text % (roadMgr.lineBasePos * 1000),
                        (30, 90), font, 1, color, 2)
        else:
            cv2.putText(middlepanel, 'Estimated at center of road',
                        (30, 90), font, 1, color, 2)

        # assemble the screen
        diagScreen = np.zeros((1080, 1920, 3), dtype=np.uint8)
        if roadMgr.diag1.shape[0] == 720:
            diagScreen[0:720, 0:1280] = roadMgr.diag1
        else:
            diagScreen[0:720, 0:1280] = cv2.resize(
                np.rot90(roadMgr.diag1), (1280, 720),
                interpolation=cv2.INTER_AREA)

        # image filters
        diagScreen[0:240, 1280:1600] = cv2.resize(
            imgFtr.diag1, (320, 240), interpolation=cv2.INTER_AREA)
        diagScreen[0:240, 1600:1920] = cv2.resize(
            imgFtr.diag2, (320, 240), interpolation=cv2.INTER_AREA)
        diagScreen[240:480, 1280:1600] = cv2.resize(
            imgFtr.diag3, (320, 240), interpolation=cv2.INTER_AREA)
        diagScreen[240:480, 1600:1920] = cv2.resize(
            imgFtr.diag4, (320, 240), interpolation=cv2.INTER_AREA) * 4

        diagScreen[600:1080, 1280:1920] = cv2.resize(
            roadMgr.final, (640, 480), interpolation=cv2.INTER_AREA)

        diagScreen[720:840, 0:1280] = middlepanel

        # projection
        diagScreen[840:1080, 0:320] = cv2.resize(
            diag2, (320, 240), interpolation=cv2.INTER_AREA)
        diagScreen[840:1080, 320:640] = cv2.resize(
            projMgr.diag1, (320, 240), interpolation=cv2.INTER_AREA)
        diagScreen[840:1080, 640:960] = cv2.resize(
            np.rot90(projMgr.diag3), (320, 240),
            interpolation=cv2.INTER_AREA)
        diagScreen[840:1080, 960:1280] = cv2.resize(
            np.rot90(projMgr.diag4), (320, 240),
            interpolation=cv2.INTER_AREA)

        return diagScreen

    ########################################################
    # Diagnostics of the Projection Manager (Single)
    ########################################################
    def projectionHD(self):
        projMgr = self.pMgr
        imgFtr = self.rMgr.curImgFtr

        # assemble the screen
        diagScreen = projMgr.diag3.astype(np.uint8)

        return diagScreen

    ########################################################
    # Diagnostics of the Projection Manager
    ########################################################
    def projectionDiag(self):
        projMgr = self.pMgr
        imgFtr = self.rMgr.curImgFtr

        diag2 = projMgr.diag2.astype(np.uint8)
        imgFtr.drawHorizon(diag2)

        # assemble the screen
        diagScreen = np.zeros((1080, 1920, 3), dtype=np.uint8)
        diagScreen[0:540, 0:960] = cv2.resize(
            diag2, (960, 540), interpolation=cv2.INTER_AREA)
        diagScreen[0:540, 960:1920] = cv2.resize(projMgr.diag1.astype(
            np.uint8), (960, 540), interpolation=cv2.INTER_AREA)
        diagScreen[540:1080, 0:960] = cv2.resize(np.rot90(
            projMgr.diag3.astype(np.uint8)), (960, 540),
            interpolation=cv2.INTER_AREA)
        diagScreen[540:1080, 960:1920] = cv2.resize(np.rot90(
            projMgr.diag4.astype(np.uint8)), (960, 540),
            interpolation=cv2.INTER_AREA)

        return diagScreen

    ########################################################
    # Diagnostics of the Image Filters
    ########################################################
    def filterDiag(self):
        imgFtr = self.rMgr.curImgFtr

        # assemble the screen
        diagScreen = np.zeros((1080, 1920, 3), dtype=np.uint8)
        diagScreen[0:540, 0:960] = cv2.resize(
            imgFtr.diag1, (960, 540), interpolation=cv2.INTER_AREA)
        diagScreen[0:540, 960:1920] = cv2.resize(imgFtr.diag2.astype(
            np.uint8), (960, 540), interpolation=cv2.INTER_AREA)
        diagScreen[540:1080, 0:960] = cv2.resize(imgFtr.diag3.astype(
            np.uint8), (960, 540), interpolation=cv2.INTER_AREA)
        diagScreen[540:1080, 960:1920] = cv2.resize(imgFtr.diag4.astype(
            np.uint8), (960, 540), interpolation=cv2.INTER_AREA)

        return diagScreen


import time, sys
import numpy as np
import matplotlib.pyplot as plt

sys.path.append('../../')
from py2Periodic.physics import twoLayerQG
from numpy import pi

pyqgParams = {
    'dt'        : 8000,
    'nx'        : 128,
    'L'         : 1.0e6,
    'beta'      : 1.5e-11,
    'rd'        : 1.5e4,
    'rek'       : 1.0e-7,
    'delta'     : 0.25,
    'H1'        : 500,
    'U1'        : 0.025,
    'U2'        : 0.0,
    'tavestart' : 0.0,
    'taveint'   : 86400.0,
    'twrite'    : 1000.0,
    'useAB2'    : False,
    'ntd'       : 2,
}

myParams = {
    'Lx'         : pyqgParams['L'],
    'beta'       : pyqgParams['beta'],
    'defRadius'  : pyqgParams['rd'],
    'H1'         : pyqgParams['H1'],
    'H2'         : pyqgParams['H1']/pyqgParams['delta'],
    'U1'         : pyqgParams['U1'],
    'U2'         : pyqgParams['U2'],
    'bottomDrag' : pyqgParams['rek'],
    'nx'         : pyqgParams['nx'],
    'dt'         : pyqgParams['dt'],
    'visc'       : 0e6,
    'viscOrder'  : 4.0,
    'timeStepper': 'AB3',
    'nThreads'   : pyqgParams['ntd'],
    'useFilter'  : True,
}

m = pyqg.QGModel(**pyqgParams)
qg = twoLayerQG.model(**myParams)
qg.describe_model()

# Initial condition
(f0, Ro) = (1.0e-4, 1.0e-3)
q1 = Ro*f0*np.random.standard_normal((m.ny, m.nx))
q2 = Ro*f0*np.random.standard_normal((m.ny, m.nx))

m.set_q1q2(q1, q2)
qg.set_q1_and_q2(q1, q2)

# Run models, interleaved within one another.
nt = 1e3

for snapshot in m.run_with_snapshots(
        tsnapstart=0, tsnapint=nt*m.dt):

    # Run qg
    qg.step_nSteps(nSteps=nt, dnLog=nt)
    qg.update_state_variables()

    fig = plt.figure('Physical', figsize=(12, 6)); plt.clf()

    # Plot qg
    plt.subplot(231); plt.imshow(qg.q1) # + qg.Q1y*qg.YY)
    plt.subplot(234); plt.imshow(qg.q2) # + qg.Q2y*qg.YY)

    # Plot pyqg
    plt.subplot(232); plt.imshow(m.q[0]) # + m.Qy1*m.y)
    plt.subplot(235); plt.imshow(m.q[1]) # + m.Qy2*m.y)

    # Plot difference
    norm = np.sqrt( (m.q[0]**2.0).mean() )
    plt.subplot(233); plt.imshow(np.abs(m.q[0]-qg.q1)/norm, vmin=0, vmax=1) # + m.Qy1*m.y)
    plt.subplot(236); plt.imshow(np.abs(m.q[1]-qg.q2)/norm, vmin=0, vmax=1) # + m.Qy2*m.y)

    plt.pause(0.01), plt.draw()

    fig = plt.figure('Spectral', figsize=(12, 6)); plt.clf()
    q1h = qg.soln[:, :, 0]
    q2h = qg.soln[:, :, 1]

    # Plot qg
    plt.subplot(231); plt.imshow(np.abs(q1h[0:qg.ny//2+1, :]))
    plt.subplot(234); plt.imshow(np.abs(q2h[0:qg.ny//2+1, :]))

    # Plot pyqg
    plt.subplot(232); plt.imshow(np.abs(m.qh[0][0:m.ny//2+1, :])) # + m.Qy1*m.y)
    plt.subplot(235); plt.imshow(np.abs(m.qh[1][0:m.ny//2+1, :])) # + m.Qy2*m.y)

    # Plot difference
    norm = np.sqrt( (np.abs(m.qh[0])**2.0).mean() )
    del1 = m.qh[0] - q1h
    del2 = m.qh[1] - q2h
    plt.subplot(233); plt.imshow(np.abs(del1[0:m.ny//2+1, :])/norm, vmin=0, vmax=1) # + m.Qy1*m.y)
    plt.subplot(236); plt.imshow(np.abs(del2[0:m.ny//2+1, :])/norm, vmin=0, vmax=1) # + m.Qy2*m.y)

    plt.pause(0.01), plt.draw()

print("Close the plot to end the program")
plt.show()


import h5py
import numpy as np
import matplotlib.pyplot as plt
import scipy
import scipy.signal

base = 'cut_5278/'
dat = [10, 20, 30, 40]
dat_2 = [0.05, 0.1, 0.15, 0.2, 0.3, 0.4]

idx = np.zeros((len(dat), len(dat_2), 25, 2024))
k=0
for j in dat:
    o = 0
    for yyy in dat_2:
        for i in range(1, 26):
            f = h5py.File(base + 'models/model_' + str(j) + str(yyy) + str(i) + '.out', 'r')
            idx[k, o, i-1, : ] = scipy.signal.resample(np.array(f['rxs']['rx1']['Ez'][:]), 2024)
        o += 1
    k += 1

np.save(base+'synth', idx)


"""Lógica Simple y Cortocircuito"""

"""
Construir una expresión lógica que use TODAS las variables y cuyo resultado sea
True si al menos una de las variables es True.
"""

esta_lloviendo = True
riego_activado = True

# COMPLETAR - INICIO

# COMPLETAR - FIN

assert piso_mojado

"""
Construir una expresión lógica que use TODAS las variables y cuyo resultado sea
True si el área es mayor a 5.
Restricción: Usar NOT.
"""

lado_cuadrado = 5
area_cuadrado = pow(lado_cuadrado, 2)

# COMPLETAR - INICIO

# COMPLETAR - FIN

assert area_mayor_a_cinco

"""
Construir una expresión lógica que use TODAS las variables y cuyo resultado sea
True si el número 1 es divisible por 7 y al mismo tiempo el número 2 no lo es.
"""

numero_1 = 49
numero_2 = 50

# COMPLETAR - INICIO

# COMPLETAR - FIN

assert resultado

"""
Construir una expresión lógica que use TODAS las variables y cuyo resultado sea
el mismo valor de la variable 3.
Restricción: sólo usar OR, NOT y el mecanismo de cortocircuito.
"""

variable_01 = False
variable_02 = True
variable_03 = 80
variable_04 = "90"
variable_05 = 100

# COMPLETAR - INICIO

# COMPLETAR - FIN

assert resultado == 80


class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        dic = {}
        res = []
        for n in nums1:
            dic[n] = 1
        for n in nums2:
            if n in dic.keys():
                dic[n] += 1
        return [k for k, v in dic.items() if v > 1]


import xlrd
a = dict()
b = []
#d = [0,0,0,0]
k1,k2,k3,k4 =0,0,0,0
rb = xlrd.open_workbook('C:\\Users\\ppirogov\\Desktop\\Паше\\trekking.xlsx')
sheet = rb.sheet_by_index(0)
sheet2 = rb.sheet_by_index(1)
vals2 =[sheet2.row_values(rownum) for rownum in range(sheet2.nrows)]
vals = [sheet.row_values(rownum) for rownum in range(sheet.nrows)]
for i in range(1, len(vals)):
    a[vals[i][0]]=vals[i][1:]
#print (a)
for q in a:
    if a[q][3] == '':
        a[q][3] = 0
    for q1 in range(len(vals2)):
        if q == vals2[q1][0]:
            k1 = k1 + a[q][0] * vals2[q1][1] / 100
            k2 = k2 + a[q][1] * vals2[q1][1] / 100
            k3 = k3 + a[q][2] * vals2[q1][1] / 100
            k4 = k4 + a[q][3] * vals2[q1][1] / 100
print (int(k1),int(k2),int(k3),int(k4))


#!/usr/bin/env python3
"""
Day 05 Advent of Code 2019. Additional functionality added from Day 02's
solution.
"""

class IntcodeComputer():
    """Main IntcodeComputer class
    :param program: List of ints that represent opcodes and inputs
    :type program: list
    """
    def __init__(self, program):
        self.og = program
        self.p = self.og.copy()
        self.cursor = 0
        self.ops_map = {
            1: lambda i, m, x: self.op1(i, i+1, i+2, m),
            2: lambda i, m, x: self.op2(i, i+1, i+2, m),
            3: lambda i, m, x: self.op3(x, i),
            4: lambda i, m, x: self.op4(i),
            5: lambda i, m, x: self.op5(i, i+1, m),
            6: lambda i, m, x: self.op6(i, i+1, m),
            7: lambda i, m, x: self.op7(i, i+1, i+2, m),
            8: lambda i, m, x: self.op8(i, i+1, i+2, m),
        }

    def op1(self, p1, p2, p3, pmodes):
        """Add the values at p1 and p2, store the result at p3"""
        p1mod, p2mod = pmodes
        self.p[self.p[p3]] = self.p_val(p1, p1mod) + self.p_val(p2, p2mod)
        self.cursor += 4

    def op2(self, p1, p2, p3, pmodes):
        """Multiply the values at p1 and p2, store the result at p3"""
        p1mod, p2mod = pmodes
        self.p[self.p[p3]] = self.p_val(p1, p1mod) * self.p_val(p2, p2mod)
        self.cursor += 4

    def op3(self, x, p1):
        """Set the value of the 'register' at p1 to the program's input value"""
        self.p[self.p[p1]] = x
        self.cursor += 2

    def op4(self, p1):
        """Output (print) the value stored at p1"""
        print(self.p[self.p[p1]], end=" ")
        self.cursor += 2

    def op5(self, p1, p2, pmodes):
        """If the value at p1 is non-zero, set the cursor to p2.
        Otherwise, do nothing.
        """
        p1mod, p2mod = pmodes
        if self.p_val(p1, p1mod) != 0:
            self.cursor = self.p_val(p2, p2mod)
        else:
            self.cursor += 3

    def op6(self, p1, p2, pmodes):
        """If the value at p1 equals zero, set the cursor to p2.
        Otherwise, do nothing.
        """
        p1mod, p2mod = pmodes
        if self.p_val(p1, p1mod) == 0:
            self.cursor = self.p_val(p2, p2mod)
        else:
            self.cursor += 3

    def op7(self, p1, p2, p3, pmodes):
        """p3 = (p1 > p2) ? 1 : 0"""
        p1mod, p2mod = pmodes
        lt = self.p_val(p1, p1mod) < self.p_val(p2, p2mod)
        self.p[self.p[p3]] = 1 if lt else 0
        self.cursor += 4

    def op8(self, p1, p2, p3, pmodes):
        """p3 = (p1 == p2) ? 1 : 0"""
        p1mod, p2mod = pmodes
        eq = self.p_val(p1, p1mod) == self.p_val(p2, p2mod)
        self.p[self.p[p3]] = 1 if eq else 0
        self.cursor += 4

    def parse_instr(self, inst):
        """For instructions with 'parameter modes':
        Return the opcode and a list of parameter modes to pass to `self.p_val`
        """
        if inst in [3, 4]:  # opcodes 3 & 4 do not need param modes
            return inst, None
        mod_bits, opcode = divmod(inst, 100)
        mod_bits, p1mod = divmod(mod_bits, 10)
        p2mod = divmod(mod_bits, 10)[1]
        param_modes = [p1mod, p2mod]

        return opcode, param_modes

    def p_val(self, pos, mode):
        """Return value based on parameter mode and index (position).
        0 ('position') mode 'dereferences' value stored at &pos
        1 ('immediate') mode uses immediate value of pos
        """
        if mode == 0:
            return self.p[self.p[pos]]
        elif mode == 1:
            return self.p[pos]

    def run(self, argx=None, show_program=False):
        """Run the int_code computer. Opcode '99' exits the program.
        :param show_program: Output the final program state after a successful run
        :type show_program: bool, defaults to False
        :param argx: Single input parameter given to the program (for opcode 3)
        :type argx: int, optional (for programs without opcode 3)
        """
        while self.p[self.cursor] != 99:
            op, modes = self.parse_instr(self.p[self.cursor])
            self.ops_map[op](self.cursor+1, modes, argx)
        if show_program:
            print(self.p)
        self.cursor = 0

if __name__ == '__main__':
    program = list(map(int, open('input.txt').read().strip('\n').split(',')))
    int_code = IntcodeComputer(program)
    int_code.run(argx=5)


#You are a shopkeeper and you have to design a utility to sum the price of
#items until user presses q.

sum = 0
while(True):
    num = input("Enter the price: ")

    if (num != 'q'):
        sum = sum + int(num)
        print(f"Total order so far: {sum}")

    else:
        print(f"Your Total Bill is: {sum}")
        break


"""
https://leetcode.com/problems/convert-to-base-2/
"""

class Solution:
    def baseNeg2(self, n: int) -> str:
        rslt = []
        while n:
            rslt.append(n & 1)
            n = -(n >> 1)

        return ''.join([str(i) for i in reversed(rslt)] or ['0'])


import os
import whisper
from moviepy.editor import VideoFileClip
import pandas as pd
import logging
from concurrent.futures import ThreadPoolExecutor

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

model = whisper.load_model("large")
output_directory = "output_chunks"

def transcribe_worker(args):
    audio_path = args
    logging.info("Starting file transcription, %s", audio_path)
    result = model.transcribe(audio_path, word_timestamps=True, fp16=False)
    logging.debug("File transcription complete, %s", audio_path)
    # print(result['segments'])
    return pd.DataFrame(result['segments'])

def transcribe(audio_file_paths: list, num_threads=4):
    args_list = [(audio_path)
                 for audio_path in audio_file_paths]
    with ThreadPoolExecutor(max_workers=num_threads) as executor:
        subframes = executor.map(transcribe_worker, args_list)

    return pd.concat(subframes)

if __name__ == "__main__":
    # Example usage
    # Multithreading attempt failed due to whisper k-v store shared resource
    # audio_dir = os.path.join("output_chunks", "audio")
    # chunks = [os.path.join(audio_dir, file) for file in os.listdir(audio_dir)]
    # print(chunks)
    # transcript = transcribe(chunks[:-1])
    transcript = transcribe(["output_chunks/audio.wav"])
    transcript.to_csv(os.path.join(output_directory, "transcript.csv"))


from PIL import Image , ImageDraw
import numpy ,os ,pyocr , pyocr.builders , re , sys

tools = pyocr.get_available_tools()
if len(tools) == 0:
    print("No OCR tool found")
    sys.exit(1)
tool = tools[0]

def get_text_ocr(src_file_name):

    #print("%s"%tool.get_name())

    #langs = tool.get_available_languages()
    #print("%s"%langs)

    res = tool.image_to_string(
        Image.open(src_file_name),
        lang="jpn",
        builder=pyocr.builders.TextBuilder(tesseract_layout=6)
    )

    #print( res )
    res = res.replace(" ","")
    res = res.replace("\n","")
    return res

if __name__ == "__main__":
    print( get_text_ocr("../png/2009h21h_fe_am_qs-4.jpg") )


import itertools
import shutil
from collections import defaultdict
from pathlib import Path
from typing import Sequence
from io import StringIO

import colorama as clr
from natsort import natsorted
from attrs import frozen

import pcleaner.structures as st
import pcleaner.helpers as hp

@frozen
class OCRAnalytic:
    num_boxes: int
    small_box_sizes: Sequence[int]
    removed_box_sizes: Sequence[int]

# I'll admit this file is a mess.
# These bar chart creators should be abstracted into a single implementation, not 3 different ones.

def terminal_width() -> int:
    # Use a fallback of 100 for unsupported terminals.
    width = shutil.get_terminal_size((100, 100)).columns
    # Make sure the width is at least 20, to avoid weirdness.
    return max(width, 20)

def show_ocr_analytics(
    analytics: Sequence[st.OCRAnalytic],
    max_ocr_size: int,
    max_columns: int = 100,
) -> str:
    """
    The analytics are gathered from the OCR pre-processing which has the goal of
    finding small boxes and to check if they contain text worth cleaning.

    The analytics for each page in the list consist of the following:
    - The number of boxes on the page.
    - The sizes of the small boxes.
    - The sizes of the boxes that were removed.
    - list of: The original file path and the removed text and the box it belonged to.

    Various statistics are then shown.

    :param analytics: The analytics gathered from each pre-processed page.
    :param max_ocr_size: The maximum size of a box to be considered small.
    :param max_columns: The maximum number of columns to use for the chart per line.
    :return: The analytics as a string.
    """
    buffer = StringIO()

    num_boxes = sum(a.num_boxes for a in analytics)
    num_small_boxes = sum(len(a.box_sizes_ocr) for a in analytics)
    small_box_sizes = list(itertools.chain.from_iterable(a.box_sizes_ocr for a in analytics))
    removed_box_sizes = list(itertools.chain.from_iterable(a.box_sizes_removed for a in analytics))
    small_box_ratio = f"{num_small_boxes / num_boxes:.0%}" if num_boxes > 0 else "N/A"
    removed_box_ratio = f"{len(removed_box_sizes) / num_boxes:.0%}" if num_boxes > 0 else "N/A"
    removed_among_small_ratio = (
        f"{len(removed_box_sizes) / num_small_boxes:.0%}" if num_small_boxes > 0 else "N/A"
    )
    # Partition the small box sizes into 5 rough size ranges, equally spaced.
    part_size = 500 if max_ocr_size < 500 * 10 else max_ocr_size // 10
    partitioned_small_box_sizes = partition_list(
        small_box_sizes, partition_size=part_size, max_value=max_ocr_size
    )
    partitioned_removed_boxes = partition_list(
        removed_box_sizes, partition_size=part_size, max_value=max_ocr_size
    )
    buffer.write("\nOCR Analytics\n")
    buffer.write("-------------\n")
    buffer.write(
        f"Number of boxes: {num_boxes} | "
        f"Number of small boxes: {num_small_boxes} ({small_box_ratio})\n"
    )
    buffer.write(
        f"Number of removed boxes: {len(removed_box_sizes)} ({removed_box_ratio} total, {removed_among_small_ratio} of small boxes)\n"
    )
    if small_box_sizes:
        buffer.write("\nSmall box sizes:\n")
        buffer.write(
            draw_pretty_ocr_result_chart(
                partitioned_small_box_sizes, partitioned_removed_boxes, max_columns
            )
            + "\n"
        )
    else:
        buffer.write("No not-removed small boxes found.\n")

    # Show removed texts.
    removed_path_texts: list[tuple[Path, str, st.Box]] = list(
        itertools.chain.from_iterable(a.removed_box_data for a in analytics)
    )

    if removed_path_texts:
        # Find and then remove the longest common prefix from the file paths.
        paths, texts, _ = zip(*removed_path_texts)
        removed_paths = hp.trim_prefix_from_paths(paths)
        removed_path_texts = list(zip(removed_paths, texts))
        # Sort by file path.
        removed_path_texts = natsorted(removed_path_texts, key=lambda p: p[0])

    buffer.write("\nRemoved bubbles:\n")
    for path, text in removed_path_texts:
        buffer.write(f"Page {path}: {text}\n")

    buffer.write("\n")

    return buffer.getvalue()

def draw_pretty_ocr_result_chart(
    small_box_data: list[tuple[str, int]],
    removed_box_data: list[tuple[str, int]],
    max_columns: int = 100,
) -> str:
    """
    Draw a pretty stacked bar chart.

    :param small_box_data: The data for the small boxes.
    :param removed_box_data: The data for the removed boxes.
    :param max_columns: The maximum number of columns to use for the chart per line.
    :return: The chart as a string.
    """
    buffer = StringIO()

    data_array = [
        (label, lower, upper)
        for (label, lower), (_, upper) in zip(small_box_data, removed_box_data)
    ]
    max_label_width = max(len(label) for label, _, _ in data_array)
    bar_width = (
        max_columns - max_label_width - 16
    )  # 16 for the spacing and trailing number and padding.
    max_value = max(lower + upper for _, lower, upper in data_array)

    for label, lower, upper in data_array:
        lower_bar = "█" * int((lower - upper) / max_value * bar_width)
        upper_bar = "█" * int(upper / max_value * bar_width)
        buffer.write(
            f"{label:<{max_label_width}}: "
            f"{lower_bar}{clr.Fore.RED}{upper_bar} {upper}{clr.Style.RESET_ALL} / {lower}\n"
        )

    # Show legend.
    buffer.write(f"\n█ Small boxes | {clr.Fore.RED}█ Removed boxes{clr.Style.RESET_ALL}")

    return buffer.getvalue()

def draw_masker_histogram(data: dict[str, tuple[int, int]], max_columns: int = 100) -> str:
    """
    Draw a histogram of the masker results.

    :param data: A dict of the mask name, (perfect uses, all uses).
    :param max_columns: The maximum number of columns to use for the histogram per line.
    :return: The histogram as a string.
    """

    # Find the maximum value in the data. (at least 1 to avoid division by zero)
    max_value = max(list(map(lambda x: x[1], data.values())))
    max_value = max(max_value, 1)

    # Longest key.
    max_label_width = max(len(k) for k in data.keys())
    bar_width = (
        max_columns - max_label_width - 16
    )  # 16 for the spacing and trailing number and padding.

    buffer = StringIO()

    # Draw the histogram.
    for key, value in data.items():
        # Use a Unicode character for the bar.
        left_bar = "█" * int(value[0] / max_value * bar_width)
        right_bar = "█" * int((value[1] - value[0]) / max_value * bar_width)
        # If both are 0 in length, but one of them isn't 0 in value, draw the right-most one as a sliver.
        if not left_bar and not right_bar and value[1] > value[0]:
            right_bar = "▏"
        elif not left_bar and not right_bar and value[0] > 0:
            left_bar = "▏"

        buffer.write(
            f"{key:<{max_label_width}}: "
            f"{clr.Fore.CYAN}{left_bar}{clr.Style.RESET_ALL}{right_bar} "
            f"{clr.Fore.CYAN}{value[0]}{clr.Fore.RESET} / {value[1]}\n"
        )

    # Show legend.
    buffer.write(f"\n{clr.Fore.CYAN}█ Perfect{clr.Style.RESET_ALL} | █ Total\n")
    return buffer.getvalue()

def partition_list(
    data: list[int],
    *,
    partition_size: int = 500,
    min_value: int | None = 0,
    max_value: int | None = None,
) -> list[tuple[str, int]]:
    """
    Partition the list into tuples of the form (range, count).
    The ranges are saved as a string: "0-499", "500-999", etc.
    If no max_value is given, the maximum value in the data is used.
    If min_value is None, the minimum value in the data is used. Otherwise it defaults to 0.

    :param data: The data to partition.
    :param partition_size: [Optional] The size of the partitions. Default: 500.
    :param min_value: [Optional] The minimum value to partition. Default: 0.
    :param max_value: [Optional] The maximum value to partition to. Default: None.
    :return: The partitioned data as a list of tuples.
    """
    if max_value is None:
        max_value = max(data)

    max_label_len = len(str(max_value))

    partition = [
        (
            f"{i * partition_size: >{max_label_len}}-{(i + 1) * partition_size: >{max_label_len}}",
            len([d for d in data if i * partition_size <= d < (i + 1) * partition_size]),
        )
        for i in range(min_value, max_value // partition_size)
    ]

    return partition

def show_masker_analytics(analytics: list[st.MaskFittingAnalytic], max_columns: int = 100) -> str:
    """
    Present the analytics gathered from the masking process.

    :param analytics: The analytics gathered from each page.
    :param max_columns: The maximum number of columns to use for the chart per line.
    :return: The analytics as a string.
    """
    buffer = StringIO()

    total_boxes = len(analytics)
    masks_succeeded = sum(1 for analytic in analytics if analytic.fit_was_found)
    perfect_masks = sum(
        1 for analytic in analytics if analytic.fit_was_found and analytic.mask_std_deviation == 0
    )
    average_border_deviation = (
        f"{sum(analytic.mask_std_deviation for analytic in analytics if analytic.fit_was_found) / masks_succeeded:.2f}"
        if masks_succeeded
        else "N/A"
    )
    success_rate = f"{masks_succeeded / total_boxes:.0%}" if total_boxes else "N/A"
    perfect_mask_rate = f"{perfect_masks / masks_succeeded:.0%}" if masks_succeeded else "N/A"
    masks_failed = total_boxes - masks_succeeded

    highest_mask_index = max(
        (analytic.mask_index for analytic in analytics if analytic.fit_was_found), default=0
    )
    # Count the number of times each mask index was used.
    mask_usages_by_index = [0] * (highest_mask_index + 1)
    # Count the number of times each mask was perfect.
    perfect_mask_usages_by_index = [0] * (highest_mask_index + 1)
    for analytic in analytics:
        if analytic.fit_was_found:
            mask_usages_by_index[analytic.mask_index] += 1
            if analytic.mask_std_deviation == 0:
                perfect_mask_usages_by_index[analytic.mask_index] += 1

    # Write the analytics.
    buffer.write("\nMask Fitment Analytics\n")
    buffer.write("----------------------\n")
    buffer.write(
        f"Total boxes: {total_boxes} | "
        f"Masks succeeded: {masks_succeeded} ({success_rate}) | "
        f"Masks failed: {clr.Fore.RED}{masks_failed}{clr.Fore.RESET}\n"
    )
    buffer.write(
        f"Perfect masks: {clr.Fore.CYAN}{perfect_masks}{clr.Fore.RESET} ({perfect_mask_rate}) | "
        f"Average border deviation: {average_border_deviation}\n"
    )
    buffer.write("\nMask usage by mask size (smallest to largest):\n")
    mask_usages_dict = {
        f"Mask {index}": perfect_total
        for index, perfect_total in enumerate(
            zip(perfect_mask_usages_by_index, mask_usages_by_index)
        )
        if index < len(mask_usages_by_index) - 1
    }
    mask_usages_dict["Box mask"] = perfect_mask_usages_by_index[-1], mask_usages_by_index[-1]

    buffer.write(draw_masker_histogram(mask_usages_dict, max_columns) + "\n")

    pages_with_success_and_fails_dict: defaultdict[Path, defaultdict[str, int]] = defaultdict(
        lambda: defaultdict(int)
    )
    for analytic in analytics:
        pages_with_success_and_fails_dict[analytic.image_path][
            "succeeded" if analytic.fit_was_found else "failed"
        ] += 1

    if not pages_with_success_and_fails_dict:
        buffer.write("All bubbles were successfully masked.\n")
        return buffer.getvalue()

    pages_with_success_and_fails: list[tuple[Path, int, int]] = [
        (page_path, counts["succeeded"], counts["failed"])
        for page_path, counts in pages_with_success_and_fails_dict.items()
        if counts["failed"]
    ]

    if pages_with_success_and_fails:
        page_paths, succeeded_counts, failed_counts = zip(*pages_with_success_and_fails)
        page_paths = hp.trim_prefix_from_paths(page_paths)
        pages_with_success_and_fails = list(zip(page_paths, succeeded_counts, failed_counts))
        pages_with_success_and_fails = natsorted(pages_with_success_and_fails, key=lambda x: x[0])

    buffer.write("\nPages with failures / total:\n")
    for page_path, succeeded, failed in pages_with_success_and_fails:
        buffer.write(f"{page_path}: {clr.Fore.RED}{failed}{clr.Fore.RESET} / {succeeded+failed}\n")

    buffer.write("\n")

    return buffer.getvalue()

def show_denoise_analytics(
    analytics: list[st.DenoiseAnalytic],
    configured_deviation_threshold: float,
    max_deviation_threshold: float,
    max_columns: int = 100,
) -> str:
    """
    Present the analytics gathered from the denoising process.

    :param analytics: The analytics gathered from each page, here standard deviations.
    :param configured_deviation_threshold: The configured deviation threshold to de denoising.
    :param max_deviation_threshold: The maximum deviation threshold to discard the mask.
    :param max_columns: The maximum number of columns to use for the chart per line.
    :return: The analytics as a string.
    """
    buffer = StringIO()

    buffer.write("\nDenoising Analytics\n")
    buffer.write("-------------------\n")

    # Get the standard deviations into one single list.
    std_deviations: list[float] = [
        *itertools.chain.from_iterable(analytic.std_deviations for analytic in analytics)
    ]

    # Split the standard deviations into two lists: one for the ones that were below the threshold,
    # and one for the ones that were above the threshold.
    below_threshold = [
        std_dev for std_dev in std_deviations if std_dev <= configured_deviation_threshold
    ]
    above_threshold = [
        std_dev for std_dev in std_deviations if std_dev > configured_deviation_threshold
    ]

    total_masks = len(std_deviations)
    above_threshold_count = len(above_threshold)
    above_ratio = f"{above_threshold_count / total_masks:.0%}" if total_masks else "N/A"

    buffer.write(
        f"Total masks: {total_masks} | Masks denoised: {clr.Fore.MAGENTA}{above_threshold_count}{clr.Fore.RESET} "
        f"({above_ratio})\n"
    )
    buffer.write(
        f"Minimum deviation to denoise: {configured_deviation_threshold} | "
        f"Maximum allowed deviation: {max_deviation_threshold}\n"
    )
    buffer.write(f"Standard deviation around masks:\n\n")

    # Show the lists in a graph.
    buffer.write(
        draw_denoise_histogram(
            below_threshold,
            above_threshold,
            max_deviation_threshold,
            max_columns,
        )
        + "\n"
    )
    buffer.write("\n")

    return buffer.getvalue()

def draw_denoise_histogram(
    below_threshold: list[float],
    above_threshold: list[float],
    max_value: float,
    max_columns: int = 100,
) -> str:
    """
    Draw a histogram of the deviations.

    :param below_threshold: The standard deviations that were below the threshold.
    :param above_threshold: The standard deviations that were above the threshold.
    :param max_value: The maximum deviation threshold to discard the mask.
    :param max_columns: The maximum number of columns to use for the histogram per line.
    :return: The histogram as a string.
    """
    # Partition the values into 10 buckets.
    # Use a cubic polynomial that passes through 0 and the max value.
    # The polynomial is a simple f(x) = ax^3, meaning the coefficient a
    # must be max_value/10^3.
    exponent = 3
    cubic_coefficient = max_value / 10**exponent
    # The buckets contain: (min, max)
    bucket_ranges = (
        (cubic_coefficient * (i - 1) ** exponent, cubic_coefficient * i**exponent)
        for i in range(1, 11)
    )
    # Set the precision so that the second bucket isn't 0.
    # Basically, if the value is 0.00143, we want a precision of 3 to still see that 1.
    second_bucket_min = str(cubic_coefficient * 1**exponent).split(".")[1]
    # Count the zeroes from the left, and add 1 to only show up to the first non-zero digit.
    precision = len(second_bucket_min) - len(second_bucket_min.lstrip("0")) + 1
    # The buckets contain: (min, max, count_below_threshold, count_above_threshold)
    buckets: list[tuple[str, str, int, int]] = [
        (
            f"{b_min:.{precision}f}",
            f"{b_max:.{precision}f}",
            sum(1 for std_dev in below_threshold if b_min <= std_dev < b_max),
            sum(1 for std_dev in above_threshold if b_min <= std_dev < b_max),
        )
        for b_min, b_max in bucket_ranges
    ]
    # Format the ranges to look better.
    number_width = len(str(f"{max_value:.{precision}f}"))
    buckets_labeled: list[tuple[str, int, int]] = [
        (
            f"{b_min: >{number_width}}-{b_max: >{number_width}}",
            below,
            above,
        )
        for b_min, b_max, below, above in buckets
    ]
    # Get the maximum count in the buckets to rescale them.
    max_count = max((below + above for _, below, above in buckets_labeled))
    max_count = max(max_count, 1)
    # Rescale the buckets.

    max_label_length = max(len(label) for label, _, _ in buckets_labeled)
    bar_width = max_columns - max_label_length - 16  # 16 is for the spaces and the brackets.

    bucket_bar_lengths: list[tuple[int, int]] = [
        (int(below * bar_width / max_count), int(above * bar_width / max_count))
        for _, below, above in buckets_labeled
    ]

    buffer = StringIO()
    # Draw the buckets.
    for (b_range, below, above), (below_len, above_len) in zip(buckets_labeled, bucket_bar_lengths):
        buffer.write(
            f"{b_range} : {'█' * below_len}{clr.Fore.MAGENTA}{'█' * above_len} {above}{clr.Fore.RESET} / {below+above}\n"
        )

    # Draw the legend.
    buffer.write(f"\n{clr.Fore.MAGENTA}█ Denoised{clr.Fore.RESET} | █ Total\n")
    return buffer.getvalue()


import copy
from unittest import TestCase, main

from bronx.patterns import getbytag

class utGetByTag(TestCase):

    def test_getbytag_basics(self):

        class Tag0(getbytag.GetByTag):
            pass

        class Tag1(Tag0):
            pass

        class Tag2(Tag0):
            _tag_topcls = False

        # topcls or not...
        a = Tag0()
        b = Tag0()
        self.assertIs(a, b)
        self.assertEqual(a.tag, 'default')
        b = Tag1()
        self.assertIsNot(a, b)
        b = Tag2()
        self.assertIs(a, b)
        # With a customized tag
        b = Tag0(tag='truc')
        self.assertIsNot(a, b)
        c = Tag0('truc')
        self.assertIs(b, c)
        # Force creation
        c = Tag0(tag='truc', new=True)
        self.assertIsNot(a, b)
        # Some of the class methods
        self.assertSequenceEqual(Tag0.tag_keys(), ['default', 'truc'])
        self.assertSetEqual(set(Tag0.tag_values()), {a, c})
        self.assertSetEqual(set(Tag0.tag_items()), {('default', a), ('truc', c)})
        self.assertSetEqual(set(Tag0.tag_classes()), {Tag0, Tag2})
        # Ugly copies
        self.assertIs(copy.copy(a), a)
        self.assertIs(copy.deepcopy(a), a)
        # The end
        Tag0.tag_clear()
        self.assertListEqual(Tag0.tag_values(), [])

    def test_getbytag_focus(self):

        class Tag0(getbytag.GetByTag):

            def __init__(self):
                self.flag = 'bare'

            def focus_loose_hook(self):
                super().focus_loose_hook()
                self.flag = 'sleeping'

            def focus_gain_hook(self):
                super().focus_gain_hook()
                self.flag = 'focused'

            def focus_gain_allow(self):
                super().focus_gain_allow()
                if self.tag == 'third':
                    raise RuntimeError('No way I will get focus')

        a = Tag0('first')
        b = Tag0('second')
        c = Tag0('third')

        for o in (a, b, c):
            self.assertEqual(o.flag, 'bare')
        # a
        a.catch_focus()
        self.assertEqual(a.flag, 'focused')
        self.assertTrue(a.has_focus())
        self.assertEqual(Tag0.tag_focus(), 'first')
        for o in (b, c):
            self.assertEqual(o.flag, 'bare')
            self.assertFalse(o.has_focus())
        # b
        Tag0.set_focus(b)
        self.assertEqual(a.flag, 'sleeping')
        self.assertFalse(a.has_focus())
        self.assertEqual(b.flag, 'focused')
        self.assertTrue(b.has_focus())
        # c
        with self.assertRaises(RuntimeError):
            # c should never be allowed to get the focus
            c.catch_focus()
        # As result nothing has changed...
        self.assertEqual(b.flag, 'focused')
        self.assertTrue(b.has_focus())
        self.assertEqual(c.flag, 'bare')

if __name__ == '__main__':
    main(verbosity=2)


from django import forms
from . models import Book , Address , CustomUser , Author , Category , BookComments
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User

# Custom fields Email Require
from django.forms import EmailField
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError

from django.utils.safestring import mark_safe
from django.forms import ImageField

class BookForm(forms.ModelForm):
    class Meta:
        # เลือกโมเดลที่จะใช้ทำฟอร์ม
        model = Book
        # กรองบางฟิลออก [] ในวงเล็บคือไม่เอา
        exclude = ['id', 'slug', 'created', 'updated' , 'created_by']

    def __init__(self, *args, **kwargs):
        super(BookForm, self).__init__(*args, **kwargs)

        # Custom Validation input Code
        self.fields['code'].error_messages = {
            'required': 'Please enter book code',
        }
        # Custom Validation input Name
        self.fields['name'].error_messages = {
            'required': 'Please enter book name',
        }
        # Custom Validation input Price
        self.fields['price'].error_messages = {
            'required': 'Please enter book price',
            'invalid': 'Please enter a valid book price',
        }

    def clean(self):
        cd = super(BookForm, self).clean()
        if not cd.get('category'):
            self.add_error('category', 'Please select category name')

        if not cd.get('level'):
            self.add_error('level', 'Please select level')

        if not cd.get('author'):
            self.add_error('author', "Please select author name")

class CreateUserForm(UserCreationForm):
    class Meta:
        model = CustomUser
        fields = ['username', 'email', 'password1', 'password2']

    # function Check Email Address  is unique
    # def clean(self):
    #    email = self.cleaned_data.get('email')
    #    if User.objects.filter(email=email).exists():
    #         raise ValidationError("Email exists")
    #    return self.cleaned_data

class AddressForm(forms.ModelForm):
    class Meta:
        model = Address
        fields = ['address']

class CreateAuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        fields = ['name']

class CreateCategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ['name']

class CreateCommentForm(forms.ModelForm):
    class Meta:
        model = BookComments
        fields = ['comment' , 'rating']

class CustomUserForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        exclude = ['password' , 'last_login' , 'date_joined']


#https://analyticsindiamag.com/hands-on-guide-reinforcement-learning-openai-gymretro/

# To set up, just pip3 install gym-retro

import retro
env = retro.make(game='Airstriker-Genesis', record='.')
env.reset()

done = False

while not done:
    env.render()
    obs, rew, done, info = env.step(env.action_space.sample())
    if done:
        obs = env.reset()
        env.close()