InfoDb = []
# List with dictionary records placed in a list
InfoDb.append({
               "Name": "Connor",
               "FavoriteSport": "Football",
               "Team": "Broncos",
               "TopFoods":["Burger", "Sushi", "Sandwich"]
              })
InfoDb.append({
               "Name": "Jean",
               "FavoriteSport": "Basketball",
               "Team": "Magic",
               "TopFoods":["Pizza", "Hot Dogs", "Bacon"]
              })
InfoDb.append({
               "Name": "Nathan",
               "FavoriteSport": "Basketball",
               "Team": "Lakers",
               "TopFoods":["Noodles", "Rice", "Sushi"]
              })
InfoDb.append({
               "Name": "Paul",
               "FavoriteSport": "Football",
               "Team": "Lions",
               "TopFoods":["Pasta", "Pizza", "Turkey"]
              })
# for loop iterates on length of InfoDb
def print_data(n):
    print(InfoDb[n]["Name"], "loves", InfoDb[n]["FavoriteSport"], "and the", InfoDb[n]["Team"])  # using comma puts space between values
    print("\t", "Top 3 Foods: ", end="")  # \t is a tab indent, end="" make sure no return occurs
    print(", ".join(InfoDb[n]["TopFoods"]))  # join allows printing a string list with separator
    print("\t", "Favorite Food: ", end="")
    print(InfoDb[n].get("TopFoods")[0])
    print()
def for_loop():
    for n in range(len(InfoDb)):
        print_data(n)
# while loop contains an initial n and an index incrementing statement (n += 1)
def while_loop(n):
    while n < len(InfoDb):
        print_data(n)
        n += 1
    return
def recursive_loop(n):
    if n < len(InfoDb):
        print_data(n)
        recursive_loop(n + 1)
    return
def main():
  print("For loop")
  for_loop()
  print("While loop")
  while_loop(0)
  print("Recursive loop")
  recursive_loop(0)
# print data


from tkinter import *
from Python.ui import list_ui

def GUI(action=None):
    root = Tk()

    # Setter for Icons, Colors and Labels
    def set_icons():
        list_ui.GUI(action.icons)

    def set_colors():
        list_ui.GUI(action.colors)

    def set_labels():
        list_ui.GUI(action.labels)

    # 4 Labels
    topic = Label(root, text="Topic")
    icons = Label(root, text="Icons")
    colors = Label(root, text="Colors")
    labels = Label(root, text="Labels")

    topic.grid(column=0, row=0)
    icons.grid(column=0, row=1)
    colors.grid(column=0, row=2)
    labels.grid(column=0, row=3)

    # 3 Buttons
    button1 = Button(root, text="+", width=10, command=set_icons)
    button2 = Button(root, text="+", width=10, command=set_colors)
    button3 = Button(root, text="+", width=10, command=set_labels)

    button1.grid(column=3, row=1)
    button2.grid(column=3, row=2)
    button3.grid(column=3, row=3)

    # 2 Entry Fields
    entry1 = Entry(root)
    entry1.insert(END, action.topic)
    entry1.grid(column=3, row=0)

    # saving the values of client and topic for further use
    # then closes the window
    def save():
        action.client = action.client
        action.topic = entry1.get()

        root.destroy()

    root.protocol("WM_DELETE_WINDOW", save)

    root.mainloop()


import numpy as np

def GetResults_sub(sub, ind, H, H1, H0, M, S, NT):
    '''Get QALY and events results for a particular subset of the population'''
    IQALY = H1.QALY[sub] - H.QALY[sub]
    ILY = H1.LY[sub] - H.LY[sub]

    days = 365.25
    M[ind,0] = (H.QALY[sub]).mean() * days
    M[ind,1] = (H1.QALY[sub]).mean() * days
    M[ind,2] = IQALY.mean() * days

    M[ind,3] = (H.LY[sub]).mean() * days
    M[ind,4] = (H1.LY[sub]).mean() * days
    M[ind,5] = ILY.mean() * days

    S[ind,0] = (H.QALY[sub]).std() * days
    S[ind,1] = (H1.QALY[sub]).std() * days
    S[ind,2] = IQALY.std() * days
    S[ind,3] = (H.LY[sub]).std() * days
    S[ind,4] = (H1.LY[sub]).std() * days
    S[ind,5] = ILY.std() * days

    ## QALY and LY gains per health check
    nhcbase = H.Attending.sum()
    nhc = H1.Attending.sum()
    IQALYscen_no = H1.QALY[sub] - H0.QALY[sub] # scenario vs no HC
    IQALYbase_no = H.QALY[sub] - H0.QALY[sub]  # base case vs no HC
    miq_scenno = IQALYscen_no.sum() / nhc
    miq_baseno = 0 if (nhcbase==0) else IQALYbase_no.sum() / nhcbase
    M[ind,6] = (miq_scenno - miq_baseno)*days
    ILYscen_no = H1.LY[sub] - H0.LY[sub]
    ILYbase_no = H.LY[sub] - H0.LY[sub]
    mil_scenno = ILYscen_no.sum() / nhc
    mil_baseno = 0 if (nhcbase==0) else ILYbase_no.sum() / nhcbase
    M[ind,7] = (mil_scenno - mil_baseno)*days
    vscen = ((IQALYscen_no - miq_scenno)**2).sum() / nhc
    vbase = 0 if (nhcbase==0) else ((IQALYbase_no - miq_baseno)**2).sum() / nhcbase
    varM6 = vscen + vbase
    S[ind,6] = np.sqrt(varM6)*days
    vscen = ((ILYscen_no - miq_scenno)**2).sum() / nhc
    vbase = 0 if (nhcbase==0) else ((ILYbase_no - miq_baseno)**2).sum() / nhcbase
    varM7 = vscen + vbase
    S[ind,7] = np.sqrt(varM7)*days

#    IQALY.sum() / nhc * days
#    ILY.sum() / nhc * days
#    S[ind,6] = np.sqrt( ((IQALY - M[ind,6])*(IQALY - M[ind,6])).sum() / nhc ) * days
#    S[ind,7] = np.sqrt( ((ILY - M[ind,7])*(ILY - M[ind,7])).sum() / nhc ) * days

    H.dead = np.logical_not(H.alive)
    H1.dead = np.logical_not(H1.alive)

    # Total QALY gain (in years) for pop of one million
    M[ind,8] = IQALY.mean() * 1000000
    S[ind,8] = IQALY.std() * 1000000
    # Total LY gain (in years) for pop of one million
    M[ind,9] = ILY.mean() * 1000000
    S[ind,9] = ILY.std() * 1000000

    k = 10

    ## Counts of events by specific ages
    H.AnyEvent = (H.IHD + H.Stroke + H.Dementia + H.LungCancer) > 0
    H1.AnyEvent = (H1.IHD + H1.Stroke + H1.Dementia + H1.LungCancer) > 0
    outcomes = ['IHD', 'Stroke', 'Dementia', 'LungCancer', 'AnyEvent']
    ages = [80]
    for i in ages:
        for j in outcomes:
            exec('D = (H.%s * (H.age == %s)).sum(axis=1)' % (j, i))
            exec('D1 = (H1.%s * (H1.age == %s)).sum(axis=1)' % (j, i))
            M[ind,k] = (D[sub]).mean()
            M[ind,k+1] = (D1[sub]).mean()
            M[ind,k+2] = M[ind,k] - M[ind,k+1]
            S[ind,k] = (D[sub]).std()
            S[ind,k+1] = (D1[sub]).std()
            S[ind,k+2] = (D[sub] - D1[sub]).std()
            k = k+3

    ## event counts by end of the model, i.e. age 99. Everyone dies by age 100.
    prevage = np.column_stack((H.age[:,0]-1, H.age[:,:-1]))
    first99 = (H.age == 99) * (prevage == 98) # get around ages after 99 being labelled 99, don't understand why this was done
    for j in outcomes:
        exec('D = (H.%s * first99).sum(axis=1)' % (j))
        exec('D1 = (H1.%s * first99).sum(axis=1)' % (j))
        M[ind,k] = (D[sub]).mean()
        M[ind,k+1] = (D1[sub]).mean()
        M[ind,k+2] = M[ind,k] - M[ind,k+1]
        S[ind,k] = (D[sub]).std()
        S[ind,k+1] = (D1[sub]).std()
        S[ind,k+2] = (D[sub] - D1[sub]).std()
        k = k+3

    outcomes = ['dead']
    ages = [75, 80]
    for i in ages:
        for j in outcomes:
            exec('D = (H.%s * (H.age == %s)).sum(axis=1)' % (j, i))
            exec('D1 = (H1.%s * (H1.age == %s)).sum(axis=1)' % (j, i))
            M[ind,k] = (D[sub]).mean()
            M[ind,k+1] = (D1[sub]).mean()
            M[ind,k+2] = M[ind,k] - M[ind,k+1]
            S[ind,k] = (D[sub]).std()
            S[ind,k+1] = (D1[sub]).std()
            S[ind,k+2] = (D[sub] - D1[sub]).std()
            k = k+3

    if (ind>=4):
        NT[ind-4] = sub.sum()
    return M,S,NT

