from bdconnect import *

nom = input("nom enfant: ")
prenom = input("prenom enfant: ")
sexe= input("sexe: ")

lastidP = 6
lastidF = 6

cursor.execute("INSERT INTO enfant (nom, prenom, sexe, id_parent,id_fonctionnaire) VALUES (%s, %s, %s,%s, %s)", [nom, prenom ,sexe, lastidP, lastidF])
baseDeDonnees.commit()

baseDeDonnees.close()


from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required, permission_required
from django.db.models import F, Sum
from django.http import HttpResponseForbidden
from django.shortcuts import render, redirect, get_object_or_404
from django.utils.http import is_safe_url

from players.models import Player
from games.models import Guess

from .models import Game, Score, GameSession, PointCode
from .forms import GuessingForm, PointCodeForm

@staff_member_required
def scoreboard_view(request):

    overall_scores = Score.objects.exclude(player_id=None).annotate(player_id=F('player'),
                                                                    first_name=F('player__user__first_name'),
                                                                    last_name=F('player__user__last_name'))\
                                                          .values('player_id', 'first_name', 'last_name')\
                                                          .annotate(score=Sum('score'))\
                                                          .order_by('-score')

    games_list = []
    include_games = request.GET.get('includeindividual', False)

    if include_games:
        games = Game.objects.all()
        games_list = games.values('pk', 'name')

        for game in games_list:
            filtered_game_sessions = GameSession.objects.all().filter(game__pk=game['pk'])
            score_list = filtered_game_sessions.annotate(player_id=F('score__player'),
                                                         first_name=F('score__player__user__first_name'),
                                                         last_name=F('score__player__user__last_name'))\
                                               .values('player_id', 'first_name', 'last_name')\
                                               .annotate(score=Sum('score__score'))\
                                               .order_by('-score')
            game['score_list'] = score_list

    if request.GET.get('partial', False):
        return render(request, 'scoreboard/scoreboard_partial.html', {'overall': overall_scores})

    return render(request, 'scoreboard/scoreboard.html', {'games': games_list, 'overall': overall_scores,
                                                          'individualgames': include_games})

@login_required
def redemption_view(request):
    try:
        current_user_player = request.user.player
    except Player.DoesNotExist:
        current_user_player = None

    if not current_user_player:
        messages.error(request, 'Your are not a registered Player!')
        return redirect('/gfp-system')

    if request.method == 'POST':
        form = PointCodeForm(request.POST)
        if form.is_valid():
            point_code = PointCode.objects.filter(code=form.cleaned_data['code'], consumed_on=None)
            if point_code.exists():
                code = point_code[0]
                code.consume_code(current_user_player)
                messages.info(request, 'You have gained {points} points!'.format(points=code.score))
            else:
                messages.error(request, 'Invalid code provided!')
        else:
            messages.error(request, 'Invalid code provided!')

        redirect_url = request.POST.get('next', None)
        if redirect_url and is_safe_url(redirect_url):
            return redirect(redirect_url)
    else:
        form = PointCodeForm()

    return render(request, 'scoreboard/pointcode.html', {'form': form})

@login_required
def guess_view(request, id):
    associated_game_session = get_object_or_404(GameSession, pk=id)
    form = GuessingForm()
    if associated_game_session.game.game_type != Game.GUESSING:
        return HttpResponseForbidden()

    game_name = associated_game_session.game.name
    if request.method == 'POST':
        try:
            current_user_player = request.user.player
        except Player.DoesNotExist:
            current_user_player = None
        if current_user_player:
            guess_object, created = Guess.objects.get_or_create(player=current_user_player,
                                                                game_session=associated_game_session)
            form = GuessingForm(request.POST, instance=guess_object)
            if form.is_valid():
                new_guess = form.save()
                messages.info(request, 'Your guess has been successfully recorded!')
            else:
                messages.error(request, 'Something went wrong!')

            redirect_url = request.POST.get('next', None)
            if redirect_url and is_safe_url(redirect_url):
                return redirect(redirect_url)
        else:
            messages.warning(request, 'You are most likely a cheeky admin!')
    return render(request, 'scoreboard/guesser.html', {'form': form, 'game': game_name})


# -*- coding: utf-8 -*-
# !/usr/bin/env python
"""
-------------------------------------------------
   File     : markdown_pic_download.py
   Author   : CoderPig
   date     : 2020-12-21 10:43
   Desc     : Markdownt图片批量下载
-------------------------------------------------
"""
import mistune
import os

import cp_utils
import urllib.request
import time

class PicRenderer(mistune.HTMLRenderer):
    def image(self, src, alt="", title=None):
        pic_url_list.append(src)
        return ''

if __name__ == '__main__':
    md_file_path = os.path.join(os.getcwd(), "../article/md/test.md")
    pic_save_dir = os.path.join(os.getcwd(), "../article/pic/")
    cp_utils.delete_file(pic_save_dir)
    cp_utils.is_dir_existed(pic_save_dir)
    file_content = cp_utils.read_file_content(md_file_path)
    pic_url_list = []
    md_content = mistune.markdown(mistune.create_markdown(renderer=PicRenderer())(file_content))
    for pic_url in pic_url_list:
        print("下载：", pic_url)
        time.sleep(1)
        urllib.request.urlretrieve(pic_url,
                                   pic_save_dir + str(int(round(time.time() * 1000))) + '.' + pic_url.split('.')[-1])


# file:largest_palindrom_product_euler_adupree.py
# description: Find the largest palindromic product of a 3 digit number.
# authors: Alex DuPree
# date: 11/17/2017
# compiler: Python 3.6

# Create a palindrom check function
# Check for largest palindrome in range of 100-1000

"""
FROM PROJECT EULER:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.
"""

def palindrome(num):
    return str(num) == str(num)[::-1]

def largest(bottom, top):
    # Loop through every combination of multiplies from a 3 digit number
    z = 0
    for x in range(top, bottom, -1):
        for y in range(top, bottom, -1):
            if palindrome(x * y):
                if x * y > z:
                    z = x * y
    return z

print(largest(100, 1000))


from smbus2 import *
from py_sensors.i2c_func import *

INA226_ADDRESS_DEFAULT = 0x40

INA226_REG_CONFIG = 0x00
INA226_REG_SHUNTVOLTAGE = 0x01
INA226_REG_BUSVOLTAGE = 0x02
INA226_REG_POWER = 0x03
INA226_REG_CURRENT = 0x04
INA226_REG_CALIBRATION = 0x05
INA226_REG_MASKENABLE = 0x06
INA226_REG_ALERTLIMIT = 0x07

INA226_BIT_SOL = 0x8000
INA226_BIT_SUL = 0x4000
INA226_BIT_BOL = 0x2000
INA226_BIT_BUL = 0x1000
INA226_BIT_POL = 0x0800
INA226_BIT_CNVR = 0x0400
INA226_BIT_AFF = 0x0010
INA226_BIT_CVRF = 0x0008
INA226_BIT_OVF = 0x0004
INA226_BIT_APOL = 0x0002
INA226_BIT_LEN = 0x0001

INA226_AVERAGES_1 = 0b000
INA226_AVERAGES_4 = 0b001
INA226_AVERAGES_16 = 0b010
INA226_AVERAGES_64 = 0b011
INA226_AVERAGES_128 = 0b100
INA226_AVERAGES_256 = 0b101
INA226_AVERAGES_512 = 0b110
INA226_AVERAGES_1024 = 0b111

INA226_BUS_CONV_TIME_140US = 0b000
INA226_BUS_CONV_TIME_204US = 0b001
INA226_BUS_CONV_TIME_332US = 0b010
INA226_BUS_CONV_TIME_588US = 0b011
INA226_BUS_CONV_TIME_1100US = 0b100
INA226_BUS_CONV_TIME_2116US = 0b101
INA226_BUS_CONV_TIME_4156US = 0b110
INA226_BUS_CONV_TIME_8244US = 0b111

INA226_SHUNT_CONV_TIME_140US = 0b000
INA226_SHUNT_CONV_TIME_204US = 0b001
INA226_SHUNT_CONV_TIME_332US = 0b010
INA226_SHUNT_CONV_TIME_588US = 0b011
INA226_SHUNT_CONV_TIME_1100US = 0b100
INA226_SHUNT_CONV_TIME_2116US = 0b101
INA226_SHUNT_CONV_TIME_4156US = 0b110
INA226_SHUNT_CONV_TIME_8244US = 0b111

INA226_MODE_POWER_DOWN = 0b000
INA226_MODE_SHUNT_TRIG = 0b001
INA226_MODE_BUS_TRIG = 0b010
INA226_MODE_SHUNT_BUS_TRIG = 0b011
INA226_MODE_ADC_OFF = 0b100
INA226_MODE_SHUNT_CONT = 0b101
INA226_MODE_BUS_CONT = 0b110
INA226_MODE_SHUNT_BUS_CONT = 0b111

class INA226:
    def __init__(self, i2c_bus=None, ina226_addr=INA226_ADDRESS_DEFAULT):
        if i2c_bus is None:
            i2c_bus = 0
        if type(i2c_bus) is int:
            self.i2c_bus = smbus2.SMBus(i2c_bus)
        elif type(i2c_bus) is SMBus:
            self.i2c_bus = i2c_bus
        self.ina226_address = ina226_addr

        self.current_lsb = 0
        self.power_lsb = 0
        self.shunt_r = 0
        self.current_max_possible = 0
        self.shunt_v_max = 0.08192

    def close(self):
        self.i2c_bus.close()

    def get_bus(self):
        return self.i2c_bus

    def read_voltage(self):
        voltage = read_int16(self.i2c_bus, self.ina226_address, INA226_REG_BUSVOLTAGE) * 0.00125
        return voltage

    def read_shunt_voltage(self):
        voltage = read_int16(self.i2c_bus, self.ina226_address, INA226_REG_SHUNTVOLTAGE) / 400000
        return voltage

    def read_current(self):
        cur_reg = read_int16(self.i2c_bus, self.ina226_address, INA226_REG_CURRENT)
        return cur_reg * self.current_lsb

    def read_calibration(self):
        return read_uint16(self.i2c_bus, self.ina226_address, INA226_REG_CALIBRATION)

    def calibrate_by_shunt(self, shunt_r=0.1, current_max_expected=1):
        self.shunt_r = float(shunt_r)
        self.current_lsb = float(current_max_expected) / 2 ** 15

        self.power_lsb = self.current_lsb * 25

        calibration_value = int(0.00512 / (self.current_lsb * self.shunt_r))

        write_int16(self.i2c_bus, self.ina226_address, INA226_REG_CALIBRATION, calibration_value)
        return

    def configure(self,
                  avg=INA226_AVERAGES_1,
                  bus_conv_time=INA226_BUS_CONV_TIME_1100US,
                  shunt_conv_time=INA226_SHUNT_CONV_TIME_1100US,
                  mode=INA226_MODE_SHUNT_BUS_CONT
                  ):
        config = 0
        config |= (avg << 9 | bus_conv_time << 6 | shunt_conv_time << 3 | mode)
        write_uint16(self.i2c_bus, self.ina226_address, INA226_REG_CONFIG, config)
        return


# file: DistortImage.py
# team: compEYEler
# authors: Ranbir Aulakh, Joseph Bartelmo,
#           Ka Bo Cheung, Brandon Ha, Robbie Kubiniec
# description: return 3 distort images...

import cv2
import numpy as np
import math
import logging
import random

