from Core.Cooldown import Cooldown, TIME_UNIT, TIME_ZERO
from collections import defaultdict
from Core.ABCSkill import Skill, AutomateActivativeSkill, OriginSkill
from Core.SpecElements import SpecVector, CreateSpecVector, CoreStat
from Skill.Attributes import *

from copy import deepcopy
import random

class CooldownManager:
    """CooldownManager는 스킬의 쿨타임을 관리합니다.

    각 스킬에 대한 쿨다운은 defaultdict를 사용하여 저장되며, 쿨타임이 0이되면 해당 스킬이 사전에서 삭제됩니다.

    Attributes:
        Cooldowns: 각 스킬에 대한 쿨타임을 저장하는 딕셔너리입니다.
        Cap: 쿨타임 상한 값을 저장하는 속성입니다. 0~8의 정수값을 가질 수 있습니다.
        Mercedes: 메르세데스 옵션 값을 저장하는 속성입니다. 5 또는 6의 정수값을 가질 수 있습니다.
        Reset: 쿨타임 리셋 값을 저장하는 속성입니다. 0~100의 정수값을 가질 수 있습니다.
    """
    def __init__(self):
        self.Cooldowns = defaultdict(Cooldown)
        # 스택형 스킬은 쿨타임 적용이 까다로우므로, 별도의 리스트를 둬서 따로 관리함
        self.StackCooldowns = defaultdict(list)
        self._Cap = 0
        self._Mercedes = 0
        self._Reset = 0

    @property
    def Cap(self):
        """Cap 속성의 getter입니다."""
        return self._Cap

    @Cap.setter
    def Cap(self, value):
        """Cap 속성의 setter입니다."""
        if not isinstance(value, int):
            raise TypeError("Cap must be an integer.")
        if not (0 <= value <= 8):
            raise ValueError("Cap value must be between 0 and 8.")
        self._Cap = value

    @property
    def Mercedes(self):
        """Mercedes 속성의 getter입니다."""
        return self._Mercedes

    @Mercedes.setter
    def Mercedes(self, value):
        """Mercedes 속성의 setter입니다."""
        if not isinstance(value, int):
            raise TypeError("Mercedes must be an integer.")
        if value not in (5, 6):
            raise ValueError("Mercedes value must be either 5 or 6.")
        self._Mercedes = value*0.01

    @property
    def Reset(self):
        """Reset 속성의 getter입니다."""
        return self._Reset

    @Reset.setter
    def Reset(self, value):
        """Reset 속성의 setter입니다."""
        if not isinstance(value, int):
            raise TypeError("Reset must be an integer.")
        if not (0 <= value <= 100):
            raise ValueError("Reset value must be between 0 and 100.")
        self._Reset = value

    def isReady(self, skill:Skill) -> bool:
        if self.GetRemainingCooldown(skill) > TIME_ZERO:
            return False
        elif self.GetRemainingCooldown(skill) == TIME_ZERO:
            return True
        else:
            raise AttributeError("스킬의 쿨다운에 의도치 않은 값이 설정되어 있음")

    def Count(self, skill: Skill, forcedCooldown = False):
        """스킬의 쿨타임을 등록하거나 업데이트합니다."""

        if not issubclass(skill, Skill):
            raise TypeError("Skill must be a callable")

        if not issubclass(skill, CooldownAttribute):
            raise TypeError("CooldownAttribute를 상속해야 관리할 수 있음")

        if not self.isReady(skill):
            return False

        if forcedCooldown is not False:
            self.Cooldowns[skill] = forcedCooldown
            return True

        # 스택형 스킬은 쿨타임 적용이 까다로우므로, 별도의 리스트를 둬서 따로 관리함
        if issubclass(skill, ChargedCooldownAttribute):
            # 이미 스택이 존재하는 경우라서 사용 가능한 경우
            stackedCool = self.StackCooldowns[skill]
            if len(stackedCool) == 0:
                # 스택형 스킬인데 쿨타임 감소가 적용되는 경우(메여축 등 특수케이스)
                if skill().IsCooldownable:
                    self.StackCooldowns[skill] = [skill().MaxBuffCharge-1, skill().SkillCooldown*(1-self.Mercedes) - Cooldown(seconds=self.Cap)]
                # 스택형 스킬인데 쿨타임 감소 적용 안되는 경우(일반적 경우)
                else:
                    self.StackCooldowns[skill] = [skill().MaxBuffCharge-1, skill().SkillCooldown]
            # 스킬이 등록되어 있고 스택이 존재하는 경우 스택만 감소시킴
            else:
                if self.StackCooldowns[skill][0] > 0:
                    self.StackCooldowns[skill][0] = self.StackCooldowns[skill][0] -1
                else:
                    raise AttributeError("스택형 스킬에 스택이 없는데 사용을 시도함")
        # 일반 스킬들의 쿨타임 관리
        else:
            # 자동 발동 스킬은 쿨감 안먹음(시프 커닝, 일격필살 등)
            if issubclass(skill, (AutomateActivativeSkill, OriginSkill)):
                self.Cooldowns[skill] = skill().SkillCooldown
            # 일반 스킬은 쿨타임 감소가 항상 먹고,
            else:
                self.Cooldowns[skill] = skill().SkillCooldown*(1-self.Mercedes) - Cooldown(seconds=self.Cap)

        return True

    def Tick(self):
        """모든 스킬의 쿨타임을 감소시킵니다."""
        # 일반 스킬의 쿨타임 감소
        for skill, cool in list(self.Cooldowns.items()):
            newCool = deepcopy(max(TIME_ZERO, cool - TIME_UNIT))
            if newCool == TIME_ZERO:
                del self.Cooldowns[skill]
            else:
                self.Cooldowns[skill] = Cooldown(cooldown=newCool)

        # 스택형 쿨타임 스킬의 쿨타임 감소
        for skill, stackCool in list(self.StackCooldowns.items()):
            newCool = deepcopy(max(TIME_ZERO, stackCool[1] - TIME_UNIT))
            # 스택의 쿨타임이 모두 찬 경우
            if newCool == TIME_ZERO:
                # 스택의 최대치까지만 상승해야함
                maxstack = skill().MaxBuffCharge
                if self.StackCooldowns[skill][0] == maxstack:
                    self.StackCooldowns[skill] = [stackCool[0]+1,TIME_ZERO]
                # 스택의 상승이 최대치가 되지 않는 경우
                else:
                    if skill().IsCooldownable:
                        self.StackCooldowns[skill] = [stackCool[0]+1, skill().SkillCooldown*(1-self.Mercedes) - Cooldown(seconds=self.Cap)]
                    else:
                        self.StackCooldowns[skill] = [stackCool[0]+1, skill().SkillCooldown]
            # 스택의 쿨타임이 모두 차지 않은 경우 쿨타임 갱신함
            else:
                self.StackCooldowns[skill] = [stackCool[0], Cooldown(cooldown=newCool)]

    def ReduceCooldown(self, targetskill:Skill, reduce:Cooldown):
        for skill, cool in list(self.Cooldowns.items()):
            if issubclass(skill, targetskill):
                if self.GetRemainingCooldown(skill) > TIME_ZERO:
                    self.Cooldowns[skill] = max(cool - reduce, TIME_ZERO)
                    return True

        return False

    def GetRemainingCooldown(self, skill:Skill):
        """특정 스킬의 남은 쿨타임을 반환합니다."""
        if not issubclass(skill, Skill):
            raise TypeError("Skill must be a callable")

        # 스택형 쿨타임 스킬의 경우 별도로 관리함
        if issubclass(skill, ChargedCooldownAttribute):
            stackedCool = self.StackCooldowns[skill]
            # 스킬이 쿨타임 매니저에 등록되어 있지 않은 경우
            if len(stackedCool) == 0:
                # 스킬이 사용 가능하다고 알림
                return TIME_ZERO
            # 스킬이 쿨타임 매니저에 등록되어 있고 스택이 남아있는 경우
            elif stackedCool[0] > 0:
                # 스킬이 사용 가능하다고 알림
                return TIME_ZERO
            else:
                # 스킬이 등록되어 있고 남은 스택이 없는 경우 쿨타임이 있음을 반환
                return self.StackCooldowns[skill][1]
        # 스택형 버프가 아닌 경우 쿨타임 반환
        else:
            return self.Cooldowns[skill]

    def __getitem__(self, skill):
        """특정 스킬의 남은 쿨타임을 반환합니다."""
        return self.GetRemainingCooldown(skill=skill)

    def __iter__(self):
        return iter(self.Cooldowns.items())

class OnAttackManager(CooldownManager):
    def __init__(self):
        super().__init__()

class BuffManager:
    """
    BuffManager 클래스는 스킬의 쿨다운, 버프 속성, 지속시간 등을 관리합니다.
    각각의 스킬은 특정 속성을 상속받아야 하며, 그렇지 않으면 TypeError를 발생시킵니다.

    Raises:
        TypeError: 스킬이 호출 가능한 객체가 아닌 경우
        TypeError: 스킬이 CooldownAttribute를 상속받지 않은 경우
        TypeError: 스킬이 BuffAttribute를 상속받지 않은 경우
        TypeError: 스킬이 DurationAttribute를 상속받지 않은 경우

    Returns:
        None
    """
    # TODO: 대입할때 deepcopy를 사용할 것
    def __init__(self):
        self.BuffList = list()

    def isRegistered(self, skill):
        for buf in self.BuffList:
            if issubclass(skill, type(buf.Skill)):
                return True

        return False

    def GetRemainingTime(self, skill):
        for buf in self.BuffList:
            if issubclass(skill, type(buf.Skill)):
                return buf.SkillLeftDuration
        return Cooldown()

    def Add(self, skill: Skill, renew = False):
        # 추가하려는 스킬과 같은 타입의 스킬이 이미 BuffList에 있는지 확인
        for buff in self.BuffList:
            if isinstance(buff.Skill, type(skill)):
                # 만약 갱신 가능하다면 지속시간 갱신
                if renew == True:
                    buff = Buff(skill)

                return  # 이미 같은 타입의 스킬이 있으므로 함수를 종료

        if not issubclass(type(skill), Skill):
            raise TypeError("Skill must be a callable")

        if not issubclass(type(skill), (BuffAttribute,DebuffAttribute)):
            raise TypeError("버프 스킬만 관리함")

        if not issubclass(type(skill), DurationAttribute):
            raise TypeError("버프 지속시간이 필요함")

        self.BuffList.append(Buff(skill))

    def GetBuff(self):
        """
        현재 BuffList에 있는 모든 버프의 통계를 반환합니다.

        Returns:
            SpecVector: 현재 버프 통계
        """
        result = SpecVector()
        for buff in self.BuffList:
            if hasattr(buff.Skill, 'DebuffStat'):
                isCallable = buff.Skill.DebuffStat
            else:
                isCallable = buff.Skill.BuffStat
            if callable(isCallable):
                # 스킬의 남은 지속시간 혹은 여러 조건들을 대입. 람다함수를 불러와서 처리함
                result += isCallable(buff.GetRealDuration() - buff.SkillLeftDuration)
            else:
                result += isCallable
        return result

    def Tick(self):
        """
        BuffList의 모든 버프의 지속 시간을 감소시킵니다.
        만약 버프의 지속 시간이 0이 되면 해당 버프를 BuffList에서 제거합니다.

        Returns:
            None
        """
        for buff in reversed(self.BuffList):
            if buff.Tick() == False:
                self.BuffList.remove(buff)

    def DeleteBuff(self, skill:Skill):
        if not issubclass(type(skill), Skill):
            raise TypeError("Skill must be a callable")

        if not issubclass(type(skill), (BuffAttribute,DebuffAttribute)):
            raise TypeError("버프 스킬만 관리함")

        if not issubclass(type(skill), DurationAttribute):
            raise TypeError("버프 지속시간이 필요함")

        for buff in reversed(self.BuffList):
            if isinstance(buff.Skill, type(skill)):
                self.BuffList.remove(buff)