def GetResults_longterm(H, H1, H0, M, S, N):
    '''Define various subpopulations of interest and get their expected sizes, QALY and events results'''
    allpop = np.ones(H1.population_size, dtype=bool)
    ## eligible, offered, or attend at least once
    el = (H1.eligible.sum(axis=1)>0)
    hc_offered = (H1.OfferedHC.sum(axis=1)>0)
    att = (H1.Attending.sum(axis=1)>0)
    t_offered = (H1.OfferedTreatment.sum(axis=1)>0)

    ## Eligible for HC and for each kind of treatment at any time, using either Q>=20 or Q>=10
    el_trtq20 = ((H1.eligible * (H1.QRisk >= 20)).sum(axis=1) > 0)
    el_trtq10 = ((H1.eligible * (H1.QRisk >= 10)).sum(axis=1) > 0)
    el_bp = ((H1.eligible * (H1.q_sbp > 140)).sum(axis=1) > 0)
    el_bmi = ((H1.eligible * (H1.bmi >= 30)).sum(axis=1) > 0)
    el_sm = ((H1.eligible * (H1.q_smoke_cat>1)).sum(axis=1) > 0)
    el_trt20 = el_trtq20 + el_bp + el_bmi + el_sm
    el_trt10 = el_trtq10 + el_bp + el_bmi + el_sm

    ## Attending and eligible for each kind of treatment
    att_trtq20 = ((H1.Attending * (H1.QRisk >= 20)).sum(axis=1) > 0)
    att_trtq10 = ((H1.Attending * (H1.QRisk >= 10)).sum(axis=1) > 0)
    att_bp = ((H1.Attending * (H1.q_sbp > 140)).sum(axis=1) > 0)
    att_bmi = ((H1.Attending * (H1.bmi >= 30)).sum(axis=1) > 0)
    att_sm = ((H1.Attending * (H1.q_smoke_cat>1)).sum(axis=1) > 0)
    att_trt20 = att_trtq20 + att_bp + att_bmi + att_sm
    att_trt10 = att_trtq10 + att_bp + att_bmi + att_sm

    ## Most and least deprived quintile
    dep = (H1.SES == 5)
    ndep = (H1.SES == 1)

    stat_off = (H1.Statins_Offered.sum(axis=1)>0)
    aht_off = (H1.Hypertensives_Offered.sum(axis=1)>0)
    sc_off = (H1.SmokingCessation_Offered.sum(axis=1)>0)
    wr_off = (H1.WeightReduction_Offered.sum(axis=1)>0)
    stat = (H1.Statins.sum(axis=1)>0)
    aht = (H1.Hypertensives.sum(axis=1)>0)
    sc = (H1.SmokingCessation.sum(axis=1)>0)
    wr = (H1.WeightReduction.sum(axis=1)>0)
    nhc = H1.Attending.sum()

    NT = np.zeros(5, dtype=int) # unused in this function
    M, S, NT = GetResults_sub(allpop,     0, H, H1, H0, M, S, NT)
    M, S, NT = GetResults_sub(el,     1, H, H1, H0, M, S, NT)
    M, S, NT = GetResults_sub(att, 2, H, H1, H0, M, S, NT)
    M, S, NT = GetResults_sub(t_offered,  3, H, H1, H0, M, S, NT)
    M, S, NT = GetResults_sub(dep,        4, H, H1, H0, M, S, NT)
    M, S, NT = GetResults_sub(ndep,       5, H, H1, H0, M, S, NT)

    N[1] = el.sum()
    N[2] = att.sum()
    N[3] = t_offered.sum()
    N[4] = dep.sum()
    N[5] = ndep.sum()
    N[6] = el_trt20.sum()
    N[7] = el_trt10.sum()
    N[8] = att_trt20.sum()
    N[9] = att_trt10.sum()
    N[10] = stat_off.sum()
    N[11] = aht_off.sum()
    N[12] = sc_off.sum()
    N[13] = wr_off.sum()
    N[14] = stat.sum()
    N[15] = aht.sum()
    N[16] = sc.sum()
    N[17] = wr.sum()
    N[18] = nhc

    return M,S,N

def FirstHC(H1):
    ''' returns time when first HC occurs for each person'''
    FHC = np.zeros((H1.population_size), dtype=np.int) - 1
    for i in range(H1.population_size):
        try:
            FHC[i] = np.where(H1.Attending[i]==1)[0][0]
        except:
            pass # no attendance for this individual
    return FHC

def PostHCOuts(H, H1):
    ''' 10-year improvement in QRisk and other factors, given by HC '''
    att = H1.Attending.sum(axis=1)>0
    HC0 = FirstHC(H1)[att]
    HC10 = np.fmin(HC0 + 10, 69) # for oldest, censor 10 year improvement at max age.
    qcon =  H.QRisk[att, HC10] - H.QRisk[att, HC0]   # change in qrisk over 10 years, neg good, will be pos as increases with age
    qhc =   H1.QRisk[att, HC10] - H1.QRisk[att, HC0]
    qdiff = qhc - qcon                # lower change under hc, negative is good
    scon =  H.q_sbp[att, HC10] - H.q_sbp[att, HC0]
    shc =   H1.q_sbp[att, HC10] - H1.q_sbp[att, HC0]
    sdiff = shc - scon
    dcon =  H.dia[att, HC10] - H.dia[att, HC0]
    dhc =   H1.dia[att, HC10] - H1.dia[att, HC0]
    ddiff = dhc - dcon
    ccon =  H.chol[att, HC10] - H.chol[att, HC0]
    chc =   H1.chol[att, HC10] - H1.chol[att, HC0]
    cdiff = chc - ccon

    posthcmeans = [ qdiff.mean(), sdiff.mean(), ddiff.mean(), cdiff.mean() ]
    posthcsds = [ qdiff.std(), sdiff.std(), ddiff.std(), cdiff.std() ]

    return np.column_stack((posthcmeans, posthcsds))

def GetResults_paper(H, H1, H0, M, S, N, P):
    M, S, N = GetResults_longterm(H, H1, H0, M, S, N)
    P = PostHCOuts(H, H1)
    return M, S, N, P

def BaselineCharsSub(H, sub):
    '''Demographic characteristics of simulated population under base case'''

    return [
        np.bincount(H.gender[sub]).tolist(),  # 0 female 1 male
        np.bincount(H.eth[sub]).tolist(),
        np.bincount(H.SES[sub]).tolist(),
        np.bincount(H.educ[sub]).tolist(),
        [H.age[sub,0].mean(), np.percentile(H.age[sub,0], 25), np.percentile(H.age[sub,0], 75)],
        [H.QRisk[sub,0].mean(), np.percentile(H.QRisk[sub,0], 25), np.percentile(H.QRisk[sub,0], 75)],
        [(H.QRisk[sub,0]>=20).sum()],
        [np.logical_and(H.QRisk[sub,0]>=10, H.QRisk[sub,0]<20).sum()],
        [H.q_sbp[sub,0].mean(), np.percentile(H.q_sbp[sub,0], 25), np.percentile(H.q_sbp[sub,0], 75)],
        [H.dia[sub,0].mean(), np.percentile(H.dia[sub,0], 25), np.percentile(H.dia[sub,0], 75)],
        [np.logical_or(H.q_sbp[sub,0]>=140, H.dia[sub,0]>=90).sum()],
        [H.q_b_treatedhyp[sub,0].sum()],
        [H.chol[sub,0].mean(), np.percentile(H.chol[sub,0], 25), np.percentile(H.chol[sub,0], 75)],
        [H.q_rati[sub,0].mean(), np.percentile(H.q_rati[sub,0], 25), np.percentile(H.q_rati[sub,0], 75)],
        [H.bmi[sub,0].mean(), np.percentile(H.bmi[sub,0], 25), np.percentile(H.bmi[sub,0], 75)],
        [(H.bmi[sub,0]>=30).sum()],
        [H.glyhb[sub,0].mean(), np.percentile(H.glyhb[sub,0], 25), np.percentile(H.glyhb[sub,0], 75)],
        [(H.glyhb[:,0]>=6.5).sum()],
        [H.diabetes[sub,0].sum()],
        np.bincount(H.q_smoke_cat[sub,0]).tolist()
    ]

def BaselineChars(H1):
    '''Demographic characteristics of simulated population at baseline, all population and specific subsets'''
    allpop = np.ones(H1.population_size, dtype=bool)
    base_all = BaselineCharsSub(H1, allpop)

    ## People who are eligible for HC at any time
    el = H1.eligible.sum(axis=1)>0
    base_el = BaselineCharsSub(H1, el)

    ## People who go on to attend HC, still at baseline
    att = H1.Attending.sum(axis=1)>0
    base_att = BaselineCharsSub(H1, att)

    flatten = lambda l: [item for sublist in l for item in sublist]
    return np.column_stack((flatten(base_all), flatten(base_el), flatten(base_att)))


#базовый класс
class Title():
    def __init__(self, title = ''):
        self.__title = title
#ограничиваем создание произвольных атрибутов
    @property
    def title(self):
        return self.__title
    @title.setter
    def title(self, title):
        self.__title = title

class Product(Title):
    def __init__(self, title, calorific = 1, cost = 1):
        Title.__init__(self, title)
#Проверяем не является ли цена, или каллорийность отрицательным числом
        if (cost or calorific) <= 0:
            raise ValueError
        self.__calorific = calorific
        self.__cost = cost
#ограничиваем создание произвольных атрибутов

    @property
    def calorific(self):
        return self.__calorific

    @calorific.setter
    def calorific(self, calorific):
        if calorific <= 0:
            raise ValueError
        self.__calorific = calorific

    @property
    def cost(self):
        return self.__cost

    @cost.setter
    def cost(self, cost):
        if cost <= 0:
            raise ValueError
        self.__cost = cost

class Ingredient:
    def __init__(self, product = [], weight = 1):
        self.__product = product
#Проверяем не является ли вес, отрицательным числом
        if weight <= 0:
            raise ValueError
        self.__weight = weight
#ограничиваем создание произвольных атрибутов
    @property
    def product(self):
        return self.__product
    @product.setter
    def product(self, product):
        self.__product = product

    @property
    def  weight(self):
        return self.__weight

    @weight.setter
    def weight(self, weight):
        if  weight <= 0:
            raise ValueError
        self.__weight =  weight

#Находим общее количество каллорий всех продуктов
    @property
    def сalories(self):
        сalories = 0
        for element in self.product:
            сalories +=  element.calorific
        return (self.weight / 100) *  сalories

#Находим общую стоймость всех продуктов
    @property
    def cost(self):
        money = 0
        for element in self.product:
            money += element.cost
        return (self.weight / 100) * money

class Pizza(Title):
    def __init__(self, title, ingredients = []):
        Title.__init__(self, title)
        self.__ingredients = ingredients

#ограничиваем создание произвольных атрибутов
    @property
    def ingredients(self):
        return self.__ingredients
    @ingredients.setter
    def ingredients(self, ingredients):
        self.__ingredients = ingredients

#Получаем каллорийность пиццы
    @property
    def сalories(self):
        сalories = 0
        for element in self.ingredients:
            сalories += element.сalories
        return float(сalories)
