import random

# Hero Class
class Hero:
    def __init__(self, name, starting_health=100):
         self.name = name
         self.abilities = list()
         self.starting_health = starting_health
         self.current_health = starting_health
         self.armors = list()
         self.deaths = 0
         self.kills  = 0

    def add_ability(self, ability):
        ''' Add ability to abilities list '''
        self.abilities.append(ability)

    def add_weapon(self, weapon):
        '''Add weapon to abilities list'''
        self.abilities.append(weapon)

    def add_armor(self, armor):
        '''Add armor object to armor list'''
        self.armors.append(armor)

    def defend(self):
        '''calculate total defense based on armor'''
        total_block = 0
        if self.current_health == 0:
            return 0
        else:
            for armor in self.armors:
                total_block += armor.block()
            return total_block

    def attack(self):
        '''Calculate damage from abilities list
        Calls Ability.attack()on every ability in self.abilities and returns total'''
        total = 0
        for ability in self.abilities:
            total += ability.attack()
        return total

    def take_damage(self, damage):
        '''Update self.current_health with the damage passed in'''
        self.current_health -= damage - min(damage, self.defend())

    def add_kill(self, num_kills):
        '''track number of kills'''
        self.kills += num_kills

    def is_alive(self):
         '''Boolean. Return true if hero is alive, false if not'''
         if self.current_health > 0:
            return True
         else:
            return False

    def fight(self, opponent):
        '''Runs a loop to attack the opponent until someone dies'''
        while self.is_alive() and opponent.is_alive():
            self.take_damage(opponent.attack())
            opponent.take_damage(self.attack())
        if not self.is_alive():
            self.deaths += 1
            opponent.add_kill(1)
            print()
            print("{} killed {}".format(opponent.name, self.name))
            print()
        if not opponent.is_alive():
            opponent.deaths += 1
            self.add_kill(1)
            print("{} killed {}".format(self.name, opponent.name))

    def show_stats(self):
        if self.deaths == 0:
            kdr = "inf"
        else:
            kdr = self.kills / self.deaths
        print("KDR for %s: %s" % (self.name, kdr))

class Ability:
    def __init__(self, name, attack_strength):
        self.name = name
        self.attack_strength = attack_strength

    def attack(self):
        '''Return random attack value between 0 and max_damage'''
        return random.randint(0, int(self.attack_strength))