class DistortImage(object):

    def waveImage(image):
        distort_2_output = np.zeros(image.shape, dtype=image.dtype)

        for i in range(image.shape[0]):
            for j in range(image.shape[1]):
                offset_x = int(25.0 * math.sin(2 * 3.14 * i / 180))
                offset_y = 0
                if j + offset_x < image.shape[0]:
                    distort_2_output[i, j] = image[i, (j + offset_x) % image.shape[1]]
                else:
                    distort_2_output[i, j] = 0

        return distort_2_output

    def blurImage(image):
        blur = cv2.GaussianBlur(image, (5,5), 17)

        return blur

    def rainbowImage(image):
        rainbow = cv2.applyColorMap(image, cv2.COLORMAP_RAINBOW)

        # cv2.imshow("Distort 3 (COLORMAP_SUMMER)", cv2.applyColorMap(image, cv2.COLORMAP_RAINBOW))
        # cv2.imshow("Distort 3 (COLORMAP_JET)", cv2.applyColorMap(image, cv2.COLORMAP_JET))

        return rainbow

    def tiltImage(image):
        center = (image.shape[0] // 2, image.shape[1] // 2)
        angle = random.uniform(-360, 360)

        rotated_image = cv2.getRotationMatrix2D(center, angle, 1.0)
        rotated_image = cv2.warpAffine(image, rotated_image, (image.shape[0], image.shape[1]), flags=cv2.INTER_AREA,
                                         borderMode=cv2.BORDER_REPLICATE)

        return rotated_image

    def randTiltImage(image):
        image_list = []
        for i in range(0, 5):
            center = (image.shape[0] // 2, image.shape[1] // 2)
            angle = random.uniform(-360, 360)

            rotated_image = cv2.getRotationMatrix2D(center, angle, 1.0)
            rotated_image = cv2.warpAffine(image, rotated_image, (image.shape[0], image.shape[1]), flags=cv2.INTER_AREA,
                                         borderMode=cv2.BORDER_REPLICATE)
            image_list.append(rotated_image)

        return image_list

    def thresholdImage(image):
        blur_image = cv2.GaussianBlur(image, (5,5), 11)
        thres, binarized = cv2.threshold(blur_image, 245, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

        return binarized

    def upsideDown(image):
        center = (image.shape[1] // 2, image.shape[0] // 2)

        upside_down_image = cv2.getRotationMatrix2D(center, 180, 1.0)
        upside_down_image = cv2.warpAffine(image, upside_down_image, (image.shape[1], image.shape[0]), flags=cv2.INTER_AREA,
                                         borderMode=cv2.BORDER_REPLICATE)

        return upside_down_image

    def DistortImage(self, image, debug):
        distort_outputs = []
        image = cv2.imread(image)

        if debug:
            cv2.imshow("Original image", image)

        # convert to grayscale
        gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        gray_image = cv2.bitwise_not(gray_image)

        if debug:
            cv2.imshow("grayImage", gray_image)

        logging.info("Distorting the image...")

        distort1_Image = DistortImage.blurImage(image)
        distort_outputs.append(distort1_Image)
        if debug:
            cv2.imshow("Distort 1 (Blur)", distort1_Image)

        distort2_Image = DistortImage.waveImage(image)
        distort_outputs.append(distort2_Image)
        if debug:
            cv2.imshow("Distort 2 (Wave)", distort2_Image)

        distort3_Image = DistortImage.rainbowImage(image)
        distort_outputs.append(distort3_Image)
        if debug:
            cv2.imshow("Distort 3 (Rainbow)", distort3_Image)

        distort4_Image = DistortImage.randTiltImage(image)
        for i in range(len(distort4_Image)):
            distort_outputs.append(distort4_Image[i])
            if debug:
                cv2.imshow("Distort " + str( (i + 4) )  + " (Tilted)", distort4_Image[i])

        distort8_Image = DistortImage.tiltImage(distort1_Image)
        distort_outputs.append(distort8_Image)
        if debug:
            cv2.imshow("Distort 8 (Tilted + Blur)", distort8_Image)

        distort9_Image = DistortImage.thresholdImage(gray_image)
        distort_outputs.append(distort9_Image)
        if debug:
            cv2.imshow("Distort 9 (Threshold)", distort9_Image)

        distort10_Image = DistortImage.upsideDown(image)
        distort_outputs.append(distort10_Image)
        if debug:
            cv2.imshow("Distort 10 (Upside Down)", distort10_Image)

        if debug:
            cv2.waitKey(0)

        return distort_outputs


import stomp, time
from multiprocessing import Process, Queue
from matplotlib import pyplot as plt

counter = 0
q = Queue()

def inserisci(q,value):
    q.put([value])

class MyListener(stomp.ConnectionListener):

    def __init__(self,conn):
        self.conn = conn

    def on_message(self, frame):
        global counter
        print('[TempAnalyzer] Ho ricevuto una richiesta')
        counter = counter+1
        global q
        value = frame.body
        intValue = int(value)

        p = Process(target=inserisci, args=(q,intValue))

        p.start()

        p.join()

if __name__ == "__main__":

    conn = stomp.Connection([('127.0.0.1', 61613)])

    conn.set_listener('', MyListener(conn))

    conn.connect(wait=True)
    conn.subscribe(destination='/topic/mytemp', id=1, ack='auto')

    print('[TempAnalyzer] Aspettando i messaggi')

    time.sleep(120)

    # Creazione del grafico dopo aver ricevuto i messaggi
    if not q.empty():
        data = []
        for _ in range(q.qsize()):  # Estrae tutti gli elementi dalla coda utilizzando un ciclo for con range
            data.append(q.get()[0]) #prende il primo elemento e lo aggiunge alla coda

        plt.figure()
        plt.plot(range(len(data)), data)#asse x -> numero di elementi in data e asse y-> valori degli elementi
        plt.title('Valori di Temperatura')
        plt.xlabel('Numero Occorrenze')
        plt.ylabel('Valori Ricevuti')
        plt.show()


from django.contrib import admin
from match import forms
# Register your models here.
from match.models import Category, Player, Team, Group, MatchHistory, PostThread
from match.proxy_model import CSGOMatchHistory, DotaMatchHistory, FutsalMatchHistory
from match import proxy_model
from match.admin_actions import team

models = [PostThread]

for i in models:
    admin.site.register(i)

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        teams = Team.objects.filter(category=obj)
        for team in teams:
            team.calibrate_score()
            team.save()

@admin.register(Group)
class GroupAdmin(admin.ModelAdmin):
    list_display = [
        'name',
        'category'
    ]

@admin.register(Player)
class PlayerAdmin(admin.ModelAdmin):
    list_display = ['name', 'team', 'category']

from match.model_admin import match_history_model_admin,team_model_admin


item_type = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

item_prioritize = {}
for index, letter in enumerate(item_type):
    item_prioritize[letter] = index + 1

def part_one():
    with open("input.txt", "r") as f:
        sum = 0
        for line in f.read().splitlines():
            first_part, second_part = line[:len(line) // 2], line[len(line) // 2:]
            sum += item_prioritize[set(first_part).intersection(set(second_part)).pop()]
        print(f"Day 3, part one answer: {sum}")

def part_two():
    with open("input.txt", "r") as f:
        sum = 0
        group = []
        for line in f.read().splitlines():
            group.append(line)
            if len(group) == 3:
                first, second, third = group[0], group[1], group[2]
                intersect = set(first) & set(second) & set(third)
                sum += item_prioritize[intersect.pop()]
                group.clear()
        print(f"Day 3, part two answer: {sum}")

if __name__ == "__main__":
    part_one()
    part_two()


"""
Common Constants

"""
import enum
import pathlib

ALTER = 'ALTER'
COMMENT = 'COMMENT'
CREATE = 'CREATE'
DROP = 'DROP'
EXECUTE = 'EXECUTE'
GRANT = 'GRANT'
REVOKE = 'REVOKE'
SET = 'SET'

AS = 'AS'
CASCADE = 'CASCADE'
CHECK = 'CHECK'
COLLATE = 'COLLATE'
COST = 'COST'
DEFAULT = 'DEFAULT'
FOR = 'FOR'
FOR_EACH = 'FOR EACH'
FROM = 'FROM'
HANDLER = 'HANDLER'
HASHES = 'HASHES'
IMMUTABLE = 'IMMUTABLE'
INLINE = 'INLINE'
IS = 'IS'
JOIN = 'JOIN'
LANGUAGE = 'LANGUAGE'
LEAKPROOF = 'LEAKPROOF'
LOCALE = 'LOCALE'
MERGES = 'MERGES'
NO = 'NO'
NOT = 'NOT'
NOT_NULL = 'NOT NULL'
NULL = 'NULL'
ON = 'ON'
OR = 'OR'
ONLY = 'ONLY'
OPTIONS = 'OPTIONS'
PARALLEL = 'PARALLEL'
RETURNS = 'RETURNS'
REPLACE = 'REPLACE'
ROWS = 'ROWS'
SECURITY = 'SECURITY'
STABLE = 'STABLE'
STRICT = 'STRICT'
SUPPORT = 'SUPPORT'
TO = 'TO'
TRANSFORM = 'TRANSFORM'
TRUSTED = 'TRUSTED'
UNIQUE = 'UNIQUE'
USING = 'USING'
VALIDATOR = 'VALIDATOR'
VERSION = 'VERSION'
VOLATILE = 'VOLATILE'
WINDOW = 'WINDOW'
WHEN = 'WHEN'
WHERE = 'WHERE'
WITH = 'WITH'
WITHOUT = 'WITHOUT'

ACL = 'ACL'
AGGREGATE = 'AGGREGATE'
ASSIGNMENT = 'ASSIGNMENT'
AUTHORIZATION = 'AUTHORIZATION'
CAST = 'CAST'
CHECK_CONSTRAINT = 'CHECK CONSTRAINT'
COLUMN = 'COLUMN'
COLLATION = 'COLLATION'
CONSTRAINT = 'CONSTRAINT'
CONVERSION = 'CONVERSION'
DATABASE = 'DATABASE'
DIRECTIVE = 'DIRECTIVE'
DIRECTIVES = 'DIRECTIVES'
DML = 'DML'
DOMAIN = 'DOMAIN'
ENCODING = 'ENCODING'
EVENT_TRIGGER = 'EVENT TRIGGER'
EXTENSION = 'EXTENSION'
IF_EXISTS = 'IF EXISTS'
IF_NOT_EXISTS = 'IF NOT EXISTS'
IMPLICIT = 'IMPLICIT'
INOUT = 'INOUT'
FOREIGN_DATA_WRAPPER = 'FOREIGN DATA WRAPPER'
FOREIGN_SERVER = 'FOREIGN SERVER'
FOREIGN_TABLE = 'FOREIGN TABLE'
FK_CONSTRAINT = 'FK CONSTRAINT'
FUNCTION = 'FUNCTION'
GROUP = 'GROUP'
INDEX = 'INDEX'
LARGE_OBJECT = 'LARGE OBJECT'
LOCATION = 'LOCATION'
MATERIALIZED_VIEW = 'MATERIALIZED VIEW'
OPERATOR = 'OPERATOR'
OPERATOR_CLASS = 'OPERATOR CLASS'
OWNER = 'OWNER'
POLICY = 'POLICY'
PROCEDURE = 'PROCEDURE'
PROCEDURAL_LANGUAGE = 'PROCEDURAL LANGUAGE'
PUBLICATION = 'PUBLICATION'
PUBLICATION_TABLE = 'PUBLICATION TABLE'
RECURSIVE = 'RECURSIVE'
ROLE = 'ROLE'
RULE = 'RULE'
SEARCHPATH = 'SEARCHPATH'
SEQUENCE_OWNED_BY = 'SEQUENCE OWNED BY'
SEQUENCE_SET = 'SEQUENCE SET'
SCHEMA = 'SCHEMA'
SECURITY_LABEL = 'SECURITY LABEL'
SEQUENCE = 'SEQUENCE'
SERVER = 'SERVER'
SHELL_TYPE = 'SHELL TYPE'
STDSTRINGS = 'STDSTRINGS'
SUBSCRIPTION = 'SUBSCRIPTION'
TABLE = 'TABLE'
TABLESPACE = 'TABLESPACE'
TEXT_SEARCH = 'TEXT SEARCH'
TEXT_SEARCH_DICTIONARY = 'TEXT SEARCH DICTIONARY'
TEXT_SEARCH_CONFIGURATION = 'TEXT SEARCH CONFIGURATION'
TEXT_SEARCH_PARSER = 'TEXT SEARCH PARSER'
TEXT_SEARCH_TEMPLATE = 'TEXT SEARCH TEMPLATE'
TRIGGER = 'TRIGGER'
TYPE = 'TYPE'
USER = 'USER'
USER_MAPPING = 'USER MAPPING'
VIEW = 'VIEW'

INSERT = 'INSERT'
UPDATE = 'UPDATE'
DELETE = 'DELETE'
SELECT = 'SELECT'
TRUNCATE = 'TRUNCATE'

AFTER = 'AFTER'
BEFORE = 'BEFORE'
INSTEAD = 'INSTEAD OF'

DATA_TYPE_MAPPING = {
    'bool': 'boolean',
    'float4': 'real',
    'float8': 'double precision',
    'int4': 'integer',
    'int8': 'bigint',
    'time': 'time without time zone',
    'timetz': 'times with time zone',
    'timestamp': 'timestamp without time zone',
    'timestamptz': 'timestamp with time zone',
    'varchar': ' character varying'
}

DEPENDENCIES = 'dependencies'

PATHS = {
    AGGREGATE: pathlib.Path('aggregates'),
    CAST: pathlib.Path('casts'),
    COLLATION: pathlib.Path('collations'),
    CONVERSION: pathlib.Path('conversions'),
    DML: pathlib.Path('dml'),
    DOMAIN: pathlib.Path('domains'),
    EVENT_TRIGGER: pathlib.Path('event_triggers'),
    FUNCTION: pathlib.Path('functions'),
    GROUP: pathlib.Path('groups'),
    MATERIALIZED_VIEW: pathlib.Path('materialized_views'),
    OPERATOR: pathlib.Path('operators'),
    PROCEDURE: pathlib.Path('procedures'),
    PUBLICATION: pathlib.Path('publications'),
    ROLE: pathlib.Path('roles'),
    SCHEMA: pathlib.Path('schemata'),
    SEQUENCE: pathlib.Path('sequences'),
    SERVER: pathlib.Path('servers'),
    SUBSCRIPTION: pathlib.Path('subscriptions'),
    TABLE: pathlib.Path('tables'),
    TABLESPACE: pathlib.Path('tablespaces'),
    TEXT_SEARCH: pathlib.Path('text_search'),
    TYPE: pathlib.Path('types'),
    USER: pathlib.Path('users'),
    USER_MAPPING: pathlib.Path('user_mappings'),
    VIEW: pathlib.Path('views'),
}

OBJ_KEYS = {
    'casts': CAST,
    'columns': COLUMN,
    'constraints': CONSTRAINT,
    'conversions': CONVERSION,
    'databases': DATABASE,
    'domains': DOMAIN,
    'extensions': EXTENSION,
    'foreign data wrappers': FOREIGN_DATA_WRAPPER,
    'foreign servers': FOREIGN_SERVER,
    'functions': FUNCTION,
    'groups': GROUP,
    'indexes': INDEX,
    'languages': PROCEDURAL_LANGUAGE,
    'large objects': LARGE_OBJECT,
    'operators': OPERATOR,
    'roles': ROLE,
    'sequences': SEQUENCE,
    'schemata': SCHEMA,
    'tables': TABLE,
    'tablespaces': TABLESPACE,
    'text_search': TEXT_SEARCH,
    'types': TYPE,
    'views': VIEW
}

ITEM_KEYS = {v: k for k, v in OBJ_KEYS.items()}

GRANT_SORT_WEIGHTS = {
    'ALL': -1,
    'SELECT': 0,
    'INSERT': 1,
    'UPDATE': 2,
    'DELETE': 3,
    'USAGE': 4,
    'TRUNCATE': 5,
    'REFERENCES': 6,
    'TRIGGER': 7,
    'CREATE': 0,
    'CONNECT': 1,
    'TEMPORARY': 2
}

OPTIONS_WEIGHTS = {
    'SUPERUSER': 0,
    'NOSUPERUSER': 0,
    'CREATEDB': 1,
    'NOCREATEDB': 1,
    'CREATEROLE': 2,
    'NOCREATEROLE': 2,
    'INHERIT': 3,
    'NOINHERIT': 3,
    'LOGIN': 4,
    'NOLOGIN': 4,
    'REPLICATION': 5,
    'NOREPLICATION': 5,
    'BYPASSRLS': 6,
    'NOBYPASSRLS': 6
}

TABLE_KEYS = {
    ACL: 'acls',
    CHECK_CONSTRAINT: 'check constraints',
    CONSTRAINT: 'constraints',
    DEFAULT: 'defaults',
    FK_CONSTRAINT: 'foreign keys',
    INDEX: 'indexes',
    RULE: 'rules',
    TRIGGER: 'triggers',
}

A_EXPR_KIND = {
    0: None,  # Normal Operator
    1: 'ANY',
    2: 'ALL',
    3: 'IS DISTINCT FROM',
    4: 'IS NOT DISTINCT FROM',
    5: 'NULLIF',
    6: 'IS {}OF',
    7: 'IN',
    8: 'LIKE',
    9: 'ILIKE',
    10: 'SIMILAR',
    11: 'BETWEEN',
    12: 'NOT BETWEEN',
    13: 'BETWEEN SYMMETRIC',
    14: 'NOT BETWEEN SYMMETRIC'
}

ACL_OBJECT_TYPE = {
    1: 'TABLE',
    10: 'SCHEMA'}

ACL_ROLE_TYPE = {
    0: 'USER',
    3: 'PUBLIC'}

BOOL_OP = {0: 'AND', 1: 'OR', 2: 'NOT'}

BOOL_TEST = {1: 'TRUE', 2: 'FALSE', 't': 'TRUE', 'f': 'FALSE'}

FK_ACTION = {
    'a': None,  # NO ACTION
    'c': 'CASCADE',
    'n': 'SET NULL',
    'r': 'RESTRICT'}

FK_MATCH = {'f': 'FULL', 'p': 'PARTIAL', 's': None}

GENERATED = {'a': 'ALWAYS', 'd': 'BY DEFAULT'}

GROUPING_SET = {
    0: None,
    1: 'SIMPLE',
    2: 'ROLLUP',
    3: 'CUBE',
    4: 'GROUPING SETS'
}

INTERVAL_FIELDS = {
    4: 'YEAR',
    2: 'MONTH',
    8: 'DAY',
    1024: 'HOUR',
    2048: 'MINUTE',
    4096: 'SECOND',
    6: 'YEAR TO MONTH',
    1032: 'DAY TO HOUR',
    3072: 'HOUR TO MINUTE',
    3080: 'DAY TO MINUTE',
    6144: 'MINUTE_TO_SECOND',
    7168: 'HOUR TO SECOND',
    7176: 'DAY TO SECOND'
}

JOIN_TYPE = {
    0: None,  # INNER
    1: 'LEFT',
    2: 'FULL',
    3: 'RIGHT',
    4: 'EXISTS',
    5: 'NOT EXISTS',
    6: 'UNIQUE OUTER',
    7: 'UNIQUE INNER'
}

NULL_ORDERING = {0: None, 1: 'FIRST', 2: 'LAST'}
NULL_TEST = {0: 'IS', 1: 'IS NOT'}

ON_CONFLICT = {
    1: 'DO NOTHING',
    2: 'DO UPDATE SET'
}

ORDERING = {0: None, 1: 'ASC', 2: 'DESC'}

ROW_COMPARE = {
    1: '<',
    2: '<=',
    3: '=',
    4: '>=',
    5: '>',
    6: '!=',
}

RULE_EVENTS = {
    1: SELECT,
    2: UPDATE,
    3: INSERT,
    4: DELETE
}

SELECT_OP = {
    0: None,
    1: 'UNION',
    2: 'INTERSECT',
    3: 'EXCEPT'
}

SQL_VALUE_FUNCTION = {
    3: 'CURRENT_TIMESTAMP'
}

SUBLINK_TYPE = {
    0: 'EXISTS',
    1: 'ALL',
    2: 'IN',   # is 'ANY' if operName is set
    3: 'ROW-COMPARE',     # ROW COMPARE
    4: 'EXPRESSION',   # EXPR
    5: 'MULTI-EXPRESSION',   # MULTI-EXPR
    6: 'ARRAY',
    7: 'WITH'  # CTE
}

TRIGGER_INSERT = (1 << 2)
TRIGGER_DELETE = (1 << 3)
TRIGGER_UPDATE = (1 << 4)
TRIGGER_TRUNCATE = (1 << 5)
TRIGGER_BEFORE = (1 << 1)
TRIGGER_AFTER = 0x00000000
TRIGGER_INSTEAD = (1 << 6)

class AlterTableType(enum.IntEnum):
    """Enum identifying the alter_table_cmd type"""
    ADD_COLUMN = 0
    ADD_COLUMN_RECURSE = 1
    ADD_COLUMN_TO_VIEW = 2
    COLUMN_DEFAULT = 3
    DROP_NOT_NULL = 4
    SET_NOT_NULL = 5
    SET_STATISTICS = 6
    SET_OPTIONS = 7
    RESET_OPTIONS = 8
    SET_STORAGE = 9
    DROP_COLUMN = 10
    DROP_COLUMN_RECURSE = 11
    ADD_INDEX = 12
    RE_ADD_INDEX = 13
    ADD_CONSTRAINT = 14
    ADD_CONSTRAINT_RECURSE = 15
    RE_ADD_CONSTRAINT = 16
    ALTER_CONSTRAINT = 17
    VALIDATE_CONSTRAINT = 18
    VALIDATE_CONSTRAINT_RECURSE = 19
    PROCESSED_CONSTRAINT = 20
    ADD_INDEX_CONSTRAINT = 21
    DROP_CONSTRAINT = 22
    DROP_CONSTRAINT_RECURSE = 23
    RE_ADD_COMMENT = 24
    ALTER_COLUMN_TYPE = 25
    ALTER_COLUMN_GENERIC_OPTIONS = 26
    CHANGE_OWNER = 27
    CLUSTER_ON = 28
    DROP_CLUSTER = 29
    SET_LOGGED = 30
    SET_UN_LOGGED = 31
    ADD_OIDS = 32
    ADD_OIDS_RECURSE = 33
    DROP_OIDS = 34
    SET_TABLE_SPACE = 35
    SET_REL_OPTIONS = 36
    RESET_REL_OPTIONS = 37
    REPLACE_REL_OPTIONS = 38
    ENABLE_TRIG = 39
    ENABLE_ALWAYS_TRIG = 40
    ENABLE_REPLICA_TRIG = 41
    DISABLE_TRIG = 42
    ENABLE_TRIG_ALL = 43
    DISABLE_TRIG_ALL = 44
    ENABLE_TRIG_USER = 45
    DISABLE_TRIG_USER = 46
    ENABLE_RULE = 47
    ENABLE_ALWAYS_RULE = 48
    ENABLE_REPLICA_RULE = 49
    DISABLE_RULE = 50
    ADD_INHERIT = 51
    DROP_INHERIT = 52
    ADD_OF = 53
    DROP_OF = 54
    REPLICA_IDENTITY = 55
    ENABLE_ROW_SECURITY = 56
    DISABLE_ROW_SECURITY = 57
    FORCE_ROW_SECURITY = 58
    NO_FORCE_ROW_SECURITY = 59
    GENERIC_OPTIONS = 60
    ATTACH_PARTITION = 61
    DETACH_PARTITION = 62
    ADD_IDENTITY = 63
    SET_IDENTITY = 64
    DROP_IDENTITY = 65

class DefElemAction(enum.IntEnum):
    """Actions for a DefElem"""
    UNSPECIFIED = 0
    SET = 1
    ADD = 2
    DROP = 3

class FunctionParameterMode(enum.Enum):
    """Modes for a function parameter"""
    IN = 105  # i
    OUT = 111  # o
    INOUT = 98  # b
    VARADIC = 118  # v
    TABLE = 116  # t

class ObjectType(enum.IntEnum):
    """PostgreSQL Object Types"""
    ACCESS_METHOD = 0
    AGGREGATE = 1
    AMOP = 2
    AMPROC = 3
    ATTRIBUTE = 4
    CAST = 5
    COLUMN = 6
    COLLATION = 7
    CONVERSION = 8
    DATABASE = 9
    DEFAULT = 10
    DEFACL = 11
    DOMAIN = 12
    DOMCONSTRAINT = 13
    EVENT_TRIGGER = 14
    EXTENSION = 15
    FDW = 16
    FOREIGN_SERVER = 17
    FOREIGN_TABLE = 18
    FUNCTION = 19
    INDEX = 20
    LANGUAGE = 21
    LARGEOBJECT = 22
    MATVIEW = 23
    OPCLASS = 24
    OPERATOR = 25
    OPFAMILY = 26
    POLICY = 27
    PUBLICATION = 28
    PUBLICATION_REL = 29
    ROLE = 30
    RULE = 31
    SCHEMA = 32
    SEQUENCE = 33
    SUBSCRIPTION = 34
    STATISTIC_EXT = 35
    TABCONSTRAINT = 36
    TABLE = 37
    TABLESPACE = 38
    TRANSFORM = 39
    TRIGGER = 40
    TSCONFIGURATION = 41
    TSDICTIONARY = 42
    TSPARSER = 43
    TSTEMPLATE = 44
    TYPE = 45
    USER_MAPPING = 46
    VIEW = 47

class VariableSetKind(enum.IntEnum):
    """Defines the various set statement kinds"""
    VALUE = 0
    DEFAULT = 1
    CURRENT = 2
    MULTI = 3
    RESET = 4
    RESET_ALL = 5

class ViewCheckOption(enum.IntEnum):
    """Defines ViewCheckOption values"""
    UNDEFINED: 0
    LOCAL: 1
    CASCADED: 2


from distutils.core import setup

with open('README.rst') as file:
    long_description = file.read()

setup(
    install_requires=['beautifulsoup4', 'requests'],
    name='python-ninegag',
    version='1.0',
    py_modules=['pyninegag'],
    url='https://github.com/sashgorokhov/python-ninegag',
    download_url='https://github.com/sashgorokhov/python-ninegag/archive/master.zip',
    keywords=['ninegag', '9gag'],
    classifiers=[],
    long_description=long_description,
    license='MIT License',
    author='sashgorokhov',
    author_email='sashgorokhov@gmail.com',
    description='Python library to get stuff from 9gag.com'
)


#!/usr/bin/python3

from pandas.core.frame import DataFrame #class

from datasets.aDataset import ADataset #class

from datasets.retailrocket.events import Events #class
from datasets.retailrocket.categoryTree import CategoryTree #class
from datasets.retailrocket.itemProperties import ItemProperties #class

class DatasetRetailRocket(ADataset):

    def __init__(self, datasetID:str, eventsDF:DataFrame, categoryTreeDF:DataFrame, itemPropertiesDF:DataFrame):
        if type(datasetID) is not str:
            raise ValueError("Argument datasetID isn't type str.")
        if type(eventsDF) is not DataFrame:
            raise ValueError("Argument eventsDF isn't type DataFrame.")
        if type(categoryTreeDF) is not DataFrame:
            raise ValueError("Argument categoryTreeDF isn't type DataFrame.")
        if type(itemPropertiesDF) is not DataFrame:
            raise ValueError("Argument itemPropertiesDF isn't type DataFrame.")

        self.datasetID = datasetID
        self.eventsDF:DataFrame = eventsDF
        self.categoryTreeDF:DataFrame = categoryTreeDF
        self.itemPropertiesDF:DataFrame = itemPropertiesDF

    @staticmethod
    def readDatasets():

        eventsDF:DataFrame = Events.readFromFile()
        categoryTreeDF:DataFrame = CategoryTree.readFromFile()
        itemPropertiesDF:DataFrame = ItemProperties.readFromFile()

        return DatasetRetailRocket("rrDivAll", eventsDF, categoryTreeDF, itemPropertiesDF)

    @staticmethod
    def readDatasetsWithFilter(minEventCount:int):

        eventsDF:DataFrame = Events.readFromFileWithFilter(minEventCount=minEventCount)
        categoryTreeDF:DataFrame = CategoryTree.readFromFile()
        itemPropertiesDF:DataFrame = ItemProperties.readFromFile()

        return DatasetRetailRocket("rrDivAll", eventsDF, categoryTreeDF, itemPropertiesDF)

    def getTheMostSold(self):

        eventsTrainDF:DataFrame = self.eventsDF

        # ratingsSum:Dataframe<(timestamp:int, visitorid:int, event:str, itemid:int, transactionid:int)>
        eventsTransDF:DataFrame = eventsTrainDF.loc[eventsTrainDF[Events.COL_EVENT] == "transaction"]

        # ratingsSum:Dataframe<(movieId:int, ratings:int)>
        eventsTransSumDF:DataFrame = DataFrame(eventsTransDF.groupby(Events.COL_ITEM_ID)[Events.COL_EVENT].count())

        # sortedAsceventsTransCountDF:Dataframe<(movieId:int, ratings:int)>
        sortedAsceventsTransCountDF:DataFrame = eventsTransSumDF.sort_values(by=Events.COL_EVENT, ascending=False)
        #print(sortedAsceventsTransCountDF)

        return sortedAsceventsTransCountDF

    def divideDataset(self, divisionDatasetPercentualSize:int, sortByTimestapmt=True):

        # create train Dataset
        eventsToSplitDF:DataFrame = self.eventsDF

        if sortByTimestapmt:
            eventsToSplitDF = eventsToSplitDF.sort_values(by=Events.COL_TIME_STAMP)

        numberOfRatings:int = eventsToSplitDF.shape[0]
        trainSize:int = (int)(numberOfRatings * divisionDatasetPercentualSize / 100)

        trainRatingsDF:DataFrame = eventsToSplitDF[0:trainSize]

        trainDatasetID:str = self.datasetID + "Div0-" + str(divisionDatasetPercentualSize)
        trainDataset:ADataset = DatasetRetailRocket(trainDatasetID, trainRatingsDF, self.categoryTreeDF, self.itemPropertiesDF)

        testRatingsDF:DataFrame = eventsToSplitDF[trainSize:]

        testDatasetID:str = self.datasetID + "Div" + str(divisionDatasetPercentualSize) + "-100"
        testDataset:ADataset = DatasetRetailRocket(testDatasetID, testRatingsDF, self.categoryTreeDF, self.itemPropertiesDF)

        return (trainDataset, testDataset)


from sqlalchemy.orm import Session
from sqlalchemy import func
from exceptions.fast_api_custom import CustomException

class BaseCrudModel:
    @classmethod
    def create(cls, db_session: Session, **kwargs):
        new = cls(**kwargs)
        db_session.add(new)
        db_session.flush()
        return new

    @classmethod
    def update(cls, db_session: Session, id: str, **kwargs):
        query = cls.query.filter_by(id=id, disabled_at=None).first()

        if query is None:
            raise CustomException(
                status_code=404,
                type="NoData",
                detail="No es posible actualizar el registro, debido a que no se encuentra disponible ó ha sido eliminado.",
            )

        for key, value in kwargs.items():
            if hasattr(query, key):
                setattr(query, key, value)

        db_session.flush()
        return query

    @classmethod
    def read_by_id(cls, id: str):
        return cls.query.filter_by(id=id, disabled_at=None).first()

    @classmethod
    def read_disabled(cls, id: str):
        return cls.query.filter_by(id=id).first()

    @classmethod
    def read_select(cls):
        return cls.query.filter_by(disabled_at=None).all()

    @classmethod
    def delete(cls, db_session: Session, id: str):
        query = cls.query.filter_by(id=id, disabled_at=None).first()

        if query is None:
            raise CustomException(
                status_code=404,
                type="NoData",
                detail="No es posible eliminar el registro, debido a que no se encuentra disponible ó ha sido eliminado.",
            )

        query.disabled_at = func.now()
        db_session.flush()
        return query

    @classmethod
    def restore(cls, db_session: Session, id: str):
        query = cls.query.filter(cls.id == id, cls.disabled_at.isnot(None)).first()

        if query is None:
            raise CustomException(
                status_code=404,
                type="NoData",
                detail="No es posible restaurar el registro, debido a que no se encuentra disponible ó ha sido eliminado.",
            )

        query.disabled_at = None
        db_session.flush()
        return query


import cv2
import numpy as np

kernel = np.ones((5, 5), np.uint8)

img = cv2.imread('img4.jpg')

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_blue = np.array([110, 50, 50])
upper_blue = np.array([130, 255, 255])

mask = cv2.inRange(hsv, lower_blue, upper_blue)
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
x, y, w, h = cv2.boundingRect(opening)

if (x, y, w, h) != (0, 0, 0, 0):
    print(x, y, w, h)

cv2.rectangle(img, (x, y), (x+w, y + h), (0, 255, 0), 3)
cv2.circle(img, (int(x+w/2), int(y+h/2)), 5, (0, 0, 255), -1)

# res = cv2.bitwise_and(img, img, mask=mask)

cv2.imshow('frame', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

'''
# Webcamera no 0 is used to capture the frames
cap = cv2.VideoCapture(0)

# This drives the program into an infinite loop.
while (1):
    # Captures the live stream frame-by-frame
    _, frame = cap.read()
    # Converts images from BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    lower_blue = np.array([110, 50, 50])
    upper_blue = np.array([130, 255, 255])

    # Here we are defining range of bluecolor in HSV
    # This creates a mask of blue coloured
    # objects found in the frame.
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    # The bitwise and of the frame and mask is done so
    # that only the blue coloured objects are highlighted
    # and stored in res
    res = cv2.bitwise_and(frame, frame, mask=mask)
    cv2.imshow('frame', frame)
    cv2.imshow('mask', mask)
    cv2.imshow('res', res)

    # This displays the frame, mask
    # and res which we created in 3 separate windows.
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

# Destroys all of the HighGUI windows.
cv2.destroyAllWindows()

# release the captured frame
cap.release()
'''

# https://www.instructables.com/Servo-Motor-Control-With-Raspberry-Pi/
# https://www.youtube.com/watch?v=ZEg2IjACG9s
# https://www.raspberrypi.org/blog/how-to-control-multiple-servo-motors-with-raspberry-pi/    for angles


import sqlite3
import os
import matplotlib.pyplot as plt
import numpy as np
def openDatabase(db_name = 'CovidObesityProject'):
    path = os.path.dirname(os.path.abspath(__file__))
    conn = sqlite3.connect(path+'/'+db_name)
    cur = conn.cursor()
    return cur, conn
def getMainData(cur,con):

    avgData = []

    cur.execute(
            """
            SELECT CountryID.Country, PovertyRankData.PovertyRank,ObesityData.ObesityRate, CovidData.TotalCases,CovidData.TotalDeaths
            FROM CountryID
            JOIN CovidData ON CovidData.Country_ID = CountryID.Country_ID
            JOIN ObesityData on ObesityData.Country_ID=CovidData.Country_ID
            JOIN PovertyRankData on PovertyRankData.Country_ID=ObesityData.Country_ID
            """)
    data = cur.fetchall()
    return data

def deathRates(data):
    newList =[]
    for toop in data:
        if toop[3] == 0:
            rate = 0
        else:
            rate = round((toop[4]/toop[3]) * 100, 2)
        newT = (toop[0], rate)
        newList.append(newT)
    return newList

def writefile(data):
    path = os.path.dirname(os.path.abspath(__file__))
    with open(path + '/deathrates.txt', 'w') as f:
        f.write("Country, " + "Death Rates\n" )
        for toop in data:
            f.write(toop[0] + ", " + str(toop[1]) + '\n')
def ObesityDeathRateScatter(data):
    obesitylist=[]
    deathratelist=[]
    for country in data:
        if country[3] == 0:
            rate = 0
        else:
            rate = round((country[4]/country[3]) * 100, 2)
        obesitylist.append(country[2])
        deathratelist.append(rate)
    x = np.array(obesitylist)
    y = np.array(deathratelist)

    plt.scatter(x, y, color='red')
    plt.xlim([0, 40])
    plt.ylim([0,10])
    z = np.polyfit(x, y, 1)
    p = np.poly1d(z)
    plt.plot(x, p(x))
    plt.title('Obesity Rate and Death Rate Scatterplot')
    plt.xlabel('Obesity Rate (%)')
    plt.ylabel('Death Rate (%)')

    plt.show()

def PovertyDeathRateScatter(data):
    povertylist=[]
    deathratelist=[]
    for country in data:
        if country[3] == 0:
            rate = 0
        else:
            rate = round((country[4]/country[3]) * 100, 2)
        povertylist.append(country[1])
        deathratelist.append(rate)
    x = np.array(povertylist)
    y = np.array(deathratelist)

    plt.scatter(x, y, color='green')
    # plt.xlim([0, 40])
    plt.ylim([0,8])
    z = np.polyfit(x, y, 1)
    p = np.poly1d(z)
    plt.plot(x, p(x))
    plt.title('Poverty Rank and Death Rate Scatterplot')
    plt.xlabel('Poverty Rank')
    plt.ylabel('Death Rate (%)')

    plt.show()

def Top10DeathRate(data):
    tuplist=[]
    for country in data:
        if country[3] == 0:
            rate = 0
        else:
            rate = round((country[4]/country[3]) * 100, 2)
        tup=(country[0],rate)
        tuplist.append(tup)
    tuplist.sort(key=lambda y: y[1], reverse=True)
    #print(tuplist)
    tuplist10=tuplist[:10]

    namelist=[]
    ratelist=[]
    for x in tuplist10:
        namelist.append(x[0])
        ratelist.append(x[1])
    x=np.array(namelist)
    y=np.array(ratelist)

    plt.barh(x, y)
    plt.title('Top 10 Death Rate')
    plt.xlabel('Death Rate')
    plt.ylabel('Countries')

    plt.show()

def bottom10DeathRate(data):
    tuplist=[]
    for country in data:
        if country[3] == 0:
            rate = 0
        else:
            rate = round((country[4]/country[3]) * 100, 2)
        tup=(country[0],rate)
        tuplist.append(tup)
    tuplist.sort(key=lambda y: y[1])
    #print(tuplist)
    tuplist10=tuplist[:10]

    namelist=[]
    ratelist=[]
    for x in tuplist10:
        namelist.append(x[0])
        ratelist.append(x[1])
    x=np.array(namelist)
    y=np.array(ratelist)

    plt.barh(x, y, color='orange')
    plt.title('Bottom 10 Death Rate')
    plt.xlabel('Death Rate')
    plt.ylabel('Countries')

    plt.show()
def PovertyObesityScatter(data):
    povertylist=[]
    obesitylist=[]
    for country in data:
        povertylist.append(country[1])
        obesitylist.append(country[2])
    x = np.array(povertylist)
    y = np.array(obesitylist)

    plt.scatter(x, y, color='purple')
    # plt.xlim([0, 40])
    # plt.ylim([0,8])
    z = np.polyfit(x, y, 1)
    p = np.poly1d(z)
    plt.plot(x, p(x))
    plt.title('Poverty Rank and Obesity Rate Scatterplot')
    plt.xlabel('Poverty Rank (lower is poorer')
    plt.ylabel('Obesity Rate (%)')

    plt.show()
def Top10PovertyRate(data):
    tuplist=[]
    for country in data:
        tup=(country[0],country[1])
        tuplist.append(tup)
    tuplist.sort(key=lambda y: y[1])
    #print(tuplist)
    tuplist10=tuplist[:10]

    namelist=[]
    povertylist=[]
    for x in tuplist10:
        namelist.append(x[0])
        povertylist.append(x[1])
    x=np.array(namelist)
    y=np.array(povertylist)

    plt.barh(x, y, color="red")
    plt.title('Top 10 Poverty Rate')
    plt.xlabel('Poverty Rank(lower means poorer)')
    plt.ylabel('Countries')

    plt.show()

def main():
    c,d=openDatabase()
    da = getMainData(c,d)
    rat = deathRates(da)
    writefile(rat)
    ObesityDeathRateScatter(da)
    PovertyDeathRateScatter(da)
    Top10DeathRate(da)
    bottom10DeathRate(da)
    PovertyObesityScatter(da)
    Top10PovertyRate(da)
main()


import webbrowser
import pyautogui as pg

computerscience = ["https://sites.google.com/gcds.net/cs2"]

fun = ["https://www.youtube.com/watch?v=hTp7PsrJBYY"]

answer = pg.prompt (
"""
Which would you like to do?
a) computer science
b) fun

"""
    )

if answer == "a":
    for i in computerscience:
        webbrowser.open(i)

elif answer == "b":
    for i in fun:
        webbrowser.open(i)


name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
words = dict()
for line in handle :
    if line.startswith('From '):
        lst = line.split()
        words[lst[1]] = words.get(lst[1],0) + 1

bigcount = 0
bigword = 0

for k,v in words.items():
    if v is None or v > bigcount:
        bigcount = v
        bigword = k

print(bigword,bigcount)

Coursera Python for Everybody/ch9assign1.py


import telegram
import telegram.ext
import modules.chat_settings as chat_settings
import modules.strings
import modules.common as common
import modules.sql as sql
import modules.users_cache as users_cache

@common.private_only_dec()
async def cmd_help(update: telegram.Update, context: telegram.ext.CallbackContext):
    """/help"""
    await update.effective_chat.send_message(parse_mode=telegram.constants.ParseMode.HTML,
                                             text=modules.strings.CMD_HELP_TEXT)

@common.private_only_dec()
async def cmd_privacy(update: telegram.Update, context: telegram.ext.CallbackContext):
    """/privacy"""
    await update.effective_chat.send_message(parse_mode=telegram.constants.ParseMode.HTML,
                                             text=modules.strings.CMD_PRIVACY_TEXT)

async def generic_command_handler(update: telegram.Update, context: telegram.ext.CallbackContext):
    """Completely ignore channels and inline queries"""
    if update.effective_chat.type == telegram.constants.ChatType.CHANNEL or update.effective_chat.type == telegram.constants.ChatType.SENDER:
        raise telegram.ext.ApplicationHandlerStop

@common.group_only_dec()
async def cmd_bonk(update: telegram.Update, context: telegram.ext.CallbackContext):
    """/bonk"""
    common.ensure_chat_in_db(update.effective_chat)

    # Get settings for group
    settings = chat_settings.get_group_settings(update.effective_chat, settings=(
        chat_settings.show_help_msgs, chat_settings.announce_top_user, chat_settings.allow_counter_bonks))
    chat_show_help_msgs = settings[chat_settings.show_help_msgs.name]
    chat_announce_top_user = settings[chat_settings.announce_top_user.name]
    chat_allow_counter_bonks = settings[chat_settings.allow_counter_bonks.name]

    # Show help message if message isn't a reply and group is set to show help messages
    if update.effective_message.reply_to_message is None:
        if chat_show_help_msgs:
            await update.effective_chat.send_message(reply_to_message_id=update.effective_message.id,
                                                     text=modules.strings.NO_REPLIED_MESSAGE)
    else:
        # Get top score and holder to use later if announce new top user is enabled
        if chat_announce_top_user:
            # Since message IDs are incremental and per chat, we can use them to determine if a message is newer without storing timestamps
            top_score = sql.fetchone(f"SELECT COUNT(*) AS bonks_count, user_id, MAX(message_id) AS last_message "
                                     f"FROM bonks "
                                     f"WHERE chat_id = {update.effective_chat.id} "
                                     f"GROUP BY user_id "
                                     f"ORDER BY bonks_count DESC, last_message ASC "
                                     f"LIMIT 1")
        bonk_user_id = update.effective_message.reply_to_message.from_user.id
        bonk_message_id = update.effective_message.reply_to_message.message_id
        bonk_message = update.effective_message.reply_to_message
        block_counter_bonk = False
        already_bonked = False if sql.fetchone(f"SELECT * "
                                              f"FROM bonks "
                                              f"WHERE user_id = {bonk_user_id} "
                                              f"AND chat_id = {update.effective_chat.id} "
                                              f"AND message_id = {bonk_message_id}") is None else True

        # If counter bonks are disallowed, check if the message contains the /bonk command
        if not chat_allow_counter_bonks:
            dict = bonk_message.parse_entities([telegram.constants.MessageEntityType.BOT_COMMAND])
            for i in dict:
                if dict[i] == "/bonk" or dict[i] == f"/bonk{context.bot.name}":
                    block_counter_bonk = True
                    break

        # Block counter bonk
        if block_counter_bonk:
            if chat_show_help_msgs:
                await update.effective_chat.send_message(reply_to_message_id=update.effective_message.id,
                                                         text=modules.strings.COUNTER_BONKS_DISABLED)
        # Bot can't bonk itself
        elif update.effective_message.reply_to_message.from_user.id == context.bot.id:
            if chat_show_help_msgs:
                await update.effective_chat.send_message(reply_to_message_id=update.effective_message.id,
                                                         text=modules.strings.CANT_BONK_BOT)
        # Can't bonk the same message more than once
        elif already_bonked:
            if chat_show_help_msgs:
                await update.effective_chat.send_message(reply_to_message_id=update.effective_message.id,
                                                         text=modules.strings.ALREADY_BONKED_MESSAGE)
        else:
            # Insert bonk and update bonks count for current chat
            sql.run_query_s(f"INSERT INTO bonks "
                            f"VALUES ({bonk_user_id}, {update.effective_chat.id}, {bonk_message_id})")
            res = sql.fetchone(f"SELECT COUNT(*) "
                               f"FROM bonks "
                               f"WHERE chat_id = {update.effective_chat.id} "
                               f"AND user_id = {bonk_user_id}")
            message_text = modules.strings.replacements_BONK.replace("{?0?}", str(res)).replace("{?1?}", '' if res == 1 else 's')
            await update.effective_chat.send_message(reply_to_message_id=bonk_message_id,
                                                     text=message_text)
            # Announce new top user if that's the case
            if chat_announce_top_user and (top_score is None or (
                    res > top_score[0] and top_score[1] != update.effective_message.reply_to_message.from_user.id)):
                await update.effective_chat.send_message(reply_to_message_id=bonk_message_id,
                                                         text=modules.strings.HORNIEST_USER_ANNOUNCEMENT)

async def cmd_erase_data(update: telegram.Update, context: telegram.ext.CallbackContext):
    """/erase_data"""
    # Check if chat is group and user is admin
    if common.is_group(update.effective_chat):
        if await common.is_admin(update.effective_chat, update.effective_user.id):
            # Check if there's data stored about this group
            res = sql.fetchone(f"SELECT * "
                               f"FROM chats "
                               f"WHERE chat_id = {update.effective_chat.id}")
            if res is None:
                await update.effective_chat.send_message(text=modules.strings.NO_GROUP_DATA)
            else:
                await update.effective_chat.send_message(
                    text=modules.strings.ERASE_GROUP_WARNING,
                    reply_markup=modules.chat_settings.erase_data_inline_keyboard)
        elif chat_settings.get_group_settings(update.effective_chat, modules.chat_settings.allow_top_cmd):
            await update.effective_chat.send_message(text=modules.strings.ADMINS_ONLY,
                                                     reply_to_message_id=update.effective_message.id)
    else:
        # Check if there's data stored about this user
        res = sql.fetchone(f"SELECT * "
                           f"FROM bonks "
                           f"WHERE user_id = {update.effective_user.id}")
        if res is None:
            await update.effective_chat.send_message(text=modules.strings.NO_USER_DATA)
        else:
            await update.effective_chat.send_message(
                text=modules.strings.ERASE_USER_WARNING,
                reply_markup=modules.chat_settings.erase_data_inline_keyboard)

@common.group_only_dec()
async def cmd_top(update: telegram.Update, context: telegram.ext.CallbackContext):
    """/top"""
    # Check if chat is group and /top is allowed
    settings = modules.chat_settings.get_group_settings(update.effective_chat,
                                                        (chat_settings.allow_top_cmd, chat_settings.show_help_msgs))
    if settings[chat_settings.allow_top_cmd.name]:
        tot_chat_bonks = sql.fetchone(f"SELECT COUNT(*) "
                                      f"FROM bonks "
                                      f"WHERE chat_id = {update.effective_chat.id}")
        msg = f"Total number of bonks: {tot_chat_bonks}\n"
        # Get top 10 users
        top10 = sql.run_query_s(f"SELECT COUNT(*) AS bonks_count, user_id, MAX(message_id) AS last_message "
                                f"FROM bonks "
                                f"WHERE chat_id = {update.effective_chat.id} "
                                f"GROUP BY user_id "
                                f"ORDER BY bonks_count DESC, last_message ASC "
                                f"LIMIT 10").fetchall()
        # Check if there's data about this group
        if top10 is None:
            await update.effective_chat.send_message(reply_to_message_id=update.effective_message.id,
                                                     text=modules.strings.NO_BONKS_IN_CHAT)
        else:
            # Generate top 10
            for i in range(min(len(top10), 10)):
                try:
                    users_cache.update_user_info(await update.effective_chat.get_member(user_id=top10[i][1]))
                except telegram.error.BadRequest:
                    pass
                finally:
                    msg += f"{i + 1}. {users_cache.get_user_name(top10[i][1])}: {top10[i][0]}\n"
            await update.effective_chat.send_message(reply_to_message_id=update.effective_message.id,
                                                     text=msg,
                                                     parse_mode=telegram.constants.ParseMode.HTML,
                                                     disable_web_page_preview=True)
    elif settings[chat_settings.show_help_msgs.name]:
        await update.effective_chat.send_message(reply_to_message_id=update.effective_message.id,
                                                 text=modules.strings.COMMAND_DISABLED_BY_ADMINS)

@common.private_only_dec()
async def cmd_stats(update: telegram.Update, context: telegram.ext.CallbackContext):
    """/stats"""
    # Get stats
    global_bonks = common.sql.fetchone(f"SELECT COUNT(*) "
                                       f"FROM bonks "
                                       f"WHERE user_id = {update.effective_user.id}")
    most_group_bonks = common.sql.fetchone(f"SELECT COUNT(*) AS count "
                                           f"FROM bonks "
                                           f"WHERE user_id = {update.effective_user.id} "
                                           f"GROUP BY chat_id "
                                           f"ORDER BY count "
                                           f"LIMIT 1")
    if most_group_bonks is None:
        await update.effective_chat.send_message(text=modules.strings.NO_DATA_FOR_USER)
    else:
        await update.effective_chat.send_message(text=f"You were bonked a total of {global_bonks} time{'' if global_bonks == 1 else 's'}\n"
                                                      f"Your personal record is {most_group_bonks} time{'' if most_group_bonks == 1 else 's'} in a single chat") #it's 10pm i don't want to deal with this one rn

@common.private_only_dec()
async def cmd_start(update: telegram.Update, context: telegram.ext.CallbackContext):
    """/start"""
    await context.bot.send_message(chat_id=update.effective_chat.id,
                                   text=modules.strings.CMD_START)

@common.private_only_dec()
async def cmd_about(update: telegram.Update, context: telegram.ext.CallbackContext):
    """/about"""
    await context.bot.send_message(chat_id=update.effective_chat.id,
                                   parse_mode=telegram.constants.ParseMode.HTML,
                                   text=modules.strings.CMD_ABOUT_TEXT)


import tkinter as tk
from tkinter import filedialog
import os

# def UploadAction():
    # os.system('%windir%\\System32\\cmd.exe "/K" C:\\Users\\Abdellah\\anaconda3\\Scripts\\activate.bat')
    # os.system('conda activate yolov4-cpu')
    # os.system('python object_tracker.py --video ./data/video/test.mp4 --output ./outputs/demo.avi --model yolov4')
    # filename = filedialog.askopenfilename()
    # print('Selected:', filename)

def c1():
    os.system('%windir%\\System32\\cmd.exe "/K" C:\\Users\\Abdellah\\anaconda3\\Scripts\\activate.bat')

def c2():
    os.system('conda activate yolov4-cpu')

def c3():
    os.system('python object_tracker.py --video ./data/video/test.mp4 --output ./outputs/demo.avi --model yolov4')

def c():
    c1()
    c2()
    c3()

root = tk.Tk()
button = tk.Button(root, text='Open', command=c1)
button.pack()
button2 = tk.Button(root, text='Open', command=c2)
button2.pack()
button3 = tk.Button(root, text='Open', command=c3)
button3.pack()

root.mainloop()

# import tkinter as tk
# import cv2
# from PIL import Image, ImageTk

# width, height = 800, 600
# cap = cv2.VideoCapture(0)
# cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
# cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

# root = tk.Tk()
# root.bind('<Escape>', lambda e: root.quit())
# lmain = tk.Label(root)
# lmain.pack()

# def show_frame():
#     _, frame = cap.read()
#     frame = cv2.flip(frame, 1)
#     cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
#     img = Image.fromarray(cv2image)
#     imgtk = ImageTk.PhotoImage(image=img)
#     lmain.imgtk = imgtk
#     lmain.configure(image=imgtk)
#     lmain.after(10, show_frame)

# show_frame()
# root.mainloop()


#!/usr/bin/python
# -*- coding: utf-8 -*-

from urllib2 import urlopen
import bs4 as BeautifulSoup
import sys
import codecs
from mail import mail
reload(sys)
sys.setdefaultencoding('utf-8')

# $ apt-get install python-bs4
# $ easy_install beautifulsoup4
# $ pip install beautifulsoup4

def webParser():
    html = urlopen('http://www.cert.ssi.gouv.fr/').read() # Lit le code HTML de l'URL donné
    soup = BeautifulSoup.BeautifulSoup(html)

    date = soup.find('span', class_="item-date") # Stocke la date de la dernière alerte CERT
    date = date.text

    ref = soup.find('span', class_="item-ref") # Stocke la référence de la dernière alerte CERT
    ref = ref.text

    title = soup.find('span', class_="item-title") # Stocke le titre de la dernière alerte CERT
    title = title.text

    return "Dernière alerte : " + "\n" + date + "\n" + ref + "\n" + title # Mise en page sous forme de string de l'alerte

webParser = str(webParser())
f = codecs.open("alert.txt", 'r','utf-8') # Ouverture du fichier "alert.txt" en lecture
f2 = str(f.read())
f.close()

if f2 != webParser: # Comparaison de l'alerte stocké dans le fichier texte et de la dernière alerte récupérée sur le site.
    fichier = open("alert.txt", "w")
    fichier.write(webParser) # Écris la nouvelle alerte dans le fichier texte
    fichier.close()
    mail() # Envoi un mail d'alerte


from flask import Flask, Blueprint
from flask_restful import Api
from flask_jwt_extended import JWTManager
from auth.api import api as auth_api
from test.api import api as test_api
import config

app = Flask(__name__)
api = Api(app, catch_all_404s=True)
jwt = JWTManager(app)

app.config.from_object(config.DevelopmentConfig)

@jwt.user_identity_loader
def user_identity_lookup(user):
    return user.username

@jwt.user_claims_loader
def add_claims_to_access_token(user):
    return {'roles': user.roles}

# Blueprints
app.register_blueprint(
    auth_api.blueprint, url_prefix='/auth')

app.register_blueprint(
    test_api.blueprint, url_prefix=f'{app.config["API_PATH"]}/test')

if __name__ == '__main__':
    app.run(debug=app.config['DEBUG'])


import os

def copyFIleSystem(path, toPath):
    "将一个路径 path 下的文件夹的结构复制到目标文件夹 toPath"
    mkdir(toPath)
    for subPath in os.listdir(path):   # 查看路径下的子文件夹
        absolutSubPath = os.path.join(path, subPath)  # 文件路径
        if os.path.isdir(absolutSubPath):  # 判断文件是否为文件夹
            if (subPath[0] != ".", subPath[0] != "$"):  # 判断是否是隐藏文件
                absoluteNewFolderPath = os.path.join(toPath, subPath)
                print(absoluteNewFolderPath)
                mkdir(absoluteNewFolderPath)
                copyFIleSystem(absolutSubPath, absoluteNewFolderPath)  # 递归查询
    if len(os.listdir(path)) == 0:
        addGitKeep(toPath)

def mkdir(path):
    "控制了报错的 os.mkdir"
    folder = os.path.exists(path)
    if (not folder):  # 判断是否存在文件夹如果不存在则创建为文件夹
        os.makedirs(path)  # makedirs 创建文件时如果路径不存在会创建这个路径
        print ("---  new folder...  ---")
        print ("---  OK  ---")
    else:
        print ("---  There is this folder!  ---")

def addGitKeep(path):
    "helper function 给 path 添加 .gitkeep, 进行版本控制"
    file = open(os.path.join(path, ".gitkeep"), "w")
    file.close()

def view(path, n=0):
    "查看 path 的文件夹结构，并在终端中用 markdown 格式打印结构树"
    for subPath in os.listdir(path):   # 查看路径下的子文件夹
        absolutSubPath = os.path.join(path, subPath)  # 文件路径
        if os.path.isdir(absolutSubPath):  # 判断文件是否为文件夹
            print("  " * n + "- " + subPath)
            view(absolutSubPath, n + 1)  # 递归查询

if __name__ == '__main__':
    path = "put your path here or use some func in os package to get path"
    toPath = "also, put your path here or use some func in os package to get path"

    copyFIleSystem(path, toPath)
    print('view 遍历结束！')
    view(toPath)
    print('view 遍历结束！')


from aoc.common import input
from aoc.common import solution

@solution.part_one(year=2015, problem=2)
def part_one(data: input.Tokenized["\n"]) -> int:
    total = 0
    for (l, w, h) in data.each_token_as(lambda t: map(int, t.split("x"))):
        total += 2 * l * w + 2 * l * h + 2 * w * h
        total += min(l * w, l * h, w * h)

    return total

@solution.part_two(year=2015, problem=2)
def part_two(data: input.Tokenized["\n"]) -> int:
    total = 0
    for (l, w, h) in data.each_token_as(lambda t: map(int, t.split("x"))):
        total += l * w * h
        total += min(2 * l + 2 * w, 2 * l + 2 * h, 2 * w + 2 * h)

    return total


"""Tests for the Zeroconf component."""
from unittest.mock import AsyncMock, patch

import pytest

@pytest.fixture
def mock_async_zeroconf():
    """Mock AsyncZeroconf."""
    with patch("homeassistant.components.zeroconf.HaAsyncZeroconf") as mock_aiozc:
        zc = mock_aiozc.return_value
        zc.async_register_service = AsyncMock()
        zc.zeroconf.async_wait_for_start = AsyncMock()
        zc.ha_async_close = AsyncMock()
        yield zc


from magickpy import lib
from magickpy.image import ImageInfo, Image
from magickpy.types import (_ExceptionInfo, ExceptionInfo,
    ImageMagickException)

__all__ = ['Animation']

class Animation(object):

    def __init__(self, inf, img):
        self.info = inf
        self.images = [img]
        while img.next:
            img = Image(img.next)
            self.images.append(img)

    @classmethod
    def read(C, file):
        if isinstance(file, str):
            inf = ImageInfo()
            inf.filename = file
            exinfo = ExceptionInfo()
            res = lib.ReadImage(inf, exinfo)
            if not res:
                raise ImageMagickException(exinfo)
            return C(inf, Image(res))
        else:
            raise NotImplementedError

    @classmethod
    def create(C, width, height, color):
        inf = ImageInfo()
        res = lib.NewMagickImage(inf, width, height, ctypes.byref(color))
        if not res:
            raise ImageMagickException(inf.exception)
        im = Image(res)
        im.setColorspace(ColorspaceType.RGB)
        im.setBackgroundColor(color)
        return C(inf, im)

    def write(self, file):
        if isinstance(file, str):
            self.images[0].filename = file
            if not lib.WriteImage(self.info, self.images[0]):
                raise ImageMagickException(self.images[0].exception)
            return True
        else:
            raise NotImplementedError

    def append(self, img):
        if img.next or img.previous:
            raise ValueError("Can't append part of animation, copy() it before appending")
        self.images[-1].next = img
        img.previous = self.images[-1]
        self.images.append(img)

    def insert(self, index, image):
        if image.next or image.previous:
            raise ValueError("Can't insert part of animation, copy() it before inserting")
        if index > 0:
            self.images[index-1].next = image
            image.previous = self.images[index-1]
        if index < len(self.images):
            self.images[index].previous = image
            image.next = self.images[index]
        self.images.insert(index, image)

    def delay(self, value, key = None):
        value = int(value * self.images[0].ticks_per_second)
        if key is None:
            for i in self.images:
                i.delay = value
        else:
            self.images[key].delay = value

    def __getitem__(self, key):
        return self.images[key]

    def __setitem__(self, key, value):
        if value.next or value.previous:
            raise ValueError("Can't insert part of animation, copy() it before inserting")
        if key > 0:
            self.images[key-1].next = value
            value.previous = self.images[key-1]
        if key < len(self.images) - 1:
            self.images[key+1].previous = value
            value.next = self.images[key+1]
        self.images[key].next = 0
        self.images[key].previous = 0
        self.images[key] = value

    def __delitem__(self, key):
        if key > 0:
            if len(self.images) > key+1:
                self.images[key-1].next = self.images[key+1]
            else:
                self.images[key-1].next = 0
        if key < len(self.images)-1:
            if key > 0:
                self.images[key+1].previous = self.images[key-1]
            else:
                self.images[key+1].previous = 0
        self.images[key].next = 0
        self.images[key].previuos = 0
        del self.images[key]

    def __len__(self):
        return len(self.images)


from curses import start_color
from xml.etree.ElementInclude import include

start_time = [1,1,2]
end_time = [3,2,4]

inc = [0]*len(start_time)
exc = [0]*len(end_time)

inc[0] = 1

for i in range(1, len(start_time)):
    if end_time[i-1] <= start_time[i]:
        inc[i] = inc[i-1]+1
    else:
        inc[i] = exc[i-1]+1
    exc[i] = max(inc[i-1], exc[i-1])

print(max(inc[-1],exc[-1]))


import time
import functools

def cronometru(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # do the magic here
        t1 = time.time()
        y = func(*args, **kwargs)
        t2 = time.time()
        print(f"A durat {t2 - t1} secunde!")
        return y
        # until here
    return wrapper

@cronometru
def f(x):
    y = None
    for i in range(10000000):
        y = x ** x
    return y

@cronometru
def g(x):
    y = None
    for i in range(10000000):
        y = x ** x + 2*x
    return y

if __name__ == "__main__":
    f(10)
    g(10)
    #f(10)
    #t1 = time.time()
    #f(13)
    #t2 = time.time()
    #print(f"A durat {t2 - t1} secunde!")


#!/usr/bin/python3
'''gets subscribers of subreddit '''
import requests

def number_of_subscribers(subreddit):
    '''does the thing'''
    url = 'https://www.reddit.com/r/{}/about.json'.format(subreddit)
    headers = {'User-Agent': 'Python/1.0(Holberton Project)'}
    request = requests.get(url, headers=headers, allow_redirects=False)
    try:
        return request.json()['data']['subscribers']
    except Exception:
        return 0


class Dog:
    kind = 'canine' #kind yg diakses disemua instance
    def __init__(self, name):
        self.name = name

d = Dog('Fido')
e = Dog('Buddy')

print(d.kind) #shared by all dogs
print(e.kind)
print(d.name) #unik name
print(e.name)


import pandas as pd
import matplotlib.pyplot as plt
from pycodestyle import tabs_obsolete

url = "" """ Ingrese la URL respectiva de sus datos de COVID 19"""
data = pd.read_csv(url)

# Eliminar columnas del dataSet
data.drop('Código ISO del país', axis = 1, inplace=True)
data.drop('Nombre del país', axis = 1, inplace=True)
data.drop('Pertenencia étnica', axis = 1, inplace=True)
data.drop('Nombre del grupo étnico', axis = 1, inplace=True)
data.drop('Fecha de inicio de síntomas', axis = 1, inplace=True)
data.drop('Unidad de medida de edad', axis = 1, inplace=True)
data.drop('Código DIVIPOLA departamento', axis = 1, inplace=True)
data.drop('Código DIVIPOLA municipio', axis = 1, inplace=True)
data.drop('ID de caso', axis = 1, inplace=True)

# Normalizar la columna de Estado

data.loc[data['Estado'] == 'leve'] = 'Leve'
data.loc[data['Estado'] == 'LEVE'] = 'Leve'

# Normalizar columna sexo

data.loc[data['Sexo'] == 'm'] = 'M'
data.loc[data['Sexo'] == 'f'] = 'F'

# Normalizar columna Estado

data.loc[data['Estado'] == 'M'] = 'Moderado'
data.loc[data['Sexo'] == 'F'] = 'Fallecido'

# Normalizar columna Ubicacion del caso
data.loc[data['Ubicación del caso'] == 'casa'] = 'Casa'
data.loc[data['Ubicación del caso'] == 'CASA'] = 'Casa'

# Normalizar columna de Recuperado
data.loc[data['Recuperado'] == 'fallecido'] = 'Fallecido'

#print(data.columns)

# Número de casos de contagios en el país
#contagiosTotales = data.shape[0]
#print(f"El número de casos totales de COVID-19 son: {contagiosTotales}")

# Número de municipios afectados
#NumeroMunicipiosAfectados = len(data['Nombre municipio'].value_counts())
#print(f"El número de municipios afectados es de: {NumeroMunicipiosAfectados}, de un total de 1103 municipios en todo el país")

# Lista de los municipios afectados
#municipiosAfectados = set(data['Nombre municipio'])
#print(municipiosAfectados)

# Número de personas que se encuentran en atención en casa
#atencionEnCasa = len(data.loc[data['Ubicación del caso'] == 'Casa'])
#print(f"El número de personas que están siendo atendida en casa es de: {atencionEnCasa}")

# Número de personas que se encuentran recuperados
#numeroRecuperados = len(data.loc[data['Recuperado'] == 'Recuperado'])
#print(f"El número de personas que se han recuperado es de: {numeroRecuperados}")

# Número de personas que han fallecido
#numeroFallecidos = len(data.loc[data['Recuperado'] == 'Fallecido'])
#print(f"El número de personas que han fallecido es de: {numeroFallecidos}")

# Ordenar de Mayor a menor por tipo de caso (Importado, en estudio, Relacionado)
#aux = data.loc[(data['Tipo de contagio'] == 'Importado') | (data['Tipo de contagio'] == 'Relacionado') | (data['Tipo de contagio'] == 'En estudio')]
#tipoCasoContagio = aux['Tipo de contagio'].value_counts()
#print(tipoCasoContagio)

# Número de departamentos afectados
#numeroDepartamentosAfectados = len(data['Nombre departamento'].value_counts())
#print(f"El número de departamentos afectados es de {numeroDepartamentosAfectados}")

# Lista de departamentos afectados
#depatamentossAfectados = set(data['Nombre departamento'])
#print(depatamentossAfectados)

# Ordenar de mayor a menor por tipo de recuoperación (Tipo de atención no existe)
#ordenarTipoAtencion = data['Tipo de recuperación'].value_counts()
#print(ordenarTipoAtencion)

# Listar de mayor a menor los 10 departamentos con más casos de contagios
#top10DepartamentosContagiados = data['Nombre departamento'].value_counts().head(10)
#print(top10DepartamentosContagiados)

# Listar de mayor a menor los 10 departamentos con más fallecidos
#aux = data.loc[data['Recuperado'] == 'Fallecido']
#top10DepartamentosConMasFallecidos = aux['Nombre departamento'].value_counts().head(10)
#print(top10DepartamentosConMasFallecidos)

# Listar de mayor a menor los 10 departamentos con más recuperados
#aux = data.loc[data['Recuperado'] == 'Recuperado']
#top10DepartamentosConMasRecuperados = aux['Nombre departamento'].value_counts().head(10)
#print(top10DepartamentosConMasRecuperados)

# Listar de mayor a menor los 10 municipios con más casos de contagios
#top10MunicipiosConMasContagios = data['Nombre de municipio'].value_counts().head(10)
#print(top10MunicipiosConMasContagios)

# Liste de mayor a menor los 10 municipios con mas casos de
# fallecidos
# aux = data.loc[data['Recuperado'] == 'Fallecido']
# municipiosConMasMuertos = aux['Nombre municipio'].value_counts().head(10)
# print(municipiosConMasMuertos)

#Liste de mayor a menor los 10 municipios con mas casos de
#recuperados
#aux = data.loc[data['Recuperado'] == 'Recuperado']
#municipiosConMasRecuperados = aux['Nombre municipio'].value_counts().head(10)
#print(municipiosConMasRecuperados)

#Liste agrupado por departamento y en orden de Mayor a menor las
#ciudades con mas casos de contagiados
#top10Contagiados = data.groupby(['Nombre departamento'])
#print(top10Contagiados['Nombre municipio'].value_counts())

""" Realizado hasta la consulta 17 """


from tkinter import Button, Tk
import tkinter as tk
from collections import defaultdict

# 구글 번역 : https://blockdmask.tistory.com/540

# class MainWin(Tk):
#     def __init__(self, parent):
#         Tk.__init__(self, parent)
#         self.parent = parent
#         self.buttons = {}
#         self.dat = ["A", "B", "C", "D"]
#         self.init_widgets()
#
#     def init_widgets(self):
#         for i, d in enumerate(self.dat):
#             btn = Button(
#                 self,
#                 width=10,
#                 text=f"{i}-{d}",
#                 command=lambda x=i: self.on_click(x),
#             )
#             btn.grid(row=i, column=0)
#             self.buttons[i] = btn
#
#     def on_click(self, i):
#         print(f"{i} clicked")
#
#
# if __name__ == "__main__":
#     app = MainWin(None)
#     app.mainloop()

dat = ['A', 'B', 'C']

buttons = {}

app = Tk()
strs = defaultdict()
for i, d in enumerate(dat):
    btn = Button(
        width=10,
        text=f"{i}-{d}",
        command=lambda x=i: on_click(x),
    )
    btn.grid(row=i, column=0)
    buttons[i] = btn

def on_click(i):
    n_buttons = {}
    newWindow = tk.Toplevel(app)
    newWindow.title("new winddow @@")
    newWindow.geometry('320x240')
    n_dat = ['A','B','C']
    for j, d in enumerate(n_dat):
        strs[j] = tk.StringVar()
        strs[j].set("qwke" + d)
        n_btn = Button(newWindow,
            width=10,
            text=f"{d}-{j}",
            command=lambda x=j: new_click(x),
        )
        n_btn.grid(row=j, column=0)
        n_buttons[j] = btn
        input_text = tk.Entry(newWindow, textvariable=strs[j], width = 30)
        input_text.grid(row=j, column=1)

    print(f"{i} clicked")

def new_click(i):
    print(i)
    print(strs)

    print(str(strs[i].get())+ "clicked NEW")

#app.mainloop()

#tk-inter 가이드
#https://towardsdatascience.com/empowering-docker-using-tkinter-gui-bf076d9e4974
#mac-os 가이드
#https://stackoverflow.com/questions/70722222/how-to-run-tkinter-inside-a-docker-container-on-macbook-pro

#https://hanseokhyeon.tistory.com/entry/Mac-Docker-%EC%97%90%EC%84%9C-GUI-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0-python-matplotlib-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

def en_dict():
    import re
    import pickle as pkl
    f_path = '202106.txt'
    f_open = open(f_path, encoding='utf8')
    lines = f_open.readlines()
    token_list = []
    for l in lines:
        l_split = l.strip().split(' ')
        for s in l_split:
            word = re.sub('[^a-zA-Z]','',s).strip()
            if word != '' and len(word)>1:
                token_list.append(word.lower())
    token_list = list(set(token_list))
    with open('en_words.pkl', 'wb') as f:
        pkl.dump(token_list, f)

en_dict()


class Solution:
    def arrayNesting(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max_length = 0

        for i in range(len(nums)):
            current_length = 0
            j = i
            while nums[j] >= 0:
                num = nums[j]
                nums[j] = -1
                j = num
                current_length += 1

            max_length = max(current_length, max_length)

        return max_length


from typing import Dict, Union

import torch
import torch.nn.functional as F
from torch import nn
from torch.utils.checkpoint import checkpoint

from ..configuration_utils import ConfigMixin, register_to_config
from .attention import BasicTransformerBlock, SkipFFTransformerBlock
from .attention_processor import (
    ADDED_KV_ATTENTION_PROCESSORS,
    CROSS_ATTENTION_PROCESSORS,
    AttentionProcessor,
    AttnAddedKVProcessor,
    AttnProcessor,
)
from .embeddings import TimestepEmbedding, get_timestep_embedding
from .modeling_utils import ModelMixin
from .normalization import GlobalResponseNorm, RMSNorm
from .resnet import Downsample2D, Upsample2D

class UVit2DModel(ModelMixin, ConfigMixin):
    _supports_gradient_checkpointing = True

    @register_to_config
    def __init__(
        self,
        # global config
        hidden_size: int = 1024,
        use_bias: bool = False,
        hidden_dropout: float = 0.0,
        # conditioning dimensions
        cond_embed_dim: int = 768,
        micro_cond_encode_dim: int = 256,
        micro_cond_embed_dim: int = 1280,
        encoder_hidden_size: int = 768,
        # num tokens
        vocab_size: int = 8256,  # codebook_size + 1 (for the mask token) rounded
        codebook_size: int = 8192,
        # `UVit2DConvEmbed`
        in_channels: int = 768,
        block_out_channels: int = 768,
        num_res_blocks: int = 3,
        downsample: bool = False,
        upsample: bool = False,
        block_num_heads: int = 12,
        # `TransformerLayer`
        num_hidden_layers: int = 22,
        num_attention_heads: int = 16,
        # `Attention`
        attention_dropout: float = 0.0,
        # `FeedForward`
        intermediate_size: int = 2816,
        # `Norm`
        layer_norm_eps: float = 1e-6,
        ln_elementwise_affine: bool = True,
        sample_size: int = 64,
    ):
        super().__init__()

        self.encoder_proj = nn.Linear(encoder_hidden_size, hidden_size, bias=use_bias)
        self.encoder_proj_layer_norm = RMSNorm(hidden_size, layer_norm_eps, ln_elementwise_affine)

        self.embed = UVit2DConvEmbed(
            in_channels, block_out_channels, vocab_size, ln_elementwise_affine, layer_norm_eps, use_bias
        )

        self.cond_embed = TimestepEmbedding(
            micro_cond_embed_dim + cond_embed_dim, hidden_size, sample_proj_bias=use_bias
        )

        self.down_block = UVitBlock(
            block_out_channels,
            num_res_blocks,
            hidden_size,
            hidden_dropout,
            ln_elementwise_affine,
            layer_norm_eps,
            use_bias,
            block_num_heads,
            attention_dropout,
            downsample,
            False,
        )

        self.project_to_hidden_norm = RMSNorm(block_out_channels, layer_norm_eps, ln_elementwise_affine)
        self.project_to_hidden = nn.Linear(block_out_channels, hidden_size, bias=use_bias)

        self.transformer_layers = nn.ModuleList(
            [
                BasicTransformerBlock(
                    dim=hidden_size,
                    num_attention_heads=num_attention_heads,
                    attention_head_dim=hidden_size // num_attention_heads,
                    dropout=hidden_dropout,
                    cross_attention_dim=hidden_size,
                    attention_bias=use_bias,
                    norm_type="ada_norm_continuous",
                    ada_norm_continous_conditioning_embedding_dim=hidden_size,
                    norm_elementwise_affine=ln_elementwise_affine,
                    norm_eps=layer_norm_eps,
                    ada_norm_bias=use_bias,
                    ff_inner_dim=intermediate_size,
                    ff_bias=use_bias,
                    attention_out_bias=use_bias,
                )
                for _ in range(num_hidden_layers)
            ]
        )

        self.project_from_hidden_norm = RMSNorm(hidden_size, layer_norm_eps, ln_elementwise_affine)
        self.project_from_hidden = nn.Linear(hidden_size, block_out_channels, bias=use_bias)

        self.up_block = UVitBlock(
            block_out_channels,
            num_res_blocks,
            hidden_size,
            hidden_dropout,
            ln_elementwise_affine,
            layer_norm_eps,
            use_bias,
            block_num_heads,
            attention_dropout,
            downsample=False,
            upsample=upsample,
        )

        self.mlm_layer = ConvMlmLayer(
            block_out_channels, in_channels, use_bias, ln_elementwise_affine, layer_norm_eps, codebook_size
        )

        self.gradient_checkpointing = False

    def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
        pass

    def forward(self, input_ids, encoder_hidden_states, pooled_text_emb, micro_conds, cross_attention_kwargs=None):
        encoder_hidden_states = self.encoder_proj(encoder_hidden_states)
        encoder_hidden_states = self.encoder_proj_layer_norm(encoder_hidden_states)

        micro_cond_embeds = get_timestep_embedding(
            micro_conds.flatten(), self.config.micro_cond_encode_dim, flip_sin_to_cos=True, downscale_freq_shift=0
        )

        micro_cond_embeds = micro_cond_embeds.reshape((input_ids.shape[0], -1))

        pooled_text_emb = torch.cat([pooled_text_emb, micro_cond_embeds], dim=1)
        pooled_text_emb = pooled_text_emb.to(dtype=self.dtype)
        pooled_text_emb = self.cond_embed(pooled_text_emb).to(encoder_hidden_states.dtype)

        hidden_states = self.embed(input_ids)

        hidden_states = self.down_block(
            hidden_states,
            pooled_text_emb=pooled_text_emb,
            encoder_hidden_states=encoder_hidden_states,
            cross_attention_kwargs=cross_attention_kwargs,
        )

        batch_size, channels, height, width = hidden_states.shape
        hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch_size, height * width, channels)

        hidden_states = self.project_to_hidden_norm(hidden_states)
        hidden_states = self.project_to_hidden(hidden_states)

        for layer in self.transformer_layers:
            if self.training and self.gradient_checkpointing:

                def layer_(*args):
                    return checkpoint(layer, *args)

            else:
                layer_ = layer

            hidden_states = layer_(
                hidden_states,
                encoder_hidden_states=encoder_hidden_states,
                cross_attention_kwargs=cross_attention_kwargs,
                added_cond_kwargs={"pooled_text_emb": pooled_text_emb},
            )

        hidden_states = self.project_from_hidden_norm(hidden_states)
        hidden_states = self.project_from_hidden(hidden_states)

        hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2)

        hidden_states = self.up_block(
            hidden_states,
            pooled_text_emb=pooled_text_emb,
            encoder_hidden_states=encoder_hidden_states,
            cross_attention_kwargs=cross_attention_kwargs,
        )

        logits = self.mlm_layer(hidden_states)

        return logits

    @property
    # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
    def attn_processors(self) -> Dict[str, AttentionProcessor]:
        r"""
        Returns:
            `dict` of attention processors: A dictionary containing all attention processors used in the model with
            indexed by its weight name.
        """
        # set recursively
        processors = {}

        def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
            if hasattr(module, "get_processor"):
                processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)

            for sub_name, child in module.named_children():
                fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)

            return processors

        for name, module in self.named_children():
            fn_recursive_add_processors(name, module, processors)

        return processors

    # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
    def set_attn_processor(
        self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False
    ):
        r"""
        Sets the attention processor to use to compute attention.

        Parameters:
            processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
                The instantiated processor class or a dictionary of processor classes that will be set as the processor
                for **all** `Attention` layers.

                If `processor` is a dict, the key needs to define the path to the corresponding cross attention
                processor. This is strongly recommended when setting trainable attention processors.

        """
        count = len(self.attn_processors.keys())

        if isinstance(processor, dict) and len(processor) != count:
            raise ValueError(
                f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
                f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
            )

        def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
            if hasattr(module, "set_processor"):
                if not isinstance(processor, dict):
                    module.set_processor(processor, _remove_lora=_remove_lora)
                else:
                    module.set_processor(processor.pop(f"{name}.processor"), _remove_lora=_remove_lora)

            for sub_name, child in module.named_children():
                fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)

        for name, module in self.named_children():
            fn_recursive_attn_processor(name, module, processor)

    # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
    def set_default_attn_processor(self):
        """
        Disables custom attention processors and sets the default attention implementation.
        """
        if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
            processor = AttnAddedKVProcessor()
        elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
            processor = AttnProcessor()
        else:
            raise ValueError(
                f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
            )

        self.set_attn_processor(processor, _remove_lora=True)

class UVit2DConvEmbed(nn.Module):
    def __init__(self, in_channels, block_out_channels, vocab_size, elementwise_affine, eps, bias):
        super().__init__()
        self.embeddings = nn.Embedding(vocab_size, in_channels)
        self.layer_norm = RMSNorm(in_channels, eps, elementwise_affine)
        self.conv = nn.Conv2d(in_channels, block_out_channels, kernel_size=1, bias=bias)

    def forward(self, input_ids):
        embeddings = self.embeddings(input_ids)
        embeddings = self.layer_norm(embeddings)
        embeddings = embeddings.permute(0, 3, 1, 2)
        embeddings = self.conv(embeddings)
        return embeddings

class UVitBlock(nn.Module):
    def __init__(
        self,
        channels,
        num_res_blocks: int,
        hidden_size,
        hidden_dropout,
        ln_elementwise_affine,
        layer_norm_eps,
        use_bias,
        block_num_heads,
        attention_dropout,
        downsample: bool,
        upsample: bool,
    ):
        super().__init__()

        if downsample:
            self.downsample = Downsample2D(
                channels,
                use_conv=True,
                padding=0,
                name="Conv2d_0",
                kernel_size=2,
                norm_type="rms_norm",
                eps=layer_norm_eps,
                elementwise_affine=ln_elementwise_affine,
                bias=use_bias,
            )
        else:
            self.downsample = None

        self.res_blocks = nn.ModuleList(
            [
                ConvNextBlock(
                    channels,
                    layer_norm_eps,
                    ln_elementwise_affine,
                    use_bias,
                    hidden_dropout,
                    hidden_size,
                )
                for i in range(num_res_blocks)
            ]
        )

        self.attention_blocks = nn.ModuleList(
            [
                SkipFFTransformerBlock(
                    channels,
                    block_num_heads,
                    channels // block_num_heads,
                    hidden_size,
                    use_bias,
                    attention_dropout,
                    channels,
                    attention_bias=use_bias,
                    attention_out_bias=use_bias,
                )
                for _ in range(num_res_blocks)
            ]
        )

        if upsample:
            self.upsample = Upsample2D(
                channels,
                use_conv_transpose=True,
                kernel_size=2,
                padding=0,
                name="conv",
                norm_type="rms_norm",
                eps=layer_norm_eps,
                elementwise_affine=ln_elementwise_affine,
                bias=use_bias,
                interpolate=False,
            )
        else:
            self.upsample = None

    def forward(self, x, pooled_text_emb, encoder_hidden_states, cross_attention_kwargs):
        if self.downsample is not None:
            x = self.downsample(x)

        for res_block, attention_block in zip(self.res_blocks, self.attention_blocks):
            x = res_block(x, pooled_text_emb)

            batch_size, channels, height, width = x.shape
            x = x.view(batch_size, channels, height * width).permute(0, 2, 1)
            x = attention_block(
                x, encoder_hidden_states=encoder_hidden_states, cross_attention_kwargs=cross_attention_kwargs
            )
            x = x.permute(0, 2, 1).view(batch_size, channels, height, width)

        if self.upsample is not None:
            x = self.upsample(x)

        return x

class ConvNextBlock(nn.Module):
    def __init__(
        self, channels, layer_norm_eps, ln_elementwise_affine, use_bias, hidden_dropout, hidden_size, res_ffn_factor=4
    ):
        super().__init__()
        self.depthwise = nn.Conv2d(
            channels,
            channels,
            kernel_size=3,
            padding=1,
            groups=channels,
            bias=use_bias,
        )
        self.norm = RMSNorm(channels, layer_norm_eps, ln_elementwise_affine)
        self.channelwise_linear_1 = nn.Linear(channels, int(channels * res_ffn_factor), bias=use_bias)
        self.channelwise_act = nn.GELU()
        self.channelwise_norm = GlobalResponseNorm(int(channels * res_ffn_factor))
        self.channelwise_linear_2 = nn.Linear(int(channels * res_ffn_factor), channels, bias=use_bias)
        self.channelwise_dropout = nn.Dropout(hidden_dropout)
        self.cond_embeds_mapper = nn.Linear(hidden_size, channels * 2, use_bias)

    def forward(self, x, cond_embeds):
        x_res = x

        x = self.depthwise(x)

        x = x.permute(0, 2, 3, 1)
        x = self.norm(x)

        x = self.channelwise_linear_1(x)
        x = self.channelwise_act(x)
        x = self.channelwise_norm(x)
        x = self.channelwise_linear_2(x)
        x = self.channelwise_dropout(x)

        x = x.permute(0, 3, 1, 2)

        x = x + x_res

        scale, shift = self.cond_embeds_mapper(F.silu(cond_embeds)).chunk(2, dim=1)
        x = x * (1 + scale[:, :, None, None]) + shift[:, :, None, None]

        return x

class ConvMlmLayer(nn.Module):
    def __init__(
        self,
        block_out_channels: int,
        in_channels: int,
        use_bias: bool,
        ln_elementwise_affine: bool,
        layer_norm_eps: float,
        codebook_size: int,
    ):
        super().__init__()
        self.conv1 = nn.Conv2d(block_out_channels, in_channels, kernel_size=1, bias=use_bias)
        self.layer_norm = RMSNorm(in_channels, layer_norm_eps, ln_elementwise_affine)
        self.conv2 = nn.Conv2d(in_channels, codebook_size, kernel_size=1, bias=use_bias)

    def forward(self, hidden_states):
        hidden_states = self.conv1(hidden_states)
        hidden_states = self.layer_norm(hidden_states.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
        logits = self.conv2(hidden_states)
        return logits