#Получаем стоимость пиццы
    @property
    def сost(self):
        money = 0
        for self.element in self.ingredients:
            money = money + self.element.cost
        return float(money)

    def __str__(self):
        return f'{self.title} ({self.сalories} kkal) - {self.сost} руб'

# Создаем продукты с указанием названия, калорийности продукта и его себестоимости
#список продуктов
dough_product = Product('Тесто', 200, 20)
water_product = Product('Вода', 5, 20)
salt_product = Product('Соль', 20, 10)

potatoes_product = Product('Картофель', 120, 30)
tomato_product = Product('Помидоры', 100, 50)
eggplant_product = Product('Баклажаны', 110, 40)

cheese_product = Product('Сыр', 100, 120)
mushrooms_product = Product('Грибы', 150, 40)
pepper_product = Product('Перец', 100, 10)

meat_product = Product('Мясо', 300, 100)
ham_product = Product('Ветчина', 250, 100)
sausage_product = Product('Колбаса', 200, 50)

# Из продуктов создаем ингредиенты. Для каждого ингредиента указываем продукт,
# из которого он состоит и вес продукта
foundation_ingredient = Ingredient([dough_product, water_product, salt_product], 150)
meat_ingredient = Ingredient([meat_product, ham_product, sausage_product], 200)
vegetables_ingredient = Ingredient([potatoes_product, tomato_product, eggplant_product], 200)
additives_ingredient = Ingredient([cheese_product, mushrooms_product, pepper_product], 180)

# Из ингредиентов создаем пиццу
pizza_margarita = Pizza('Маргарита', [meat_ingredient, foundation_ingredient, vegetables_ingredient, additives_ingredient])

print(pizza_margarita)


from urllib import request
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from .models import *
import json
# Create your views here.

class DepartamentoView(View):

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def get(self, request, id=0):
        if (id>0):
            departamentos=list(Departamento.objects.filter(id=id).values())
            if len(departamentos)>0:
                departamento = departamentos[0]
                datos={'message':'Success','departamento':departamento}
            else:
                datos={'message':'Departamento not found'}
            return JsonResponse(datos)
        else:
            departamentos=list(Departamento.objects.values())
            if len(departamentos)>0:
                datos={'message':'Success','departamento':departamentos}
            else:
                datos={'message':'Departamento not found'}
            return JsonResponse(datos)

    def post(self, request):
        jd = json.loads(request.body)
        Departamento.objects.create(name = jd['name'])
        datos={'message':'Success'}
        return JsonResponse(datos)

    def put(self,request, id):
        jd = json.loads(request.body)
        departamentos=list(Departamento.objects.filter(id=id).values())

        if len(departamentos)>0:
            departamento = Departamento.objects.get(id=id)
            departamento.name=jd['name']
            departamento.save()
            datos={'message':'Success'}
        else:
            datos={'message':'Departamento not found'}
        return JsonResponse(datos)

    def delete(self,request, id):
        departamento=list(Departamento.objects.filter(id=id).values())
        if len(departamento)>0:
            departamento.objects.filter(id=id).delete()
            datos={'message':'Success'}
        else:
            datos={'message':'Departamento not found'}
        return JsonResponse(datos)

class CiudadView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def get(self, request, id=0):
        if (id>0):
            ciudades=list(Ciudad.objects.filter(id=id).values())
            if len(ciudades)>0:
                ciudad = ciudades[0]
                datos={'message':'Success','ciudad':ciudad}
            else:
                datos={'message':'ciudad not found'}
            return JsonResponse(datos)
        else:
            ciudades=list(Ciudad.objects.values())
            if len(ciudades)>0:
                datos={'message':'Success','ciudades':ciudades}
            else:
                datos={'message':'ciudades not found'}
            return JsonResponse(datos)

    def post(self, request):
        jd = json.loads(request.body)
        departamento_id=jd['departemento']
        departamento = Departamento.objects.get(id=departamento_id)
        Ciudad.objects.create(name = jd['name'],departamento = departamento)
        datos={'message':'Success'}
        return JsonResponse(datos)

    def put(self,request, id):
        jd = json.loads(request.body)
        ciudades=list(Ciudad.objects.filter(id=id).values())

        if len(ciudades)>0:
            ciudad = Ciudad.objects.get(id=id)
            ciudad.name=jd['name']
            ciudad.departamento=jd['departamento']
            ciudad.save()
            datos={'message':'Success'}
        else:
            datos={'message':'ciudad not found'}
        return JsonResponse(datos)

    def delete(self,request, id):
        ciudad=list(Ciudad.objects.filter(id=id).values())
        if len(ciudad)>0:
            Ciudad.objects.filter(id=id).delete()
            datos={'message':'Success'}
        else:
            datos={'message':'ciudad not found'}
        return JsonResponse(datos)

class LocalidadView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def get(self, request, id=0):
        if (id>0):
            localidades=list(Localidad.objects.filter(id=id).values())
            if len(localidades)>0:
                localidad = localidades[0]
                datos={'message':'Success','localidad':localidad}
            else:
                datos={'message':'localidad not found'}
            return JsonResponse(datos)
        else:
            localidades=list(Localidad.objects.values())
            if len(localidades)>0:
                datos={'message':'Success','localidades':localidades}
            else:
                datos={'message':'localidad not found'}
            return JsonResponse(datos)

    def post(self, request):
        jd = json.loads(request.body)
        ciudad_id = jd['ciudad']
        ciudad = Ciudad.objects.get(id=ciudad_id)
        # print(ciudad)
        Localidad.objects.create(name = jd['name'],ciudad = ciudad)
        datos={'message':'Success'}
        return JsonResponse(datos)

    def put(self,request, id):
        jd = json.loads(request.body)
        localidad=list(Localidad.objects.filter(id=id).values())

        if len(localidad)>0:
            localidad = Localidad.objects.get(id=id)
            localidad.name=jd['name']
            localidad.ciudad=jd['ciudad']
            localidad.save()
            datos={'message':'Success'}
        else:
            datos={'message':'localidad not found'}
        return JsonResponse(datos)

    def delete(self,request, id):
        localidad=list(Localidad.objects.filter(id=id).values())
        if len(localidad)>0:
            Localidad.objects.filter(id=id).delete()
            datos={'message':'Success'}
        else:
            datos={'message':'localidad not found'}
        return JsonResponse(datos)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 19 17:42:31 2017