class Buff:
    """
    Buff 클래스는 개별 버프의 지속 시간을 관리합니다.
    각 버프는 Skill 객체를 참조하며, 지속 시간은 Skill 객체의 Duration 속성에서 얻습니다.

    Args:
        skill (Skill): 버프와 관련된 스킬 객체

    Returns:
        None
    """
    def __init__(self, skill:Skill):
        self.Skill = skill

        self.SkillLeftDuration = self.GetRealDuration()

    def GetRealDuration(self):
        add = Cooldown()
        if self.Skill.ServerLack == True:
            add = Cooldown(seconds = 3)
        mult = 1
        if self.Skill.IsBuffMult == True:
            mult = (self.Skill.Owner._BuffDuration/100 + 1)
        return self.Skill.Duration * mult + add

    def Tick(self):
        """
        버프의 지속 시간을 감소시킵니다.
        만약 버프의 지속 시간이 0이 되면 False를 반환하며, 그렇지 않으면 None을 반환합니다.

        Returns:
            bool or None: 버프의 지속 시간이 0이 되면 False, 아니면 None
        """
        if self.SkillLeftDuration == TIME_ZERO:
            return False
        else:
            self.SkillLeftDuration -= TIME_UNIT

class ProjectileManager:
    def __init__(self) -> None:
        self.Scheduler = defaultdict(lambda: Cooldown(seconds=random.random()))

    def Add(self, skill:Skill, isImmediate=False, ForcedDelay=None):
        if not isinstance(skill, Skill):
            raise TypeError("skill must be a Skill type")

        self.Scheduler[skill]
        if hasattr(skill, "Maximum"):
            if self.Scheduler[skill] > Cooldown(seconds=skill.Maximum):
                self.Scheduler[skill] = Cooldown(seconds=skill.Maximum)
        if hasattr(skill, "Minimum"):
            if self.Scheduler[skill] < Cooldown(seconds=skill.Minimum):
                self.Scheduler[skill] = Cooldown(seconds=skill.Minimum)
        if isImmediate:
            self.Scheduler[skill] = Cooldown()

        if ForcedDelay is not None:
            self.Scheduler[skill] = ForcedDelay

    def Tick(self):
        result = []
        for projectile, cool in list(self.Scheduler.items()):
            cool.update()
            if cool == TIME_ZERO:
                projLogs = projectile.UseSkill()

                if None !=projLogs:
                    for log in projLogs:
                        if log is not None:
                            result.append(log)

                del self.Scheduler[projectile]
        return result

    def isRegistered(self, skill:Skill):
        for proj in self.Scheduler.keys():
            if issubclass(skill, type(proj)):
                return True

        return False

class SummonManager:
    """소환수 인스턴스를 입력받아서 관리함
    """
    def __init__(self):
        self.Summons = defaultdict(Cooldown)

    def Add(self, skill: Skill):
        # 소환수 인스턴스를 받음
        if not isinstance(skill, Skill):
            raise TypeError("skill must be a Skill type")

        if not issubclass(type(skill), DurationAttribute):
            raise TypeError("소환수는 지속시간이 있어야 함")

        if not issubclass(type(skill), IntervalAttribute):
            raise TypeError("소환수는 사용 간격이 있어야 함")

        if skill.IsBuffMult:
            mult = (skill.Owner._SummonDuration/100 + 1)
        else:
            mult = 1

        # 소환수:(스킬 이름, 공격 주기) = 스킬의 지속시간
        if hasattr(skill, 'AttackDelay'):
            if hasattr(skill, "FirstAttackDelay"):
                self.Summons[Summon(skill=skill, interval=skill.FirstAttackDelay)] =  skill.Duration * mult - TIME_UNIT
            else:
                self.Summons[Summon(skill=skill, interval=skill.Interval+skill.AttackDelay)] =  skill.Duration * mult - TIME_UNIT
        else:
            self.Summons[Summon(skill=skill, interval=skill.Interval)] =  skill.Duration * mult - TIME_UNIT

    def Tick(self):
        resultlogs = []
        # 소환수의 지속시간을 감소시킨다
        for summon, cool in list(self.Summons.items()):
            # 소환수의 공격 간격을 갱신함
            summonlogs = summon.Tick()
            if None !=summonlogs:
                for log in summonlogs:
                    if log is not None:
                        resultlogs.append(log)
            # 소환수의 지속시간을 갱신함
            cool.update()
            # 만약 소완수의 지속시간이 0초가 된다면
            if cool == TIME_ZERO:
                #  소환수 사라질 때 호출
                summon.Skill.EndSummon()
                del self.Summons[summon]
        return resultlogs

    def isSummoned(self, skill):
        for summon, cool in self.Summons.items():
            if issubclass(skill, type(summon.Skill)):
                return cool

class Summon:
    """소환수 스킬 인스턴스
        ActiveInterval: 남은 사용 주기
    """
    def __init__(self, skill:Skill, interval:Cooldown):
        self.Skill = skill
        if hasattr(skill, 'AttackDelay'):
            self.ActiveInterval = interval
        else:
            self.ActiveInterval = Cooldown(seconds=0)

    def Tick(self):
        if self.ActiveInterval == TIME_ZERO:
            # 공격 간격이 일정한 경우

            self.ActiveInterval = deepcopy(self.Skill.Interval - TIME_UNIT)
            return self.Skill.UseSkill()

        else:
            self.Skill.Duration -= TIME_UNIT
            self.ActiveInterval -= TIME_UNIT
            return None

    # TODO: 소환수 사라질 때 호출할 것.
    def Timeout(self):
        pass

    def __del__(self):
        self.Timeout()


import telebot
import secret
import currency

bot = telebot.TeleBot(secret.TOKEN)
keyboard1 = telebot.types.ReplyKeyboardMarkup(True, True)
keyboard1.row('Привет', 'Пока')

@bot.message_handler(commands=['start'])
def start_command(message):
    bot.send_message(
        message.chat.id,
        'Привет! Я могу показать вам курсы валют.\n' +
        'Чтобы узнать курсы валют, нажмите /exchange.\n' +
        'Чтобы получить помощь, нажмите /help.'
    )

@bot.message_handler(commands=['help'])
def help_command(message):
    keyboard = telebot.types.InlineKeyboardMarkup()
    keyboard.add(
        telebot.types.InlineKeyboardButton(
            'Написать разработчику', url='t.me/pin4uck'
        )
    )
    bot.send_message(
        message.chat.id,
        '1) Чтобы получить список доступных волют, нажмите /exchange.\n' +
        '2) Нажмите на интересующую вас валюту.\n' +
        '3) Вы получите сообщение, содержащее информацию об курсе валюты, установленным Национальным банком РБ.\n',
        reply_markup=keyboard
    )

@bot.message_handler(commands=['exchange'])
def exchange_command(message):
    keyboard = telebot.types.InlineKeyboardMarkup()
    keyboard.row(
            telebot.types.InlineKeyboardButton('USD', callback_data='get-USD')
    )
    keyboard.row(
            telebot.types.InlineKeyboardButton('EUR', callback_data='get-EUR'),
            telebot.types.InlineKeyboardButton('RUB', callback_data='get-RUB')
    )
    bot.send_message(
            message.chat.id,
            'Нажмите на необходимую валюту:',
            reply_markup=keyboard
    )

@bot.callback_query_handler(func=lambda call: True)
def iq_callback(query):
    data = query.data
    if data.startswith('get-'):
        get_ex_callback(query)

def get_ex_callback(query):
    bot.answer_callback_query(query.id)
    send_exchange_result(query.message, query.data[4:])

def send_exchange_result(message, ex_code):
    bot.send_chat_action(message.chat.id, 'typing')
    ex = currency.get_currency_rate(ex_code)
    bot.send_message(
        message.chat.id, serialize_ex(ex, ex_code),
        parse_mode='HTML'
    )

def serialize_ex(ex_json, ex_code):
    result = '<b>' + ex_code + ' -> ' + 'BYN' + ':</b>\n\n' + \
             'Rate: ' + str(ex_json)
    return result

@bot.message_handler(content_types=['text'])
def sent_text(message):
    if message.text.lower() == 'привет':
        bot.send_message(message.chat.id, 'Привет, мой создатель')
    elif message.text.lower() == 'пока':
        bot.send_message(message.chat.id, 'До встречи, создатель')
    elif message.text.lower() == 'я тебя люблю':
        bot.send_sticker(message.chat.id, 'CAACAgIAAxkBAAM0YDaQ24SzhzkWTzYu8pVRCblOTrgAAgEAA8A2TxMYLnMwqz8tUR4E')

@bot.message_handler(content_types=['sticker'])
def sticker_id(message):
    print(message)

bot.polling(none_stop=True)


nodes: dict[str, list[str]] = {}

with open('data.txt') as data_file:
	for line in data_file.read().split('\n'):
		parts = line.split('-')

		n1 = nodes.get(parts[0], [])
		n1.append(parts[1])
		nodes[parts[0]] = n1

		n2 = nodes.get(parts[1], [])
		n2.append(parts[0])
		nodes[parts[1]] = n2

paths: list[str] = []

def walk(node, path):
	if node == 'end':
		paths.append([*path, node])
		return
	for adjacent in nodes[node]:
		if adjacent in path and adjacent.islower():
			continue
		walk(adjacent, [*path, node])

walk('start', [])

print(len(paths))


#title:GetPicture.py
#author:Dong
#date:20181015
#usage:
#   python GetPicture.py --picture_path=./pictures
#   python GetPicture.py --picture_path=./pictures --serial_port=/dev/ttyUSB0 --camera_id=0
#python_version:3.5
import cv2
import os
import argparse
import Driver

def parse_args():
    '''Get command line arguments'''
    helps='''This script is to get pictures of cube. \n
           To run this script,you need a camera at least. \n
           press s: save one shot for the cube \n
           press t: turn the cube for another face'''
    parser = argparse.ArgumentParser(description=helps)
    parser.add_argument(
        '--picture_path',
        type=str,
        required=True,
        help="path to save pictures")
    parser.add_argument(
        '--sample_start',
        type=int,
        required=False,
        default=0,
        help="the start number for samples")
    parser.add_argument(
        '--serial_port',
        type=str,
        required=False,
        default="",
        help="serial port to robot")
    parser.add_argument(
        '--camera_id',
        type=int,
        required=False,
        default=0,
        help="id for camera")
    return parser.parse_args()

def main():
    '''This script is to get pictures of cube.

        To run this script,you need a camera at least.
        press s: save one shot for the cube.
        press t: turn the cube for another face(only when you have a serial port).'''
    print(main.__doc__)
    args = parse_args()
    cap=cv2.VideoCapture(args.camera_id)
    group_count = args.sample_start
    pic_path = args.picture_path
    pic_count = 0
    robot = None
    if(len(args.serial_port)!=0):
        robot = Driver.Robot(args.serial_port)
    while True:
        ret, img = cap.read()
        ch = cv2.waitKey(1)
        cv2.imshow('img',img)
        if ch==27:
            break
        if ch==ord('s'):
            if(pic_count==3):
                pic_count=0
                group_count+=1
            savename=pic_path+'/'+str(group_count)+'_'+str(pic_count)+'.jpg'
            if not os.path.exists(pic_path):
                os.makedirs(pic_path)
            cv2.imwrite(savename,img)
            print("write %s done!\n"%(savename))
            pic_count+=1
        if ch==ord('t'):
            if(robot is not None):
                robot.CubeRotate(1,1)
                robot.CubeRotate(0,3)
                robot.sendOrder()
    cv2.destroyAllWindows()
    cap.release()
    exit()