class Weapon(Ability):
    def attack(self):
        """Return a random value between half-full weapon attack power"""
        return random.randint((self.attack_strength//2),self.attack_strength)

class Team:
    def __init__(self, team_name):
        self.name = team_name
        self.heroes = list()

    def add_hero(self, hero):
        '''Add Hero object to heroes list'''
        self.heroes.append(hero)

    def remove_hero(self, name):
        '''Remove hero from heroes list. If Hero isn't found return 0'''
        if not (len(self.heroes) > 0):
            return 0
        else:
            for hero_obj in self.heroes:
                if hero_obj.name == name:
                    self.heroes.remove(hero_obj)
                    return 1
        return 0

    def alive_heroes(self):
        alive_heroes = []
        for hero in self.heroes:
        	if hero.is_alive():
        		alive_heroes.append(hero)
        return alive_heroes

    def attack(self, other_team):
        '''randomly select living hero from each team, fight until a team has no heroes'''
        while len(self.alive_heroes()) > 0 and len(other_team.alive_heroes()) > 0:
            random_hero_1 = random.choice(self.alive_heroes())
            random_hero_2 = random.choice(other_team.alive_heroes())
            random_hero_1.fight(random_hero_2)

    def revive_heroes(self, health=100):
      '''reset hero health'''
      for hero in self.heroes:
            hero.current_health = health

    def stats(self):
        '''prints kill/death ratio for teammates'''
        print()
        print("Showing Stats for Team %s" % self.name)
        for hero in self.heroes:
            hero.show_stats()

    def view_all_heroes(self):
        '''Print all heroes to the console.'''
        for hero in self.heroes:
            print(hero.name)

class Armor:
    def __init__(self, name, max_block):
        '''Instantiate name and defense strength'''
        self.name = name
        self.max_block = max_block

    def block(self):
        '''return random value between 0-max_block strength'''
        return random.randint(0, int(self.max_block))

class Arena:
    def __init__(self):

        self.team_one = None
        self.team_two = None

    def create_ability(self):
        print("CREATING A NEW ABILITY")
        name = input("Ability name: ")
        attack_strength = int(input("Ability attack strength: "))
        print()
        return Ability(name, attack_strength)

    def create_weapon(self):
        print("CREATING A NEW WEAPON")
        name = input("Weapon name: ")
        attack_strength = int(input("Weapon attack strength: "))
        print()
        return Weapon(name, attack_strength)

    def create_armor(self):
        print("CREATING NEW ARMOR")
        name = input("Armor name: ")
        max_block = int(input("Armor max block: "))
        print()
        return Armor(name, max_block)

    def create_hero(self):
        print("CREATING NEW HERO")
        name = input("Hero name: ")
        hero = Hero(name)
        while True:
            create_option = input("What do you want to add? <armor, ability, weapon, none>: ")
            if create_option == "none":
                break
            elif create_option == "armor":
                hero.add_armor(self.create_armor())
            elif create_option == "ability":
                hero.add_ability(self.create_ability())
            elif create_option == "weapon":
                hero.add_weapon(self.create_weapon())
            else:
                print("Invalid option!")
        return hero
        print()

    def build_team_one(self):
        """Build 1st team """
        print('Putting team one together ....')
        name = input("Choose a team name: ")
        self.team_one = Team(name)
        num_heroes = int(input("Num heroes: "))
        for _ in range(num_heroes):
            self.team_one.add_hero(self.create_hero())

    def build_team_two(self):
        """Build 2nd team """
        print('Putting team two together ....')
        name = input("Choose a team name: ")
        self.team_two = Team(name)
        num_heroes = int(input("Num heroes: "))
        for _ in range(num_heroes):
            self.team_two.add_hero(self.create_hero())

    def team_battle(self):
        '''fights two teams'''
        self.team_one.attack(self.team_two)
        print()
        if self.team_one.alive_heroes():
            print('{} team won the battle!'.format(self.team_one.name))
        elif self.team_two.alive_heroes():
            print('{} team won the battle!'.format(self.team_two.name))
        else:
            print("BOTH TEAMS DESTROYED EACHOTHER!")

    def show_stats(self):
        """Print hero in arena stats(kill/death ratio) """
        print('Printing stats')
        self.team_one.stats()
        self.team_two.stats()

# GAME LOOP
if __name__ == "__main__":
    game_is_running = True

    arena = Arena()

    arena.build_team_one()
    arena.build_team_two()

    while game_is_running:
        arena.team_battle()
        arena.show_stats()
        print()
        play_again = input("Play Again? Y or N:")
        # Check player input
        if play_again.lower() == "n":
           game_is_running = False
        else:
           # Revive heroes and play again
           arena.team_one.revive_heroes()
           arena.team_two.revive_heroes()

    # # TESTS
    # hero = Hero("Wonder Woman")
    # print(hero.attack())
    # ability = Ability("Divine Speed", 20)
    # hero.add_ability(ability)
    # print(hero.attack())
    # new_ability = Ability("Super Human Strength", 30)
    # hero.add_ability(new_ability)
    # print(hero.attack())
    # hero2 = Hero("Jodie Foster")
    # ability2 = Ability("Science", 800)
    # hero2.add_ability(ability2)
    # # hero.fight(hero2)
    # hero2.fight(hero)
    # print("Jodie Foster num kills: %s" % hero2.kills)
    # print("Jodie Foster num deaths: %s" % hero2.deaths)
    # print("Wonder Woman num kills: %s" % hero.kills)
    # print("Wonder Woman num deaths: %s" % hero.deaths)
    # print (hero.name)


#This file is designed to have all the functions for preprocess data in both the product df and the review data frames
#It will act as the library to import from functions needed in the preprocess_data.py
import pandas as pd
import numpy as np
from collections import Counter

################################################################################################
##PRODUCT DF FUNCTIONS
################################################################################################
def clean_categories_column(df):
    """clean_categories_column takes in a dataframe and return the categories
    per item that meet the occurrence threshold set in params.yaml file or more times in the full product space

    Clean_categories_column starts by generating a total category list
    of all categories tagged to every product
    then it counts the occurrance of every cat in the list and extracts only the list
    with equal or more occurrences than the set in params.yaml file.
    finally it updates the category column to only include these categories per product to
    help with feature selection/ generation.

    Args:
        df (data_frame): data_frame that includes "category" labelled column

    Returns:
        df: same data_frame with the category column updated
    """
    import yaml
    with open("params.yaml", "r") as file:
        params= yaml.safe_load(file)
    occurrence= params["preprocess_products"]["occurrence_threshold"]
    #extracting the most common
    print("Extracting total category list")
    total_cat_lst= [word.lower() for lst in df["category"] for word in lst]
    print("Extracting categories with at least {} occurrences".format(occurrence))
    cat_counter_dict= dict(Counter(total_cat_lst))
    cat_500= [cat for cat in cat_counter_dict if cat_counter_dict[cat]>= occurrence]
    df["category"]= df["category"].apply(lambda row : [word.lower() for word in row if word in cat_500])
    print("category column successfully processed!")
    return df

def clean_text(sent):
    """takes a string and returns a list of lemmatized words that are not in the NLTK english stopwords
    Args:
        sent (str|list): string or list of strings
    Returns:
        list: list of lemmatized version of the original text
    """
    import re
    from nltk.stem import WordNetLemmatizer
    from nltk.corpus import stopwords
    stop_words= stopwords.words("english")
    lemmatizer= WordNetLemmatizer()

    if type(sent) == list:
        # print("dtype is list of strings")
        text= " ".join(sent)
        extracted_words=  re.findall(r'(?:\\+[\']?t|\\+n|<[^>]+>|[-]{2,}|&amp|https?://[^\s]+)|(\d+[,]\d+ ?[xX]? ?\d+[,]\d+|[a-zA-Z0-9-/.]+)', string= text)
        filtered_words= [word.lower() for word in extracted_words if (word not in stop_words) & (len(word)>1)]
        lemmatized_words= [lemmatizer.lemmatize(word) for word in filtered_words]
        return lemmatized_words
    elif type(sent) == str:
        # print("dtype is string")
        extracted_words=  re.findall(r'(?:\\+[\']?t|\\+n|<[^>]+>|[-]{2,}|&amp|https?://[^\s]+)|(\d+[,]\d+ ?[xX]? ?\d+[,]\d+|[a-zA-Z0-9-/.]+)', string= sent)
        filtered_words= [word.lower() for word in extracted_words if (word not in stop_words) & (len(word)>1)]
        lemmatized_words= [lemmatizer.lemmatize(word) for word in filtered_words]
        return lemmatized_words

def consolidate_text_columns(df):
    """consolidate_text_columns takes the df and combines vectorized text from category, description, brand, feature, title
    columns into one consolidated_text column and extract alphanumeric characters only

    Args:
        df (dataframe): target dataframe

    Returns:
        df (dataframe): updated dataframe with full_feature column
    """
    df["consolidated_text_column"]= (df["category"]+ df["description"]+ df["brand"].str.split()+ df["feature"] +df["title"]).map(pd.unique)
    # df.drop(columns= ["category", "description", "brand", "feature", "title"], inplace= True)
    print("Consolidated vectorized text column created")
    return df

############################################################################################################################################
#REVIEW DF FUNCTIONS
############################################################################################################################################
def clean_review_column(df):
    """
    clean_review_text_column function takes in a dataframe, dropping any reviewText duplicates

    Args:
        df (data_frame): review data_frame
    Returns:
        df: cleaned version of the dataframe
    """

    #dropping any duplicates
    print('Dropping any duplicates in the reviewText column')
    df = df.drop_duplicates(subset=['reviewText'])

    #filtering any unverified reviews out
    # print('Let us filter the unverified reviews out')
    # df = df[df['verified']==True]
    return df

def clean_review(sent):
    """
    takes a string
    - remove punctuations
    - lowercase all words
    - tokenize
    - lemmatize
    - remove stopwords

    and returns a list of lemmatized words that are not in the NLTK english stopwords

    Args:
        sent (str|list): string or list of strings
    Returns:
        list: list of lemmatized version of the original text
    """

    import re
    from nltk.stem import WordNetLemmatizer
    from nltk.corpus import stopwords
    stop_words= stopwords.words('english')
    lemmatizer= WordNetLemmatizer()

    if (type(sent) == list):
        text= ' '.join(sent)
        extracted_words=  re.findall(r'(\w+|\d\'\d)', string=text)
        filtered_words= [word.lower() for word in extracted_words if (word not in stop_words) & (len(word)>1)]
        lemmatized_words= [lemmatizer.lemmatize(word) for word in filtered_words]
        return lemmatized_words
    elif type(sent) == str:
        # print('dtype is string')
        extracted_words=  re.findall(r"(\w+|\d\'\d)", string=sent) #FIX THIS, if want to capture 5'6" for example
        filtered_words= [word.lower() for word in extracted_words if (word not in stop_words) & (len(word)>1)]
        lemmatized_words= [lemmatizer.lemmatize(word) for word in filtered_words]
        return lemmatized_words

def create_full_feature_review(df):
    """
    create_full_feature_review takes the review df,
    and combines reviewText, summary columns
    into one full_review_features column and extract alphanumeric characters only

    Args:
        df (dataframe): target dataframe
    Returns:
        df (dataframe): updated dataframe with full_review_features column
    """
    df["reviewText"]= df["reviewText"].apply(lambda row: row if isinstance(row, list) else [])
    df["summary"]= df["summary"].apply(lambda row: row if isinstance(row, list) else [])
    df['features']= (df['reviewText']+ df['summary']).map(pd.unique)
    df.drop(columns= ['reviewText', 'summary'], inplace= True)
    return df

##########################################################################################################################
#FEATURE SELECTION HELPER FUNCTIONS
#########################################################################################################################
def handpicked_features_creator(df):
    """quantify_features returns a df with a new column 'quantified_features_array' where it grants a binary classification of availability or absence of tech1, tech2 and calculates number of images per products and words in description

    Args:
        df (dataframe): target dataframe

    Returns:
        df: dataframe with a new 'quantified_features_array' column
    """
    # creating binary columns for tech1 and tech2 where 1 is given if it contains data else 0
    df["len_tech1"], df["len_tech2"]= [np.where(df[tech].map(len) >0, 1, 0) for tech in ["tech1", "tech2"]]
    #create column to count how many images are provided for a product
    df["num_image"]= df["imageURLHighRes"].map(len)
    #counting the number of words in description column
    df["descrption_num"]= df["description"].map(len)
    df["handpicked_features"]= [np.array([float(len_tech1), float(len_tech2), float(num_img), float(desc_num)]) for len_tech1, len_tech2, num_img, desc_num in zip(df["len_tech1"], df["len_tech2"], df["num_image"], df["descrption_num"])]
    return df

def wordvec_features_creator(df):
    from word2vec import get_pretrained_model, generate_dense_features
    """wordvec_features is a helper function that initiated a pretrained wordvec model, runs it on the consolidated_text_column and
    returns a features column of the either the mean or the full wordvec array for the every product

    Args:
        df (data frame): target data frame with a consolidated_text_column

    Returns:
        data frame: data frame with
    """
    import yaml
    with open("params.yaml", 'r') as file:
        params= yaml.safe_load(file)
    word2vec_model_name= params["preprocess_products"]["word2vec_model_name"]

    #Get and initialize pretrained word2vec model
    word2vec_model= get_pretrained_model(word2vec_model_name)
    #creating wordvec columns to the df
    df["word2vec_features"]= df["consolidated_text_column"].apply(lambda text: generate_dense_features(tokenized_text= text, model= word2vec_model, use_mean= True))
    return df

def tfidf_vectorizer_df(df):
    from sklearn.feature_extraction.text import TfidfVectorizer
    '''
    This function taking in a df and extracts the consolidated_text_column as a corpus that is a list of text (sentences),
    or list of strings
    and appends the results to the tfidf features.

    Inputs:
    1. corpus: per category review data, list of strings

    Outputs:
    1. df with a tfidf features column
'''
    import yaml
    with open("params.yaml", "r") as file:
        params= yaml.safe_load(file)
    max_df= params["tfidf"]["max_df"]
    min_df= params["tfidf"]["min_df"]

    corpus= [" ".join(lst) for lst in df.consolidated_text_column]
    vectorizer= TfidfVectorizer(max_df=max_df, min_df=min_df)
    vec= vectorizer.fit_transform(corpus)
    df["tfidf"]= [np.array(i) for i in zip(*vec.toarray().T)]

    return df

def tfidf_vectorizer_arr(X_train, X_val, X_test, min_df, max_df):
    from sklearn.feature_extraction.text import TfidfVectorizer

    train_corpus= [" ".join(lst) for lst in X_train]
    val_corpus= [" ".join(lst) for lst in X_val]
    test_corpus= [" ".join(lst) for lst in X_test]
    vectorizer= TfidfVectorizer(max_df=max_df, min_df=min_df)
    #create vecs from trained vectorizer on train coprus
    train_vec= vectorizer.fit_transform(train_corpus)
    val_vec= vectorizer.transform(val_corpus)
    test_vec= vectorizer.transform(test_corpus)
    train_arr= [np.array(i) for i in zip(*train_vec.toarray().T)]
    val_arr= [np.array(i) for i in zip(*val_vec.toarray().T)]
    test_arr= [np.array(i) for i in zip(*test_vec.toarray().T)]
    return train_arr, val_arr, test_arr


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2018/5/23 14:15
# @Author  : zhouyuyao
# @File    : demon1.py
import multiprocessing
import os
import time
from datetime import datetime

def subprocess(number):
    # 子进程
    print('这是第{0}个子进程'.format(number))
    pid = os.getpid()              # 得到当前进程号
    print('当前进程号：{0}，开始时间：{1}'.format(pid, datetime.now().isoformat()))
    time.sleep(30)                 # 当前进程休眠30秒
    print('当前进程号：{0}，结束时间：{1}'.format(pid, datetime.now().isoformat()))

def mainprocess():
    # 主进程
    print('这是主进程，进程编号：{0}'.format(os.getpid()))
    t_start = datetime.now()
    pool = multiprocessing.Pool()
    for i in range(8):
        pool.apply_async(subprocess, args=(i,))
    pool.close()
    pool.join()
    t_end = datetime.now()
    print('主进程用时：{0}毫秒'.format((t_end - t_start).microseconds))

if __name__ == '__main__':
    # 主测试函数
    mainprocess()


from django.shortcuts import render, get_object_or_404
from .models import Download, Item

# Create your views here.
def list_page(request):
    queryset = Download.objects.all()
    context = {
        'object_list': queryset
    }
    return render(request, 'downloads/list.html', context)

def detail_page(request, item_id):
    qs = get_object_or_404(Download, pk=item_id)
    context = {
        'object': qs
    }
    return render(request, 'downloads/detail.html', context)


print("========== LOJAS AMERICANAS ==========")
valor = float(input("Valor das compras? R$"))
print("[1] á vista dinheiro/cheque")
print("[2] á vista no cartão")
print("[3] em até 2x no cartão")
print("[4] 3x ou mais no cartão")

opcao = int(input("Qual a sua opção? "))

if opcao == 1:
    novo = valor * 10/100

    print(f"O valor de R${valor} pagando á vista no dinheiro/cheque terá um desconto de 10%, então ficara R${valor - novo}")
elif opcao == 2:
    novo2 = valor * 5/100

    print(f"O valor de R${valor} pagando á vista no cartão terá um desconto de 5%, então ficara R${valor - novo2}")
elif opcao == 3:
    parcela = int(input("Digite em quantas vezes: "))

    if parcela <= 2:
        novo3 = valor / parcela
        print(f"Parcelando em {parcela} sairá por R${novo3} por mês")
    else:
        print("Para parcelar acima de 2x selecione a opção número 4")

elif opcao == 4:
    parcela = int(input("Digite em quantas vezes: "))

    if parcela >= 3:
        novo4 = valor / parcela
        juros = (novo4 * 20/100) + novo4
        print(f"O valor de R${valor} parcelando em 3x ou mais no cartão terá 20% de juros, então saira por R${juros}")
    else:
        print("Para parcelar abaixo de 3x selecione a opção 3")
else:
    print("OPÇÃO INVÁLIDA de pagamento. Tente novamente!!!")


"""
Hold the functionality of Image Recognition and Verification
"""

import face_recognition
import numpy as np
from PIL import Image, ImageDraw

class Image_recog:
    """ Holds the functionality of testing similarity between two images """

    def __init__(self, im1, im_smiling, im_not_smiling):
        self.im_known = im1
        self.im_smiling = im_smiling
        self.im_not_smiling = im_not_smiling

    def is_similar(self):
        """
        Checks if two images are similar - the same person

        Returns:
             bool. True for the same person False otherwise
        """
        known_image = face_recognition.load_image_file(self.im_known)
        unknown_image = face_recognition.load_image_file(self.im_not_smiling)

        known_encoding = face_recognition.face_encodings(known_image)[0]
        unknown_encoding = face_recognition.face_encodings(unknown_image)[0]

        results = face_recognition.compare_faces([known_encoding],
                                                 unknown_encoding)
        return results[0]

    def calc_distance(self, a, b):
        """
        Calculates the distance between two points

        Args:
            a(tuple): first point (x,y)
            b(tuple): second point (x,y)

        Returns:
            (float): The distance between two points
        """
        return ((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) ** .5

    def calc_distance_from_line(self, m, y, point):
        """
        Calculate the distance of a point from a line

        Args:
            m(float): the slop of the line
            y(float): the intercept of the line
            point(tuple): the given point (x,y)

        Returns:

        slope in decimal, y intercept, (x,y)
        """
        a = m
        b = -1
        c = y
        m = point[0]
        n = point[1]
        return abs(a * m + b * n + c) / ((a) ** 2 + (b) ** 2) ** .5

    def calc_slop_intercept(self, a, b):
        """
        Calculates the slop and intercept between two points

        Args:
            a(tuple): 1st point (x,y)
            b(tuple): 2nd point (x,y)

        Return
            float. slope(m),
            float. y intercept(y)
        """
        x1, y1, x2, y2 = a[0], a[1], b[0], b[1]
        x1 = float(x1)
        y1 = float(y1)
        slope = (x2 - x1) / (y2 - y1)
        x, y = a[0], a[1]
        while x != 0:
            if x < 0:
                x += 1
                y += slope
            if x > 0:
                x -= 1
                y -= slope
        yint = y
        return slope, yint

    def calc_triangle_area(self, a, b, c):
        """
        Calculate triangle area given 3 points

        Args:
            a(tuple): 1st point (x,y)
            b(tuple): 2nd point (x,y)
            c(tuple): 3rd point (x,y)

        Returns:
             float. triangle area
        """
        h = self.calc_distance(a, b)
        m, y = self.calc_slop_intercept(a, b)
        b = self.calc_distance_from_line(m, y, c)
        return .5 * h * b

    def is_smiling_ratio(self):
        image = face_recognition.load_image_file(self.im_smiling)
        face_landmarks_list = face_recognition.face_landmarks(image)

        # print("I found {} face(s) in this photograph.".format(
        # len(face_landmarks_list)))

        if not self.is_similar_smiling():
            return False

        for face_landmarks in face_landmarks_list:

            # Print the location of each facial feature in this image
            facial_features = [
                'chin',
                'left_eyebrow',
                'right_eyebrow',
                'nose_bridge',
                'nose_tip',
                'left_eye',
                'right_eye',
                'top_lip',
                'bottom_lip'
            ]

            # for facial_feature in facial_features:
            # print("The {} in this face has the following points: {
            # }".format(facial_feature, face_landmarks[facial_feature]))

            x_1 = [z[0] for z in face_landmarks["bottom_lip"]]
            x_2 = [z[0] for z in face_landmarks["top_lip"]]
            y_1 = [z[1] for z in face_landmarks["bottom_lip"]]
            y_2 = [z[1] for z in face_landmarks["top_lip"]]

            """plt.plot(x_1 + x_2, y_1 + y_2)
            plt.plot(x_1[3], y_1[3], "*", c='r')
            plt.plot(x_2[3], y_2[3], "*", c='b')
            plt.plot(x_1[9], y_1[9], "*", c='g')
            plt.plot(x_2[9], y_2[9], "*", c='k')
            plt.savefig('data/' + "tal")"""

            lowest = y_1[3]
            low = y_1[9]
            uppest = y_2[3]
            up = y_2[9]
            # distance_smile.append(triArea(left, right, top))
            ratio = np.abs((low - up) / (lowest - uppest))

            # print(distance_smile[i])

            # Let's trace out each facial feature in the image with a line!
            pil_image = Image.fromarray(image)
            d = ImageDraw.Draw(pil_image)

            for facial_feature in facial_features:
                d.line(face_landmarks[facial_feature], width=5)

            # pil_image.show()

        if ratio > 0.30:
            return True
        else:
            return False

    def is_similar_smiling(self):
        """
        Checks if two images are similar - the same person

        Returns:
             bool. True for the same person False otherwise
        """
        known_image = face_recognition.load_image_file(self.im_known)
        unknown_image = face_recognition.load_image_file(self.im_smiling)

        known_encoding = face_recognition.face_encodings(known_image)[0]
        unknown_encoding = face_recognition.face_encodings(unknown_image)[0]

        results = face_recognition.compare_faces([known_encoding],
                                                 unknown_encoding)
        return results[0]

    def is_smiling(self):
        """
        Compares two picture and check if a person is smiling or not

        Returns:
            bool. : True if smiling, False otherwise
        """
        # Retrive images:
        image1 = face_recognition.load_image_file(self.im_smiling)
        image2 = face_recognition.load_image_file(self.im_not_smiling)
        distance_smile = []

        print(self.is_similar_smiling())
        if not self.is_similar_smiling():
            return False

        i = 0
        images = [image1, image2]
        for image in images:

            face_landmarks_list = face_recognition.face_landmarks(image)

            for face_landmarks in face_landmarks_list:

                # Print the location of each facial feature in this image
                facial_features = [
                    'chin',
                    'left_eyebrow',
                    'right_eyebrow',
                    'nose_bridge',
                    'nose_tip',
                    'left_eye',
                    'right_eye',
                    'top_lip',
                    'bottom_lip'
                ]

                x_1 = [z[0] for z in face_landmarks["bottom_lip"]]
                x_2 = [z[0] for z in face_landmarks["top_lip"]]
                y_1 = [z[1] for z in face_landmarks["bottom_lip"]]
                y_2 = [z[1] for z in face_landmarks["top_lip"]]

                left = (x_2[0], y_2[0])
                right = (x_1[0], y_1[0])
                top = (x_1[3], y_1[3])
                distance_smile.append(
                    self.calc_triangle_area(left, right, top))

                # Let's trace out each facial feature in the image with a line!
                pil_image = Image.fromarray(image)
                d = ImageDraw.Draw(pil_image)

                for facial_feature in facial_features:
                    d.line(face_landmarks[facial_feature], width=5)

                i += 1

        # Smiling if the ration of lips triangle is larger than 1:
        if (distance_smile[0] / distance_smile[1]) > 1:
            return (True and self.is_similar_smiling())
        else:
            return (False and self.is_similar_smiling())

# test_reco = Image_recog("/Users/carlalasry/Downloads/carla1.png",
# "/Users/carlalasry/Desktop/carla_smile.jpg",
# "/Users/carlalasry/Desktop/carla_not_smile.jpg")


# Menu drive banking app
# PAN number is considered as Primary key for all banking operations
# Customer Name,Account Number,Balance, Date of Birth, Phone Number, Address are stored as customer details

import datetime
import os,sys
import re
import random
import csv
import pandas as pd

def create_acc():
    custName = input("Enter the account holderr name: ")
    custName = custName.title()

    # input validation for date to check if in DD/MM/YYYY format
    dob = input("Enter the date of birth in format DD/MM/YYYY: ")
    try:
        d_o_b = datetime.datetime.strptime(dob, "%d/%m/%Y")
    except:
        print("Incorrect date!")
        sys.exit(1)

    # input data validation to check if phone number is 10 digits and starts with 91 or 0
    phnum = input("Enter phone number: ")
    regex= "^(0|91)?[7-9][0-9]{9}$"
    if re.match(regex,phnum):
        pass
    else:
        print("Invalid phone number")
        sys.exit(1)

    # input validation to check if PAN is valid
    pan = input("Enter PAN number: ")
    regex1 = "[A-Z]{5}[0-9]{4}[A-Z]{1}"
    if re.match(regex1,pan):
        pass
    else:
        print("Invalid PAN")
        sys.exit(1)

    address = input("Enter address: ")

    balance = int(input("Enter a minimum deposit amount of 1000: "))

    # generate a 7 digit unique and random account number
    account_no = int(''.join(random.sample('0123456789', 5)))+int(''.join(random.sample('0123456789', 7)))

    customer_details = [custName,account_no,balance,dob,phnum,pan,address]

    with open(r'bank_details.csv', 'a') as f:
        writer = csv.writer(f)
        writer.writerow(customer_details)

    print("Do you want to perform any other operation? (y / n)")
    choice = input().strip()
    if choice == "y":
        main()
1

def deposit_amt():

    pan = input("Enter your PAN number: ")

    deposit_amt = int(input("Enter the amount to be deposited: "))

    df = pd.read_csv("bank_details.csv")

    current_balance = df.loc[df['PAN'] == pan ,'Balance']
    print("Current Balance: ",current_balance)

    add_balance = int(current_balance) + int(deposit_amt)

    df.loc[df["PAN"] == pan, "Balance"] = add_balance

    df.to_csv("bank_details.csv", index=False)

    new_balance = df.loc[df['PAN'] == pan ,'Balance']
    # convert the data frame output to string to remove Name and dtype columns
    print("New Balance: ",new_balance.to_string(index=False))

    print("Do you want to perform any other operation? (y / n)")
    choice = input().strip()
    if choice == "y":
        main()

def withdraw_amt():
    pan = input("Enter your PAN number: ")

    withdraw_amt = int(input("Enter the amount to withdraw: "))

    df = pd.read_csv("bank_details.csv")

    current_balance = df.loc[df['PAN'] == pan ,'Balance']
    print("Current Balance: ",current_balance)

    # check if the amount entered doesnt exceed the current balance, abort withdrawal operation

    if int(current_balance) >= int(withdraw_amt):
        deduct_balance = int(current_balance) - int(withdraw_amt)
    else:
        print("WARNING: Insufficient balance in account to withdraw..!!!")
        sys.exit(1)

    df.loc[df["PAN"] == pan, "Balance"] = deduct_balance

    df.to_csv("bank_details.csv", index=False)

    new_balance = df.loc[df['PAN'] == pan ,'Balance']
    print("New Balance: ",new_balance.to_string(index=False))

    print("Do you want to perform any other operation? (y / n)")
    choice = input().strip()
    if choice == "y":
        main()

def balance_enquiry():
    pan = input("Enter your PAN number: ")

    df = pd.read_csv("bank_details.csv")

    current_balance = df.loc[df['PAN'] == pan ,'Balance']
    print("Currently you balance is : ",current_balance.to_string(index=False))

    print("Do you want to perform any other operation? (y / n)")
    choice = input().strip()
    if choice == "y":
        main()

def modify_acc_det():
    pan = input("Enter your PAN number: ")

    df = pd.read_csv("bank_details.csv")

    print("(1)Phone Number")
    print("(2)Address")

    c = int(input("Enter choice to modify account details: "))

    if c == 1:
        new_phone_num = input("Enter the phone number to be updated: ")
        df.loc[df["PAN"] == pan, "Phone Number"] = new_phone_num
        df.to_csv("bank_details.csv", index=False)

    elif c ==2:
        new_address = input("Enter you new residence address to be updated: ")
        df.loc[df["PAN"] == pan, "Address"] = new_address
        df.to_csv("bank_details.csv", index=False)
    else:
        print("Invalid Option...Exiting \n")
        sys.exit(1)

    print("Do you want to perform any other operation? (y / n)")
    choice = input().strip()
    if choice == "y":
        main()

def close_acc():
    pan = input("Enter your PAN number: ")

    df = pd.read_csv("bank_details.csv")

    current_balance = df.loc[df['PAN'] == pan ,'Balance']

    # delete/close an account only if the currect balance is nil

    if (current_balance.to_string(index=False)) > '0':
        print("Cannot close account, as account has more than zero balance. Do appropriate withdrawal \n")
    else:
        print("Closing account")
        df = pd.read_csv("bank_details.csv", index_col = "PAN")
        df.drop([pan], inplace = True)
        df.to_csv("bank_details.csv", index=False)

    print("Do you want to perform any other operation? (y / n)")
    choice = input().strip()
    if choice == "y":
        main()

# Main Function for Menu-Driven
def main():

    print("(1)Create New Account")
    print("(2)Deposit")
    print("(3)Withdrawal")
    print("(4)Balance Enquiry")
    print("(5)Modify Account Details")
    print("(6)Close Account")

    choice = int(input("Enter choice: "))

    choice_dict = {
        1: create_acc,
        2: deposit_amt,
        3: withdraw_amt,
        4: balance_enquiry,
        5: modify_acc_det,
        6: close_acc,
    }

    choice_dict[choice]()

if __name__ == "__main__":
    print("----------------------Welcome to Banking App----------------------")

main()


############## 주의 ##############
# 입력을 받기위한 input 함수는 절대 사용하지 않습니다.
# 내장 함수 sum, min, max, len 함수를 사용하지 않습니다.
# 사용시 감점처리 되니 반드시 확인 바랍니다.
def get_row_col_maxsum(matrix):
    length_r = 0                # 행의 크기
    length_c = 0                # 열의 크기
    flag = 0                    # 최대값이 나온 줄이 행인지 열인지 판단
    ans = -int(10e10)           # 설마 이거보다 작은 수가 최대값이겠나
    for _ in matrix:            # 행의 크기를 구해보자
        length_r += 1
    for _ in matrix[0]:         # 열의 크기를 구해보자.
        length_c += 1           # 직사각행렬임이 보장된다고 했다. 0번째만 보면 되겠지.

    for j in range(length_c):      # 특정 열의 합이 가장 큰 지부터 살펴보자.
        total = 0                  # 매순간 합계를 초기화
        for i in range(length_r):
            total += matrix[i][j]  # 특정 행의 모든 j번째 숫자를 더하기
        if total > ans:            # 만일 다 더한 수가 이전 합보다 크다면?
            ans = total            # 이 수가 제일 크네
            flag = 1               # 그리고 이 합계는 열에서 나온거야

    for i in range(length_r):      # 이번에는 특정 행의 합을 보자
        total = 0
        for j in range(length_c):
            total += matrix[i][j]
        if total > ans:
            ans = total
            flag = 0               # 이 합계는 행에서 나왔음.

    if flag:
        return 'col', ans
    else:
        return 'row', ans
    # 여기에 코드를 작성하여 함수를 완성합니다.

# 아래 코드는 실행 확인을 위한 코드입니다.
if __name__ == '__main__':
    # 예시 코드는 수정하지 마세요.
    example_matrix = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16]
    ]

    example_matrix2 = [
        [11, 5, 49, 20],
        [28, 16, 20, 33],
        [63, 17, 1, 15]
    ]
    print(get_row_col_maxsum(example_matrix))   # => ('row', 58)
    print(get_row_col_maxsum(example_matrix2))  # => ('col', 102)

    # 여기부터 아래에 추가 테스트를 위한 코드 작성 가능합니다.


#!/usr/bin/env python3

def main():
    with open('input.txt') as f:
        lines = [x.strip() for x in f.readlines()]

    output_sum = 0

    for l in lines:
        print(l)
        (pattern, output) = l.split(' | ')
        pattern = pattern.split()
        output = output.split()

        known_pat = {}
        known_pat[1] = [x for x in pattern if len(x) == 2][0]
        print('#1 is %s' % known_pat[1])
        known_pat[4] = [x for x in pattern if len(x) == 4][0]
        print('#4 is %s' % known_pat[4])
        known_pat[7] = [x for x in pattern if len(x) == 3][0]
        print('#7 is %s' % known_pat[7])
        known_pat[8] = [x for x in pattern if len(x) == 7][0]
        print('#8 is %s' % known_pat[8])

        known_seg = {}
        # 0 doesn't appear in digit 1, does in 7
        known_seg[0] = [x for x in known_pat[7] if x not in known_pat[1]][0]
        print('0 is %s' % known_seg[0])
        # Segment 5 is always lit except for on digit 2, so will appear exactly 9 times.
        all_seg = ''.join(pattern)
        known_seg[5] = [x for x in all_seg if all_seg.count(x) == 9][0]
        print('5 is %s' % known_seg[5])
        # Segment 2 is the other segment of digit 1
        known_seg[2] = [x for x in known_pat[1] if x != known_seg[5]][0]
        print('2 is %s' % known_seg[2])
        # digit 6 is missing only segment 2
        known_pat[6] = [x for x in pattern if len(x) == 6 and known_seg[2] not in x][0]
        print('#6 is %s' % known_pat[6])
        # Digit 2 has length 5 and missing segment 5
        known_pat[2] = [x for x in pattern if len(x) == 5 and known_seg[5] not in x][0]
        print('#2 is %s' % known_pat[2])
        # Digit 3 has length 5 and 0,2,5
        known_pat[3] = [x for x in pattern if len(x) == 5 and (known_seg[0] in x and known_seg[2] in x and known_seg[5] in x)][0]
        print('#3 is %s' % known_pat[3])
        # Digit 5 has length 5 and missing segment 2
        known_pat[5] = [x for x in pattern if len(x) == 5 and known_seg[2] not in x][0]
        print('#5 is %s' % known_pat[5])
        # Just 9 and 0 to go. I am very good at programming.
        # Segment 4 is not in 3, 4 or 5
        known_seg[4] = [x for x in 'abcdefg' if x not in known_pat[3] and x not in known_pat[4] and x not in known_pat[5]][0]
        print('4 is %s' % known_seg[4])
        known_pat[9] = [x for x in pattern if len(x) == 6 and known_seg[4] not in x][0]
        print('#9 is %s' % known_pat[9])
        known_pat[0] = [x for x in pattern if x not in known_pat.values()][0]
        print('#0 is %s' % known_pat[0])

        real_output = ''
        for o in output:
            real_output += str([x for x in known_pat.keys() if sorted(known_pat[x]) == sorted(o)][0])

        output_sum += int(real_output)

    print('Output sum: %d' % (output_sum))

if __name__ == '__main__':
    main()


class Solution:
    def maxScore(self, cardPoints: List[int], k: int) -> int:
        cumaltativeSum = [0]
        count = 0
        for i in cardPoints:
            count+=i
            cumaltativeSum.append(count)
        count = 0
        backsum = [0]
        for i in cardPoints[::-1]:
            count+=i
            backsum.append(count)
        final = [cumaltativeSum[i] + backsum[k-i] for i in range(k+1)]
        #print(cumaltativeSum,backsum,final)
        return max(final)


from scipy.ndimage import label as bwlabel
from computeNsSystem import computeNsSystem
from computeLinesDC import computeLinesDC, compute_lines_data_cost
from computeLinesLabelCost import computeLineLabelCost
import numpy as np
from LineExtraction_GC_MRFminimization import LineExtraction_GC_MRFminimization, line_extraction_GC

# @partial_image(2, "post_process_by_mfr")
def post_process_by_mfr(labeled_raw_components, raw_components_num, lines_mask, char_range):
    cc_sparse_ns = computeNsSystem(labeled_raw_components, raw_components_num)
    [result, labels, num_lines] = post_process_by_mfr_helper(labeled_raw_components,
                                                             raw_components_num,
                                                             lines_mask,
                                                             char_range,
                                                             cc_sparse_ns)
    return [result, labels, num_lines]

def post_process_by_mfr_helper(labeled_raw_components, raw_components_num, line_mask, char_range, cc_sparse_ns=None):
    # line mask should be binarized already
    line_mask_lables, n_masked_lines = bwlabel(line_mask, np.ones((3,3)))
    data_cost = compute_lines_data_cost(line_mask_lables, n_masked_lines, labeled_raw_components, raw_components_num,
                                         char_range[1])

    label_cost = computeLineLabelCost(labeled_raw_components, line_mask_lables, n_masked_lines)

    labels = line_extraction_GC(raw_components_num, n_masked_lines, data_cost, cc_sparse_ns, label_cost)

    result = drawLabels(labeled_raw_components, labels)
    return [result, labels, n_masked_lines]

# L = original image
def PostProcessByMRFHelper(L, num, LineMask, CCsparseNs, charRange):
    # LineLabels, n_label = bwlabel(LineMask.__invert__())
    LineLabels, n_label = bwlabel(LineMask)
    print("got {} labels".format(n_label))
    Lines, numLines = LineLabels, n_label
    # Lines, numLines = permuteLabels(LineLabels)
    Dc = computeLinesDC(Lines, numLines, L, num, charRange[1])
    LabelCost = computeLineLabelCost(L, Lines, numLines)
    Labels = LineExtraction_GC_MRFminimization(numLines, num, CCsparseNs, Dc, LabelCost)
    Labels[Labels == numLines + 1] = 0
    # residualLines = np.isin(Lines, Labels)
    # Lines[residualLines.__invert__()] = 0
    result = drawLabels(L, Labels)
    # RefinedCCs = RefineBinnaryOverlappingComponents(L, num, Lines, numLines)

    # tempMask = RefinedCCs >= 0

    # result[tempMask] = RefinedCCs[tempMask]
    return [result, Labels, numLines]

def drawLabels(L, Labels):
    L = np.uint16(L)
    LUT = np.zeros(65536, np.uint16)
    LUT[1:len(Labels) + 1] = Labels
    result = np.double(LUT[L])
    return result


# -*- coding: utf-8 -*-
"""
Created on Mon Nov  7 21:37:25 2022

@author: Han
"""

import torch
import numpy as np
import pandas as pd
import warnings
import time
from utils import mapping, normalization
from ATCNN_model import ATCNN, switch, to_binary, ATCNN_9LiFi
warnings.filterwarnings("ignore")

# test normalised and mirrored dataset
def test_acc_ATCNN(input_path, output_path, AP_num, UE_num):
    #print('******Loading Input data******')
    data = pd.read_csv(input_path, header=None)
    values = np.array(data).T.tolist() # with dimension of 256*300
    trained_output = []
    test_UE_num = 1 # revise here
    sample_number = 256

    for i in range(sample_number):
        condition = values[i]
        condition = torch.tensor(condition)
        output_instance = []
        for j in range(test_UE_num):
            raw_condition = torch.tensor(values[i])
            condition_now = switch(raw_condition, j, AP_num+1) # switch j-th UE into last position
            condition_now = torch.tensor([condition_now])

            # Target = condition_now[..., 0:user_dim]
            Target = condition_now[..., 0+j*user_dim:(j+1)*user_dim]
            # Target = condition_now[..., -user_dim:]

            Condition = condition_now[..., 0:]

            output = Trained_Net.forward(Target, Condition)
            binary_output = to_binary(AP_num, output.tolist())
            output_instance.extend(binary_output)
        trained_output.append(output_instance) ###

    #print('******Loading Output data******')
    label = pd.read_csv(output_path, header=None)
    real_output = pd.DataFrame(label)
    real_output = np.array(real_output).T.tolist()

    count = 0
    for i in range(sample_number):
        for j in range(test_UE_num):
            real_output_now = real_output[i][0+j*AP_num:(j+1)*AP_num]
            # real_output_now = real_output[i][0+(j+9)*AP_num:(j+10)*AP_num]
            trained_output_now = np.array(trained_output[i][0+j*AP_num:(j+1)*AP_num])
            if all(real_output_now == trained_output_now):
                pass
            else:
                count = count + 1
    acc = 1 - count/sample_number/test_UE_num
    return acc

# test raw dataset without normalization and mapping
def test_acc_ATCNN_raw(input_path, output_path, AP_num, UE_num, test_UE_num, SNR_min):
    #print('******Loading Input data******')
    data = pd.read_csv(input_path, header=None)
    values = np.array(data).T.tolist() # with dimension of 256*300
    trained_output = []

    for i in range(256):
        condition = values[i]
        condition = torch.tensor(condition)
        output_instance = []
        for j in range(test_UE_num):
            raw_condition = torch.tensor(values[i])
            condition_now = switch(raw_condition, j, AP_num+1)
            condition_now = torch.tensor([condition_now])

            mirroring_condition = mapping([UE_num]*256, condition_now.tolist(), AP_num)

            nor_mirroring_condition = normalization(50, AP_num, mirroring_condition, 60, SNR_min, 1000) # nomalization is correct

            nor_mirroring_condition = torch.tensor(nor_mirroring_condition).to(torch.float32)

            Target = nor_mirroring_condition[..., 0:user_dim]
            Condition = nor_mirroring_condition[..., 0:]

            output = Trained_Net.forward(Target, Condition)
            binary_output = to_binary(AP_num, output.tolist())
            output_instance.extend(binary_output)
        trained_output.append(output_instance) ###

    #print('******Loading Output data******')
    label = pd.read_csv(output_path, header=None)
    real_output = pd.DataFrame(label)
    real_output = np.array(real_output).T.tolist()

    count = 0
    for i in range(256):
        for j in range(test_UE_num):
            real_output_now = real_output[i][0+j*AP_num:(j+1)*AP_num]
            trained_output_now = np.array(trained_output[i][0+j*AP_num:(j+1)*AP_num])
            if all(real_output_now == trained_output_now):
                pass
            else:
                count = count + 1
    acc = 1 - count/256/test_UE_num
    return acc

# 9 LiFi size
# user_dim = 11 #
# output_dim = 10 #
# cond_dim = 550 #
# SNR_min = -20

# 4 LiFi size
user_dim = 6 #
output_dim = 5 #
cond_dim = 300 #
# SNR_min = 0 # 4 LiFi, 1W case
SNR_min = 15 # 4 LiFi, 3W case

Trained_Net = ATCNN(input_dim=user_dim, cond_dim=cond_dim, cond_out_dim=user_dim, output_dim=output_dim)
# Trained_Net = ATCNN_9LiFi(input_dim=user_dim, cond_dim=cond_dim, cond_out_dim=user_dim, output_dim=output_dim)
device = torch.device('cpu')

model_name = "trained_model/GT_ATCNN_4LiFi_3W_Final.pth"
# model_name = "trained_model/4LiFi_AP_SNR_Loss_Final/4LiFi_AP_epoch0.pth"

print('******Loading Net******')
print("Testing ATCNN model name is:", model_name)
Trained_Net.load_state_dict(torch.load(model_name,map_location=torch.device('cpu')), strict=False) # 1000 batch case

# confirmed that the saved net parameters are loaded and unchangable
Trained_Net.eval()
Trained_Net.to(device)
print('******Starting testing different UE number******')

# test dataset used in training process
# input_path = 'dataset/GT_4LiFi_AP_SNR_3W/input_test/nor_mirror_input_batch'
# output_path = 'dataset/GT_4LiFi_AP_SNR_3W/output_test/mirror_output_batch'

# new test dataset
input_path = 'dataset/GT_4LiFi_AP_SNR_3W/input_test_8UE/input_batch'
output_path = 'dataset/GT_4LiFi_AP_SNR_3W/output_test_8UE/output_batch'

input_path_list = []
output_path_list = []

for i in range(5):
    input_path_list.append(input_path+'%s.csv'%(str(i+1001)))
    output_path_list.append(output_path+'%s.csv'%str((i+1001)))

acc_list = []
for i in range(5):
    # UE_list = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
    UE_list = [8]*10

    input_path = input_path_list[i]
    output_path = output_path_list[i]
    UE_num = UE_list[i]
    AP_num = 5
    # acc = test_acc_ATCNN(input_path, output_path, AP_num, UE_num)
    acc = test_acc_ATCNN_raw(input_path, output_path, AP_num, UE_num, 1, SNR_min)
    acc_list.append(acc)
    print('UE number is:', UE_num, 'and Accuracy is:', acc)

print('Aver Acc is:', sum(acc_list)/len(acc_list))


import abc
from typing import (
    Callable,
    TypeVar,
    Any,
    NamedTuple,
    Optional,
    Union,
    Set,
    List,
    Dict,
    Type,
    Tuple,
)

from livestatus import SiteId
from marshmallow import Schema  # type: ignore[import]
from marshmallow.fields import (  # type: ignore[import]
    List as MList, Dict as MDict, Constant, Integer, String, Nested, Boolean,
)

from functools import partial
ReqList = partial(MList, required=True)
ReqDict = partial(MDict, required=True)
ReqConstant = partial(Constant, required=True)
ReqInteger = partial(Integer, required=True)
ReqString = partial(String, required=True)
ReqNested = partial(Nested, required=True)
ReqBoolean = partial(Boolean, required=True)

MacroMappings = Dict[str, str]
SearchResult = Dict[str, str]

import cmk.utils.plugin_registry as plugin_registry
from cmk.utils.bi.type_defs import (
    ActionConfig,
    ComputationConfigDict,
    GroupConfigDict,
    SearchConfig,
)
from cmk.utils.type_defs import (
    HostName,
    ServiceName,
    HostState,
    ServiceState,
    ServiceDetails,
)

NodeComputeResult = NamedTuple("NodeComputeResult", [
    ("state", int),
    ("downtime_state", int),
    ("acknowledged", bool),
    ("output", str),
    ("in_service_period", bool),
    ("state_messages", dict),
])

NodeResultBundle = NamedTuple("NodeResultBundle", [
    ("actual_result", NodeComputeResult),
    ("assumed_result", Optional[NodeComputeResult]),
    ("nested_results", List),
    ("instance", Any),
])

SitesCallback = NamedTuple("SitesCallback", [
    ("states", Callable),
    ("query", Callable),
])

MapGroup2Value = Dict[str, str]

BIServiceData = NamedTuple("BIServiceData", [
    ("tags", Set[str]),
    ("labels", MapGroup2Value),
])

BIHostData = NamedTuple("BIHostData", [
    ("site_id", str),
    ("tags", Set[str]),
    ("labels", MapGroup2Value),
    ("folder", str),
    ("services", Dict[str, BIServiceData]),
    ("children", Tuple[HostName]),
    ("parents", Tuple[HostName]),
    ("alias", str),
    ("name", HostName),
])

BIHostSpec = NamedTuple("BIHostSpec", [
    ("site_id", SiteId),
    ("host_name", HostName),
])
BINeededHosts = Set[BIHostSpec]

BIServiceWithFullState = NamedTuple("BIServiceFullState", [
    ("state", Optional[ServiceState]),
    ("has_been_checked", bool),
    ("plugin_output", ServiceDetails),
    ("hard_state", Optional[ServiceState]),
    ("current_attempt", int),
    ("max_check_attempts", int),
    ("scheduled_downtime_depth", int),
    ("acknowledged", bool),
    ("in_service_period", bool),
])
BIHostStatusInfoRow = NamedTuple("BIStatusInfoRow", [
    ("state", Optional[HostState]),
    ("hard_state", Optional[HostState]),
    ("plugin_output", str),
    ("scheduled_downtime_depth", int),
    ("in_service_period", bool),
    ("acknowledged", bool),
    ("services_with_fullstate", Dict[ServiceName, BIServiceWithFullState]),
    ("remaining_row_keys", dict),
])
BIStatusInfo = Dict[BIHostSpec, BIHostStatusInfoRow]

BIHostSearchMatch = NamedTuple("BIHostSearchMatch", [
    ("host", BIHostData),
    ("match_groups", tuple),
])

BIServiceSearchMatch = NamedTuple("BIServiceSearchMatch", [
    ("host", BIHostData),
    ("service_description", str),
    ("match_groups", tuple),
])

class ABCWithSchema(metaclass=abc.ABCMeta):
    @classmethod
    @abc.abstractmethod
    def schema(cls):
        raise NotImplementedError()

def create_nested_schema_for_class(
        class_template: Type[ABCWithSchema],
        default_schema: Optional[Type[Schema]] = None,
        example_config: Optional[Union[list, Dict[str, Any]]] = None) -> Nested:
    class_schema = class_template.schema()
    return create_nested_schema(class_schema, default_schema, example_config)

def create_nested_schema(base_schema,
                         default_schema: Optional[Type[Schema]] = None,
                         example_config: Optional[Union[list, Dict[str, Any]]] = None) -> Nested:
    """

    >>> from marshmallow import fields
    >>> class Foo(Schema):
    ...      field = fields.String()

    >>> nested = create_nested_schema(Foo)
    >>> nested.default
    {}

    Args:
        base_schema:
        default_schema:
        example_config:

    Returns:

    """
    default_config = get_schema_default_config(default_schema or base_schema)
    example = example_config or default_config
    return ReqNested(
        base_schema,
        default=default_config,
        example=example,
    )

def get_schema_default_config(schema: Type[Schema], params=None) -> Dict[str, Any]:
    """

    >>> from marshmallow import fields
    >>> class Foo(Schema):
    ...       field = fields.String(default="bar")

    >>> get_schema_default_config(Foo)
    {'field': 'bar'}

    >>> get_schema_default_config(Foo, {'field': 'foo', 'omit': 'this'})
    {'field': 'foo'}

    Args:
        schema:
        params:

    Returns:

    """
    return schema().dump({} if params is None else params)

class RequiredBIElement(NamedTuple):
    site_id: SiteId
    host_name: HostName
    service_description: Optional[ServiceName]

class BIAggregationComputationOptions(ABCWithSchema):
    def __init__(self, computation_config: ComputationConfigDict):
        super().__init__()
        self.disabled = computation_config["disabled"]
        self.use_hard_states = computation_config["use_hard_states"]
        self.escalate_downtimes_as_warn = computation_config["escalate_downtimes_as_warn"]

    @classmethod
    def schema(cls) -> Type["BIAggregationComputationOptionsSchema"]:
        return BIAggregationComputationOptionsSchema

class BIAggregationComputationOptionsSchema(Schema):
    disabled = ReqBoolean(default=False, example=False)
    use_hard_states = ReqBoolean(default=False, example=False)
    escalate_downtimes_as_warn = ReqBoolean(default=False, example=False)

class BIAggregationGroups(ABCWithSchema):
    def __init__(self, group_config: GroupConfigDict):
        super().__init__()
        self.names: List[str] = group_config["names"]  # type: ignore
        self.paths: List[List[str]] = group_config["paths"]  # type: ignore

    def count(self) -> int:
        return len(self.names) + len(self.paths)

    @classmethod
    def schema(cls) -> Type["BIAggregationGroupsSchema"]:
        return BIAggregationGroupsSchema

class BIAggregationGroupsSchema(Schema):
    names = MList(ReqString(), default=[], example=["group1", "group2"])
    paths = MList(MList(ReqString()), default=[], example=[["path", "of", "group1"]])

class BIParams(ABCWithSchema):
    def __init__(self, params_config: Dict[str, List[str]]):
        super().__init__()
        self.arguments = params_config["arguments"]
        # Note: The BIParams may get additional options
        # Like keywords which are passed down the tree, without being explicit set for a rule

    @classmethod
    def schema(cls) -> Type["BIParamsSchema"]:
        return BIParamsSchema

class BIParamsSchema(Schema):
    arguments = ReqList(String, default=[], example=["testhostParams"])

T = TypeVar("T", str, dict, list)

def replace_macros(pattern: T, macros: MacroMappings) -> T:
    if isinstance(pattern, str):
        return replace_macros_in_string(pattern, macros)
    if isinstance(pattern, list):
        return replace_macros_in_list(pattern, macros)
    if isinstance(pattern, dict):
        return replace_macros_in_dict(pattern, macros)

def replace_macros_in_list(elements: List[str], macros: MacroMappings) -> List[str]:
    new_list: List[str] = []
    for element in elements:
        new_list.append(replace_macros(element, macros))
    return new_list

def replace_macros_in_dict(old_dict: Dict[str, str], macros: MacroMappings) -> Dict[str, str]:
    new_dict: Dict[str, str] = {}
    for key, value in old_dict.items():
        new_dict[replace_macros(key, macros)] = replace_macros(value, macros)
    return new_dict

def replace_macros_in_string(pattern: str, macros: MacroMappings) -> str:
    for macro, replacement in macros.items():
        pattern = pattern.replace(macro, replacement)
    return pattern

#   .--Results-------------------------------------------------------------.
#   |                   ____                 _ _                           |
#   |                  |  _ \ ___  ___ _   _| | |_ ___                     |
#   |                  | |_) / _ \/ __| | | | | __/ __|                    |
#   |                  |  _ <  __/\__ \ |_| | | |_\__ \                    |
#   |                  |_| \_\___||___/\__,_|_|\__|___/                    |
#   |                                                                      |
#   +----------------------------------------------------------------------+

class ABCBISearcher(metaclass=abc.ABCMeta):
    def __init__(self):
        self.hosts = {}
        self._host_regex_match_cache = {}
        self._host_regex_miss_cache = {}

    @abc.abstractmethod
    def search_hosts(self, conditions: Dict) -> List[BIHostSearchMatch]:
        raise NotImplementedError()

    @abc.abstractmethod
    def search_services(self, conditions: Dict) -> List[BIServiceSearchMatch]:
        raise NotImplementedError()

    @abc.abstractmethod
    def get_host_name_matches(self, hosts: List[BIHostData],
                              pattern: str) -> Tuple[List[BIHostData], Dict]:
        raise NotImplementedError()

    @abc.abstractmethod
    def get_service_description_matches(self, hosts: List[BIHostData],
                                        pattern: str) -> List[BIServiceSearchMatch]:
        raise NotImplementedError()

    @abc.abstractmethod
    def filter_host_choice(self, hosts: List[BIHostData],
                           condition: Dict) -> Tuple[List[BIHostData], Dict]:
        raise NotImplementedError()

    @abc.abstractmethod
    def filter_host_tags(self, hosts: List[BIHostData], condition: Dict) -> List[BIHostData]:
        raise NotImplementedError()

class ABCBIStatusFetcher(metaclass=abc.ABCMeta):
    def __init__(self, sites_callback: SitesCallback):
        self._sites_callback = sites_callback
        self.states: BIStatusInfo = {}
        self.assumed_states: Dict = {}

class ABCBICompiledNode(metaclass=abc.ABCMeta):
    def __init__(self):
        super().__init__()
        self.required_hosts = []

    @classmethod
    @abc.abstractmethod
    def type(cls) -> str:
        raise NotImplementedError()

    @abc.abstractmethod
    def services_of_host(self, host_name: str) -> Set[ServiceName]:
        raise NotImplementedError()

    @abc.abstractmethod
    def compile_postprocess(
        self,
        bi_branch_root: "ABCBICompiledNode",
        bi_searcher: ABCBISearcher,
    ) -> List["ABCBICompiledNode"]:
        raise NotImplementedError()

    @abc.abstractmethod
    def compute(self,
                computation_options: BIAggregationComputationOptions,
                bi_status_fetcher: ABCBIStatusFetcher,
                use_assumed=False) -> Optional[NodeResultBundle]:
        raise NotImplementedError()

    @abc.abstractmethod
    def required_elements(self) -> Set[RequiredBIElement]:
        raise NotImplementedError()

#   .--Action--------------------------------------------------------------.
#   |                       _        _   _                                 |
#   |                      / \   ___| |_(_) ___  _ __                      |
#   |                     / _ \ / __| __| |/ _ \| '_ \                     |
#   |                    / ___ \ (__| |_| | (_) | | | |                    |
#   |                   /_/   \_\___|\__|_|\___/|_| |_|                    |
#   |                                                                      |
#   +----------------------------------------------------------------------+

class ABCBIAction(metaclass=abc.ABCMeta):
    def __init__(self, action_config: Dict[str, Any]):
        super().__init__()

    @classmethod
    @abc.abstractmethod
    def type(cls) -> str:
        raise NotImplementedError()

    @classmethod
    @abc.abstractmethod
    def schema(cls) -> Type[Schema]:
        raise NotImplementedError()

    @abc.abstractmethod
    def execute(self, search_result: Dict[str, str],
                bi_searcher: ABCBISearcher) -> List[ABCBICompiledNode]:
        raise NotImplementedError()

class BIActionRegistry(plugin_registry.Registry[Type[ABCBIAction]]):
    def plugin_name(self, instance: Type[ABCBIAction]) -> str:
        return instance.type()

    def instantiate(self, action_config: ActionConfig) -> ABCBIAction:
        return self._entries[action_config["type"]](action_config)

bi_action_registry = BIActionRegistry()

#   .--Search--------------------------------------------------------------.
#   |                   ____                      _                        |
#   |                  / ___|  ___  __ _ _ __ ___| |__                     |
#   |                  \___ \ / _ \/ _` | '__/ __| '_ \                    |
#   |                   ___) |  __/ (_| | | | (__| | | |                   |
#   |                  |____/ \___|\__,_|_|  \___|_| |_|                   |
#   |                                                                      |
#   +----------------------------------------------------------------------+

class ABCBISearch(metaclass=abc.ABCMeta):
    def __init__(self, search_config: Dict[str, Any]):
        super().__init__()

    @classmethod
    @abc.abstractmethod
    def type(cls) -> str:
        raise NotImplementedError()

    @classmethod
    @abc.abstractmethod
    def schema(cls) -> Type[Schema]:
        raise NotImplementedError()

    @abc.abstractmethod
    def execute(self, macros: MacroMappings, bi_searcher: ABCBISearcher) -> List[Dict]:
        raise NotImplementedError()

class BISearchRegistry(plugin_registry.Registry[Type[ABCBISearch]]):
    def plugin_name(self, instance: Type[ABCBISearch]) -> str:
        return instance.type()

    def instantiate(self, search_config: SearchConfig) -> ABCBISearch:
        return self._entries[search_config["type"]](search_config)

bi_search_registry = BISearchRegistry()

#   .--AggrFunction--------------------------------------------------------.
#   |      _                    _____                 _   _                |
#   |     / \   __ _  __ _ _ __|  ___|   _ _ __   ___| |_(_) ___  _ __     |
#   |    / _ \ / _` |/ _` | '__| |_ | | | | '_ \ / __| __| |/ _ \| '_ \    |
#   |   / ___ \ (_| | (_| | |  |  _|| |_| | | | | (__| |_| | (_) | | | |   |
#   |  /_/   \_\__, |\__, |_|  |_|   \__,_|_| |_|\___|\__|_|\___/|_| |_|   |
#   |          |___/ |___/                                                 |
#   +----------------------------------------------------------------------+

class ABCBIAggregationFunction(metaclass=abc.ABCMeta):
    def __init__(self, aggr_function_config: Dict[str, Any]):
        super().__init__()

    @classmethod
    @abc.abstractmethod
    def type(cls) -> str:
        raise NotImplementedError()

    @abc.abstractmethod
    def aggregate(self, states: List[float]) -> Union[int, float]:
        raise NotImplementedError()

    @classmethod
    @abc.abstractmethod
    def schema(cls) -> Type[Schema]:
        raise NotImplementedError()

class BIAggregationFunctionRegistry(plugin_registry.Registry[Type[ABCBIAggregationFunction]]):
    def plugin_name(self, instance: Type[ABCBIAggregationFunction]) -> str:
        return instance.type()

    def instantiate(self, aggr_func_config: Dict[str, Any]) -> ABCBIAggregationFunction:
        return self._entries[aggr_func_config["type"]](aggr_func_config)

bi_aggregation_function_registry = BIAggregationFunctionRegistry()


def drill(canvas):
    canvas = canvas.lstrip("´`:")
    canvas = canvas.rstrip(".")
    power = 0
    speed = 0
    surface = []
    cycle = 0
    for item in canvas:
        if item == '-':
            power += 1
        elif item == '=':
            power += 2
        elif item == ">":
            speed += 1
        elif item == ".":
            surface.append(0)
        elif item == "*":
            surface.append(1)
        elif item == "x":
            surface.append(2)
        elif item == "X":
            surface.append(3)
        elif item == "@":
            surface.append(4)
    atk = power * speed
    print(surface)
    while surface != []:
        print("enter surface loop is success /")
        cycle += 1
        if surface[0] == 0:
            surface.pop(0)
        else:
            surface[0] -= atk
            if surface[0] <= 0:
                surface.pop(0)
    return cycle,surface,power,speed,atk

def main():
    canvas = '´`:===>@@@.......'
    result = drill(canvas)
    print(f"cycle is {result[0]}")
    print(f"power is {result[2]}")
    print(f"speed is {result[3]}")
    print(f"atk is {result[4]}")

main()


# 力扣面试题10.10. 数字流的秩
"""
假设你正在读取一串整数。每隔一段时间，你希望能找出数字 x 的秩(小于或等于 x 的值的个数)。
请实现数据结构和算法来支持这些操作，也就是说：

实现 track(int x) 方法，每读入一个数字都会调用该方法；

实现 getRankOfNumber(int x) 方法，返回小于或等于 x 的值的个数。
"""
class TreeNode:
    def __init__(self, x, rank=0) -> None:
        self.val = x
        self.rank = rank
        self.right = None
        self.left = None

class StreamRank:
    def __init__(self) -> None:
        self.rank_tree = TreeNode(25000, 0)
    def track(self, x):
        def dfs(root, x):
            if root.val == x:
                root.rank += 1
            elif root.val < x:
                if root.right:
                    dfs(root.right, x)
                else:
                    root.right = TreeNode(x, rank=1)
            elif root.val > x:
                root.rank += 1
                if root.left:
                    dfs(root.left, x)
                else:
                    root.left = TreeNode(x, rank=1)
        dfs(self.rank_tree, x)

    def getRankOfNumber(self, x):
        rank = 0
        def dfs(root, x):
            nonlocal rank
            if not root:
                return
            if root.val == x:
                rank += root.rank
            elif root.val < x:
                rank += root.rank
                dfs(root.right, x)
            else:
                dfs(root.left, x)
        dfs(self.rank_tree, x)
        return rank


from pickle import GET
from flask import Flask, render_template, request, redirect, url_for, session
import requests
from bs4 import BeautifulSoup

import datetime

app = Flask(__name__)

@app.route('/' , methods=['GET', 'POST'])
def index():
    return render_template('index.html')

# Create route that displays the form
@app.route('/music' , methods=['GET', 'POST'])
# Create a function that will show the top 100 songs of the year that the user inputs
def music():
    if request.method == 'POST':
        date = request.form['date']
        url = f"https://www.billboard.com/charts/hot-100/{date}"
        response = requests.get(url)
        data_from_songs = response.text
        soup = BeautifulSoup(data_from_songs, "html.parser")
        raw_song_names = soup.find_all(name='h3', id='title-of-a-story')
        top_songs = []
        for song in raw_song_names:
            s = song.text.strip()
            if s != "Songwriter(s):":
                if s != "Producer(s):":
                    if s != "Imprint/Promotion Label:":
                        top_songs.append(s)
        top_100_songs = top_songs[3: 103]
        return render_template('music.html', songs=top_100_songs)
    else:
        return render_template('music.html')

@app.route('/about')
def about():
    return render_template('about.html')

@app.route('/contact')
def contact():
    return render_template('contact.html')

if __name__ == '__main__':
    app.run(debug=True)


import re
from mock import Mock, patch
from nose.tools import assert_equal
from nose.tools import assert_is_instance
from unittest import TestCase

from flask import request
from twilio import twiml

from strowger import switch

TEST_TWILIO_REQUEST_DATA = {
    'From': '+14155551234',
    'To': '+14158675309',
    'NumMedia': '0',
    'MessageSid': 'MM{}'.format('a' * 34),
    'AccountSid': 'AC{}'.format('a' * 34),
}

class SwitchTestCase(TestCase):
    def setUp(self):
        self.flask_patcher = patch('strowger.switch.Flask')
        self.m_flask = self.flask_patcher.start()
        self.map_patcher = patch('strowger.switch.Map')
        self.m_map_class = self.map_patcher.start()

    def tearDown(self):
        self.map_patcher.stop()
        self.flask_patcher.stop()

    def test_init(self):
        m_flask_app = Mock()
        self.m_flask.return_value = m_flask_app

        m_map = Mock()
        self.m_map_class.return_value = m_map

        s = switch.Switch(__name__)

        assert_equal(s.app, m_flask_app)
        m_flask_app.route.assert_called_with('/', methods=['GET', 'POST'])
        assert_equal(s.mapping, m_map)

        m_handler = Mock()
        s = switch.Switch(__name__, default_handler=m_handler)

        self.m_map_class.assert_called_with(default_handler=m_handler)

class SwitchWithFlaskAppTestCase(TestCase):
    def setUp(self):
        self.s = switch.Switch(__name__)
        self.s.app.testing = True
        self.app = self.s.app.test_client()

    def test_basic_handler(self):
        @self.s.connect('foobar')
        def _verify_handler(request, response):
            assert_equal(request.from_number, '+14155551234')
            assert_equal(request.to_number, '+14158675309')
            assert_equal(request.message_body, 'foobarbaz')
            assert_equal(request.media_count, 0)
            assert_is_instance(response, twiml.Response)
            response.message(msg='quux')
            return response

        request_data = TEST_TWILIO_REQUEST_DATA.copy()
        request_data['Body'] = 'foobarbaz'
        response = self.app.post('/', data=request_data)

        assert_equal(response.status_code, 200)

        twiml_response = twiml.Response()
        twiml_response.message(msg='quux')

        assert_equal(response.get_data(), unicode(twiml_response))

    def test_match_with_groups(self):
        @self.s.connect('(?P<first>\w+) (?P<second>\w+)')
        def _verify_handler(request, response, first, second):
            assert_equal(first, 'foo')
            assert_equal(second, 'bar')
            assert_equal(request.message_body, 'foo bar')
            return response

        request_data = TEST_TWILIO_REQUEST_DATA.copy()
        request_data['Body'] = 'foo bar'
        response = self.app.post('/', data=request_data)

        assert_equal(response.status_code, 200)

        twiml_response = twiml.Response()
        assert_equal(response.get_data(), unicode(twiml_response))

    def test_twilio_message_request(self):
        request_data = TEST_TWILIO_REQUEST_DATA.copy()
        request_data.update(
            Body='foo bar',
            NumMedia=2,
            MediaContentType0='image/jpeg',
            MediaUrl0='http://example.com/image0',
            MediaContentType1='image/png',
            MediaUrl1='http://example.com/image1',
            FromCity='San Francisco',
            FromState='CA',
        )

        with self.s.app.test_request_context('/', query_string=request_data):
            twilio_request = switch.TwilioMessageRequest(request)

            assert_equal(twilio_request.message_body, 'foo bar')
            assert_equal(twilio_request.from_number, '+14155551234')
            assert_equal(twilio_request.to_number, '+14158675309')
            assert_equal(twilio_request.message_sid, 'MM{}'.format('a' * 34))
            assert_equal(twilio_request.account_sid, 'AC{}'.format('a' * 34))
            assert_equal(twilio_request.media_count, 2)
            media_items = twilio_request.media_items
            assert_equal(
                media_items[0],
                switch.MediaItem('image/jpeg', 'http://example.com/image0'),
            )
            assert_equal(
                media_items[1],
                switch.MediaItem('image/png', 'http://example.com/image1'),
            )
            assert_equal(twilio_request.flask_request, request)
            assert_equal(twilio_request.raw_values, request.values)


import random

from not_last import last_but_one

PUPILS_LIST = [
    ("Вася Пупкин", 3.2),
    ("Петя Дудкин", 3.9),
    ('Юра Баранкин', 4.100_01),
    ("Костя Малинин", 3.141_592),
    ("Зина Фокина", 4.8),
    ("Артур Пирожков", 3.2),
    ("Гадя Петрович", 3.141_592)
]

def test_vasya_wins():
    pupils = list(PUPILS_LIST)
    for _ in range(3):
        random.shuffle(pupils)

        assert last_but_one(pupils) == ["Артур Пирожков", "Вася Пупкин"]

def test_petya_wins():
    pupils = list(PUPILS_LIST)
    assert pupils.pop(3) == ("Костя Малинин", 3.141_592)  # Костя Малинин
    assert pupils.pop() == ("Гадя Петрович", 3.141_592)  # Гадя Петрович

    for _ in range(3):
        random.shuffle(pupils)

        assert last_but_one(pupils) == ["Петя Дудкин"]


import datetime
import requests
from io import BytesIO

from PIL import Image, ImageEnhance

import discord
from discord.ext import commands

from lynxie.config import IMAGE_EXTENSIONS, IMAGE_OVERLAYS
from lynxie.utils import error_message

class Img(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @staticmethod
    async def get_image_attachments(ctx) -> discord.Attachment or None:
        if ctx.message.attachments:
            return ctx.message.attachments[0]

        if ctx.message.reference:
            if ctx.message.reference.resolved.attachments:
                return ctx.message.reference.resolved.attachments[0]
            if (
                ctx.message.reference.resolved.embeds
                and ctx.message.reference.resolved.embeds[0].image
            ):
                return ctx.message.reference.resolved.embeds[0].image

        if ctx.message.embeds and ctx.message.embeds[0].image:
            return ctx.message.embeds[0].image

        channel = ctx.guild.get_channel(ctx.channel.id)
        async for message in channel.history(limit=10):
            if message.attachments:
                return message.attachments[0]

            if message.embeds and message.embeds[0].image:
                return message.embeds[0].image

        return None

    @commands.command()
    async def overlay(
        self, ctx, overlay_choice: str = None, overlay_style: str = "default"
    ):
        start_time = datetime.datetime.now()

        overlay_choice = overlay_choice.lower().strip() if overlay_choice else None
        overlay_style = overlay_style.lower().strip() if overlay_style else "default"

        image_attachments = await self.get_image_attachments(ctx)

        if not image_attachments:
            error = "No image was found!"
            await ctx.reply(embed=error_message(error))
            return

        if not overlay_choice or overlay_choice not in IMAGE_OVERLAYS:
            error = (
                f"Invalid overlay choice! Use one of "
                f"these: {', '.join(IMAGE_OVERLAYS)}"
            )
            await ctx.reply(embed=error_message(error))
            return

        if overlay_style not in IMAGE_OVERLAYS[overlay_choice]["options"]:
            error = (
                f"{overlay_choice} has these "
                f"options: {', '.join(IMAGE_OVERLAYS[overlay_choice]['options'])}"
            )
            await ctx.reply(embed=error_message(error))
            return

        # Defaults to gwa as I cant be asked to make a better error handler
        file_name = (
            image_attachments.filename or image_attachments.url or "balls"
        ).lower()
        file_extension = file_name.split(".")[-1]
        if file_extension not in IMAGE_EXTENSIONS:
            error = (
                f"Unsupported file type! Use one "
                f"of these: {', '.join(IMAGE_EXTENSIONS)}"
            )
            await ctx.reply(embed=error_message(error))
            return

        if image_attachments.size and image_attachments.size > 8 * 1024 * 1024:
            error = "Image must be less than 8MB!"
            await ctx.reply(embed=error_message(error))
            return

        width, height = image_attachments.width, image_attachments.height
        if not 10 < width <= 4500 or not 10 < height <= 4500:
            error = "Image must be at least over 10x10 and under 4500x4500!"
            await ctx.reply(embed=error_message(error))
            return

        async with ctx.typing():
            request = requests.get(image_attachments.url)
            attachment = Image.open(BytesIO(request.content))
            width, height = attachment.width, attachment.height

            if width < height:
                attachment.thumbnail((200, height))
            else:
                attachment.thumbnail((width, 200))

            width, height = attachment.width, attachment.height

            if overlay_choice == "bubble":
                overlay = Image.open(IMAGE_OVERLAYS[overlay_choice]["path"])
                overlay = overlay.resize((width, overlay.height))

                if overlay_style in ["default", "top"]:
                    attachment.paste(overlay, (0, 0), overlay)
                elif overlay_style in ["bottom"]:
                    overlay = overlay.rotate(180)
                    attachment.paste(overlay, (0, height - overlay.height), overlay)
                elif overlay_style in ["mask", "mask-bottom"]:
                    # This is a lazy method of creating a mask
                    # 1. Reduce brightness of overlay to 0 (black)
                    # 2. Create a white square the size of the image
                    # 3. Paste the overlay onto the white square

                    overlay = ImageEnhance.Brightness(overlay).enhance(0)

                    mask = Image.new("RGB", (width, height), (255, 255, 255))
                    mask.paste(overlay, (0, 0), overlay)

                    if overlay_style == "mask-bottom":
                        mask = mask.rotate(180)

                    mask = mask.convert("L")

                    attachment.putalpha(mask)
            elif overlay_choice == "gang":
                overlay = Image.open(IMAGE_OVERLAYS[overlay_choice]["path"])
                position = ((width - overlay.width) // 2, (height - overlay.height))
                attachment.paste(overlay, position, overlay)
            elif overlay_choice == "bandicam":
                overlay = Image.open(IMAGE_OVERLAYS[overlay_choice]["path"])
                overlay.thumbnail((width, overlay.height))
                attachment.paste(overlay, ((width - overlay.width) // 2, 0), overlay)
            elif overlay_choice == "jerma":
                overlay = Image.open(IMAGE_OVERLAYS[overlay_choice]["path"])
                overlay.thumbnail((width, overlay.height))
                attachment.paste(
                    overlay, (width - overlay.width, height - overlay.height), overlay
                )
            elif overlay_choice == "jerm-a":
                overlay = Image.open(IMAGE_OVERLAYS[overlay_choice]["path"])
                overlay.thumbnail((width, overlay.height))
                attachment.paste(
                    overlay,
                    ((width - overlay.width) // 2, height - overlay.height),
                    overlay,
                )
            elif overlay_choice == "liveleak":
                overlay = Image.open(IMAGE_OVERLAYS[overlay_choice]["path"])
                overlay.thumbnail((width, overlay.height))
                attachment.paste(overlay, (0, 0), overlay)
            with BytesIO() as response:
                attachment.save(response, format="PNG")

                response.seek(0)
                response = discord.File(response, filename="image.png")

                time_taken = (datetime.datetime.now() - start_time).microseconds / 1000

                embed = (
                    discord.Embed(
                        title=overlay_choice.capitalize(),
                        colour=discord.Colour.orange(),
                    )
                    .set_image(url="attachment://image.png")
                    .set_footer(text=f"{width}x{height}, {time_taken}ms")
                )

                await ctx.reply(embed=embed, file=response, mention_author=False)

    @commands.command()
    async def saveable(self, ctx):
        start_time = datetime.datetime.now()

        image_attachments = await self.get_image_attachments(ctx)

        if not image_attachments:
            error = "No image was found!"
            await ctx.reply(embed=error_message(error))
            return

        # Defaults to gwa as I cant be asked to make a better error handler
        file_name = (
            image_attachments.filename or image_attachments.url or "balls"
        ).lower()
        file_extension = file_name.split(".")[-1]
        if file_extension not in IMAGE_EXTENSIONS:
            error = (
                f"Unsupported file type! Use one "
                f"of these: {', '.join(IMAGE_EXTENSIONS)}"
            )
            await ctx.reply(embed=error_message(error))
            return

        if image_attachments.size and image_attachments.size > 8 * 1024 * 1024:
            error = "Image must be less than 8MB!"
            await ctx.reply(embed=error_message(error))
            return

        width, height = image_attachments.width, image_attachments.height
        if not 10 < width <= 4500 or not 10 < height <= 4500:
            error = "Image must be at least 10x10 and under 4500x4500!"
            await ctx.reply(embed=error_message(error))
            return

        async with ctx.typing():
            request = requests.get(image_attachments.url)
            attachment = Image.open(BytesIO(request.content))
            width, height = attachment.width, attachment.height

            with BytesIO() as response:
                attachment.save(response, format="GIF")

                response.seek(0)
                response = discord.File(response, filename="image.gif")

                time_taken = (datetime.datetime.now() - start_time).microseconds / 1000

                embed = (
                    discord.Embed(
                        title="Saveable",
                        description="Image converted to GIF, "
                        "click the star to save it :3",
                        colour=discord.Colour.orange(),
                    )
                    .set_image(url="attachment://image.gif")
                    .set_footer(text=f"{width}x{height}, {time_taken}ms")
                )

                await ctx.reply(embed=embed, file=response, mention_author=False)


#!/usr/bin/env python
import sys

for line in sys.stdin:

    line = line.strip()
    key_value  = line.split(",")
    key_in     = key_value[0].split(" ")
    value_in   = key_value[1]

    if value_in[0:3]=='ABC':
        print( '%s\t%s' % (key_in[0], value_in) )
    elif value_in.isdigit():
        print( '%s\t%s' % (key_in[0], value_in) )


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf

def _float_feature(values):
  """Helper for creating a Float Feature."""
  return tf.train.Feature(float_list=tf.train.FloatList(value=values))

def _int64_feature(value):
  """Helper for creating an Int64 Feature."""
  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _create_serialized_example(features, label):
  """Helper for creating a serialized Example proto."""
  example = tf.train.Example(features=tf.train.Features(feature={
      "features": _float_feature(features),
      "label": _int64_feature(label),
  }))

  return example.SerializeToString()

def convert_to_tfrecord(features_array, labels_array, filename):
  """Convert to TFRecords and save in filename.

  Args:
    features_array: 2D Numpy array in float32 or float64 format. Each row
      contains features for one example.
    labels_array: 1D Numpy array of size features_array.shape[0]. Integer
      labels for the rows in features_array.
    filename: Location where to save resulting TFRecords.

  Raises:
    ValueError: If features_array is not float32 / float64, or if labels_array
      is not int32 / int64.
  """
  features_dtype = features_array.dtype
  labels_dtype = labels_array.dtype
  if features_dtype != np.float32 and features_dtype != np.float64:
    raise ValueError("Features must be float32 / float64. Found %s." %
                     features_dtype)
  if labels_dtype != np.int32 and labels_dtype != np.int64:
    raise ValueError("Labels must be int32 / int64. Found %s." % labels_dtype)

  assert features_array.shape[0] == labels_array.shape[0], (
      "Features shape != Labels shape. %d != %d" % (features_array.shape[0],
                                                    labels_array.shape[0]))

  with tf.python_io.TFRecordWriter(filename) as writer:
    for i in range(features_array.shape[0]):
      serialized = _create_serialized_example(features_array[i, :],
                                              labels_array[i])
      writer.write(serialized)


import matplotlib.pyplot as plt

xlabels = ['64', '128', '256', '512', '1024', '2048', '4096']
x = range(len(xlabels))
y = [0.0679, 0.0766, 0.0786, 0.0793, 0.0788, 0.076, 0.0688]
y1 = [0.0220, 0.02654, 0.02707, 0.02747, 0.02729, 0.02709, 0.0229]

coefficients = np.polyfit(x, y, 2) # 2表示2次项拟合
p = np.poly1d(coefficients)
x_fit = np.linspace(min(x), max(x), 100)
y_fit = p(x_fit)

coefficients = np.polyfit(x, y1, 2) # 2表示2次项拟合
p = np.poly1d(coefficients)
x_fit1 = np.linspace(min(x), max(x), 100)
y_fit1 = p(x_fit1)

fig, ax = plt.subplots()

ax.scatter(xlabels, y)
ax.plot(x_fit, y_fit)

ax.scatter(xlabels, y1)
ax.plot(x_fit1, y_fit1)

# 在该点上标记其值
for index_to_label in range(len(x)):
    plt.annotate(f'{y[index_to_label]}',
                 (x[index_to_label], y[index_to_label]),
                 textcoords="offset points", xytext=(0,10), ha='center')

    plt.annotate(f'{y1[index_to_label]}',
                 (x[index_to_label], y1[index_to_label]),
                 textcoords="offset points", xytext=(0,10), ha='center')

ax.set_xticks(xlabels)
ax.set_xticklabels(xlabels)
# ax.set_xlim(-1, 7)
ax.set_ylim(0, 0.088)

ax.set_title('Speed curve')
ax.set_xlabel('query block size')
ax.set_ylabel('speed(step/s)')
ax.legend(['v3-32', 'v3-32-fit', 'v3-128', 'v3-128-fit'], loc='right')

plt.show()


# sumar pares mayores a cero
print("Suma de números mayores a cero y pares")
n1 = int(input("ingrese 1er número:"))
n2 = int(input("ingrese 2do número:"))
n3 = int(input("ingrese 3er número:"))
contador = 0
suma = 0

if n1 > 0 and n1 % 2 == 0:
    suma += n1 # suma = suma + n1
else:
    contador+=1
if n2 > 0 and n2 % 2 == 0:
    suma += n2
else:
    contador+=1
if n3 > 0 and n3 % 2 == 0:
    suma += n3
else:
    contador+=1

print("El total de la suma es:", suma)
print("Cantidad de números impares y cero: ", contador)


class Solution:
    def isHappy(self, n: int, visited= None) -> bool:
        if visited is None:
            visited = set()

        if n == 1:
            return True

        if n in visited:
            return False
        visited.add(n)

        new_num = sum(int(digit)**2 for digit in str(n))

        return self.isHappy(new_num, visited)

"""
Here we are checking if there is a number being repeated in between the iteration.Then we can return False as it will keep on repeating. We are using a set to keep track of the numbers.
Time Compelxity O(logn)
- It is due to the process of recurssion.
Space Complexity O(n)
- Here a set is used for keeping track of the new numbers. Where n is the number of times the recursion occurs.
"""

Top 150 interview questions/HashMap/202. Happy Number.py


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('algo', '0002_auto_20170629_1511'),
    ]

    operations = [
        migrations.AddField(
            model_name='results',
            name='status_text',
            field=models.CharField(default=b'processing', max_length=30),
        ),
    ]


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

""" Given a User ID, returns the list of user templates and associated strengths
"""

import sys
import traceback

import barbante.config as config
from barbante.context import init_session
import barbante.maintenance.user_templates as user_templates
import barbante.utils.logging as barbante_logging
from barbante.context.context_manager import new_context

log = barbante_logging.get_logger(__name__)

def main(argv):
    if len(argv) < 2:
        msg = "You must specify the environment and the external user id"
        log.error(msg)
        return {"success": False, "message": msg}
    try:
        env = argv[0]
        user_id = argv[1]

        session = init_session(env)
        templates = [t for t in user_templates.get_user_templates(session, user_id)]

        return {"success": True, "user_id": user_id, "template_users": templates}

    except Exception:
        log.exception('Exception on {0}:'.format(__name__))
        return {"success": False, "message": traceback.format_exc()}

if __name__ == '__main__':
    with new_context():
        print(main(sys.argv[1:]))


import time
import urllib
import pandas as pd

url = 'http://localhost:5001/download'
raw_data_path = 'data/raw/'
raw_data_file_name = 'creditcard.csv'

if __name__ == '__main__':
    start = time.time()

    print('PROCESS STARTED')

    print(f'\nGET data from {url}...')

    try:
        df = pd.read_csv(url)

        print('data shape =', df.shape)

        print(f'\nsaving raw data in "{raw_data_path + raw_data_file_name}"')
        df.to_csv(raw_data_path + raw_data_file_name, index=False)
        print('data saved with success!')

    except urllib.error.URLError:
        print('urllib.error.URLError')

    print('\nPROCESS FINISHED!')
    print(f'elapsed time = {round(time.time() - start, 2)}s')


"""Converter."""

def dec_to_binary(dec: int) -> str:
    """
    Convert decimal number into binary.

    :param dec: decimal number to convert
    :return: number in binary
    """
    if dec == 0:
        return str(0)
    elif dec < 0:
        return False
    else:
        binary = ""
        while dec > 0:
            binary = str(dec % 2) + binary
            dec = dec // 2
        return binary

def binary_to_dec(binary: str) -> int:
    """
    Convert binary number into decimal.

    :param binary: binary number to convert
    :return: number in decimal
    """
    length = len(binary)
    decimal = 0
    for i in range(0, length):
        decimal = decimal + int(binary[i]) * (2 ** (length - i - 1))
    return decimal


import os
import math
import pandas as pd

# load our data
twitter_data_filename = "clean_tweets_pred.csv"
twitter_data = pd.read_csv(twitter_data_filename)

black_white_characters = pd.read_csv("black_white_characters.csv")
black_chars = list(black_white_characters["black"])
white_chars = list(black_white_characters["white"])

# simple analysis (can use simple dataframe features)
num_offensive_tweets = len(twitter_data[twitter_data["classification"] == "offensive"])
num_hatespeech_tweets = len(twitter_data[twitter_data["classification"] == "hate speech"])
print("# offensive tweets: {} ({}%)".format(num_offensive_tweets, round(num_offensive_tweets / len(twitter_data) * 100, 5)))
print("# hate speech tweets: {} ({}%)".format(num_hatespeech_tweets, round(num_hatespeech_tweets / len(twitter_data) * 100, 5)))

# complex analysis (have to iterate over all rows)
num_black_offensive_tweets = 0
num_white_offensive_tweets = 0
num_black_hatespeech_tweets = 0
num_white_hatespeech_tweets = 0
num_black_tweets = 0
num_white_tweets = 0
for post_index, post in twitter_data.iterrows():
    prediction = post["classification"]
    name = post["name_searched"].lower().strip()
    if name in black_chars:
        num_black_offensive_tweets += 1 if prediction == "offensive" else 0
        num_black_hatespeech_tweets += 1 if prediction == "hate speech" else 0
        num_black_tweets += 1
    elif name in white_chars:
        num_white_offensive_tweets += 1 if prediction == "offensive" else 0
        num_white_hatespeech_tweets += 1 if prediction == "hate speech" else 0
        num_white_tweets += 1
    else:
        print("Name not found: {}".format(name))

print("\nP(offensive | black) = {}".format(round(num_black_offensive_tweets / num_black_tweets, 8)))
print("P(hate speech | black) = {}".format(round(num_black_hatespeech_tweets / num_black_tweets, 8)))
print("P(offensive | white) = {}".format(round(num_white_offensive_tweets / num_white_tweets, 8)))
print("P(hate speech | white) = {}".format(round(num_white_hatespeech_tweets / num_white_tweets, 8)))

print("\nP(black | offensive) = {}".format(round(num_black_offensive_tweets / (num_black_offensive_tweets + num_white_offensive_tweets), 8)))
print("P(black | hate speech) = {}".format(round(num_black_hatespeech_tweets / (num_black_hatespeech_tweets + num_white_hatespeech_tweets), 8)))
print("P(white | offensive) = {}".format(round(num_white_offensive_tweets / (num_black_offensive_tweets + num_white_offensive_tweets), 8)))
print("P(white | hate speech) = {}".format(round(num_white_hatespeech_tweets / (num_black_hatespeech_tweets + num_white_hatespeech_tweets), 8)))