@author: EmileMathieu
"""

import numpy as np
import math

class Optimizer(object):
    def __init__(self, lambda_reg, batch):
        self._reset_state()
        self.lambda_reg = lambda_reg
        self.batch = batch
    def __call__(self, layer_id, weight_type, objective, grad):
        raise NotImplementedError()
    def zero_grad(self):
        self._reset_state()
    def _reset_state(self):
        self.state = {}

class SGD(Optimizer):
    def __init__(self, lr=0.1, momentum=0, lambda_reg=0, batch=16):
        super().__init__(lambda_reg, batch)
        self.lr = lr
        self.momentum = momentum

    def get_state(self, key):
        if self.momentum != 0 and key in self.state:
            mu = self.state[key]
        else:
            mu = 0
        return mu

    def __call__(self, layer_id, weight_type, objective, grad):
        key = str(layer_id) + weight_type
        old_v = self.get_state(key)
        new_v = self.lr * grad

        new_v += self.momentum * old_v
        self.state[key] = new_v
        return objective - new_v

class Adam(Optimizer):
    """
    ADAM Gradient descent optimization algorithm
    -------------
    Parameters:
        lr  (float, default: 0.001):
            learning rate of the gradient descent
        betas   (tuple[float, float], default: [0.9, 0.999]):
            decay rates for first and second order momentums
        eps     (float, default: 10e-8):
            term for numerical stability

    """
    def __init__(self, lr=0.001, betas=[0.9, 0.999], eps=10e-8, lambda_reg=0, batch=16):
        super().__init__(lambda_reg, batch)
        self.lr = lr
        self.betas = betas
        self.eps = eps

    def get_state(self, key, shape):
        if key in self.state:
            m, v, step = self.state[key]
        else:
            m = np.zeros(shape)
            v = np.zeros(shape)
            step = 0
        return m, v, step

    def __call__(self, layer_id, weight_type, objective, grad):
        """
        Performs a step of Gradient descent with ADAM optimization
        -------------
        Pameters:
            gradient (array)
              Gradient of the function to optimize
            objective (array):
              Initial point
        """
        key = str(layer_id) + weight_type
        m, v, step = self.get_state(key, grad.shape)
        step = step + 1
        beta1 = self.betas[0]
        beta2 = self.betas[1]
        m = beta1 * m + (1 - beta1) * grad ## Estimate of the mean of the gradient
        v = beta2 * v + (1 - beta2) * grad * grad ## Estimate of the variance of the gradient
        self.state[key] = m, v, step
        ## Correct biases
        m_unbiased = m / (1 - beta1)
        v_unbiased = v / (1 - beta2)
        ## Compute step size
        bias_correction1 = 1 - beta1 ** step
        bias_correction2 = 1 - beta2 ** step
        step_size = self.lr * math.sqrt(bias_correction2) / bias_correction1
        ## Define new step
        objective = (1 - self.lambda_reg*step_size/self.batch) * objective - step_size / (np.sqrt(v_unbiased) + self.eps) * m_unbiased
        return objective

class RMSprop(Optimizer):
    def __init__(self, lr=0.01, alpha=0.99, eps=10e-8, lambda_reg=0, batch=16):
        super().__init__(lambda_reg, batch)
        self.lr = lr
        self.alpha = alpha
        self.eps = eps

    def get_state(self, key, shape):
        if key in self.state:
            square_avg, step = self.state[key]
        else:
            square_avg = np.zeros(shape)
            step = 0
        return square_avg, step

    def __call__(self, layer_id, weight_type, objective, grad):
        key = str(layer_id) + weight_type
        square_avg, step = self.get_state(key, grad.shape)
        step = step + 1
        square_avg = self.alpha * square_avg + (1 - self.alpha) * grad * grad
        self.state[key] = square_avg, step
        avg = np.sqrt(square_avg + self.eps)

        return (1 - self.lambda_reg*self.lr/self.batch) * objective - self.lr * grad / avg


from cefpython3 import cefpython
from direct.showbase.DirectObject import DirectObject

__author__ = 'Marius'

class EventHandler(DirectObject):
    def __init__(self, browser):
        """

        :type browser: cefpython.PyBrowser
        """
        DirectObject.__init__(self)
        self.keyModifiers = 0
        self.modifierKeys = {
            "shift": cefpython.VK_SHIFT,
            "ctrl": cefpython.VK_CONTROL,
            "alt": cefpython.VK_MENU
        }
        self.translateKeys = {
            "f1": cefpython.VK_F1, "f2": cefpython.VK_F2,
            "f3": cefpython.VK_F3, "f4": cefpython.VK_F4,
            "f5": cefpython.VK_F5, "f6": cefpython.VK_F6,
            "f7": cefpython.VK_F7, "f8": cefpython.VK_F8,
            "f9": cefpython.VK_F9, "f10": cefpython.VK_F10,
            "f11": cefpython.VK_F11, "f12": cefpython.VK_F12,

            "arrow_left": cefpython.VK_LEFT,
            "arrow_up": cefpython.VK_UP,
            "arrow_down": cefpython.VK_DOWN,
            "arrow_right": cefpython.VK_RIGHT,

            "enter": cefpython.VK_RETURN,
            "tab": cefpython.VK_TAB,
            "space": cefpython.VK_SPACE,
            "escape": cefpython.VK_ESCAPE,
            "backspace": cefpython.VK_BACK,
            "insert": cefpython.VK_INSERT,
            "delete": cefpython.VK_DELETE,
            "home": cefpython.VK_HOME,
            "end": cefpython.VK_END,
            "page_up": cefpython.VK_PAGEUP,
            "page_down": cefpython.VK_PAGEDOWN,

            "num_lock": cefpython.VK_NUMLOCK,
            "caps_lock": cefpython.VK_CAPITAL,
            "scroll_lock": cefpython.VK_SCROLL,

            "lshift": cefpython.VK_LSHIFT,
            "rshift": cefpython.VK_RSHIFT,
            "lcontrol": cefpython.VK_LCONTROL,
            "rcontrol": cefpython.VK_RCONTROL,
            "lalt": cefpython.VK_LMENU,
            "ralt": cefpython.VK_RMENU,
        }

        self.lastY = None
        self.lastX = None
        self.browser = browser

    def getMousePixelCoordinates(self, mouse):
        # This calculation works only for the browser area.
        x = (mouse.getX() + 1) / 2.0 * base.win.getXSize()
        y = (-mouse.getY() + 1) / 2.0 * base.win.getYSize()

        return x, y

    def mouseEvent(self, button, up):
        if base.mouseWatcherNode.hasMouse():
            mouse = base.mouseWatcherNode.getMouse()
            (x, y) = self.getMousePixelCoordinates(mouse)

            type = None
            if button == 1:
                type = cefpython.MOUSEBUTTON_LEFT
            elif button == 2:
                type = cefpython.MOUSEBUTTON_MIDDLE
            else:
                type = cefpython.MOUSEBUTTON_RIGHT

            self.browser.SendMouseClickEvent(x, y, type, up, 1)

    def mouseWheelEvent(self, up):
        if base.mouseWatcherNode.hasMouse():
            mouse = base.mouseWatcherNode.getMouse()
            (x, y) = self.getMousePixelCoordinates(mouse)

            if up:
                self.browser.SendMouseWheelEvent(x, y, 0, 120)
            else:
                self.browser.SendMouseWheelEvent(x, y, 0, -120)

    def updateMouseTask(self, task):
        if base.mouseWatcherNode.hasMouse():
            mouse = base.mouseWatcherNode.getMouse()
            (x, y) = self.getMousePixelCoordinates(mouse)

            if x != self.lastX or y != self.lastY:
                self.browser.SendMouseMoveEvent(x, y, False)

                self.lastX = x
                self.lastY = y

        return task.cont

    def installMouseHandlers(self):
        self.accept("mouse1", self.mouseEvent, [1, False])
        self.accept("mouse2", self.mouseEvent, [2, False])
        self.accept("mouse3", self.mouseEvent, [3, False])

        self.accept("mouse1-up", self.mouseEvent, [1, True])
        self.accept("mouse2-up", self.mouseEvent, [2, True])
        self.accept("mouse3-up", self.mouseEvent, [3, True])

        self.accept("wheel_up", self.mouseWheelEvent, [True])
        self.accept("wheel_down", self.mouseWheelEvent, [False])

        taskMgr.add(self.updateMouseTask, 'ChromiumMouseUpdateTask')

    def initKeyboardHandlers(self):
        base.buttonThrowers[0].node().setKeystrokeEvent('keystroke')
        base.buttonThrowers[0].node().setButtonDownEvent('button-down')
        base.buttonThrowers[0].node().setButtonUpEvent('button-up')
        base.buttonThrowers[0].node().setButtonRepeatEvent('button-repeat')

        self.accept("keystroke", self.onKeystroke)
        self.accept("button-down", self.onButtonDown)
        self.accept("button-up", self.onButtonUp)
        self.accept("button-repeat", self.onButtonDown)

        self.keyModifiers = 0

    def keyInfo(self, key):
        if self.translateKeys.has_key(key):
            return self.translateKeys[key]
        else:
            return ord(key)

    def onKeystroke(self, key):
        event = {
            "type": cefpython.KEYEVENT_CHAR,
            "modifiers": self.keyModifiers,
            "windows_key_code": self.keyInfo(key),
            "native_key_code": self.keyInfo(key),
        }

        self.browser.SendKeyEvent(event)

    def onButtonDownOrUp(self, keyType, key):
        if self.modifierKeys.has_key(key):
            self.keyModifiers |= self.modifierKeys[key]
        else:
            if self.translateKeys.has_key(key):
                event = {
                    "type": keyType,
                    "modifiers": self.keyModifiers,
                    "windows_key_code": self.keyInfo(key),
                    "native_key_code": self.keyInfo(key),
                }

                self.browser.SendKeyEvent(event)

    def onButtonDown(self, key):
        self.onButtonDownOrUp(cefpython.KEYEVENT_KEYDOWN, key)

    def onButtonUp(self, key):
        self.onButtonDownOrUp(cefpython.KEYEVENT_KEYUP, key)

    def installEventHandlers(self):
        self.installMouseHandlers()
        self.initKeyboardHandlers()

    def removeEventHandlers(self):
        self.ignoreAll()


from tkinter import*
from tkinter import ttk
from PIL import Image, ImageTk
from student import Student
import os
import subprocess, sys
import cv2
import numpy as np
from tkinter import messagebox

class train:
    def __init__(self, root):
        self.root=root
        self.root.geometry("1150x590+0+0")
        self.root.title("face reco system")
        img1=Image.open("colleges_images/1.jpeg")
        img1=img1.resize((200,100))
        self.photoimg1=ImageTk.PhotoImage(img1)

        f_lb1=Label(self.root, image=self.photoimg1)
        f_lb1.place(x=0, y=0, width=200, height=100)

        img2=Image.open("colleges_images/2.jpeg")
        img2=img2.resize((200,100))
        self.photoimg2=ImageTk.PhotoImage(img2)

        f_lb2=Label(self.root, image=self.photoimg2)
        f_lb2.place(x=201, y=0, width=200, height=100)

        img3=Image.open("colleges_images/3.jpeg")
        img3=img3.resize((200,100))
        self.photoimg3=ImageTk.PhotoImage(img3)

        f_lb3=Label(self.root, image=self.photoimg3)
        f_lb3.place(x=402, y=0, width=200, height=100)

        title_lb1=Label(text="TRAIN DATASET")
        title_lb1.place(x=300, y=102, width=100, height=20)

        img4=Image.open("colleges_images/4.jpeg")
        img4=img4.resize((200,100))
        self.photoimg4=ImageTk.PhotoImage(img4)

        b1=Button(self.root, image=self.photoimg4, command=self.train_classifier,  cursor="hand2")
        b1.place(x=102, y=200, width=200, height=100)

        b1=Button(self.root, text="Train Data",command=self.train_classifier, cursor="hand2")
        b1.place(x=102, y=300, width=200, height=20)

    def train_classifier(self):
        data_dir=("data")
        path=[os.path.join(data_dir, file1) for file1 in os.listdir(data_dir)]

        faces=[]
        ids=[]

        for image in path:
            img=Image.open(image).convert("L")
            imageNp=np.array(img, 'uint8')
            id1=int(os.path.split(image)[1].split('.')[1])

            faces.append(imageNp)
            ids.append(id1)
            cv2.imshow("Training", imageNp)
            cv2.waitKey(1)==13
        ids=np.array(ids)

        #training and save
        clf=cv2.face.LBPHFaceRecognizer_create()
        clf.train(faces, ids)
        clf.write("classifier.xml")
        cv2.destroyAllWindows()
        messagebox.showinfo("Result", "Training datasets completed!!")

# python -m pip install --user opencv-contrib-python

        # Function Button hifi
        # testing my laptop

if __name__=="__main__":
    root=Tk()
    obj=train(root)
    root.mainloop()


import matplotlib.pyplot as plt
import librosa
import librosa.display
import numpy as np
import json
import os
import logging
from google.cloud import storage

client = storage.Client()

def make_spectrogram(event, context):
    """Triggered by a change to a cloud storage bucket
    Args:
        event (dict): Event payload.
        context (google.cloud.functions.Context): Metadata for the event.

        1. Downloads the .wav file to the cloud function instance
        2. Creates a spectrogram image using librosa
        3. Saves the image to the cloud function instance
        5. Uploads the image to a separate GCS bucket.
    """

    # Getting GCS File
    file = event
    bucket = file["bucket"]
    filename = file["name"]
    bucket = client.get_bucket(bucket)
    blob = bucket.blob(filename)

    # Downloading file to a new location on the cloud function instance
    int_folder = filename[: filename.rfind("/")]
    temp_store_loc = "/tmp/raw/" + int_folder
    os.makedirs(temp_store_loc, exist_ok=True)

    audio_data = "/tmp/raw/" + filename  # filename includes temp_store_loc

    logging.info(f"Writing raw file to location: {temp_store_loc}")
    blob.download_to_filename(audio_data)
    logging.info(f"Raw Audio filepath: {audio_data}")

    # Creating a location to the store the processed spectrogram
    processed_file_loc = "/tmp/processed/" + int_folder
    os.makedirs(processed_file_loc, exist_ok=True)
    export_path = "/tmp/processed/" + filename  # filename includes processed_file_loc

    # Creating the spectrogram
    y, sr = librosa.load("/tmp/raw/" + filename)
    n_fft = 2048
    hop_length = 256

    D = np.abs(librosa.stft(y, n_fft=n_fft, hop_length=hop_length))
    D = librosa.amplitude_to_db(D, ref=np.max)

    librosa.display.specshow(D, sr=sr, x_axis="time", y_axis="log")

    logging.info(f"Writing processed image to location: {processed_file_loc}")

    # Writing to a location on the cloud function instance
    export_path = "/tmp/processed/" + filename.replace(".wav", ".png")
    plt.axis("off")
    plt.savefig(export_path, pad_inches=0, bbox_inches="tight")
    plt.close()

    # Uploading to a separate GCS bucket.
    target_bucket = client.get_bucket("birdcall-id-spectrograms")

    gcs_export_path = export_path.replace("/tmp/processed/", "")
    logging.info(f"Exporting to GCS location: {gcs_export_path}")

    new_audio_seg = target_bucket.blob(gcs_export_path)
    new_audio_seg.upload_from_filename(export_path)

    return None

if __name__ == "__main__":
    """ testing for sample event before pushing to a cloud function """
    event_string = '{"bucket": "birdcall-id-processed-mp3s", "contentType": "audio/x-wav", "crc32c": "j08FGg==", "etag": "CNPYwKLYy+oCEAE=", "generation": "1594693512080467", "id": "birdcall-id-processed-mp3s/amebit/XC127371.mp3_0_10.wav/1594693512080467", "kind": "storage#object", "md5Hash": "Oa1F2iA0y/nX7TNpyWsn8A==", "mediaLink": "https://www.googleapis.com/download/storage/v1/b/birdcall-id-processed-mp3s/o/amebit%2FXC127371.mp3_0_10.wav?generation=1594693512080467&alt=media", "metageneration": "1", "name": "amebit/XC127371.mp3_0_10.wav", "selfLink": "https://www.googleapis.com/storage/v1/b/birdcall-id-processed-mp3s/o/amebit%2FXC127371.mp3_0_10.wav", "size": "882044", "storageClass": "STANDARD", "timeCreated": "2020-07-14T02:25:12.080Z", "timeStorageClassUpdated": "2020-07-14T02:25:12.080Z", "updated": "2020-07-14T02:25:12.080Z"}'
    event = json.loads(event_string)
    make_spectrogram(event, None)


# -*- coding: utf-8 -*-
"""
Created by susy at 2020/4/26
"""
from controller.action import BaseHandler
from controller.auth_service import auth_service
from utils.constant import USER_TYPE
import json

class WXAppPut(BaseHandler):

    def parsePutCMD(self, **params):
        cmd = u'' + params.get("cmd", "")
        print("cmd:", cmd)
        rs = {"status": 0}

        return rs

    def get(self):

        cmd = self.get_argument("cmd", "")
        name = self.get_argument("name", "")
        params = {"cmd": cmd, "name": name}
        if "openid" == cmd:
            params["code"] = self.get_argument("code", "")
        rs = self.parsePutCMD(**params)

        self.to_write_json(rs)

    def post(self):
        # self.get()
        rs = {"status": 0}
        cmd = self.get_argument("cmd", "")
        bd = self.request.body
        _params = json.loads(bd)
        if cmd:
            _params['cmd'] = cmd
        if _params:
            rs = self.parsePutCMD(**_params)
        self.to_write_json(rs)


import email
import os
import base64
from typing import List
import time
from connect_to_gmail import connect_to_gmail
import re

class GmailException(Exception):
    """gmail base exception class"""

class NoEmailFound(GmailException):
    """no email found"""

def search_emails(query_stirng: str, label_ids: List = None):
    try:
        message_list_response = service.users().messages().list(
            userId='me',
            labelIds=label_ids,
            q=query_string
        ).execute()

        message_items = message_list_response.get('messages')
        next_page_token = message_list_response.get('nextPageToken')

        while next_page_token:
            message_list_response = service.users().messages().list(
                userId='me',
                labelIds=label_ids,
                q=query_string,
                pageToken=next_page_token
            ).execute()

            message_items.extend(message_list_response.get('messages'))
            next_page_token = message_list_response.get('nextPageToken')
        return message_items
    except Exception as e:
        raise NoEmailFound('No emails returned')

def get_file_data(message_id, attachment_id, file_name, save_location):
    response = service.users().messages().attachments().get(
        userId='me',
        messageId=message_id,
        id=attachment_id
    ).execute()

    file_data = base64.urlsafe_b64decode(response.get('data').encode('UTF-8'))
    return file_data

def get_message_detail(message_id, msg_format='metadata', metadata_headers: List = None):
    message_detail = service.users().messages().get(
        userId='me',
        id=message_id,
        format=msg_format,
        metadataHeaders=metadata_headers
    ).execute()
    return message_detail

if __name__ == '__main__':
    CLIENT_FILE = 'credentials.json'
    API_NAME = 'gmail'
    API_VERSION = 'v1'
    SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
    service = connect_to_gmail(CLIENT_FILE, API_NAME, API_VERSION, SCOPES)

    query_string = 'has:attachment'

    # save_location = os.getcwd()
    base_location = os.path.abspath(os.path.join(os.getcwd(), "..","GMAIL API Output"))

    email_messages = search_emails(query_string, ['UNREAD', 'INBOX'])

    for email_message in email_messages:
        messageDetail = get_message_detail(email_message['id'], msg_format='full', metadata_headers=['parts'])
        messageDetailPayload = messageDetail.get('payload')

        # Get some email info
        msgId = messageDetail['id']
        msgLabels = messageDetail['labelIds']
        msgSnip = messageDetail['snippet']
        msgInternalDate = messageDetail['internalDate']

        if 'headers' in messageDetailPayload:
            for msgHeader in messageDetailPayload['headers']:
                if msgHeader['name']=="From":
                    msgSentFrom = msgHeader['value']
                if msgHeader['name']=="Date":
                    msgSentDate = msgHeader['value']
                if msgHeader['name']=="Subject":
                    try:
                        msgSubject = msgHeader['value']
                        pattern = "Fwd: New Assignment(.*)" # Strip off un-needed text
                        compiled = re.compile(pattern)
                        ms = compiled.search(msgSubject)
                        msgSubject = ms.group(1).strip()
                    except:
                        pass

        if 'parts' in messageDetailPayload:
            for msgPayload in messageDetailPayload['parts']:

                file_name = msgSubject + '_' + msgPayload['filename']
                body = msgPayload['body']

                if 'attachmentId' in body:
                    attachment_id = body['attachmentId']
                    attachment_content = get_file_data(email_message['id'], attachment_id, file_name, base_location)

        print(f'ID: {msgId}')
        print(f'Labels: {msgLabels}')
        print(f'Snippet: {msgSnip}')
        print(f'Received by Google Date: {msgInternalDate}')
        print(f'Message Sent From:  {msgSentFrom}')
        print(f'Message Sent Date:  {msgSentDate}')
        print(f'Message Subject:  {msgSubject}')

        # Create folders based on assignment, messageID, and timestamp/epoch date
        save_location = os.path.join(base_location, msgSubject + '_' + msgId + '_'+  msgInternalDate)
        os.mkdir(save_location)

        with open(os.path.join(save_location, file_name), 'wb') as _f:
            _f.write(attachment_content)
            print(f'File {file_name} is saved at {save_location}')
            time.sleep(0.5)


import datetime

from raiden.api.v1.encoding import BaseSchema, TimeStampField

class SchemaTest(BaseSchema):
    timestamp = TimeStampField()

    class Meta:
        fields = ("timestamp",)
        strict = True
        decoding_class = dict

def test_timestamp_field():
    now = datetime.datetime.now()
    assert (
        SchemaTest().dump({}) == {}
    ), "timestamp fields should only be serialized when the date is provided"
    assert SchemaTest().dump({"timestamp": now}) == {
        "timestamp": now.isoformat()
    }, "timestamp fields should be formatted as ISO8601"


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

import Actions, Characters

Kandorn = Characters.Character('Kandorn')

def process_combatant(self):
  self.remove_sont_situations()
  if self.conscious:
    self.print_actions()
    action_choice = InputHandler.number_choice('Which Action? ', self.actions)
    this_action = self.actions[int(action_choice)]
    this_action.process()
    raw_input('')
  self.saving_throws()


from torch_pesq import BarkScale, nr_of_hz_bands_per_bark_band_16k
import torch

def test_sums():
    tmp = BarkScale()

    assert torch.all(
        tmp.fbank.sum(dim=1) == torch.tensor(nr_of_hz_bands_per_bark_band_16k)
    )
    assert torch.all(tmp.fbank.sum(dim=0) == 1.0)


"""
    Configure Logging Module