if __name__=="__main__":
    main()


from source_code.base_class.setting import setting
from sklearn.model_selection import KFold
import numpy as np

class Setting_KFold_CV(setting):
    fold = 3

    def load_run_save_evaluate(self):

        # load dataset
        if self.data_split:
            train_loaded_data = self.train_dataset.load()
            test_loaded_data = self.test_dataset.load()
        else:
            loaded_data = self.dataset.load()

        # kf = KFold(n_splits=self.fold, shuffle=True)

        # fold_count = 0
        score_dict = {}
        # for train_index, test_index in zip(kf.split(train_loaded_data['X']), kf.split(test_loaded_data['X'])):
        #     fold_count += 1
        #     print('************ Fold:', fold_count, '************')
        # no need to use cross-validator in this stage
        X_train, X_test = np.array(train_loaded_data['X']), np.array(test_loaded_data['X'])
        y_train, y_test = np.array(train_loaded_data['y']), np.array(test_loaded_data['y'])

        # run MethodModule
        self.method.data = {'train': {'X': X_train, 'y': y_train}, 'test': {'X': X_test, 'y': y_test}}
        learned_result = self.method.run()

        # save raw ResultModule
        self.result.data = learned_result
        # self.result.fold_count = fold_count
        self.result.save()

        self.evaluate.data = learned_result
        score_dict, metric_report = self.evaluate.evaluate()

        # return np.mean(score_list), np.std(score_list)
        return score_dict, metric_report


import pyperclip

while True:
    lines = []
    print("Bitte geben Sie mehrere Zeilen Text ein (leere Zeile zum Beenden):")
    while True:
        line = input()
        if line:
            lines.append(line)
        else:
            break
    if not lines:
        break

    result = ""
    for line in lines:
        for symbol in [".", "-", "+", "<", ">", ":"]:
            line = line.replace(" "+symbol, symbol).replace(symbol+" ", symbol)
        line = line.lstrip('0123456789 ')
        line = line.replace("’", "'")
        result += line + "\n"

    pyperclip.copy(result.strip())
    print("Der bereinigte Text wurde in die Zwischenablage kopiert.")

print("Programm beendet.")


import hashlib

from decouple import config

import schemas
import schemas_ee
from chalicelib.utils import pg_client, helper
from chalicelib.utils.TimeUTC import TimeUTC
from chalicelib.utils.storage import StorageClient
from chalicelib.utils.storage import extra

def generate_file_key(project_id, key):
    return f"{project_id}/{hashlib.md5(key.encode()).hexdigest()}"

def presign_record(project_id, data: schemas_ee.AssistRecordPayloadSchema, context: schemas_ee.CurrentContext):
    key = generate_file_key(project_id=project_id, key=f"{TimeUTC.now()}-{data.name}")
    presigned_url = StorageClient.get_presigned_url_for_upload(bucket=config('ASSIST_RECORDS_BUCKET'), expires_in=1800,
                                                               key=key)
    return {"URL": presigned_url, "key": key}

def save_record(project_id, data: schemas_ee.AssistRecordSavePayloadSchema, context: schemas_ee.CurrentContext):
    extra.tag_record(file_key=data.key, tag_value=config('RETENTION_L_VALUE', default='vault'))
    params = {"user_id": context.user_id, "project_id": project_id, **data.dict()}
    with pg_client.PostgresClient() as cur:
        query = cur.mogrify(
            f"""INSERT INTO assist_records(project_id, user_id, name, file_key, duration, session_id)
                VALUES (%(project_id)s, %(user_id)s, %(name)s, %(key)s,%(duration)s, %(session_id)s)
                RETURNING record_id, user_id, session_id, created_at, name, duration,
                        (SELECT name FROM users WHERE users.user_id = %(user_id)s LIMIT 1) AS created_by, file_key;""",
            params)
        cur.execute(query)
        result = helper.dict_to_camel_case(cur.fetchone())
        result["URL"] = StorageClient.get_presigned_url_for_sharing(
            bucket=config("ASSIST_RECORDS_BUCKET"), key=result.pop("fileKey"),
            expires_in=config("PRESIGNED_URL_EXPIRATION", cast=int, default=900)
        )
    return result

def search_records(project_id: int, data: schemas_ee.AssistRecordSearchPayloadSchema,
                   context: schemas_ee.CurrentContext):
    conditions = ["projects.tenant_id=%(tenant_id)s",
                  "projects.deleted_at ISNULL",
                  "projects.project_id=%(project_id)s",
                  "assist_records.deleted_at ISNULL"]
    if data.startTimestamp:
        conditions.append("assist_records.created_at>=%(startDate)s")
    if data.endTimestamp:
        conditions.append("assist_records.created_at<=%(endDate)s")

    params = {"tenant_id": context.tenant_id, "project_id": project_id,
              "startDate": data.startTimestamp, "endDate": data.endTimestamp,
              "p_start": (data.page - 1) * data.limit, "p_limit": data.limit,
              **data.dict()}
    if data.user_id is not None:
        conditions.append("assist_records.user_id=%(user_id)s")
    if data.query is not None and len(data.query) > 0:
        conditions.append("(users.name ILIKE %(query)s OR assist_records.name ILIKE %(query)s)")
        params["query"] = helper.values_for_operator(value=data.query,
                                                     op=schemas.SearchEventOperator._contains)
    with pg_client.PostgresClient() as cur:
        query = cur.mogrify(f"""SELECT COUNT(assist_records.record_id) OVER () AS count,
                                       record_id, user_id, session_id, assist_records.created_at,
                                       assist_records.name, duration, users.name AS created_by
                                FROM assist_records
                                      INNER JOIN projects USING (project_id)
                                      LEFT JOIN users USING (user_id)
                                WHERE {" AND ".join(conditions)}
                                ORDER BY assist_records.created_at {data.order}
                                LIMIT %(p_limit)s OFFSET %(p_start)s;""",
                            params)
        cur.execute(query)
        rows = helper.list_to_camel_case(cur.fetchall())
        if len(rows) == 0:
            return {"total": 0, "records": []}

        results = {"total": rows[0]["count"]}
        for r in rows:
            r.pop("count")
        results["records"] = rows

    return results

def get_record(project_id, record_id, context: schemas_ee.CurrentContext):
    conditions = ["projects.tenant_id=%(tenant_id)s",
                  "projects.deleted_at ISNULL",
                  "assist_records.record_id=%(record_id)s",
                  "assist_records.deleted_at ISNULL"]
    params = {"tenant_id": context.tenant_id, "project_id": project_id, "record_id": record_id}
    with pg_client.PostgresClient() as cur:
        query = cur.mogrify(f"""SELECT record_id, user_id, session_id, assist_records.created_at,
                                       assist_records.name, duration, users.name AS created_by,
                                       file_key
                                FROM assist_records
                                         INNER JOIN projects USING (project_id)
                                         LEFT JOIN users USING (user_id)
                                WHERE {" AND ".join(conditions)}
                                LIMIT 1;""", params)
        cur.execute(query)
        result = helper.dict_to_camel_case(cur.fetchone())
        if result:
            result["URL"] = StorageClient.get_presigned_url_for_sharing(
                bucket=config("ASSIST_RECORDS_BUCKET"), key=result.pop("fileKey"),
                expires_in=config("PRESIGNED_URL_EXPIRATION", cast=int, default=900)
            )
    return result

def update_record(project_id, record_id, data: schemas_ee.AssistRecordUpdatePayloadSchema,
                  context: schemas_ee.CurrentContext):
    conditions = ["assist_records.record_id=%(record_id)s", "assist_records.deleted_at ISNULL"]
    params = {"tenant_id": context.tenant_id, "project_id": project_id, "record_id": record_id, "name": data.name}
    with pg_client.PostgresClient() as cur:
        query = cur.mogrify(f"""UPDATE assist_records
                                SET name= %(name)s
                                FROM (SELECT users.name AS created_by
                                      FROM assist_records INNER JOIN users USING (user_id)
                                      WHERE record_id = %(record_id)s
                                        AND assist_records.deleted_at ISNULL
                                      LIMIT 1) AS users
                                WHERE {" AND ".join(conditions)}
                                RETURNING record_id, user_id, session_id, assist_records.created_at,
                                       assist_records.name, duration, created_by, file_key;""", params)
        cur.execute(query)
        result = helper.dict_to_camel_case(cur.fetchone())
        if not result:
            return {"errors": ["record not found"]}
        result["URL"] = StorageClient.get_presigned_url_for_sharing(
            bucket=config("ASSIST_RECORDS_BUCKET"), key=result.pop("fileKey"),
            expires_in=config("PRESIGNED_URL_EXPIRATION", cast=int, default=900)
        )
    return result

def delete_record(project_id, record_id, context: schemas_ee.CurrentContext):
    conditions = ["assist_records.record_id=%(record_id)s"]
    params = {"tenant_id": context.tenant_id, "project_id": project_id, "record_id": record_id}
    with pg_client.PostgresClient() as cur:
        query = cur.mogrify(f"""UPDATE assist_records
                                SET deleted_at= (now() at time zone 'utc')
                                WHERE {" AND ".join(conditions)}
                                RETURNING file_key;""", params)
        cur.execute(query)
        result = helper.dict_to_camel_case(cur.fetchone())
        if not result:
            return {"errors": ["record not found"]}
        extra.tag_record(file_key=result["fileKey"], tag_value=config('RETENTION_D_VALUE', default='default'))
    return {"state": "success"}


# Count IP Addresses (https://www.codewars.com/kata/526989a41034285187000de4)

# Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one).

# All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one.

# Examples

# * With input "10.0.0.0", "10.0.0.50"  => return   50
# * With input "10.0.0.0", "10.0.1.0"   => return  256
# * With input "20.0.0.10", "20.0.1.0"  => return  246

import re

def ips_between(start, end):
        start = [int(i) for i in re.findall(r'[0-9]+', start)]
        end = [int(i) for i in re.findall(r'[0-9]+', end)]
        ip1 = (start[0]*(256**3))+(start[1]*(256**2))+(start[2]*256)+start[3]
        ip2 = (end[0]*(256**3))+(end[1]*(256**2))+(end[2]*256)+end[3]
        return ip2 - ip1


import copycat.toolbox as toolbox
from copycat.coderack import Codelet

class BondBottomUpScout(Codelet):
    """Choose an object and a neighbor of that object probabilistically by
    intra string salience. Choose a bond facet probabilistically by
    relevance in the string. Check if there is a bond between the two
    descriptors of this facet. Post a bond strength tester codelet with
    urgency a function of the degree of association of bonds of the bond
    category."""

    structure_category = 'bond'

    def run(self, coderack, slipnet, workspace):
        from_object = workspace.choose_object('intra_string_salience')
        to_object = from_object.choose_neighbor()
        if not to_object:
            return # Fizzle

        bond_facet = workspace.choose_bond_facet(from_object, to_object)
        if not bond_facet:
            return # Fizzle

        from_descriptor = from_object.get_descriptor(bond_facet)
        to_descriptor = to_object.get_descriptor(bond_facet)
        if not from_descriptor or not to_descriptor:
            return # Fizzle

        bond_category = slipnet.get_bond_category(from_descriptor, to_descriptor)
        if not bond_category:
            return # Fizzle

        return workspace.propose_bond(from_object, to_object, bond_category,
                                      bond_facet, from_descriptor, to_descriptor)