"""

import logging

LOGGER_NAME = 'TO_PARQUET'

def configure_logging(w):
    """
    Configure Logging Class
    :param w: Class
    :return: Void
    """

    logger = logging.getLogger(LOGGER_NAME)
    logger.setLevel(logging.INFO)

    log_format = '%(asctime)s - %(levelname)s: %(message)s'
    formatter = logging.Formatter(log_format)

    view_handler = logging.StreamHandler(w['-OUTPUT-'])
    view_handler.setFormatter(formatter)

    logger.addHandler(view_handler)

def log():
    """
    Get Logger
    :return:
    """

    return logging.getLogger(LOGGER_NAME)


import pygame, states, words, keybinds
from weapon import Weapon
from data import *
from ui import Text_UI

class Inventory:
	def __init__(self):
		self.display_surface = pygame.display.get_surface()
		self.alpha = 255
		self.intro = True

		self.animation_move_speed_x = WIDTH/25
		self.animation_move_speed_y = HEIGHT/25

		self.a = WIDTH/8.5
		self.b = self.a + WIDTH/1.3 - WIDTH/2.7
		self.c = HEIGHT/1.4

		self.d = self.a - 5*self.animation_move_speed_x
		self.e = self.b + 5*self.animation_move_speed_x
		self.f = self.c + 5*self.animation_move_speed_y

		self.inventory1_rect_pos = pygame.math.Vector2(self.d, HEIGHT/12)
		self.inventory2_rect_pos = pygame.math.Vector2(self.e, HEIGHT/12)
		self.inventory3_rect_pos = pygame.math.Vector2(WIDTH/8.5, self.f)

		self.inventory1_height_capacity = 2
		self.inventory1_width_capacity = 2

		self.items = []

		self.selected_item = 0

	def general_appearance(self):
		self.bg.set_alpha(self.alpha)
		self.display_surface.blit(self.bg, self.bg.get_rect(topleft=(0, 0)))

		inventory1_surf = pygame.image.load('graphics/menu/inventory1.png')
		inventory1_surf = pygame.transform.scale(inventory1_surf, (WIDTH/3.2, WIDTH/3.2))
		inventory1_rect = inventory1_surf.get_rect(topleft=(self.inventory1_rect_pos.x, self.inventory1_rect_pos.y))
		self.display_surface.blit(inventory1_surf, inventory1_rect)

		inventory2_surf = pygame.image.load('graphics/menu/inventory2.png')
		inventory2_surf = pygame.transform.scale(inventory2_surf, (WIDTH/2.7, WIDTH/3.2))
		inventory2_rect = inventory2_surf.get_rect(topleft=(self.inventory2_rect_pos.x, self.inventory2_rect_pos.y))
		self.display_surface.blit(inventory2_surf, inventory2_rect)

		inventory3_surf = pygame.image.load('graphics/menu/inventory3.png')
		inventory3_surf = pygame.transform.scale(inventory3_surf, (WIDTH/1.3, HEIGHT/5.5))
		inventory3_rect = inventory3_surf.get_rect(topleft=(self.inventory3_rect_pos.x, self.inventory3_rect_pos.y))
		self.display_surface.blit(inventory3_surf, inventory3_rect)

		self.show_quests(inventory2_rect)

	def run(self):
		self.items_update()
		self.general_appearance()
		self.show_items()
		if self.intro:
			if self.inventory1_rect_pos.x < self.a:
				self.inventory1_rect_pos.x += self.animation_move_speed_x
			if self.inventory2_rect_pos.x > self.b:
				self.inventory2_rect_pos.x -= self.animation_move_speed_x
			if self.inventory3_rect_pos.y > self.c:
				self.inventory3_rect_pos.y -= self.animation_move_speed_y

			if self.alpha > 100:
				self.alpha -= 10
		else:
			if self.inventory1_rect_pos.x > self.d:
				self.inventory1_rect_pos.x -= self.animation_move_speed_x
			if self.inventory2_rect_pos.x < self.e:
				self.inventory2_rect_pos.x += self.animation_move_speed_x
			if self.inventory3_rect_pos.y < self.f:
				self.inventory3_rect_pos.y += self.animation_move_speed_y
			else:
				states.current_state = states.PLAYING

			if self.alpha < 255:
				self.alpha += 10

	def show_items(self):
		for itemIndex, item in enumerate(self.items):
			image = pygame.transform.scale(item.image, (item.image.get_width()*2.5, item.image.get_height()*2.5))
			itemWidth = image.get_width()
			itemHeight = image.get_height()
			itemRect = image.get_rect(topleft=(self.inventory1_rect_pos.x+0.3*itemWidth + itemWidth*(itemIndex%self.inventory1_width_capacity) +25*(itemIndex%self.inventory1_width_capacity), self.inventory1_rect_pos.y+0.3*itemHeight + itemWidth*((itemIndex)//self.inventory1_width_capacity) + 25*(itemIndex//self.inventory1_width_capacity)))
			if itemIndex == self.selected_item:
				pygame.draw.rect(self.display_surface, 'gold', itemRect, 5, border_radius=5)
			self.display_surface.blit(image, itemRect)

	def show_quests(self, inventory_2_rect):
		for i, quest in enumerate(quests):
			quest_text = Text_UI((inventory_2_rect.x + inventory_2_rect.width/10, inventory_2_rect.y + inventory_2_rect.height/20 + i*inventory_2_rect.width/6), f"{quest.dialogue} : ({quest.current_subquest}/{quest.number_of_subquests})", 3)
			self.display_surface.blit(quest_text.text, quest_text.rect)
			subquest_text = Text_UI((inventory_2_rect.x + inventory_2_rect.width/8, quest_text.rect.bottom), f"{quest.subquests[quest.current_subquest].dialogue} : ({quest.subquests[quest.current_subquest].current_objective_amount}/{quest.subquests[quest.current_subquest].objective_amount})", 2)
			self.display_surface.blit(subquest_text.text, subquest_text.rect)

	def selection_keys(self, key):
		if key == keybinds.keybinds['LEFT']:
			if not self.selected_item % self.inventory1_width_capacity == 0:
				self.selected_item-=1
		if key ==  keybinds.keybinds['RIGHT']:
			if not self.selected_item % self.inventory1_width_capacity == 5:
				if not self.selected_item+1 >= len(self.items):
					self.selected_item+=1
		if key ==  keybinds.keybinds['UP']:
			if not self.selected_item // self.inventory1_height_capacity == 0:
				self.selected_item-= self.inventory1_width_capacity
		if key == keybinds.keybinds['DOWN']:
			if not self.selected_item // self.inventory1_height_capacity == 5:
				if not self.selected_item+self.inventory1_height_capacity >= len(self.items):
					self.selected_item+= self.inventory1_width_capacity

	def items_update(self):
		for item in self.items:
			for quest in quests:
				quest.check_quest(item.item_type, 'collect')


# Task - Convert an IPv4 address to equivalent binary

ip_address = "10.10.10.100"
print(ip_address)
# split the string into 4 octets : delimiter '.'
octets = ip_address.split('.')
print(octets)

# convert each octet to integer
first_octet = int(octets[0])
second_octet = int(octets[1])
third_octet = int(octets[2])
fourth_octet = int(octets[3])

# refer to 02_integer_to_binary.py exercise
first_octet_binary = bin(first_octet)[2:].zfill(8)
second_octet_binary = bin(second_octet)[2:].zfill(8)
third_octet_binary = bin(third_octet)[2:].zfill(8)
fourth_octet_binary = bin(fourth_octet)[2:].zfill(8)

# create a binary list and populate the items
binary_list = [first_octet_binary, second_octet_binary, third_octet_binary, fourth_octet_binary]
print(binary_list)

# jon the binary_list using '.' as delimiter
ip_address_binary = '.'.join(binary_list)
print(ip_address_binary)


from typing import Optional
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def __init__(self):
        self.mp={}
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        #值判断是否高度平衡（左右子树高度差小于等于1）而不是判断是否二叉搜索树
        if not root:return True
        lH,rH=0,0
        if root.left:lH=1+self.getH(root.left)
        if root.right: rH = 1 + self.getH(root.right)
        if lH>rH+1 or rH>lH+1:return False
        return self.isBalanced(root.left) and self.isBalanced(root.right)

    def getH(self,node):
        if not node:return 0
        if self.mp.__contains__(node):return self.mp[node]
        l,r = 0,0
        if node.left:l=1+self.getH(node.left)
        if node.right: r = 1 + self.getH(node.right)
        self.mp[node] = max(l,r)
        return max(l,r)

'''
110. Balanced Binary Tree
Easy
Given a binary tree, determine if it is
height-balanced
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2:

Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Example 3:

Input: root = []
Output: true

Constraints:

The number of nodes in the tree is in the range [0, 5000].
-104 <= Node.val <= 104
'''


class string_to_bytes:

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

    def convert_to_bytes(self):
        arrays = bytes(self.text, 'utf-8')

        for array in arrays:
            print(array, end='')

letters = input('Enter a string of text:')
food = string_to_bytes(letters)
print(food.convert_to_bytes())


import re

from collections import OrderedDict
from klever.core.vtg.emg.common import get_or_die
from klever.core.vtg.emg.common.c.types import Pointer
from klever.core.vtg.emg.common.process import Process
from klever.core.vtg.emg.common.c import Function, Variable
from klever.core.vtg.emg.generators.abstract import AbstractGenerator

class ScenarioModelgenerator(AbstractGenerator):

    def make_scenarios(self, abstract_task_desc, collection, source, specifications):
        """
        This generator generates processes for verifying Zephyr drivers. It generates the main process which calls
        module and kernel initialization functions and then modules exit functions.

        :param abstract_task_desc: Abstract task dictionary.
        :param collection: ProcessCollection.
        :param source: Source collection.
        :param specifications: dictionary with merged specifications.
        :return: None
        """
        functions_collection = OrderedDict()

        # Import Specifications
        self.logger.info("Generate an entry process on base of given functions list")
        if collection.entry:
            raise ValueError(
                "Do not expect any main process already attached to the model, reorder EMG generators in configuration")

        # Read configuration in abstract task
        self.logger.info("Determine functions to call in the environment model")

        # Allow setting file regex to filter functions with several definitions
        expressions = []
        for expr in self.conf.get("initialization functions"):
            if isinstance(expr, str):
                obj = re.compile(expr)
                expressions.append((None, obj))
            elif isinstance(expr, list) and len(expr) == 2:
                file_obj = re.compile(expr[0])
                func_obj = re.compile(expr[1])
                expressions.append((file_obj, func_obj))
            else:
                raise ValueError("Unknown element given instead of a file and function regular expressions pair: {!r}".
                                 format(str(expr)))

        for file_expr, func_expr in expressions:
            for func in source.source_functions:
                objs = source.get_source_functions(func)
                suits = []
                for obj in objs:
                    if obj.definition_file:
                        if func_expr.fullmatch(func) and (not file_expr or file_expr.fullmatch(obj.definition_file)):
                            self.logger.debug('Add function {!r} from {!r}'.format(func, obj.definition_file))
                            suits.append(obj)
                            break
                if suits:
                    functions_collection[func] = suits
                    break

        if len(functions_collection) == 0:
            raise ValueError("There is no suitable functions to call in the environment model")

        # Read configuration in private configuration about headers
        # todo: in current implementation it is useless but may help in future
        # headers_map = self.conf.get("additional headers")
        # if headers_map:
        #     for func in (f for f in set(headers_map.keys).intersection(set(functions_list))):
        #         functions_collection[func].headers.extend(headers_map[func])

        # Generate scenario
        self.logger.info('Generate main scenario')
        new = self.__generate_calls(functions_collection)
        collection.entry = new

    def __generate_calls(self, functions_collection):

        def indented_line(t, s):
            return (t * "\t") + s

        # Generate process
        ep = Process("main")
        ep.comment = "Call exported functions."
        ep.pretty_id = 'zephyr/generic'
        ep.process = ''

        caller_func = Function("ldv_zephr", "void a(void)")

        # Generate actions for all sequence
        expressions = []
        identifier = 0
        for func in functions_collection:
            for obj in functions_collection[func]:
                self.logger.info("Call function {!r} from {!r}".format(func, obj.definition_file))
                expr = self.__generate_call(ep, func, obj, identifier)
                expressions.append(expr)

        # Generate process description
        tab = 0
        cnt = 0
        for expr in expressions:
            caller_func.body.append(indented_line(tab, "{}".format(expr)))
            cnt += 1

        ep.actions.add_condition('function_calls', [], ["{}();".format(caller_func.name)],
                         'Call all initialization functions in asc order of level.')
        ep.process = "<function_calls>"
        ep.add_definition("environment model", caller_func.name, caller_func.define() + ["\n"])

        return ep

    def __generate_call(self, ep, func, obj, identifier):
        # Add declaration of caller
        caller_func = Function("emg_{}_caller_{}".format(func, identifier), "void a(void)")
        ep.add_declaration("environment model", caller_func.name, caller_func.declare(True)[0])
        expression = ""
        body = []
        initializations = []

        # Check retval and cast to void call
        # if obj.declaration.return_value and obj.declaration.return_value.identifier != 'void':
        #     expression += "(void) "

        # Get arguments and allocate memory for them
        args = []
        free_args = []
        for index, arg in enumerate(obj.declaration.parameters):
            if not isinstance(arg, str):
                argvar = Variable("emg_arg_{}".format(index), arg)
                body.append(argvar.declare() + ";")
                args.append(argvar.name)
                if isinstance(arg, Pointer):
                    elements = self.conf.get("initialize strings as null terminated")
                    if elements and arg == 'char **':
                        if isinstance(elements, int) or elements.isnumeric():
                            elements = int(elements)
                        else:
                            elements = 'ldv_undef_int()'
                        argvar_len = Variable(argvar.name + '_len', 'int')
                        # Define explicitly number of arguments, since undef value is too difficult sometimes
                        initializations.append("int {} = {};".format(argvar_len.name, elements))
                        initializations.append("{} = (char **) ldv_xmalloc({} * sizeof(char *));".
                                               format(argvar.name, argvar_len.name))
                        # Initialize all elements but the last one
                        initializations.append("for (int i = 0; i < {} - 1; i++)".format(argvar_len.name))
                        # Some undefined data
                        initializations.append("\t{}[i] = (char *) external_allocated_data();".format(argvar.name))
                        # The last element is a string
                        initializations.append("{}[{}] = (char * ) 0;".format(argvar.name, elements - 1))
                        free_args.append(argvar.name)
                    elif self.conf.get("allocate external", True):
                        value = "external_allocated_data();"
                        initializations.append("{} = {}".format(argvar.name, value))
                    else:
                        if self.conf.get("allocate with sizeof", True):
                            apt = arg.points.to_string('', typedef='complex_and_params')
                            value = "ldv_xmalloc(sizeof({}));".\
                                format(apt if apt != 'void' else apt + '*')
                        else:
                            value = "ldv_xmalloc_unknown_size(0);"
                        free_args.append(argvar.name)
                        initializations.append("{} = {}".format(argvar.name, value))

        # Generate call
        if func != "main":
            expression += "int ret = "
        expression += "{}({});".format(func, ", ".join(args))

        # Generate function body
        body += initializations + [expression]
        if func != "main":
            body += ["ldv_assume(ret==0);"]

        # Free memory
        for arg in free_args:
            body.append("ldv_free({});".format(arg))

        caller_func.body = body

        # Add definition of caller
        ep.add_definition(obj.definition_file, caller_func.name, caller_func.define() + ["\n"])

        # Return call expression
        return "{}();".format(caller_func.name)


class Solution:
    """
    Leetcode medium: https://leetcode.com/problems/decode-ways
    Couldn't solve it :( ; problem wasn't actually that hard, but I couldn't properly figure out the code
    to return # paths in recursive tree instead of # nodes
    The way to do that is to simply return 1 when leaf node is reached (don't know why I couldn't figure this easy shit out)
    Did a good job in covering edge cases before submitting though
    """

    def getNumDecodings(self, s: str, memo: Dict[str, int]) -> int:
        # If end of string is reached
        if s in memo:
            return memo[s]
        if len(s) == 0:
            return 1
        # Check for 0 before base case of len(s) == 1!
        if s[0] == "0":
            return 0
        if len(s) == 1:
            return 1

        # s[0] is guaranteed to map to a digit unless it's 0, so continue on this path
        num_decodings = self.getNumDecodings(s[1:], memo)
        if int(s[0:2]) <= 26:
            # Only continue on this path if s[0:2] maps to a valid letter
            num_decodings += self.getNumDecodings(s[2:], memo)
        memo[s] = num_decodings
        return num_decodings

    def numDecodings(self, s: str) -> int:
        """
        22 => B, V
        Recursive case: num_decodings(s) = [
            1 (num_decodings(s[0:1])) + num_decodings(s[1:]),
            1 (num_decodings(s[0:2])) + num_decodings(s[2:])
        ]
        Base case: num_decodings(s) = len(s) if len(s) == 0 | 1
        Exceptions for if s[idx] == "0"; then skip that digit and the digit after and return num_decodings(s[2:])
        THAT'S NOT CORRECT; this will give # nodes in DFS tree instead of # paths (leaf nodes)!

        Instead of this recursive definition, we don't add a number each time we make a recursive call; we ONLY add 1 when end of string is reached (len(s) == 0 | 1)
        Recusive case: num_decodings(s) = num_decodings(s[1:]) + num_decodings(s[2:]) if s[]
        Base cases:
        1) num_decodings(s) = 1 if len(s) == 0 | 1 (leaf node is reached; return 1)
        2) num_decodings(s) = 0 if s[0] == 0 (stop going down this path and return 0)

        Test cases:
        "12" => 2
        "226" => 3
        "06" => 0 (0 at prefix of string)
        "" => 0
        "1" => 1
        "29" => 1 (number greater than 26)
        "11106" => 2 (0 in middle of string)
        "20" => 1 (0 at end of string)
        """
        memo = {}
        return self.getNumDecodings(s, memo)


# pylint: disable=missing-class-docstring,missing-function-docstring,missing-module-docstring

from __future__ import annotations

import copy
import time
from collections.abc import Sequence, Generator
from typing import Collection, Any, TypeVar, cast, Callable
from dataclasses import dataclass, field
from contextlib import contextmanager

import pygame
import numpy as np
import numpy.typing as npt

T = TypeVar("T")

def non_optional(x: T | None) -> T:
    assert x is not None
    return x

def namespace(cls: type[T]) -> T:
    return dataclass(cls)()

@namespace
class Context:
    display: pygame.Surface | None = None
    clock: pygame.time.Clock | None = None
    fps: int | None = None
    bg: pygame.Surface | None = None
    font_cache: dict[tuple[str, int], pygame.font.Font] = field(default_factory=lambda: {})

def preload_font(name: str, size: int, system_font: bool=False) -> None:
    if system_font:
        Context.font_cache["sys:" * system_font + name, size] = pygame.font.SysFont(name, size)
    else:
        Context.font_cache["sys:" * system_font + name, size] = pygame.font.Font(name, size)

def get_font(name: str, size: int, system_font: bool=False) -> pygame.font.Font:
    if ("sys:" * system_font + name, size) not in Context.font_cache:
        preload_font(name, size, system_font)
    return Context.font_cache["sys:" * system_font + name, size]

def set_context(width: int, height: int, fps: int=30) -> None:
    display = pygame.display.set_mode((width, height))
    Context.display = display
    Context.clock = pygame.time.Clock()
    Context.fps = fps
    Context.bg = pygame.Surface((width, height), pygame.SRCALPHA).convert_alpha()
    Context.font_cache = {}

def bg_texture() -> pygame.Surface:
    return cast(pygame.Surface, Context.bg)

def draw_texture(texture: pygame.Surface, pos: Collection[int], size: float, angle: float,
                 anchor: Collection[float] = (.5, .5)) -> None:
    surf = pygame.transform.rotozoom(texture, angle, size)
    final_pos: npt.NDArray[np.float_] = -np.array(anchor) * surf.get_size() + pos * np.array((1, -1)) + np.array(non_optional(Context.display).get_size()) / 2
    non_optional(Context.display).blit(surf, cast(Sequence[int], final_pos.astype(np.int32)))

def rotated_rectangle_extents(width: float, height: float, angle: float) -> pygame.Rect:
    corners = [
        (-width // 2, -height // 2),
        (-width // 2, +height // 2),
        (+width // 2, +height // 2),
        (+width // 2, -height // 2),
    ]
    angle = np.radians(90.0 - angle)
    for idx, corner in enumerate(corners):
        corners[idx] = (
            corner[0] * np.cos(angle) - corner[1] * np.sin(angle),
            corner[0] * np.sin(angle) + corner[1] * np.cos(angle)
        )

    minx, maxx = min(i[0] for i in corners), max(i[0] for i in corners)
    miny, maxy = min(i[1] for i in corners), max(i[1] for i in corners)
    return pygame.Rect(0, 0, maxx-minx, maxy-miny)

@contextmanager
def frame() -> Generator[None, None, None]:
    non_optional(Context.clock).tick(non_optional(Context.fps))
    non_optional(Context.display).fill((255, 255, 255))
    if Context.bg:
        non_optional(Context.display).blit(Context.bg, (0, 0))
    yield
    pygame.display.flip()

# Scratch stuff
def draw_thought_bubble(text: str, pos: Sequence[float]) -> None:
    font = get_font("Arial", 14, system_font=True)

    split_text = [i + " " for i in str(text).split() if i != ""]
    lines = [""]
    for word in split_text:
        text_width = font.size(word)[0]
        line_width = font.size(lines[-1])[0]
        if line_width + text_width > 108:
            lines.append(word)
        else:
            lines[-1] += word
    width = max(32 + max(font.size(i)[0] for i in lines), 55)
    height = 41 + len(lines) * 22

    bubble = pygame.Surface((width, height), pygame.SRCALPHA).convert_alpha()
    pygame.draw.rect(bubble, (255, 255, 255), (4, 4, width - 4, height - 24), border_radius=12)
    pygame.draw.rect(bubble, (220, 220, 220), (4, 4, width - 4, height - 24), width=2,
                     border_radius=12)
    pygame.draw.circle(bubble, (255, 255, 255), (width//2 + 2, height - 20), 8)
    pygame.draw.circle(bubble, (220, 220, 220), (width//2 + 2, height - 22), 8, width=2,
                       draw_bottom_left=True, draw_bottom_right=True, draw_top_left=False,
                       draw_top_right=False)
    pygame.draw.circle(bubble, (255, 255, 255), (width//2 + 9, height - 13), 4)
    pygame.draw.circle(bubble, (220, 220, 220), (width//2 + 9, height - 13), 4, width=2)
    pygame.draw.circle(bubble, (255, 255, 255), (width//2 + 16, height - 10), 3)
    pygame.draw.circle(bubble, (220, 220, 220), (width//2 + 16, height - 10), 3, width=2)

    for lineno, line in enumerate(lines):
        bubble.blit(font.render(line, True, (20, 20, 20)), (16, 16 + lineno * 22))

    non_optional(Context.display).blit(bubble, (
        pos[0] + 240 - bubble.get_width() * 3 // 4,
        -pos[1] + 180 - bubble.get_height() + 7,
    ))

@dataclass
class TextInputState:
    text: str
    cursor_location: int | None
    edit_start: float
    closed: bool

def draw_question_box(state: TextInputState | None = None, key_events: list[pygame.event.Event] | None = None) -> TextInputState:
    font = get_font("calibril.ttf", 12)

    if state is None:
        state = TextInputState("", None, time.perf_counter(), False)
    else:
        state = copy.copy(state)
    if key_events is None:
        key_events = []

    edit_bounds = pygame.Rect(27, 301, 428, 32)
    if pygame.mouse.get_pressed()[0] and edit_bounds.collidepoint(pygame.mouse.get_pos()):
        state.cursor_location = 0
        state.edit_start = time.perf_counter()

    if state.cursor_location is not None:
        for event in key_events:
            if event.type == pygame.TEXTINPUT:
                state.edit_start = time.perf_counter()
                state.text = state.text[:state.cursor_location] + event.text + state.text[state.cursor_location:]
                state.cursor_location += len(event.text)

            elif event.type == pygame.KEYDOWN:
                state.edit_start = time.perf_counter()
                if event.key == pygame.K_BACKSPACE:
                    state.text = (
                        state.text[:max(state.cursor_location-1,0)] + state.text[state.cursor_location:]
                    )
                    if state.cursor_location > 0:
                        state.cursor_location -= 1
                elif event.key == pygame.K_DELETE:
                    state.text = (
                        state.text[:state.cursor_location] + state.text[state.cursor_location+1:]
                    )
                elif event.key == pygame.K_LEFT:
                    if state.cursor_location > 0:
                        state.cursor_location -= 1
                elif event.key == pygame.K_RIGHT:
                    if state.cursor_location < len(state.text):
                        state.cursor_location += 1
                elif event.key == pygame.K_RETURN:
                    state.closed = True

    pygame.draw.rect(non_optional(Context.display), (255, 255, 255), (7, 284, 468, 66), border_radius=10)
    pygame.draw.rect(non_optional(Context.display), (210, 210, 210), (7, 284, 468, 66), width=2,
                     border_radius=10)

    pygame.draw.rect(non_optional(Context.display), (255, 255, 255), (27, 301, 428, 32), border_radius=15)
    pygame.draw.rect(non_optional(Context.display), (210, 210, 210), (27, 301, 428, 32), width=1, border_radius=15)

    pygame.draw.circle(non_optional(Context.display), (135, 80, 195), (438, 317), 13)

    pygame.draw.line(non_optional(Context.display), (255, 255, 255), (432, 322), (429, 318), 5)
    pygame.draw.line(non_optional(Context.display), (255, 255, 255), (433, 322), (441, 314), 5)
    pygame.draw.circle(non_optional(Context.display), (255, 255, 255), (429, 318), 2)
    pygame.draw.circle(non_optional(Context.display), (255, 255, 255), (433, 323), 2)

    pygame.draw.circle(non_optional(Context.display), (255, 255, 255), (442, 314), 2)

    non_optional(Context.display).blit(font.render(state.text, True, (50, 50, 50)), (38, 311))
    if state.cursor_location is not None and (time.perf_counter() - state.edit_start) % 2 <= 1:
        width = font.size(state.text[:state.cursor_location])[0]
        pygame.draw.line(non_optional(Context.display), (0, 0, 0), (38 + width, 311), (38 + width, 321))

    return state


from _2048.manager import GameManager
from _2048.game import Game2048
import pygame
import os
import numpy as np

class Game2048_wrapper(GameManager):
    def __init__(self, screen, p1, p2):
        super().__init__(Game2048, screen, p1, p2)
        pygame.init()
        pygame.display.set_caption("2048!")
        pygame.display.set_icon(Game2048.icon(32))
        self.actionSpace =  [
            pygame.event.Event(pygame.KEYDOWN, {'key': pygame.K_LEFT}), # LEFT
            pygame.event.Event(pygame.KEYDOWN, {'key': pygame.K_UP}),   # UP
            pygame.event.Event(pygame.KEYDOWN, {'key': pygame.K_RIGHT}), # RIGHT
            pygame.event.Event(pygame.KEYDOWN, {'key': pygame.K_DOWN}), # DOWN
            ]
        data_dir = "./data/game/"
        os.makedirs(data_dir, exist_ok=True)

    def reset(self, test_mode = True):
        self.new_game()
        if not test_mode:
            self.game.ANIMATION_FRAMES = 1
            self.game.WIN_TILE = 999999
        else:
            self.game.ANIMATION_FRAMES = 10
            self.game.WIN_TILE = 999999
        return self.game.grid

    def step(self, action):
        old_score = self.game.score
        event = self.actionSpace[action]
        self.dispatch(event)
        state = self.game.grid
        reward = self.calcReward(old_score)
        done = self.game.won or self.game.lost
        info = np.max(state)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.close()
            elif event.type == pygame.MOUSEBUTTONUP:
                self.dispatch(event)
        return state, reward, done, info

    def calcReward(self, old_score):
        if self.game.lost or self.game.won:
            return -100
        elif self.game.score == old_score:
            return -1
        grid = np.array(self.game.grid).reshape(-1)
        reward1 = np.log2(grid.max()) * 2
        reward2 = (len(grid) - np.count_nonzero(grid))
        return reward1 + reward2

    def render(self):
        super().draw()


from gc import is_tracked
from io import BytesIO
from json import loads
from urllib import response
from uuid import uuid4

from app.helpers.handler.handler_errors import HandlerErrors
from app.helpers.messages.success_msg import SUCCESS_CODE_3001
from models import db

class Middleware:

    def __init__(self, app):
        self.wsgi_app = app.wsgi_app
        self.app = app
        self.redirect_msg = "Sera direccionado automaticamnte al URL destino"
        self.customer_header = "HTTP_LOG_ID"

    def __call__(self, environ, start_response):
        try:
            with self.app.test_request_context():
                is_trackable = environ["REQUEST_METHOD"] != "GET"
                if is_trackable:
                    environ[self.customer_header] = 1
                    response = self.wsgi_app(environ, start_response)
                    pay_load = b"".join(response).decode("utf-8")
                    json_date = self.get_json_response(pay_load)
                    return [pay_load.encode("utf-8")]
                else:
                    return self.wsgi_app(environ, start_response)
        except Exception as error:
            with self.app.test_request_context():
                if is_trackable:
                    response = HandlerErrors.handler_middleware_errors(error, 0)
                else:
                    response = HandlerErrors.handler_middleware_errors(error)
                return response(environ, start_response)

    def commit(self):
        with self.spp.test_request_context():
            try:
                db.session.commit()
            except Exception as error:
                db.session.rollback()
                print("No fue posible guardar el log en la base de datos")
                print(f"Error: {error}")

    def get_json_response(self, pay_load):
        if self.redirect_msg not in pay_load:
            json_data = loads(pay_load)
        else:
            json_data = {"data": pay_load, "app_code": SUCCESS_CODE_3001}
        return json_data


import subprocess
from subprocess import PIPE
from datetime import datetime

from NotifierMailer import bs_extractor, run, sendmail, alert, composemail
import NotifierMailer as nm

from apps.sprouen_checker import makemail, extractf, make_table, url, emails

def predicate(new, old):
    def voeu_definitif(l):
        return len([e['etudiant'] for e in l if e['statut']=='affecté'])
    return old is None or (voeu_definitif(new) > voeu_definitif(old))

if __name__ == "__main__":
    run(
        extractf=extractf,
        actions=dict(
            predicate_true=[
                sendmail(emails, makemail),
                alert(lambda new, old: dict(title="Céline notification!", content=f"{make_table(new)}"),
                      "pokecenter",
                      nm.browse(lambda new, old: url))
            ]
        ),
        predicate=predicate
    )


n, m = map(int, input().split())
lst = list(map(int, input().split()))

def binary_search(lst, start, end, target):
    # 떡 길이의 중간값
    result = 0
    while start <= end:
        mid = (start + end) // 2
        sum = 0
        for i in range(n):
            dis = lst[i] - mid
            if dis > 0:
                sum += dis

        if sum == target:
            return mid
        elif sum > target:
            start = mid + 1
            result = mid
        else:
            end = mid - 1
    return result

print(binary_search(lst, 0, max(lst), m))

7. 이진 탐색/떡볶이 떡 만들기.py

떡볶이 떡 만들기.py