class BondBuilder(Codelet):
    """Attempt to build the proposed bond, fighting with any competitiors."""

    structure_category = 'bond'

    def run(self, coderack, slipnet, workspace):
        bond = self.arguments[0]
        string = bond.string
        from_object = bond.from_object
        to_object = bond.to_object

        objects = workspace.objects()
        if (from_object not in objects) or (to_object not in objects):
            return # Fizzle

        existing_bond = string.get_existing_bond(bond)
        if existing_bond:
            existing_bond.bond_category.activation_buffer += workspace.activation
            direction_category = existing_bond.direction_category
            if direction_category:
                direction_category.activation_buffer += workspace.activation
            string.remove_proposed_bond(bond)
            return # Fizzle

        string.remove_proposed_bond(bond)

        incompatible_bonds = bond.incompatible_bonds()
        if not workspace.fight_it_out(bond, 1, incompatible_bonds, 1):
            return # Fizzle

        incompatible_groups = workspace.get_common_groups(from_object, to_object)
        spans = [group.letter_span() for group in incompatible_groups]
        strength = 0 if len(spans) == 0 else max(spans)
        if not workspace.fight_it_out(bond, 1, incompatible_groups, strength):
            return # Fizzle

        incompatible_corrs = []
        at_edge = bond.is_leftmost_in_string() or bond.is_rightmost_in_string()
        if bond.direction_category and at_edge:
            incompatible_corrs = bond.incompatible_correspondences()
            if not workspace.fight_it_out(bond, 2, incompatible_corrs, 3):
                return # Fizzle

        for ibond in incompatible_bonds:
            workspace.break_bond(ibond)

        for igroup in incompatible_groups:
            workspace.break_group(igroup)

        for icorrespondence in incompatible_corrs:
            workspace.break_correspondence(icorrespondence)

        return workspace.build_bond(bond)

class BondStrengthTester(Codelet):
    """Calculate the proposed bond's strength and decide probabilistically
    whether to post a bond builder codelet with urgency a function of the
    strength."""

    structure_category = 'bond'

    def run(self, coderack, slipnet, workspace):
        bond = self.arguments[0]

        bond.update_strengths()
        strength = bond.total_strength

        probability = strength / 100.0
        probability = workspace.temperature_adjusted_probability(probability)
        if not toolbox.flip_coin(probability):
            bond.string.remove_proposed_bond(bond)
            return # Fizzle

        bond.proposal_level = 2

        bond.from_object_descriptor.activation_buffer += workspace.activation
        bond.to_object_descriptor.activation_buffer += workspace.activation
        bond.bond_facet.activation_buffer += workspace.activation

        return [(BondBuilder([bond]), strength)]

class BondTopDownCategoryScout(Codelet):
    """Choose a string probabilistically by the relevance of the category in
    the string and the string's unhappiness. Chooses an object and a neighbor
    of the object in the string probabilistically by instra string salience.
    Choose a bond facet probabilistically by relevance in in the string.
    Checks if there is a bond of the category between the two descriptors of
    the facet, posting a bond strength tester codelet with urgency a function
    of the degree of association of bonds of the category."""

    structure_category = 'bond'

    def run(self, coderack, slipnet, workspace):
        category = self.arguments[0]

        initial_string = workspace.initial_string
        target_string = workspace.target_string
        i_relevance = initial_string.local_bond_category_relevance(category)
        t_relevance = target_string.local_bond_category_relevance(category)
        i_unhappiness = initial_string.intra_string_unhappiness
        t_unhappiness = target_string.intra_string_unhappiness
        values = [round(toolbox.average(i_relevance, i_unhappiness)),
                  round(toolbox.average(t_relevance, t_unhappiness))]
        string = toolbox.weighted_select(values, [initial_string, target_string])

        obj = string.get_random_object('intra_string_salience')
        neighbor = obj.choose_neighbor()
        if neighbor is None:
            return # Fizzle

        facet = workspace.choose_bond_facet(obj, neighbor)
        if facet is None:
            return # Fizzle

        object_descriptor = obj.get_descriptor(facet)
        neighbor_descriptor = neighbor.get_descriptor(facet)
        if object_descriptor is None or neighbor_descriptor is None:
            return # Fizzle

        if slipnet.get_bond_category(object_descriptor,
                                     neighbor_descriptor) == category:
            from_object = obj
            to_object = neighbor
            from_descriptor = object_descriptor
            to_descriptor = neighbor_descriptor
        elif slipnet.get_bond_category(neighbor_descriptor,
                                       object_descriptor) == category:
            from_object = neighbor
            to_object = obj
            from_descriptor = neighbor_descriptor
            to_descriptor = object_descriptor
        else:
            return # Fizzle

        return workspace.propose_bond(from_object, to_object, category, facet,
                                      from_descriptor, to_descriptor)

class BondTopDownDirectionScout(Codelet):
    """Choose a string probabilistically by the relevance of the direction
    category in the string and the string's unhappiness. Chooses an object
    in the string probabilisitically by intra string salience. Chooses a
    neighbor of the object in the given direction. Chooses a bond facet
    probabilistically by relevance in the string. Checks if there is a
    bond of the given direction between the two descriptors of the facet,
    posting a bond strength tester codelet with urgency a function of the
    degree of association of bonds of the bond category."""

    structure_category = 'bond'

    def run(self, coderack, slipnet, workspace):
        category = self.arguments[0]

        initial_string = workspace.initial_string
        target_string = workspace.target_string
        i_relevance = initial_string.local_direction_category_relevance(category)
        t_relevance = target_string.local_direction_category_relevance(category)
        i_unhappiness = initial_string.intra_string_unhappiness
        t_unhappiness = target_string.intra_string_unhappiness
        values = [round(toolbox.average(i_relevance, i_unhappiness)),
                  round(toolbox.average(t_relevance, t_unhappiness))]
        string = toolbox.weighted_select(values, [initial_string, target_string])

        obj = string.get_random_object('intra_string_salience')
        if category == slipnet.plato_left:
            neighbor = obj.choose_left_neighbor()
        elif category == slipnet.plato_right:
            neighbor = obj.choose_right_neighbor()
        if neighbor is None:
            return # Fizzle

        facet = workspace.choose_bond_facet(obj, neighbor)
        if facet is None:
            return # Fizzle

        object_descriptor = obj.get_descriptor(facet)
        neighbor_descriptor = neighbor.get_descriptor(facet)
        if object_descriptor is None or neighbor_descriptor is None:
            return # Fizzle

        bond_category = slipnet.get_bond_category(object_descriptor,
                                                  neighbor_descriptor)
        if bond_category is None or not bond_category.directed:
            return # Fizzle

        return workspace.propose_bond(obj, neighbor,
                                      bond_category, facet,
                                      object_descriptor, neighbor_descriptor)


# -*- coding: utf-8 -*-
"""
acousticHMS.py
------------

Acoustic signal analysis routines implementing the Hearing Model of Sottek,
defined in the ECMA-418-2 standard (currently 2022).

Requirements
------------
numpy (1.23.4)
scipy (1.9.3)
matplotlib (3.6.2)

Ownership and Quality Assurance
-------------------------------
Author: Mike JB Lotinga (m.j.lotinga@edu.salford.ac.uk)
Institution: University of Salford

Date created: 27/10/2023
Date last modified: 29/10/2023
Python version: 3.10.11

Copyright statement: This file and code is part of work undertaken within
the RefMap project (www.refmap.eu), and is subject to licence as detailed
in the code repository
(https://github.com/acoustics-code-salford/refmap-psychoacoustics)

Checked by:
Date last checked:

"""

import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt

# set plot parameters
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'Arial'
mpl.rcParams.update({'font.size': 14, 'mathtext.fontset': 'stix'})
mpl.rcParams['figure.autolayout'] = True

def acousticHMSPreProc(signal, blockSize, hopSize):
    """Function signalFadePad = acousticHMSPreProc(signal, blockSize, hopSize)

    Returns signal with fade-in and zero-padding pre-processing according to
    ECMA-418-2:2022 (the Hearing Model of Sottek) for an input signal.

    Inputs
    ------
    signal : 1D or 2D array
             the input signal/s

    blockSize : integer
                the maximum signal segmentation block size

    hopSize : integer
              the maximum signal segmentation hop size
              = (1 - overlap)*blockSize

    Returns
    -------
    signalFadePad : 1D or 2D array
                    the output faded, padded signal

    Assumptions
    -----------
    The input signal is oriented with time on axis 0 (and channel # on axis
    1), ie, the fade and padding operation is applied along axis 0.
    The input signal must be sampled at 48 kHz.

    Requirements
    ------------
    numpy

    Ownership and Quality Assurance
    -------------------------------
    Authors: Mike JB Lotinga (m.j.lotinga@edu.salford.ac.uk)
    Institution: University of Salford

    Date created: 26/09/2023
    Date last modified: 19/10/2023
    Python version: 3.10.11

    Copyright statement: This file and code is part of work undertaken within
    the RefMap project (www.refmap.eu), and is subject to licence as detailed
    in the code repository
    (https://github.com/acoustics-code-salford/refmap-psychoacoustics)

    Checked by:
    Date last checked:

    """
    # Signal processing

    # Input pre-processing
    # --------------------
    #
    # Check signal dimensions and add axis if 1D input
    #
    if np.size(signal.shape) == 1:
        numChans = 1
        signal = signal[:, np.newaxis]
    else:
        numChans = signal.shape(1)

    if numChans > 2:
        raise ValueError("Input signal must be 1- or 2-channel")

    # Fade in weighting function Section 5.1.2 ECMA-418-2:2022

    fadeWeight = 0.5 - 0.5*np.cos(np.pi*np.arange(0, 240)/240)[:, np.newaxis]
    # Apply fade in
    signalFade = np.concatenate((fadeWeight*signal[0:240, :],
                                 signal[240:, :]))

    # Zero-padding Section 5.1.2 ECMA-418-2:2022
    n_zeross = int(blockSize)  # start zero-padding
    n_samples = signal.shape[0]
    n_new = int(hopSize*(np.ceil((n_samples + hopSize + n_zeross)/hopSize) - 1))
    n_zerose = n_new - n_samples  # end zero-padding
    # Apply zero-padding
    signalFadePad = np.concatenate((np.zeros((n_zeross, numChans)), signalFade,
                                    np.zeros((n_zerose, numChans))))

    return signalFadePad  # end of acousticHMSPreProc function


import os
import argparse
import logging

from hisup.config import cfg
from hisup.detector import BuildingDetector
from hisup.utils.logger import setup_logger
from hisup.utils.checkpoint import DetectronCheckpointer
from tools.test_pipelines import TestPipeline

import torch
torch.multiprocessing.set_sharing_strategy('file_system')

def parse_args():
    parser = argparse.ArgumentParser(description='Testing')

    parser.add_argument("--config-file",
                        metavar="FILE",
                        help="path to config file",
                        type=str,
                        default=None,
                        )

    parser.add_argument("--eval-type",
                        type=str,
                        help="evalutation type for the test results",
                        default="coco_iou",
                        choices=["coco_iou",  "boundary_iou", "polis"]
                        )

    parser.add_argument("opts",
                        help="Modify config options using the command-line",
                        default=None,
                        nargs=argparse.REMAINDER
                        )

    args = parser.parse_args()

    return args

def test(cfg, args):
    logger = logging.getLogger("testing")
    device = cfg.MODEL.DEVICE
    model = BuildingDetector(cfg, test=True)
    model = model.to(device)

    if args.config_file is not None:
        checkpointer = DetectronCheckpointer(cfg,
                                         model,
                                         save_dir=cfg.OUTPUT_DIR,
                                         save_to_disk=True,
                                         logger=logger)
        _ = checkpointer.load()
        model = model.eval()

    test_pipeline = TestPipeline(cfg, args.eval_type)
    test_pipeline.test(model)
    # test_pipeline.eval()

if __name__ == "__main__":
    args = parse_args()
    if args.config_file is not None:
        cfg.merge_from_file(args.config_file)
    else:
        cfg.OUTPUT_DIR = 'outputs/default'
        os.makedirs(cfg.OUTPUT_DIR,exist_ok=True)

    cfg.merge_from_list(args.opts)
    cfg.freeze()

    output_dir = cfg.OUTPUT_DIR
    logger = setup_logger('testing', output_dir)
    logger.info(args)
    if args.config_file is not None:
        logger.info("Loaded configuration file {}".format(args.config_file))
    else:
        logger.info("Loaded the default configuration for testing")

    test(cfg, args)


import face_recognition
import cv2
import pickle
from imutils import paths
from pathlib import Path
import cvlib as cv
import dlib

def FindFaces(img):

    detectedFacesLoc = []
    cnn_face = dlib.cnn_face_detection_model_v1('./detection_model/mmod_human_face_detector.dat')

    face_locations =cnn_face(img,0)

    if (len(face_locations) > 0):
        for face in face_locations:
            x1 = face.rect.left()
            y1 = face.rect.top()
            x2 = face.rect.right()
            y2 = face.rect.bottom()
            c = 1
            count = 1
            detectedFacesLoc.append([x1,y1,x2,y2,c,count])

    try:
        grayscale_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    except:
        print("Something went wrong")

    finally:
        face_locations = face_recognition.face_locations(grayscale_image)

    if (len(face_locations) > 0):
        for face in face_locations:
            y1,x2,y2,x1 = face
            found = 0
            for dface in detectedFacesLoc:
                if (x1 < dface[0] + 30 and x1 > dface[0] - 30):
                    found = 1
                    dface[5] += 1
                    break
            if (found == 0):
                c = 2
                detectedFacesLoc.append([x1,y1,x2,y2,c,1])

    face_locations, confidences = cv.detect_face(img)
    if (len(face_locations) > 0):
        for face in face_locations:
            x1,y1,x2,y2 = face
            found = 0
            for dface in detectedFacesLoc:
                if (x1 < dface[0] + 30 and x1 > dface[0] - 30):
                    found = 1
                    dface[5] += 1
                    break
            if (found == 0):
                c = 3
                detectedFacesLoc.append([x1,y1,x2,y2,c,1])

    if (detectedFacesLoc[0][5] > 1 or len(detectedFacesLoc)== 1):
        face_crop=img[detectedFacesLoc[0][1]: detectedFacesLoc[0][3],
                          detectedFacesLoc[0][0]:detectedFacesLoc[0][2]]
    else:
        detectedFacesLoc.remove(detectedFacesLoc[0])
        face_crop=img

    return face_crop, detectedFacesLoc

#get paths of each file in folder named Images
#Images here contains my data(folders of various persons)
imagePaths = list(paths.list_images('./augmented_cropped_images'))
knownEncodings = []
knownNames = []
# loop over the image paths
for (i, imagePath) in enumerate(imagePaths):
    # extract the person name from the image path
    name = (Path(imagePath).stem).split(sep=" ")[0]
    # to dlib ordering (RGB)
    image = cv2.imread(imagePath)
    im_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    h,w,c = im_rgb.shape
    if h > 1280 and w > 720:
        im_rgb=cv2.resize(im_rgb, dsize=(1280,720), interpolation=cv2.INTER_CUBIC)

    detect_face_img , face_location= FindFaces(im_rgb);
    #Use Face_recognition to locate faces
    # compute the facial embedding for the face
    encodings = face_recognition.face_encodings(detect_face_img)
    if (len(encodings)==0 and len(face_location)!=0):
        new_img = im_rgb[face_location[0][1] - 20: face_location[0][3] + 20,
                                  face_location[0][0] - 10:face_location[0][2] + 10]
        encodings = face_recognition.face_encodings(new_img)

    if len(encodings)==0:
        encodings = face_recognition.face_encodings(im_rgb)

    for encoding in encodings:
        if len(encoding) !=0:
            print("Done image of ", i)
            knownEncodings.append(encoding)
            knownNames.append(name)

#save emcodings along with their names in dictionary data
data ={"encodings":knownEncodings, "names": knownNames}

#use pickle to save data into a file for later use
f = open("face_encoding", "wb")

f.write(pickle.dumps(data))

f.close()

# writing to csv file
'''with open("face_encoding.csv", 'w') as csvfile:
    # creating a csv writer object
    csvwriter = csv.writer(csvfile)

    # writing the fields
    csvwriter.writerow(knownNames)

    # writing the data rows
    csvwriter.writerow(knownEncodings)'''


import json
import numpy as np
import os
import csv
from random import shuffle

"""
This program prepares an additional test dataset from independent self labeled data.
"""

test_dataset=[]
count = [0, 0, 0]
print("Reading sentiments that were manually annotated.")
sources = {"positive", "neutral", "negative"}
for source in sources:
    with open('../Testdata/' + source + '_labels_for_accuracy_test.csv', newline='', encoding='utf-8') as csvfile:
        readfile = csv.reader(csvfile, delimiter=',', quotechar='|')
        for row in readfile:
            if row[3] != "" and row[4] == "" and row[2] != "":
                count[int(row[3])+1]+=1
                test_dataset.append([row[2], int(row[3])])
print("Done.")
print("Data distribution [Negative, Neutral, Positive]:", count)
shuffle(test_dataset)

print("Preping Dataset.")
dataset = {"labels": [], 'text_input': []}
for i, data in enumerate(test_dataset):
    if  data[1] == -1:
        sentiment = [1., 0., 0.]
    elif data[1] == 0:
        sentiment = [0., 1., 0.]
    elif data[1] == 1:
        sentiment = [0., 0., 1.]
    else:
        print("Error!\n", data[1])
    dataset["labels"].append(sentiment)
    dataset["text_input"].append( data[0] )

print("Writing datasets to file.")
with open( '../Testdata/accuracy_dataset.json', 'w') as fp:
    json.dump(dataset, fp)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 14 10:00:30 2019

@author: lagerwer
"""

import numpy as np
import reg_param as rp
from tqdm import tqdm
from odl.contrib import fom
import os
import pylab

# %%
# Phantom type
PH = 'TGV'

# Number of pixels in the x and y direction
pix = 64

# Number of projection angles
angles = 90 # 64

# Type of noise and its level
noise = ['Gaussian', 0.1] # None

# Number of iterations for PDHG
niter = 500

# Reconstruction method
method = 'TGV' # 'Sob'

# Create the fine grid of regularization parameters
lam1 = np.logspace(-4, 2, 31)
lam2 = np.logspace(-2, 2, 16)
lam = [lam1, lam2]
# Number of interpolation points
Nip_list = [[5, 5], [8, 5]]

# %% Make a path for saving the reconstructions to speed up later runs
# If you change something above, you should recompute the recons
recompute = True
path = 'recons'
if not os.path.exists(path):
    os.makedirs(path)
save_path = path + '/' + method
# %% Define the problem and create the method
IP = rp.problem_definition_class(PH, pix, angles, noise)
MC = rp.method_class(IP, method)

# %% Create the reconstructions
recs = rp.recon_2param_class(MC, lam)

if recompute:
    recs.compute(niter)
    rp.save_recs_2D(pix, lam, recs, save_path)

if os.path.exists(save_path + '_x_list.npy'):
    if not hasattr(recs, 'x'):
        recs.load(save_path)
else:
    recs.compute(niter)
    rp.save_recs_2D(pix, lam, recs, save_path)

# %% Create interpolations for varying number of interpolation points
IC = []
for Nip in Nip_list:
    IC += [rp.interp_2param_class(Nip, recs)]

# %% Show some results
pylab.close('all')

# Show QM figures
rp.show_QM_2param(lam, recs, IC)

## Show the MSE and SSIM curve of the interpolations and the reconstructions
rp.show_rec_2param(IC[1], recs)


#!/usr/bin/env python3
"""
# Purpose: Get all shared drive ACLs for a list of suspended users from a CSV file;
#    the user's primary email and aliases are checked
# Note: This script requires Advanced GAM:
#	https://github.com/taers232c/GAMADV-XTD3
# Python: Use python or python3 below as appropriate to your system; verify that you have version 3
#  $ python -V   or   python3 -V
#  Python 3.x.y
# Usage:
# 1: Prepare a CSV file with a list of suspended user email addresses and aliases
#  $ gam redirect csv ./SuspendedUsers.csv print users query "isSuspended=True" fields primaryemail aliases
# 2: Get Shared Drive ACLs
#  $ gam config csv_output_header_drop_filter "User" redirect csv ./SharedDriveACLs.csv print shareddriveacls fields id,emailaddress,role,type
# 3: From that list of ACLs, output a CSV file with headers "id,name,createdTime,permissionId,role,emailAddress"
#    that lists the Shared Drive id, name and createdTime, permissionId, role and email address for the specified users
#  $ python3 GetSuspendedUserSharedDriveACLs.py SharedDriveACLs.csv SuspendedUserSharedDriveACLS.csv SuspendedUsers.csv
"""

import csv
import re
import sys

# The header in the CSV file that contains the user email addresses
USER_HEADER = 'primaryEmail'

QUOTE_CHAR = '"' # Adjust as needed
LINE_TERMINATOR = '\n' # On Windows, you probably want '\r\n'

ALIASES_N = re.compile(r"aliases.(\d+)")
PERMISSIONS_N_TYPE = re.compile(r"permissions.(\d+).type")

userSet = set()
inputFile = open(sys.argv[3], 'r', encoding='utf-8')
for row in csv.DictReader(inputFile, quotechar=QUOTE_CHAR):
  user = row['primaryEmail'].lower()
  if user:
    userSet.add(user)
  for k, v in iter(row.items()):
    mg = ALIASES_N.match(k)
    if mg and v:
      userSet.add(v.lower())
inputFile.close()

outputFile = open(sys.argv[2], 'w', encoding='utf-8', newline='')
outputCSV = csv.DictWriter(outputFile, ['id', 'name', 'createdTime', 'permissionId', 'role', 'emailAddress'],
                           lineterminator=LINE_TERMINATOR, quotechar=QUOTE_CHAR)
outputCSV.writeheader()

inputFile = open(sys.argv[1], 'r', encoding='utf-8')

for row in csv.DictReader(inputFile, quotechar=QUOTE_CHAR):
  for k, v in iter(row.items()):
    mg = PERMISSIONS_N_TYPE.match(k)
    if mg and v == 'user':
      permissions_N = mg.group(1)
      if row.get(f'permissions.{permissions_N}.deleted', '') == 'True':
        continue
      emailAddress = row[f'permissions.{permissions_N}.emailAddress'].lower()
      if emailAddress in userSet:
        outputCSV.writerow({'id': row['id'],
                            'name': row['name'],
                            'createdTime': row['createdTime'],
                            'permissionId': f'id:{row[f"permissions.{permissions_N}.id"]}',
                            'role': row[f'permissions.{permissions_N}.role'],
                            'emailAddress': emailAddress})

inputFile.close()
outputFile.close()


"""
Даны координаты двух точек на плоскости, требуется определить, лежат ли они в одной
координатной четверти или нет (все координаты отличны от нуля)
"""

x = int(input())   # Вводим числовые значения
y = int(input())
z = int(input())
g = int(input())

if (x > 0 and y > 0) and (z > 0 and g > 0):   # Перебираем все условия нахождения в одной четверти (А так не говнокод ли?)
    print("Yes")
elif (x < 0 and y < 0) and (z < 0 and g < 0):
    print("Yes")
elif (x < 0 and y > 0) and (z < 0 and g > 0):
    print("Yes")
elif (x > 0 and y < 0) and (z > 0 and g < 0):
    print("Yes")
else:
    print("No")


import os
import json
import argparse
import time as t
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn import preprocessing
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix

from utils.helper import *

def submit(clf, test_set, scaler, class_label_pair, filepath):
    Xtest, ids = get_submission_data(test_set)
    X_test_scaled = scaler.transform(Xtest)
    print("Predicting on {} ...".format(test_set.split('/')[-1]))
    predictions = clf.predict(X_test_scaled)
    make_submission(predictions, ids, class_label_pair, filepath)

def main ():
    parser = argparse.ArgumentParser(description="NetML Challenge 2020 Random Forest Classifier Baseline", add_help=True)
    parser.add_argument('-d', '--dataset', action="store", help="Dataset path")
    parser.add_argument('-a', '--anno', action="store", help="Annoation level: {top, mid, fine}")
    parser.add_argument('-s', '--submit', action="store", help="{test-std, test-challenge, both} Select which set to submit")

    args = parser.parse_args()

    if args.dataset == None or not os.path.isdir(args.dataset) or args.anno == None:
        print ("No valid dataset set or annotations found!")
        return
    elif args.submit is not None and args.submit not in ["test-std", "test-challenge", "both"]:
        print("Please select which set to submit: {test-std, test-challenge, both}")
        return
    elif args.anno not in ["top", "mid", "fine"]:
        print("Please select one of these for annotations: {top, mid, fine}. e.g. --anno top")
        return
    elif args.anno == "mid" and (args.dataset.find("NetML") > 0 or args.dataset.find("CICIDS2017") > 0):
        print("NetML and CICIDS2017 datasets cannot be trained with mid-level annotations. Please use either top or fine.")
        return
    else:
        training_set = args.dataset+"/2_training_set"
        training_anno_file = args.dataset+"/2_training_annotations/2_training_anno_"+args.anno+".json.gz"
        test_set = args.dataset+"/1_test-std_set"
        challenge_set = args.dataset+"/0_test-challenge_set"

    # Create folder for the results
    time_ = t.strftime("%Y%m%d-%H%M%S")

    save_dir = os.getcwd() + '/results/' + time_
    os.makedirs(save_dir)

    # Get training data in np.array format
    Xtrain, ytrain, class_label_pair, Xtrain_ids = get_training_data(training_set, training_anno_file)

    # Split validation set from training data
    X_train, X_val, y_train, y_val = train_test_split(Xtrain, ytrain,
                                                    test_size=0.2,
                                                    random_state=42,
                                                    stratify=ytrain)

    # Get name of each class to display in confusion matrix
    class_names = list(sorted(class_label_pair.keys()))

    # Preprocess the data
    scaler = preprocessing.StandardScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_val_scaled = scaler.transform(X_val)

    # Train RF Model
    print("Training the model ...")
    clf = RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42, n_jobs = -1, max_features="auto")
    clf.fit(X_train_scaled, y_train)

    # Output accuracy of classifier
    print("Training Score: \t{:.5f}".format(clf.score(X_train_scaled, y_train)))
    print("Validation Score: \t{:.5f}".format(clf.score(X_val_scaled, y_val)))

    # Print Confusion Matrix
    ypred = clf.predict(X_val_scaled)

    np.set_printoptions(precision=2)

    # Plot normalized confusion matrix
    plot_confusion_matrix(directory=save_dir, y_true=y_val, y_pred=ypred,
                            classes=class_names,
                            normalize=False)

    # Make submission with JSON format
    if args.submit == "test-std" or args.submit == "both":
        submit(clf, test_set, scaler, class_label_pair, save_dir+"/submission_test-std.json")
    if args.submit == "test-challenge" or args.submit == "both":
        submit(clf, challenge_set, scaler, class_label_pair, save_dir+"/submission_test-challenge.json")

if __name__ == "__main__":
    main()


import gc
import random
import os

import numpy as np
import PIL
import streamlit as st
import streamlit.components.v1 as components
from PIL import Image
from torch import autocast

from app_model import *

pipe_manager = PipeManager()

# Image preprocessing
def preprocess(image, sizemax):
    w, h = sizemax
    w, h = map(lambda x: x - x % 32, (w, h))  # resize to integer multiple of 32
    image = image.resize((w, h))
    image.thumbnail(sizemax, resample=PIL.Image.Resampling.LANCZOS)
    image = np.array(image).astype(np.float32) / 255.0
    image = image[None].transpose(0, 3, 1, 2)
    image = torch.from_numpy(image)
    return 2.0 * image - 1.0

# Inference function
def infer(
    model: str,
    prompt: str,
    negative_prompt: str,
    init_image_file,
    width: int,
    height: int,
    steps: int,
    cfg_scale: float,
    scheduler: str,
    strength: float,
    num_images: int,
    seed: int,
    upsampling_model: str,
    upsampler_scale: float,
    upsampler_half_precision: bool,
    upsampler_gfpgan: bool,
    progress_bar,
):
    global pipe_manager

    if seed is None or seed == 0:
        seed = random.randrange(0, np.iinfo(np.uint32).max)
    generator = torch.Generator("cuda").manual_seed(seed)
    seed_origin = seed

    # pipe initialisation
    if init_image_file is not None:
        init_image = Image.open(init_image_file)
        init_image = preprocess(init_image, (width, height))
        pipe_manager.type = "img2img"
    else:
        pipe_manager.type = "txt2img"

    pipe_manager.scheduler = scheduler
    pipe_manager.model = model
    pipe = pipe_manager.open_pipe()

    upsampler_flag = False
    if upsampling_model != "None":
        upsampler = setup_upscaler(
            upsampling_model, upsampler_scale, upsampler_half_precision
        )
        if upsampler is not None:
            upsampler_flag = True

    # Memory cleanup
    gc.collect()
    torch.cuda.empty_cache()

    images_origin = []
    images_upscaled = []
    progress_total = num_images * (2 if upsampler_flag else 1)
    progress_count = 0
    with autocast("cuda"):
        for i in range(num_images):
            if pipe_manager.type == "txt2img":
                results_origin = pipe(
                    prompt=prompt,
                    negative_prompt=negative_prompt,
                    num_inference_steps=steps,
                    width=width,
                    height=height,
                    guidance_scale=cfg_scale,
                    generator=generator,
                ).images
            elif pipe_manager.type == "img2img":
                results_origin = pipe(
                    init_image=init_image,
                    prompt=prompt,
                    negative_prompt=negative_prompt,
                    num_inference_steps=steps,
                    guidance_scale=cfg_scale,
                    strength=strength,
                    generator=generator,
                ).images
            images_origin.extend(results_origin)
            progress_count = progress_count + len(results_origin)
            progress_bar.progress(float(progress_count / progress_total))

            if upsampler_flag:
                for im_origin in results_origin:
                    im_origin = np.asarray(im_origin)
                    if upsampler_gfpgan:
                        face_enhancer = GFPGANer(
                            model_path="../Real-ESRGAN/experiments/pretrained_models/GFPGANv1.3.pth",
                            upscale=upsampler_scale,
                            arch="clean",
                            channel_multiplier=2,
                            bg_upsampler=upsampler,
                        )
                        _, _, output = face_enhancer.enhance(
                            im_origin,
                            has_aligned=False,
                            only_center_face=False,
                            paste_back=True,
                        )
                    else:
                        output, _ = upsampler.enhance(
                            im_origin, outscale=upsampler_scale
                        )
                    images_upscaled.append(output)
                    progress_count = progress_count + 1
                    progress_bar.progress(float(progress_count / progress_total))
            # deterministic seed for next image
            seed = seed + 1
            generator = torch.Generator("cuda").manual_seed(seed)
    return images_origin, images_upscaled, seed_origin

st.set_page_config(
    page_title="Stable Diffusion All in One",
    page_icon="ðŸ§Š",
    layout="wide",
    initial_sidebar_state="expanded",
)

st.subheader(
    "Stable Diffusion txt2img and img2img, with upscaling (RealESRGAN and GFPGAN)"
)
with st.sidebar:
    with st.expander("Optional image input"):
        init_image = st.file_uploader(
            "Initial Image", type=["png", "jpg", "webp", "jpeg"]
        )
        strength = st.slider(
            "Strength (used with initial image)",
            min_value=0.0,
            max_value=1.0,
            step=0.05,
            value=0.75,
        )
    width = st.slider("Width", min_value=256, max_value=768, step=64, value=512)
    height = st.slider("Height", min_value=256, max_value=768, step=64, value=512)
    steps = st.slider("Sampling Steps", min_value=1, max_value=150, step=1, value=30)
    cfg_scale = st.slider(
        "Classifier Free Guidance Scale",
        min_value=1.0,
        max_value=20.0,
        step=0.5,
        value=7.0,
    )
    scheduler = st.selectbox(
        "Scheduler",
        options=["DDIM", "LMS", "Euler", "EulerA"],
        index=1,
    )
    num_images = st.slider("Num Images", min_value=1, max_value=20, step=1, value=1)
    with st.expander("Upsampling"):
        upsampling_model = st.selectbox(
            "Upsampling Model",
            options=["None", "RealESRGAN_x4plus", "RealESRGAN_x4plus_anime_6B"],
            index=0,
        )
        if upsampling_model != "None":
            upsampler_scale = st.slider(
                "Upsampler scale", min_value=1.0, max_value=4.0, step=0.5, value=4.0
            )
            upsampler_half_precision = st.checkbox("Half precision", value=False)
            upsampler_gfpgan = st.checkbox(
                "Use GFPGAN for face enhancement", value=False
            )
        else:
            upsampler_scale = 0
            upsampler_half_precision = False
            upsampler_gfpgan = False
    seed = st.number_input("Seed", min_value=0)
    st.write(" ")
    st.write(" ")

# get models list
models_list = next(os.walk(MODEL_PATH))[1]
model = st.selectbox(
    "Model",
    options=models_list,
    index=0,
)
prompt = st.text_input(
    "Prompt",
    placeholder="bouquet of roses",
)
negative_prompt = st.text_input(
    "Negative prompt",
    placeholder="red rose",
)
with st.expander("Prompt build helper"):
    components.iframe(
        "https://promptomania.com/generic-prompt-builder/", height=600, scrolling=True
    )

if st.button("Run !"):
    with st.spinner("Generating..."):
        progress_bar = st.progress(0)
        prompt = prompt.replace(
            "!dream ", ""
        )  # in case of a copy / paste from a !dream prompt
        try:
            images_origin, images_upscaled, seed = infer(
                model,
                prompt,
                negative_prompt,
                init_image,
                width,
                height,
                steps,
                cfg_scale,
                scheduler,
                strength,
                num_images,
                seed,
                upsampling_model,
                upsampler_scale,
                upsampler_half_precision,
                upsampler_gfpgan,
                progress_bar,
            )
        except Exception as e:
            st.error(e, icon="ðŸ’¥")
            raise e
        else:
            st.info("Seed : " + str(seed))
            if upsampling_model != "None":
                tab1, tab2 = st.columns(2)
                with tab1:
                    st.header("Original images")
                    with st.container():
                        st.image(images_origin)
                with tab2:
                    st.header("Upscaled images")
                    with st.container():
                        st.image(images_upscaled)
            else:
                with st.container():
                    st.image(images_origin)


import sys
command = sys.argv
df = "e2"
k = 3
voting = "1/d"
if "-k" in command:
    p_k = command.index("-k") + 1
    k = int(command[p_k])
if "-d" in command:
    p_d = command.index("-d") + 1
    df = command[p_d]
if "-unitw" in command:
    p_u = command.index("-unitw") + 1
    voting = command[p_u]
if "-train" in command:
    p_t = command.index("-train") + 1
    f_train = command[p_t]
if "-test" in command:
    p_e = command.index("-test") + 1
    f_test = command[p_e]

#read file
file_train = open(f_train,"r")
file_test = open(f_test,"r")
i = 0 #get the number of lines in file
train = []
test = []
for line in file_train.readlines():
  line = line.strip()
  each = line.split(",")
  for i in range(0,len(each)-1):
    each[i] = float(each[i])
  train.append(each)
for line in file_test.readlines():
  line = line.strip()
  each = line.split(",")
  for i in range(0,len(each)-1):
    each[i] = float(each[i])
  test.append(each)

category_number = 0
category = []
for t in train:
  if t[-1] not in category:
    category.append(t[-1])
    category_number += 1
category = sorted(category)

distance = []
classify_result = []

for cp in test:

  classify_point = cp[:-1]
  calculate_result = []
  for tp in train:
    train_point = tp[:-1]
    result = 0
    for c in range(0,len(train_point)):
      if df == "e2":
        result += pow(classify_point[c] - train_point[c],2)
      elif df == "manh":
        result += abs(classify_point[c] - train_point[c])
    calculate_result.append(result)
  find_copy = calculate_result.copy()
  find_k = []
  index_list = []
  train_classify = []
  for fd in range(0,k):
    min_value = min(find_copy)
    find_k.append(min_value)
    k_place = find_copy.index(min_value)
    index_list.append(k_place)
    find_copy[k_place] = 1000000000
    train_classify.append(train[k_place][-1])
  category_score = [0] * category_number
  if voting == "unit":
    for c in train_classify:
      place = category.index(c)
      category_score[place] += 1
    max_score = max(category_score)
    max_score_place = category_score.index(max_score)
    classify_result.append(category[max_score_place])
  elif voting == "1/d":
    for h in range(0,len(train_classify)):
      place = category.index(train_classify[h])
      category_score[place] += 1/max(find_k[h],0.0001)
    max_score = max(category_score)
    max_score_place = category_score.index(max_score)
    classify_result.append(category[max_score_place])

true_classify = []
for tc in test:
  true_classify.append(tc[-1])
for ou in range(0,len(classify_result)):
  midd = []
  midd.append("want = ")
  midd.append(true_classify[ou])
  midd.append("  ")
  midd.append("got = ")
  midd.append(classify_result[ou])
  classify_print = "".join(midd)
  print(classify_print)

#precision
precision = []
recall = []
for c in category:
  true_positive = 0
  false_positive = 0
  false_negative = 0
  m_p = []
  m_r = []
  for f in range(0,len(true_classify)):
    if c != true_classify[f]:
      if c == classify_result[f]:
        false_positive += 1
    elif c == true_classify[f]:
      if c == classify_result[f]:
        true_positive += 1
      elif c != classify_result[f]:
        false_negative += 1
  mp_denominator = true_positive + false_positive
  mr_denominator = true_positive + false_negative
  m_p.append(str(true_positive))
  m_p.append("/")
  m_p.append(str(mp_denominator))
  m_r.append(str(true_positive))
  m_r.append("/")
  m_r.append(str(mr_denominator))
  mp = "".join(m_p)
  mr = "".join(m_r)
  precision.append(mp)
  recall.append(mr)

for p in range(0,len(category)):
  mid = []
  mid.append("Label = ")
  mid.append(category[p])
  mid.append("  ")
  mid.append("Precision = ")
  mid.append(str(precision[p]))
  mid.append("  ")
  mid.append("Recall = ")
  mid.append(str(recall[p]))
  evaluation_print = "".join(mid)
  print(evaluation_print)


from flask import Flask, render_template, url_for, flash, redirect, jsonify, make_response
from forms import RegistrationForm, LoginForm
import jsonResponse
from flask_api import status
import json

app = Flask(__name__)

app.config['SECRET_KEY'] = '77196fc89f9f3bd9318a95e2d83824eb'

posts = [
    {
        'author': 'Niloy Dey',
        'title': 'New Flask Post'
    },
]

@app.errorhandler(404)
def not_found_error(error):
    return jsonResponse.makeJsonResponse(False, 'Not Found', 404, {})

@app.errorhandler(500)
def internal_error(error):
    return jsonResponse.makeJsonResponse(False, 'Internal Server Error', 500, {})

@app.route('/')
def hello_world():
    return jsonResponse.makeJsonResponse(200, "Hello World", None, "Hello")

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

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        flash(f'Account Created For {form.username.data}!')
        return redirect(url_for('register'))
    return render_template('Register.html',
                           title='Register',
                           form=form
                           )

@app.route('/login')
def login():
    form = LoginForm()
    return render_template('Login.html',
                           title='Login',
                           form=form
                           )

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


"""
this is battle boats, this file contains the functions to play the game as
well as an abstract class named playerboard and two inherited classes I have
imported for a human and computer player. random is an external library I
have imported
"""
import random
from scripts.Player_Board import Player_Board
from scripts.Computer_Board import Computer_Board

boardSize = 5
sub_num = 5
frig_num = 2

def populate_board(board, num_of_subs, num_of_frigates):
    """
    randomly populates the game board with subs and frigates.

    subs are created by checking a random set of co-ordinates on the board
    is free, if yes, that location is added to a list of ships(used for
    logic checking) and a list of subs(used to mark its location on the
    board).

    frigates are created by then making essentially a sub, but then picking
    a random direction for the second tile, if those co-ordinates are free
    then both sets of co-ordinates are added to the list of ships and list
    of frigates.
    """
    i = 0
    while i < int(num_of_subs):
        new_sub = random.randint(
            0, board.size-1
        ), random.randint(0, board.size-1)
        if new_sub not in board.ships:
            board.subs.append(new_sub)
            board.ships.append(new_sub)
            i += 1
    i = 0
    while i < int(num_of_frigates):
        new_big_ship_x = random.randint(0, board.size-1)
        new_big_ship_y = random.randint(0, board.size-1)
        new_frigate = new_big_ship_x, new_big_ship_y

        if new_frigate not in board.ships:
            timeout = 0

            while timeout < 4:
                direction = random.randint(1, 4)

                if direction == 1:
                    if new_big_ship_x + 1 <= boardSize-1 and (
                        new_big_ship_x + 1, new_big_ship_y
                    ) not in board.ships:
                        new_frigate_part_2 = new_big_ship_x + 1, new_big_ship_y
                        board.frigates.append(new_frigate)
                        board.ships.append(new_frigate)
                        board.frigates.append(new_frigate_part_2)
                        board.ships.append(new_frigate_part_2)
                        i += 1
                        break
                elif direction == 2:
                    if new_big_ship_y + 1 <= boardSize-1 and (
                        new_big_ship_x, new_big_ship_y + 1
                    ) not in board.ships:
                        new_frigate_part_2 = new_big_ship_x, new_big_ship_y + 1
                        board.frigates.append(new_frigate)
                        board.ships.append(new_frigate)
                        board.frigates.append(new_frigate_part_2)
                        board.ships.append(new_frigate_part_2)
                        i += 1
                        break
                elif direction == 3:
                    if new_big_ship_x - 1 >= 0 and (
                        new_big_ship_x - 1, new_big_ship_y
                    ) not in board.ships:
                        new_frigate_part_2 = new_big_ship_x - 1, new_big_ship_y
                        board.frigates.append(new_frigate)
                        board.ships.append(new_frigate)
                        board.frigates.append(new_frigate_part_2)
                        board.ships.append(new_frigate_part_2)
                        i += 1
                        break
                elif direction == 4:
                    if new_big_ship_y - 1 >= 0 and (
                        new_big_ship_x, new_big_ship_y - 1
                    ) not in board.ships:
                        new_frigate_part_2 = new_big_ship_x, new_big_ship_y - 1
                        board.frigates.append(new_frigate)
                        board.ships.append(new_frigate)
                        board.frigates.append(new_frigate_part_2)
                        board.ships.append(new_frigate_part_2)
                        i += 1
                        break
                timeout += 1
    board.num_of_ships = num_of_subs + num_of_frigates * 2

def play_game(player_board, computer_board):
    """
    called when the game has finished setting up, calls for guesses to be continously
    entered via a loop and breaks when either players score equals the number of ships.
    """
    player_board.display_player_ships()

    player_score = 0
    computer_score = 0
    while player_score < int(
        player_board.num_of_ships
    ) and computer_score < int(computer_board.num_of_ships):
        computer_board.print_board()
        player_board.print_board()

        if computer_board.guesses:
            print(f"Player Score: {player_score}, Computer Score : {computer_score}")
            num_of_guesses = computer_board.print_player_guesses()
            if num_of_guesses == boardSize * boardSize:
                break

        print("\n")

        x, y = make_guess(computer_board)

        while True:
            computer_x_guess = random.randint(0, boardSize-1)
            computer_y_guess = random.randint(0, boardSize-1)

            if is_new_coordinates(computer_x_guess, computer_y_guess, player_board):
                break

        if computer_board.guess_against(x, y, player_board) is True:
            player_score += 1

        if player_board.guess_against(
            computer_x_guess, computer_y_guess, computer_board
        ) is True:
            computer_score += 1

    computer_board.print_board()
    player_board.print_board()

    print("\n")

    if player_score == computer_score:
        print("game was a draw")
    elif player_score >= player_board.num_of_ships:
        print(f"{player_board.name} has won\n")
    elif computer_score >= computer_board.num_of_ships:
        print(f"{computer_board.name} has won\n")

    input("please any key to continue")
    menu()

def make_guess(board):
    """
    function that creates a tuple out of the inputs made by the player,
    checks they are valid and returns it
    """
    while True:
        while True:
            x_guess = input(f"please choose an x coordinate(a number between 0 and {boardSize -1}): ")
            if validate_int(x_guess, 1, 0, board.size - 1) is True:
                break
            print("please pick again")

        while True:
            y_guess = input(f"please choose an y coordinate(a number between 0 and {boardSize-1}): ")
            if validate_int(y_guess, 1, 0, board.size - 1) is True:
                break
            print("please pick again")

        if is_new_coordinates(x_guess, y_guess, board) is True:
            break

    return x_guess, y_guess

def menu():
    """
    Main menu of the game, here you can change settings and start a game.
    """
    global boardSize
    global sub_num
    global frig_num

    print("           " + "-" * 35)
    print("               Welcome to BATTLE BOATS")
    print(f"           board size: {boardSize}, subs: {sub_num} frigates: {frig_num}")
    print("           " + "-" * 35)
    print("q: Start Game    w: Change Board Size    e: Change Ship Number \n")

    option = input("Please choose and option: ").lower()

    while True:
        if option in ("q", "w", "e"):
            break
        print("Invalid option, please press q, w or e\n")
        option = input("Please choose and option: ").lower()

    if option == "q":
        new_game()
    elif option == "w":
        boardSize = int(change_board_size())
        menu()
    elif option == "e":
        sub_num, frig_num = change_ship_num()
        menu()

def change_board_size():
    """
    simply takes a value from input and assigns it to the BoardSize variable
    """
    print("please pick a number between 5 and 10 to change the game board")
    while True:
        new_size = input()
        if validate_int(new_size, 2, 5, 10):
            break
        print("Please pick another number between 5 and 10 ")
    return new_size

def change_ship_num():
    """
    simply takes a value from input and assigns it to the BoardSize function
    """
    print("how many subs would you like? (pick a number between 1 and 6)")
    while True:
        new_sub_num = input()
        if validate_int(new_sub_num, 1, 1, 6):
            break
        print("Please pick another number between 1 and 6")

    print("how many frigates would you like? (pick a number between 1 and 3)")

    while True:
        new_frig_num = input()
        if validate_int(new_frig_num, 1, 1, 3):
            break
        print("Please pick another number between 1 and 4")

    return new_sub_num, new_frig_num

def validate_str(string):
    """
    validates strings, making sure no numbers or special chracters are present
    """
    if string.isalpha():
        return True
    print("your name cannot contain numbers of special symbols")
    return False

def validate_int(int_for_validation, length, min_value, max_value):
    """
    validates interger values, checks if the input is an interger and
    that it doesnt exceed its target length, or value range
    """
    try:
        if str(int_for_validation).isdigit() is not True:
            raise ValueError(f"input must be an integer")
        int_for_validation = int(int_for_validation)
        if len(str(int_for_validation)) > length:
            raise ValueError(f"input has exceeded the maximum length of {length} chracters")
        if int_for_validation < min_value:
            raise ValueError(f"input cannot be less than {min_value}")
        if int_for_validation > max_value:
            raise ValueError(f"input cannot be more than {max_value}")
    except ValueError as e:
        print(f"Invalid: {e}\n")
        return False
    return True

def is_new_coordinates(x, y, board):
    """
    checks if a set of co ordinates have already been guessed, returns true if
    they were new.
    """
    entry = [int(x), int(y)]
    if entry not in board.guesses:

        return True
    else:
        if board.type == "computer":
            print(f"co-ordinates ({x}, {y}) have already been guessed, pick again\n")
        return False

def new_game():
    """
    called when a new game is started, creates 2 boards, one for each
    player, and populates them with ships. then calls the play game function.
    """
    while True:
        player_name = input("What is your name?: ")
        if validate_str(player_name):
            break

    print("\n")
    shipNum = frig_num * 2 + sub_num
    player_board = Player_Board(player_name, boardSize, shipNum, "player")
    computer_board = Computer_Board("computer", boardSize, shipNum, "computer")
    player_board.board.reverse()
    computer_board.board.reverse()

    populate_board(player_board, sub_num, frig_num)
    populate_board(computer_board, sub_num, frig_num)

    play_game(player_board, computer_board)

def main():
    """
    Main function
    """
    menu()

main()


import math

class Integer():

    def __init__(self, p: int) -> None:
        self.p = p
        self.prime = self.check_prime()

    #check whether a number is prime
    def check_prime(self) -> bool:
        for divisor in range(2, math.floor(math.sqrt(self.p))+1):
            if self.p % divisor == 0:
                return False
        return True

    # return the order of a mod p
    def order_a_mod_p(self, a: int) -> int:
        if a % self.p == 0:
            return 0
        k = 1
        while k < self.p - 1:
            if (self.p - 1) % k == 0 and (Integer.exp_by_squaring(a,k, self.p) % self.p) == 1:
                return k
            else:
                k += 1
        return k

    # return True if a is a primitive root mod p, False if not
    def check_primitive_root(self, a: int) -> bool:
        if self.order_a_mod_p(a) < (self.p - 1):
            return False
        return True

#     @staticmethod
#     def exp_by_squaring(a: int, k: int) -> int:
#         if k == 0:
#             return 1
#         elif k % 2 == 0:
#             return Integer.exp_by_squaring(a**2, k/2)
#         else:
#             return a * Integer.exp_by_squaring(a, k-1)

    # suggested by Greg Martin
    @staticmethod
    def exp_by_squaring(a: int, k: int, p: int) -> int:
        if k == 0:
            return 1
        elif k % 2 == 0:
            return Integer.exp_by_squaring(a**2 % p, k/2, p)
        else:
            return (a * Integer.exp_by_squaring(a, k-1, p)) % p

    @staticmethod
    def prime_factorize(num):
        factors = {}
        for integer in range(2, num+1):
            if num == 1:
                break
            elif Integer(integer).prime:
                while num % integer == 0:
                    try:
                        factors[integer] += 1
                    except KeyError:
                        factors[integer] = 1
                    finally:
                        num /= integer
        return factors

    def get_Omega(self, a: int, order: int = None) -> int:
        total_multiplicity = 0
        if order == None:
            factor_multiplicity = Integer.prime_factorize(a).values()
        else:
            factor_multiplicity = Integer.prime_factorize(order).values()
        for multiplicity in factor_multiplicity:
            total_multiplicity += multiplicity
        return total_multiplicity

    def get_omega(self, a: int, order: int = None) -> int:
        if order == None:
            return len(Integer.prime_factorize(a))
        return len(Integer.prime_factorize(order))


# -*- coding: utf-8 -*-
"""
Created on Thu Apr 18 22:20:42 2019

@author: RAJ KUMAR GAUTAM
"""

# -*- coding: utf-8 -*-
"""
Created on Fri Apr  5 04:50:36 2019

@author: RAJ KUMAR GAUTAM
"""

#import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
warnings.filterwarnings('ignore')
#%matplotlib inline
np.random.seed(0)  #for reproducibility
iris=pd.read_csv('D:\iris.csv')
iris.head()
iris["Species"].value_counts() #check how many unique species of iris ara in the dataset
val_plot=iris.Species.value_counts().plot(kind="pie",autopct='%.1f%%',figsize=(8,8))
val_plot.savefig('D:\\file6.png')
sns_plot=sns.pairplot(iris.drop("Id",axis=1),hue="Species",size=3) #visualize the relationship between pairs of features
sns_plot.savefig('D:\\file5.png')
y=iris.Species    #set target variable
X=iris.drop(["Species","Id"],axis=1) #select feature variable
le=LabelEncoder() #load the label encoder
y=le.fit_transform(y)
encoder=OneHotEncoder(sparse=False)
encoder.fit_transform(y.reshape(-1,1))
sc=StandardScaler() #load the standard scaler
sc.fit(X) #compute the mean and std of the feature data
X_scaled=sc.transform(X) #Scale the feature data to be of mean 0 and variance 1
X_train,X_test,y_train,y_test=train_test_split(X_scaled,y,test_size=.3,random_state=1) #split the dataset into 30% testing and 70%training
model=KNeighborsClassifier(n_neighbors=3) #load our classifier
model.fit(X_train,y_train)  #fit our model on the training data
prediction=model.predict(X_test)#make prediction with our trained model on the data
accuracy=accuracy_score(y_test,prediction)*100 #compare accuracy of predicted classes with test data
print('k-Nearest Neighbours accuracy | '+str(round(accuracy,4))+'%.')
plt.figure(figsize=(12,10))
plt.scatter(X_train[:,1],y_train)
plt.savefig('D:\\file1.png')
plt.scatter(X_test[:,1],prediction,color='green')
plt.savefig('D:\\file2.png')
plt.plot(X_test[:,1],prediction,color='pink')
plt.xlabel('id')
plt.ylabel('binary notation of iris_species')
plt.title('KNN CLASSIFIER IRIS DATASET')
plt.savefig('D:\\file3.png')
X_train.shape
neighRange = range(1,30)
# We can create Python dictionary using [] or dict()
scores = []
for k in neighRange:
    model = KNeighborsClassifier(n_neighbors=k)
    model.fit(X_train, y_train)
    pred = model.predict(X_test)
    scores.append(accuracy_score(y_test, pred))
print('mean accuracy while k varies from (1 to 30) | '+str(round(sum(scores)/len(scores)*100,2))+'%.')


from flask import Flask, jsonify, request, redirect, url_for
from werkzeug.exceptions import TooManyRequests

from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

from flask_cors import CORS

import re
import json

import backend_setup
import backend_create_new_game
import backend_run_game
import custom_word
from backend_setup import print_err

app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False
CORS(app)

limiter = Limiter(
    app,
    key_func=get_remote_address,
    default_limits=["90 per minute"]
    )

# Initialize server
myCache, common_words, all_words = backend_setup.start_up_game_backend('A')

# Ping
@app.route('/')
def hello_world():
  return "Polywordle is live at version /v1/", 200

@app.route('/v1')
def list_endpoints():
    return {"/v1/game, POST" : "Start a new game. Include /solution/ in request to set solution.",
            "/v1/game/<game_uuid>, POST" : "Post a new guess - include /guess/ in request.",
            "/v1/game/<game_uuid>, GET" : "Get the status of a given game."
            }, 200

# Creating a new game
@app.route('/v1/newgame', methods=['POST'])
@limiter.limit("100 per minute")
def api_new_game():
  if request.get_json(silent=True) == None and request.form.get('solution') == None:
    # Assume a random game is requested
    newGameState = backend_create_new_game.GameState()
    newGameState.set_random_solution(common_words)
    result = myCache.save_game_state_to_cache(newGameState)
    if "error" in result:
      return result, 404
    game_uuid = newGameState.uuid()
    return {"game_uuid":game_uuid}, 200

  custom_solution = None
  if request.get_json(silent=True) != None and 'solution' in request.get_json():
    print_err(request.get_json())
    custom_solution = str(request.get_json()['solution'])[:6]
  elif request.form.get('solution') != None:
    custom_solution = str(request.form.get('solution'))[:6]

  if custom_solution is not None:
    print_err("Recieved new custom solution:", custom_solution)
    newGameState = backend_create_new_game.GameState()
    solution_result = custom_word.set_custom_solution(newGameState, custom_solution, all_words)
    result = myCache.save_game_state_to_cache(newGameState)
    if "error" in solution_result:
      return solution_result, 404
    game_uuid = newGameState.uuid()
    return {"game_uuid":game_uuid}, 200
  return "", 500

# Getting status of game in cache
@app.route('/v1/game/<game_uuid>', methods=['GET'])
def api_show_game(game_uuid):
  good_game_uuid = str(game_uuid)[:40]
  if good_game_uuid not in myCache.game_states:
    return {"error":"game not found"}, 404
  response = backend_run_game.prepare_json_response(myCache.game_states[good_game_uuid])
  if "error" in response:
      return "", 404
  else:
    return response

# Guessing new word or making new solution
@app.route('/v1/game/<game_uuid>', methods=['POST'])
def api_game_new_guess(game_uuid):
  game_uuid = str(game_uuid)[:40]
  if game_uuid not in myCache.game_states:
    return {"error": "no game found for that UUID"}, 404

  if myCache.game_states[game_uuid].data['progress'] in ['victory', 'loss']:
    return {"error":"game already over"}, 200

  current_guess = None
  if request.get_json(silent=True) != None and 'guess' in request.get_json():
    current_guess = str(request.get_json()['guess'])[:8].lower()
  elif request.form.get('guess') != None:
    current_guess = str(request.form.get('guess'))[:8].lower()

  if not current_guess:
    return {"error":"POST methods require a guess."}, 400
  else:
    print_err("Recieved new guess:",current_guess)
    if current_guess in myCache.game_states[game_uuid].data['guess_history']:
      return {"error": "duplicate guess"}, 200
    guess_result = backend_run_game.process_new_guess(current_guess, myCache.game_states[game_uuid], all_words)
    if "error" in guess_result:
      return guess_result, 200
    return {"success":"guess posted"}, 200

if __name__ == '__main__':
    app.run(threaded=False)


# -*- coding: utf-8 -*-
# @Time    : 2021/7/1 1:03 上午
# @Author  : xu.junpeng

WORK_DIR = '/Users/xujunpeng/xcx-img'
SERVER_PORT = 8002

SUCC_CODE = 20000
SUCC_MSG = "图片上传成功"

FAIL_CODE = 200001
FAIL_MSG = "图片上传失败"

USER_VALID_CODE = 20002
USER_VALID_MSG = "非正常用户"

IMG_VALID_CODE = 20004
IMG_VALID_MSG = "图片非法"


import requests
from bs4 import BeautifulSoup

def get_malayalam_news(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')

    # Find the div with the specified class and id
    article = soup.find('div', class_='article-content no-border', id='mainArticleContent')
    if article:
        text = ' '.join([p.text for p in article.find_all('p')])
        return text
    else:
        return 'Could not find article body.'

url = "https://www.asianetnews.com/entertainment-news/bigg-boss-malayalam-season-5-is-akhil-marar-evicted-from-bb-house-fans-reaction-on-social-media-vvk-rvolmr"
print(get_malayalam_news(url))


from collections import deque
from typing import Optional

from utils import TreeNode

# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        q = deque([root])
        while q:
            node = q.popleft()
            if node.right:
                q.append(node.right)
            if node.left:
                q.append(node.left)
        return node.val
# leetcode submit region end(Prohibit modification and deletion)