import requests
from bs4 import BeautifulSoup, BeautifulStoneSoup
from fake_useragent import UserAgent
from openpyxl import load_workbook, workbook
from requests.api import request
from time import sleep

print("""Şehir kodları:
0-Adana
1-Antalya
2-Aydın
3-Denizli
4-Hatay
5-Isparta
6-Muğla
7-Bütün İller
""")

location_code = input("Arama yapmak istediğiniz şehir veya şehirlerin kodlarını girin: ")
location_list = ["adana", "antalya", "aydin", "denizli", "hatay", "isparta", "mugla"]
selected_locations = list(map(int, location_code.split()))

if(selected_locations[0]==7):
    selected_locations = location_list[0:11]
else:
    for i in range(len(selected_locations)):
        selected_locations[i] = location_list[selected_locations[i]]

print("Seçtiğiniz Şehirler =>", selected_locations)
workbook = load_workbook(filename="Template.xlsx")
sheet = workbook.active

def beautify(string):
    string=" ".join(string.replace("\n","").split())
    return string

for selected_location in selected_locations:
    page_index = 1
    while(True):
        user_agent = {'User-Agent':str(UserAgent().random)}
        url = f"https://www.hepsiemlak.com/{selected_location}-satilik?page={page_index}"
        page = requests.get(url,headers=user_agent)
        while(page.status_code !=200):
            print("Çok fazla istek atildi")
            sleep(60*5)
            user_agent = {'User-Agent':str(UserAgent().random)}
            url = f"https://www.hepsiemlak.com/{selected_location}-satilik?page={page_index}"
            page = requests.get(url,headers=user_agent)

        soup = BeautifulSoup(page.content,"html.parser")
        home_links = soup.find_all("a",class_="card-link")
        if(home_links == []):
            break

        for home_link in home_links:
            home_link = home_link['href']
            home_url = f"https://www.hepsiemlak.com{home_link}"
            home_page = requests.get(home_url,headers=user_agent)
            while(home_page.status_code !=200):
                print("Çok fazla istek atildi")
                sleep(60*5)
                user_agent = {'User-Agent':str(UserAgent().random)}
                home_url = f"https://www.hepsiemlak.com{home_link}"
                home_page = requests.get(home_url,headers=user_agent)

            home_soup = BeautifulSoup(home_page.content,"html.parser")

            home_title = beautify(home_soup.find("h1",class_="fontRB").text)
            home_price = beautify(home_soup.find("p",class_="fontRB fz24 price").text)
            home_properties = (home_soup.find("ul",class_="short-info-list")).find_all("li")
            home_info = home_soup.findAll("li",class_="spec-item")

            home_city = beautify(home_properties[0].text)
            home_town = beautify(home_properties[1].text)
            home_district = beautify(home_properties[2].text)
            home_type = beautify(home_properties[3].text+" "+home_properties[4].text)
            home_room = beautify(home_properties[5].text)
            home_size = beautify(home_properties[6].text)
            home_no = ""
            home_date = ""
            home_floor = ""
            home_age = ""
            home_heating = ""
            home_top_floor = ""
            home_credit = ""
            home_furniture = ""
            home_bathrooms = ""
            home_building = ""
            home_state = ""
            home_status = ""
            home_deed = ""
            home_dues = ""
            home_trade = ""
            home_front = ""
            home_rent = ""
            home_fuel = ""
            home_office = ""
            home_site = ""
            home_council = ""
            home_island = ""
            home_parcel = ""

            row_index = 2
            while True:
                if(sheet[f'A{row_index}'].value!=None):
                    row_index += 1
                else:
                    break
            sheet[f'A{row_index}'].value = home_title
            sheet[f'B{row_index}'].value = home_price
            sheet[f'C{row_index}'].value = home_city
            sheet[f'D{row_index}'].value = home_town
            sheet[f'E{row_index}'].value = home_district
            sheet[f'F{row_index}'].value = home_type
            sheet[f'G{row_index}'].value = home_room
            sheet[f'H{row_index}'].value = home_size

            print("Başlık:", home_title)
            print("Ücret:", home_price)
            print("Şehir:", home_city)
            print("İlçe:", home_town)
            print("Mahalle:", home_district)
            print("Konut Tipi:", home_type)
            print("Oda Sayısı:", home_room)
            print("Büyüklük:", home_size)

            for i in home_info:
                if "İlan no" in i.text :
                    home_no = (i.text)[8:]
                    sheet[f'I{row_index}'].value = home_no
                    print("İlan no:", home_no)
                elif "Son Güncelleme Tarihi" in i.text:
                    home_date = (i.text)[22:]
                    sheet[f'J{row_index}'].value = home_date
                    print("Son Güncelleme Tarihi:", home_date)
                elif "Bulunduğu Kat" in i.text:
                    home_floor = (i.text)[14:]
                    sheet[f'K{row_index}'].value = home_floor
                    print("Bulunduğu Kat:", home_floor)
                elif "Bina Yaşı" in i.text:
                    home_age = (i.text)[10:]
                    sheet[f'L{row_index}'].value = home_age
                    print("Bina Yaşı:", home_age)
                elif "Isınma Tipi" in i.text:
                    home_heating = (i.text)[12:]
                    sheet[f'M{row_index}'].value = home_heating
                    print("Isınma Tipi:", home_heating)
                elif "Kat Sayısı" in i.text:
                    home_top_floor = (i.text)[11:]
                    sheet[f'N{row_index}'].value = home_top_floor
                    print("Kat Sayısı:", home_top_floor)
                elif "Krediye Uygunluk" in i.text:
                    home_credit = (i.text)[17:]
                    sheet[f'O{row_index}'].value = home_credit
                    print("Krediye Uygunluk:", home_credit)
                elif "Eşya Durumu" in i.text:
                    home_furniture = (i.text)[12:]
                    sheet[f'P{row_index}'].value = home_furniture
                    print("Eşya Durumu:", home_furniture)
                elif "Banyo Sayısı" in i.text:
                    home_bathrooms = (i.text)[13:]
                    sheet[f'Q{row_index}'].value = home_bathrooms
                    print("Banyo Sayısı:", home_bathrooms)
                elif "Yapı Tipi" in i.text:
                    home_building = (i.text)[10:]
                    sheet[f'R{row_index}'].value = home_building
                    print("Yapı Tipi:", home_building)
                elif "Yapının Durumu" in i.text:
                    home_state = (i.text)[15:]
                    sheet[f'S{row_index}'].value = home_state
                    print("Yapının Durumu:", home_state)
                elif "Kullanım Durumu" in i.text:
                    home_status = (i.text)[16:]
                    sheet[f'T{row_index}'].value = home_status
                    print("Kullanım Durumu:", home_status)
                elif "Tapu Durumu" in i.text:
                    home_deed = (i.text)[12:]
                    sheet[f'U{row_index}'].value = home_deed
                    print("Tapu Durumu:", home_deed)
                elif "Takas" in i.text:
                    home_trade = (i.text)[6:]
                    sheet[f'V{row_index}'].value = home_trade
                    print("Takas:", home_trade)
                elif "Cephe" in i.text:
                    home_front = (i.text)[6:]
                    sheet[f'W{row_index}'].value = home_front
                    print("Cephe:", home_front)
                elif "Site İçerisinde" in i.text:
                    home_site = (i.text)[16:]
                    sheet[f'X{row_index}'].value = home_site
                    print("Site İçerisinde:", home_site)
                elif "Yakıt Tipi" in i.text:
                    home_fuel = (i.text)[11:]
                    sheet[f'Y{row_index}'].value = home_fuel
                    print("Yakıt Tipi:", home_fuel)
                elif "Yetkili Ofis" in i.text:
                    home_office = (i.text)[13:]
                    sheet[f'Z{row_index}'].value = home_office
                    print("Yetkili Ofis:", home_office)
                elif "Aidat" in i.text:
                    home_dues = (i.text)[6:]
                    sheet[f'AA{row_index}'].value = home_dues
                    print("Aidat:", home_dues)
                elif "Kira Getirisi" in i.text:
                    home_rent = (i.text)[14:]
                    sheet[f'AB{row_index}'].value = home_rent
                    print("Kira Getirisi:", home_rent)
                elif "Ada" in i.text:
                    home_island = (i.text)[3:]
                    sheet[f'AC{row_index}'].value = home_island
                    print("Ada:", home_island)
                elif "Parsel" in i.text:
                    home_parcel = (i.text)[6:]
                    sheet[f'AD{row_index}'].value = home_parcel
                    print("Parsel:", home_parcel)
                elif "İlgili Belediye" in i.text:
                    home_council = (i.text)[15:]
                    sheet[f'AE{row_index}'].value = home_council
                    print("İlgili Belediye:", home_council)

            print("------------------------------------------------")
        page_index +=1
        workbook.save("Sonuc.xlsx")
input("Bitti")


import uuid
from datetime import datetime

from pytz import UTC

def datetime_utc(dt=None):
    if not dt:
        dt = datetime.utcnow()
    return dt.replace(tzinfo=UTC)

def date_id(prefix=""):
    def call(pre=prefix):
        suf = datetime_utc().replace(tzinfo=None).isoformat().replace(".", ":")
        suf = suf + "_" + str(uuid.uuid4())
        suf = suf or suf
        if pre:
            pre = pre + "::"
        return pre + suf

    return call


import datetime
import enum
import json
from typing import Dict

from ravendb import constants
from ravendb.documents.conventions import DocumentConventions
from ravendb.documents.queries.index_query import IndexQuery
from ravendb.documents.queries.query import ProjectionBehavior
from ravendb.tools.utils import Utils

class JsonExtensions:
    @staticmethod
    def try_get_conflict(metadata: dict) -> bool:
        if constants.Documents.Metadata.CONFLICT in metadata:
            return bool(metadata.get(constants.Documents.Metadata.CONFLICT))
        return False

    @staticmethod
    def write_index_query(conventions: DocumentConventions, query: IndexQuery) -> dict:
        generator: Dict[str, object] = {"Query": query.query}
        if query.is_page_size_set and query.page_size >= 0:
            generator["PageSize"] = query.page_size
        if query.wait_for_non_stale_results:
            generator["WaitForNonStaleResults"] = query.wait_for_non_stale_results

        if query.start is not None and query.start > 0:
            generator["Start"] = query.start

        if query.wait_for_non_stale_results_timeout is not None:
            generator["WaitForNonStaleResultsTimeout"] = query.wait_for_non_stale_results_timeout

        if query.disable_caching:
            generator["DisableCaching"] = query.disable_caching

        if query.skip_duplicate_checking:
            generator["SkipDuplicateChecking"] = query.skip_duplicate_checking

        if query.query_parameters is not None:
            generator["QueryParameters"] = JsonExtensions.params_deep_convert_to_json(
                query.query_parameters, conventions
            )
        else:
            generator["QueryParameters"] = None
        if query.projection_behavior is not None and query.projection_behavior is not ProjectionBehavior.DEFAULT:
            generator["ProjectionBehavior"] = query.projection_behavior.value
        return generator

    @staticmethod
    def params_deep_convert_to_json(
        query_parameters: Dict[str, object], conventions: DocumentConventions
    ) -> Dict[str, object]:
        """
        Converts params to serializable (by json.dump) json dictionary.
        If there's custom to_json() method defined inside the parameter class, it is used to do so (mainly used to
        fix keys casing).
        Collections and dicts are converted deeply.
        """
        updated_params = {}
        for name, value in query_parameters.items():
            updated_params[name] = JsonExtensions._convert_parameter_to_json(value, conventions)
        return updated_params

    @staticmethod
    def _convert_parameter_to_json(param: object, conventions: DocumentConventions) -> object:
        if isinstance(param, list):
            param: list
            updated = []
            for item in param:
                updated.append(JsonExtensions._convert_parameter_to_json(item, conventions))
            return updated

        elif isinstance(param, set):
            param: set
            updated = set()
            for item in param:
                updated.add(JsonExtensions._convert_parameter_to_json(item, conventions))
            return updated

        elif isinstance(param, dict):
            param: dict
            updated = {}
            for key, value in param.items():
                updated.update({key: JsonExtensions._convert_parameter_to_json(value, conventions)})
            return updated

        elif isinstance(param, tuple):
            param: tuple
            updated = []
            for i in range(len(param)):
                updated.append(JsonExtensions.params_deep_convert_to_json(param[i], conventions))
            return tuple(updated)

        # todo: create typing protocol (Python 3.8) with to_json inside and typehint the param when it has to_json
        elif constants.json_serialize_method_name in param.__class__.__dict__:
            return param.__class__.__dict__.get(constants.json_serialize_method_name)(param)
        else:
            return param

    @staticmethod
    def write_value_as_bytes(value: object) -> bytes:
        return (
            json.dumps(value.to_json())
            if getattr(value, "to_json", None) and getattr(value.to_json, "__call__", None)
            else json.dumps(value)
        ).encode("utf-8")


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

import sys
import os
import urllib
import tarfile
import zipfile

class Download:
    """
    classe per gestire i download del dataset

    """

    def __init__(self):

        pass

    def maybe_downlaod_and_extract(self,url,download_dir):

        """

        :param url: url per scaricare il dataset
        :param download_dir: Cartella dove sono salvati i file scaricati
        :return:
        """

        filename= url.split('/')[-1]
        #path alla cartella dove salverò il dataset
        file_path=os.path.join(download_dir,filename)

        if not os.path.exists(file_path):

            #verfico se esiste la cartella di download
            if not os.path.exists(download_dir):
                os.makedirs(download_dir)

        #downlaod the file from the internet

            file_path, =urllib.urlretrieve(url=url,
                                               filename=file_path,
                                               reporthook=self._print_download_progress)

            if file_path.endswith(".zip"):
                zipfile.ZipFile(file=file_path,mode="r").extractall(download_dir)
            elif file_path.endswith((".tar.gz",".tgz")):
                tarfile.open(name=file_path,mode="r:gz").extractall(download_dir)

        else:
            print ("I dati sembrano essere già stati scaricati")

    def _print_download_progress(self,count, block_size, total_size):
        """
        Function used for printing the download progress.
        Used as a call-back function in maybe_download_and_extract().
        """

        # Percentage completion.
        pct_complete = float(count * block_size) / total_size

        # Status-message. Note the \r which means the line should overwrite itself.
        msg = "\r- Download progress: {0:.1%}".format(pct_complete)

        # Print it.
        sys.stdout.write(msg)
        sys.stdout.flush()


import discord
from discord.ext import commands
import urllib
from .utils.dataIO import dataIO
from urllib.request import urlopen

try: # check if BeautifulSoup4 is installed
	from bs4 import BeautifulSoup
	soupAvailable = True
except:
	soupAvailable = False
import aiohttp

class Mycog:
    """My custom cog that does stuff!"""

    def __init__(self, bot):
        self.bot = bot
        self.countComs = dataIO.load_json("data/countcoms/countcoms.json")

    @commands.command()
    async def xander(self):

        #Prints all Xander face emojis in a line
        await self.bot.say("<:xhearteyes:283866074980810752> <:xandercool:235634201678839809> <:xandertilted:235633458779521024> <:xander:235610087190822913> <:hueh:235633477179932672> <:LUL:235611940590845952> <:xhearteyes:283866074980810752>")

    @commands.command()
    async def wiff(self):
        w = "wiff"

        if w in self.countComs:
            wiffnum = int(self.countComs["wiff"])
        else:
            wiffnum = 0
        wiffnum = wiffnum+1
        self.countComs["wiff"] = str(wiffnum)
        dataIO.save_json("data/countcoms/countcoms.json", self.countComs)
        await self.bot.say("We have collectively whiffed " + str(wiffnum) + " times")

    @commands.command(pass_context=True)
    async def echo(self, ctx, message):

        author = ctx.message.author
        myString = ctx.message.content
        await self.bot.say("{} {}".format(author.mention, myString[6:]))

    @commands.command()
    async def rlnow(self):
        """How many players are online atm?"""

        #Your code will go here
        url = "https://steamdb.info/app/252950/graphs/" #build the web adress
        async with aiohttp.get(url) as response:
            soupObject = BeautifulSoup(await response.text(), "html.parser")
        try:
            online = soupObject.find(class_='home-stats').find('li').find('strong').get_text()
            await self.bot.say(online + ' players are playing Rocket League at the moment')
        except:
           await self.bot.say("Couldn't load amount of players. No one is playing this game anymore or there's an error.")

    #@commands.command()
    #async def hours(self, user):
        #"""Returns hours played by a user"""

        #link = user
        #substringCheck = "https://steamcommunity.com/profiles/"
        #substringCheck2 = "https://steamcommunity.com/id/"
        #if substringCheck in link:
        #    url = link + "/games/?tab=all"  # build the web address
        #if substringCheck2 in link:
        #    url = link + "/games/?tab=all"  # build the web address
        #else:
        #    url = substringCheck2 + link + "/games/?tab=all"

        #url = "http://steamcommunity.com/id/xanderdagr8/games/?tab=all"

        #await self.bot.say(url)
        #async with aiohttp.get(url) as response:
            #soup = BeautifulSoup(await response.text(), "html.parser")
            #await self.bot.say(soup.renderContents())
        #try:
            #name_box = soup.find('h5').get_text()
            #await self.bot.say(name_box)
        #except:
           #await self.bot.say("This user does not own Rocket League")

def setup(bot):
	if soupAvailable:
		bot.add_cog(Mycog(bot))
	else:
		raise RuntimeError("You need to run `pip3 install beautifulsoup4`")


from datetime import datetime
from PIL import Image, ImageDraw, ImageFont

import qrcode

class QRCard:

    def __init__(self, qrCode, artWork, title):

        self.qrCode = qrCode
        self.artWork = artWork
        self.title = title

    def generate(self):

        # Create the Card image - Actual size is 78mm x 45mm - 300dpi = 921 x 532
        cardWidth = 921 * 2
        cardHeight = 532
        borderSize = 2
        marginSize = 10

        self.imgCard = Image.new('RGB', (cardWidth, cardHeight))

        # Draw bounding rectangle
        draw = ImageDraw.Draw(self.imgCard)
        draw.rectangle((0, 0, cardWidth - 1, cardHeight - 1), fill='white', outline='grey', width=2)

        # Draw vertical center line
        draw.line((int(cardWidth / 2) - 1, 0, int(cardWidth / 2) - 1, cardHeight), fill='grey', width=2)

        # Create QR code image
        qr = qrcode.QRCode(version=1, box_size=16, border=5)

        qr.add_data(self.qrCode)

        qr.make(fit=True)

        imgQR = qr.make_image(fill='black', back_color='white')

        qrWidth, qrHeight = imgQR.size

        # Get a font
        font = ImageFont.truetype('/usr/share/fonts/truetype/piboto/Piboto-Bold.ttf', 30)

        # Add some useful meta to the qr card in readable (qrcard value, date)
        imgCardMeta = Image.new("RGB", (400, 100), (255, 255, 255))

        metaWidth, metaHeight = imgCardMeta.size

        writing = ImageDraw.Draw(imgCardMeta)

        date = datetime.now().strftime("%d/%m/%Y %H:%M:%S")

        textWidth, textHeight, metaWrapped = self.textWrap([self.qrCode, date], font, writing, metaWidth, metaHeight)

        writing.text((int((metaWidth - textWidth) / 2) ,2), metaWrapped, font=font, align='center', fill=(0,0,0,255))

        imgCardMeta = imgCardMeta.transpose(Image.ROTATE_90)

        metaWidth, metaHeight = imgCardMeta.size

        # Paste the text image on to the card image
        self.imgCard.paste(imgCardMeta, ((int(cardWidth / 2) - metaWidth - borderSize), int((cardHeight - metaHeight) / 2)))

        # Paste the QR code image onto the card image
        self.imgCard.paste(imgQR, (3, int((cardHeight - qrHeight) / 2)))

        # Load the artwork image, rotate and resize
        imgArtwork = Image.open(self.artWork).convert('RGB')

        imgArtwork = imgArtwork.transpose(Image.ROTATE_270)

        imageHeight = cardHeight - (2 * (borderSize + marginSize))
        imageWidth = imageHeight

        imgArtwork = imgArtwork.resize((imageWidth, imageHeight))

        # Paste the artwork image on to the card image
        self.imgCard.paste(imgArtwork, (cardWidth - (imageWidth + borderSize + marginSize), borderSize + marginSize))

        # Get a font
        font = ImageFont.truetype('/usr/share/fonts/truetype/piboto/Piboto-Bold.ttf', 75)

        # Draw the metadata - Artist, Album
        imgMeta = Image.new("RGB", (cardHeight - ((borderSize + marginSize + 10) * 2), int(cardWidth / 2) - (imageWidth + ((borderSize + marginSize) * 2))), (255, 255, 255))

        metaWidth, metaHeight = imgMeta.size

        writing = ImageDraw.Draw(imgMeta)

        textWidth, textHeight, metaWrapped = self.textWrap(self.title, font, writing, metaWidth, metaHeight)

        writing.text((int((metaWidth - textWidth) / 2) ,2), metaWrapped, font=font, align='center', fill=(0,0,0,255))

        imgMeta = imgMeta.transpose(Image.ROTATE_270)
        metaWidth, metaHeight = imgMeta.size

        # Paste the text image on to the card image
        self.imgCard.paste(imgMeta, (cardWidth - (imageWidth + borderSize + marginSize + metaWidth), int((cardHeight - metaHeight) / 2)))

    def save(self, fileName):

        self.imgCard.save(fileName)

    def textWrap(self, paras, font, draw, max_width, max_height):

        if not isinstance(paras, list):
            paras = [paras]

        lines = [[]]

        for text in paras:

            words = text.split()

            for word in words:

                # try putting this word in last line then measure
                lines[-1].append(word)
                (w,h) = draw.multiline_textsize('\n'.join([' '.join(line) for line in lines]), font=font)

                if w > max_width: # too wide

                    # take it back out, put it on the next line, then measure again
                    lines.append([lines[-1].pop()])
                    (w,h) = draw.multiline_textsize('\n'.join([' '.join(line) for line in lines]), font=font)

                    if h > max_height: # too high now, cannot fit this word in, so take out - add ellipses

                        lines.pop()

                        # try adding ellipses to last word fitting (i.e. without a space)
                        lines[-1][-1] += '...'

                        # keep checking that this doesn't make the textbox too wide,
                        # if so, cycle through previous words until the ellipses can fit
                        while draw.multiline_textsize('\n'.join([' '.join(line) for line in lines]),font=font)[0] > max_width:
                            lines[-1].pop()
                            lines[-1][-1] += '...'
                        break

            if len(paras) > 1:
                lines[-1].append('\n')

        return [w, h, '\n' . join([' ' . join(line) for line in lines])]


import socket
from DH import dh_
import json

class ClientSocket:
	def __init__(self, debugflag):
		self.__dh = dh_.DH()
		self.__debugflag = debugflag

	def initDiffieHellman(self, socket):
		socket.send("connected".encode())
		step1 = socket.recv(1024)
		if self.__debugflag:
			print(step1)
		jsonData = json.loads(step1.decode())
		jsonData = jsonData["dh-keyexchange"]
		self.__dh.base = int(jsonData["base"])
		self.__dh.sharedPrime = int(jsonData["prime"])
		publicSecret = int(jsonData["publicSecret"])
		calcedPubSecret = str(self.__dh.calcPublicSecret())
		step2 = "{"
		step2 += "\"dh-keyexchange\":"
		step2 += "{"
		step2 += "\"step\": {},".format(2)
		step2 += "\"publicSecret\": {}".format(calcedPubSecret)
		step2 += "}}"
		socket.send(step2.encode())
		self.__dh.calcSharedSecret(publicSecret)

	def start_client(self, ip):
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			sock.connect((ip, 50000));
			self.initDiffieHellman(sock)
			print("The secret key is {}".format(self.__dh.key))
		finally:
			sock.close()


import news_classes
import numpy as np
import os
import pandas as pd
import pickle
import sys
import tensorflow as tf
import time

from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
#from tensorflow.contrib.learn.python.learn.estimators import model_fn
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

from keras.preprocessing.sequence import pad_sequences
from tensorflow import keras
from keras.utils import to_categorical
from keras.layers import LSTM

# import packages in trainer
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'trainer'))
#import news_cnn_model

#learn = tf.contrib.learn

SERVER_HOST = 'localhost'
SERVER_PORT = 6060

MODEL_DIR = '../model'
MODEL_UPDATE_LAG_IN_SECONDS = 10

TOKENIZER_SAVE_FILE = '../model/tokenizer.pickle'
#DATA_SET_FILE = '../data/DATA_SET_FILE.csv'
DATA_SET_FILE  = '../data/labeled_news.csv'
MAX_SEQUENCE_LENGTH = 100 # maximum length of a sentence
EMBEDDING_DIM = 100 # word dimensions
VALIDATION_SPLIT = 0.16 # the proportion of validation set to all set
TEST_SPLIT = 0.2 # the proportion of test set to all set
LEARNING_RATE = 0.01
EPOCHS = 2
BATCH_SIZE = 256

#N_CLASSES = 8

VARS_FILE = '../model/vars'
# VOCAB_PROCESSOR_SAVE_FILE = '../model/vocab_procesor_save_file'
TOKENIZER_SAVE_FILE = '../model/tokenizer.pickle'

#n_words = 0

#MAX_DOCUMENT_LENGTH = 500
#vocab_processor = None

#classifier = None

"""
def restoreVars():
    with open(VARS_FILE, 'rb') as f:
        global n_words
        n_words = pickle.load(f)

    global vocab_processor
    vocab_processor = learn.preprocessing.VocabularyProcessor.restore(
        VOCAB_PROCESSOR_SAVE_FILE)
"""
def restoreVars():
    global tokenizer
    # loading
    with open(TOKENIZER_SAVE_FILE, 'rb') as handle:
        tokenizer = pickle.load(handle)
"""
def loadModel():
    global classiﬁer
    # use n_words to initialize the model
    classiﬁer = learn.Estimator(
        model_fn=news_cnn_model.generate_cnn_model(N_CLASSES, n_words),
        model_dir=MODEL_DIR)
"""
def loadModel():
    global model
    model = keras.models.load_model(VARS_FILE)

    # Prepare training and testing
    """
    df = pd.read_csv('../data/labeled_news.csv', header=None)

    # TODO: fix this until https://github.com/tensorflow/tensorflow/issues/5548 is solved.
    # We have to call evaluate or predict at least once to make the restored Estimator work.
    train_df = df[0:400]
    x_train = train_df[1]
    x_train = np.array(list(vocab_processor.transform(x_train)))
    y_train = train_df[0]
    classifier.evaluate(x_train, y_train)
    """
restoreVars()
loadModel()

class ReloadModelHandler(FileSystemEventHandler):
    def on_any_event(self, event):
        # Reload model
        print("Model update detected. Loading new model.")
        time.sleep(MODEL_UPDATE_LAG_IN_SECONDS)
        retoreVars()
        loadModel()

observer = Observer()
observer.schedule(ReloadModelHandler(), path=MODEL_DIR, recursive=False)
observer.start()

def classify(text):
    # get row of text
    #text_series = pd.Series([text])
    # vocab_processor is stored when we training the data
    """
    predict_x = np.array(list(vocab_processor.transform(text_series)))
    print(predict_x)

    y_predicted = [
        p['class'] for p in classifier.predict(
            predict_x, as_iterable=True)
    ]
    print(y_predicted[0])
    """
    text_list = []
    text_list.append(text)
    predict_x = tokenizer.texts_to_sequences(text_list)
    predict_x = pad_sequences(predict_x, maxlen=MAX_SEQUENCE_LENGTH)
    #y_predicted = model.predict_classes(predict_x)
    y_predicted = np.argmax(model.predict(predict_x), axis=-1)
    print(y_predicted)
    print('------------------')
    topic = news_classes.class_map[str(y_predicted[0])]
    print('news type'+topic)
    return topic

sentence = 'I like sports, for example nba and football'
classify(sentence)

RPC_SERVER = SimpleJSONRPCServer((SERVER_HOST, SERVER_PORT))
RPC_SERVER.register_function(classify, 'classify')

print(("Starting RPC server on %s:%d" % (SERVER_HOST, SERVER_PORT)))

RPC_SERVER.serve_forever()


# -*- coding: utf-8 -*-
import scrapy

class CarsSpider(scrapy.Spider):
    name = 'cars'
    allowed_domains = ['cars.av.by']
    start_urls = ['https://cars.av.by/audi']

    def parse(self, response):

        # cars = response.xpath('//div[@class="listing-item"]')
        cars = response.css('div.listing-item')

        for car in cars:

            # TITLE
            title = car.xpath('.//div[@class="listing-item__about"]/h3/a/span').get()
            title = title.replace('', '').replace('', '').replace('', '').split()

            made = {
                "brand": title[0],
                "model": title[1],
                "submodel": title[2]
            }

            # LINK
            link = car.xpath('.//div[@class="listing-item__about"]/h3/a/@href').get()

            # IMAGE
            image = car.xpath('.//div[@class="listing-item__photo"]/img/@data-src').get()

            # LOCATION
            location = car.xpath('.//div[@class="listing-item__location"]/text()').get()

            # TIME
            time = car.xpath('.//div[@class="listing-item__date"]/text()').get()

            # YEAR
            year = car.xpath('.//div[@class="listing-item__params"]/div[1]/text()').get()
            year = year.replace('г.', '').strip()

            # ENGINE
            engine = car.xpath('.//div[@class="listing-item__params"]/div[2]').get()
            engine = engine.replace('
', '').replace('', '').replace('
', '').replace('л,', '').replace(',', '').split()

            engine = {
                "transmision": engine[0],
                "volume": float(engine[1]),
                "type": engine[2]
            }

            # MILES
            miles = car.xpath('.//div[@class="listing-item__params"]/div[3]/span/text()').get()
            try:
                miles = miles.replace('км', '')
                miles = miles.split()

                for x in miles:
                    x = int(x)

                miles = miles[0] + miles[1]
                miles = int(miles)
                # print(type(fmiles))
            except:
                miles = 0

            # PRICE BY
            price_by = car.xpath('.//div[@class="listing-item__price"]/text()').get()
            price_by = price_by.replace('р.', ' ').strip().split()
            try:
                for x in price_by:
                    x = int(x)
                price_by = price_by[0] + price_by[1]
                price_by = int(price_by)
                # print(type(price_ru))
            except:
                price_by = 0

            # PRICE USD
            price_usd = car.xpath('.//div[@class="listing-item__priceusd"]/text()').get()
            price_usd = price_usd.replace('≈', ' ').replace('$', ' ').strip().split()
            try:
                for x in price_usd:
                    x = int(x)
                price_usd = price_usd[0] + price_usd[1]
                price_usd = int(price_usd)
            except:
                price_usd = 0

            # absolute_url = f"https://cars.av.by{link}"
            absolute_url = response.urljoin(link)

            # yield response.follow(url=link)
            # print(response.follow(url=link))

            yield {
                'made': made,
                'link': absolute_url,
                'image': image,
                'location': location,
                'time': time,
                'year': year,
                'engine': engine,
                'miles': miles,
                'price_by': price_by,
                'price_usd': price_usd,
            }

        # next = response.xpath('//div[@class="paging__button"]/a/@href').get()
        # next_page = response.urljoin(next)
        # print(next_page)

        # if next_page is not None:
        #     yield response.follow(url=next_page, callback=self.parse)


from hashlib import sha256
import rsa
import json
from random import randint
import binascii
from pprint import pprint

"""
what to do
1. make 3 signed transaction
2. create a merkle root
3. hash the header, not the whole block
4. set a target difficulty (not in hex) and mine it

there are 2 important things to keep in mind
- the metadata of the block
- the data of the transaction

it doesn't need to inlcude everything
your goal is to make cool block using the merkle tree
"""

def edit_json(msg, attr, attr_data):
    new_data = json.loads(msg.decode())
    new_data[attr] = attr_data
    new_json_data = json.dumps(new_data)
    return str.encode(new_json_data)

def gen_key_list(amount):
    # key_dict = {}
    key_list = []

    for i in range(amount):
        key_dict = {}
        (pub, priv) = rsa.newkeys(512)
        key_dict['public'] = pub
        key_dict['private'] = priv

        key_list.append(key_dict)

    return key_list

def get_hex(key):
    # export the key to DER format
    der = key.save_pkcs1('DER')

    # since DER is a binary, it can be translated
    # to hex using hexlify
    hex = binascii.hexlify(der)
    # print(public_hex.decode())
    return hex.decode()

keys = gen_key_list(3)

# ===== make the transaction =====
"""
key 0 -> key 1 x amount
key 1 -> key 2 x amount
key 2 -> key 0 x amount
"""
transaction_list = []
for i in range(len(keys)):
    data = {}
    sender_public = keys[i]['public']
    sender_private = keys[i]['private']
    try:
        receiver_public = keys[i+1]['public']
    except IndexError:
        receiver_public = keys[0]['public']

    data['sender'] = get_hex(sender_public)
    data['receiver'] = get_hex(receiver_public)
    data['amount'] = randint(1, 5)

    # sign the transaction
    temp_message = json.dumps(data).encode()
    signature = rsa.sign(temp_message, sender_private, 'SHA-256')
    data['signature'] = binascii.hexlify(signature).decode()

    transaction_list.append(data)

# ===== find merkle root =====
# if the transaction is odd, then duplicate the last index
"""
the reason you use merkle root is to proove that a transaction is
present on the block without checking one by one, i actually need
to read more about this
"""

total_length = len(transaction_list)
if total_length % 2 != 0:
    transaction_list.append(transaction_list[-1])
# print(transaction_list)

# change name to make it understandable
hash_list = transaction_list
if len(hash_list) == 0:
    # return error or some shit
    pass
elif len(hash_list) == 2:
    # hash that one transaction
    pass
else:
    while len(hash_list) != 1:
        # every iteration starts with empty temp list
        # that will be filled with the combination of the current
        # hash list
        temp_list = []
        for i in range(0, len(hash_list), 2):
            # combine the hash here
            json_tx1 = json.dumps(hash_list[i])
            tx1 = json_tx1.encode()

            json_tx2 = json.dumps(hash_list[i+1])
            tx2 = json_tx2.encode()

            """
            for some reason, the bitcoin protocol requires the transactions to be
            hashed twice, the digest here is a function that returns the
            binary of the hash
            """
            hash1 = sha256(sha256(tx1).digest()).digest()
            hash2 = sha256(sha256(tx2).digest()).digest()

            parent_hash = sha256(sha256(hash1 + hash2).digest()).hexdigest()
            temp_list.append(parent_hash)

        # the temp list is a list of calculated parent hashes
        # put it in the main hash list so it can be processed next
        hash_list = temp_list

    root_merkle_hash = hash_list[0]

# ===== make block ======
block = {}
block['header'] = {
    'merkle_root': root_merkle_hash,
    'nonce': 0,
    # the target is just a random hex that starts with three 0s converted to int
    'target': 15802950234683020252676755972449664373407456225394263496399282190354680851
    }
block['transaction'] = transaction_list

# ===== mine ======
# the hash result is hex, turn it into a int first
# int(sha.hexdigest(), 16) -> you can do it like this
while True:
    target = block['header']['target']
    nonce = block['header']['nonce']

    block_msg = json.dumps(block['header']).encode()
    # lmao for some reason when I do it manually it doesn't work
    header_hash = sha256(sha256(block_msg).digest()).hexdigest()
    # print(header_hash)

    hash_int = int(header_hash, 16)
    if hash_int < target:
        print('nonce is: ', nonce)
        print(sha256(block_msg).digest())
        print(header_hash)
        break
    else:
        block['header']['nonce'] += 1

# print(block)


#%% Import section
import numpy as np
import cv2
#%%
reference_file = open('Reference.txt', 'w')
test_file = open('Test.txt', 'w')
#%% define centroid function:
def centroid(moments):
    """Returns centroid based on moments"""
    if moments['m00'] == 0:
        print('Zero Value')
        return 0,0
    x_centroid = round(moments['m10'] / moments['m00'])
    y_centroid = round(moments['m01'] / moments['m00'])
    return x_centroid, y_centroid
def draw_contour_outline(img, cnts, color, thickness=1):
    """Draws contours outlines of each contour"""

    for cnt in cnts:
        cv2.drawContours(img, [cnt], 0, color, thickness)
#%% Opening Image
reference_image = cv2.imread('ReferenceImages/rearCIC.jpg', cv2.IMREAD_GRAYSCALE)
test_image = cv2.imread('TestImages/rear/a-petrelli-rearCIC.jpg', cv2.IMREAD_GRAYSCALE)
#%% Thresholding images
#thresh, reference_image_binary = cv2.threshold(reference_image, 127, 255, 0)
#thresh, test_image_binary = cv2.threshold(test_image, 127, 255, 0)
#%% Bluring
reference_image = cv2.blur(reference_image, (3,3))
test_image = cv2.blur(test_image, (3,3))
#%% Bilateral filter #TODO da capire bene come usarlo potrebbe essere migliore del gaussian
test_image = cv2.bilateralFilter(test_image, 9, 9, 9)
#%% Canny
reference_image_canny = cv2.Canny(reference_image, 100, 200)
test_image_canny = cv2.Canny(test_image, 100, 200)
#%% Morphological operation
kernel = np.ones((5,5),np.uint8)
reference_image_canny_morph = cv2.morphologyEx(reference_image_canny, cv2.MORPH_CLOSE, kernel)
test_image_canny_morph = cv2.morphologyEx(test_image_canny, cv2.MORPH_CLOSE, kernel)
#%% Finding Contours on binary image
#test_image_connected = cv2.connectedComponents(test_image_canny)
reference_contours, reference_hierarchy = cv2.findContours(reference_image_canny, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
test_contours, test_hierarchy = cv2.findContours(test_image_canny, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
reference_contours = sorted(reference_contours, key=cv2.contourArea, reverse= True)
test_contours = sorted(test_contours, key=cv2.contourArea, reverse= True)
#%% Computing reference Moments
reference_hu_moment_dict = {}
for index, contour in enumerate(reference_contours):
    reference_hu_moment_dict[index] = { 'moment': cv2.moments(contour),
                                        'hu_moment': cv2.HuMoments(cv2.moments(contour)),
                                        #'log_hu_moment': -np.sign(cv2.HuMoments(cv2.moments(contour)))*np.log10(np.abs(cv2.HuMoments(cv2.moments(contour))))
                                        }
#%% Computing test Moments
test_hu_moment_dict = {}
for index, contour in enumerate(test_contours):
    test_hu_moment_dict[index] = { 'moment': cv2.moments(contour),
                                   'hu_moment': cv2.HuMoments(cv2.moments(contour)),
                                   #'log_hu_moment': -np.sign(cv2.HuMoments(cv2.moments(contour)))*np.log10(np.abs(cv2.HuMoments(cv2.moments(contour))))
                                   }
#%% Computing Reference Centroid of the moments
reference_centroid = {}
for index in reference_hu_moment_dict.keys():
    reference_centroid[index] = centroid(reference_hu_moment_dict[index]['moment'])
#%% Computing Test Centroid of the moments
test_centroid = {}
for index in test_hu_moment_dict.keys():
    reference_centroid[index] = centroid(test_hu_moment_dict[index]['moment'])
#%% Print Result:
for index in reference_hu_moment_dict.keys():
    print('Reference Moment at contour index: ', index, file= reference_file)
    print(reference_hu_moment_dict[index], file= reference_file)
for index in test_hu_moment_dict.keys():
    print('Test Moment at contour index: ', index, file= test_file)
    print(test_hu_moment_dict[index], file= test_file)
for index in reference_centroid.keys():
    print('Reference centroid at contour index: ', index, file= reference_file)
    print(reference_centroid[index], file= reference_file)
for index in test_centroid.keys():
    print('Test centroid at contour index: ', index, file= test_file)
    print(test_centroid[index], file= test_file)
#%% Sercing Hu Moment Matches
matched_contours = {}
for i, ref_c in enumerate(reference_contours):
    for k, test_c in enumerate(test_contours):
        matched_contours[(i,k)] = cv2.matchShapes(ref_c, test_c, 3, 0)

#%% Showing Contours:
# Draw the outline of the detected contour:
#draw_contour_outline(reference_image, reference_contours, (255, 0, 0), 10)
#draw_contour_outline(test_image, test_image, (255, 0, 0), 10)
cv2.imwrite('ContoursHU/Reference_CannyBlur.jpg', reference_image_canny)
cv2.imwrite('ContoursHU/Test_cannyBlur.jpg', test_image_canny)
reference_image_copy = reference_image.copy()
test_image_copy = test_image.copy()
cv2.drawContours(reference_image_copy, reference_contours[0], -1, (0, 255, 0), 2)
cv2.drawContours(test_image_copy, test_contours[0], -1, (0, 255, 0), 2)
cv2.imwrite('ContoursHU/Reference_ContoursBlur.jpg', reference_image)
cv2.imwrite('ContoursHU/Test_ContoursBlur.jpg', test_image)
# cv2.imshow('Reference Canny', reference_image_canny)
# cv2.imshow('Test Canny', test_image_canny)
# cv2.imshow("Reference Image", reference_image)
# cv2.imshow("Test Image", test_image)
#
# cv2.waitKey(0)
# cv2.destroyAllWindows()
#%% Bounding rect usage:
x, y, w, h = cv2.boundingRect(reference_contours[0])
cv2.rectangle(reference_image, (x,y), (x+w, y+h),(255,0,255), 5)
x, y, w, h = cv2.boundingRect(test_contours[0])
cv2.rectangle(test_image, (x,y), (x+w,y+h), (255,0,255), 5)
cv2.imshow('Reference', reference_image)
cv2.imshow('Test', test_image)
cv2.waitKey(0)
cv2.destroyAllWindows()


import requests
import asyncio
from aiohttp import ClientSession
from functools import wraps
from time import time

URL = "https://httpbin.org/delay/{}"

def duration(func):
    async def helper(func, *args, **kwargs):
        if asyncio.iscoroutinefunction(func):
            print(f"this function is a coroutine: {func.__name__}")
            return await func(*args, **kwargs)
        else:
            print(f"not a coroutine: {func.__name__}")
            return func(*args, **kwargs)

    @wraps(func)
    async def wrapper(*args, **kwargs):
        start_ts = time()
        result = await helper(func, *args, **kwargs)
        dur = time() - start_ts
        print("{} took {:.2} seconds".format(func.__name__, dur))

        return result

    return wrapper

@duration
async def _get_completed():
    async with ClientSession() as session:
        tasks = [
            session.get(URL.format(delay)) for delay in [2, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        ]
        responses = await asyncio.gather(*tasks)
        rs = [await response.json() for response in responses]
    return rs

def get_completed():
    """async call to get all of the completed challanges and their metadata in json format."""
    return asyncio.get_event_loop().run_until_complete(_get_completed())

@duration
def sync_get():
    resp = [requests.get(URL.format(delay)) for delay in [1, 1, 1, 1, 1]]
    return resp

if __name__ == "__main__":
    get_completed()


import logging
from uuid import UUID

from pydantic import BaseModel

from ipaddress import IPv4Address

_LOGGER = logging.getLogger(__name__)

class Stats():
    def __init__(self, accounts, services, uuid, remote_addr, dns_update):
        self.accounts = accounts
        self.services = services
        self.uuid = uuid
        self.remote_addr = remote_addr
        self.dns_update = dns_update

    def __repr__(self):
        return (
            f'<Stats(accounts={self.accounts},services={self.services},'
            f'uuid={self.uuid},remote_addr={self.remote_addr},'
            f'dns_update={self.dns_update})>'
        )

    def as_dict(self):
        return {
            'accounts': self.accounts,
            'services': self.services,
            'uuid': self.uuid,
            'remote_addr': self.remote_addr,
            'dns_update': self.dns_update
        }

class StatsResponseModel(BaseModel):
    accounts: int
    services: int
    dns_update: bool
    remote_addr: IPv4Address
    uuid: UUID | None = None


from lib.primes import getNextPrimeGenerator
from lib.convenience import factors
import math

# generalized sieve approach
def findAllPhiUnderX(x):
    arr = [i for i in range(2, x)]
    gen = getNextPrimeGenerator()
    for prime in gen:
        if prime > x:
            break
        for i in range(prime, x, prime):
            arr[i - 2] = int(arr[i - 2] * (1 - 1/prime))
    return arr

# sieve approach
def phi(x):
    coprimesArr = [True for _ in range(0, x)]
    facts = [*set(factors(x))]
    facts.sort()
    for p in facts:
        if p == 1:
            continue
        for i in range(0, x, p):
            coprimesArr[i] = False
    return len([i for i in coprimesArr if i is True])

def is_coprime(x, y):
    return math.gcd(x, y) == 1

# def phi(x):
#     return len([i for i in range(2,x) if math.gcd(i, x) == 1])


from typing import List

from pytest import mark

class Solution:
    def restoreIpAddresses(s: str) -> List[str]:
        ans = []

        def backtrack(index: int, path: List[str]) -> None:
            if index > len(s) or len(path) > 4:
                return
            if index == len(s) and len(path) == 4:
                ans.append('.'.join(path))
                return
            for i in range(1,4):
                if (index + i) <= len(s) and int(s[index:index+i]) <= 255:
                    if not (s[index] == '0' and i > 1):
                        backtrack(index+i, path+[s[index:index+i]])
        backtrack(0, [])
        return ans

@mark.parametrize('s, expected', [
        ("0000", ["0.0.0.0"]),
        ("1111", ["1.1.1.1"]),
        ("010010", ['0.10.0.10', '0.100.1.0']),
        ("101023", ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"])
    ])

def test_restoreIpAddresses(s, expected):
    ans_brute = Solution.restoreIpAddresses(s)
    assert ans_brute == expected


# напиши здесь код основного приложения и первого экрана
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QLabel, QPushButton
from instr import *
import second_win

class MainWin(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.connects()
        self.set_appear()
        self.show()
    def initUI(self):
        self.btn_next = QPushButton(txt_next)
        self.hello_text = QLabel(txt_hello)
        self.instruction = QLabel(txt_instruction)
        self.laoyut_line = QVBoxLayout()
        self.laoyut_line.addWidget(self.hello_text, alignment = Qt.AlignLeft)
        self.laoyut_line.addWidget(self.instruction, alignment = Qt.AlignLeft)
        self.laoyut_line.addWidget(self.btn_next, alignment = Qt.AlignCenter)
        self.setLayout(self.laoyut_line)
    def next_click(self):
        self.hide()
        self.tw = second_win.TestWin()
    def connects(self):
        self.btn_next.clicked.connect(self.next_click)
    def set_appear(self):
        self.setWindowTitle(txt_title)
        self.resize(win_width, win_height)
        self.move(win_x, win_y)

app = QApplication([])
mv = MainWin()
app.exec_()


#!/usr/bin/env python3
import copy
import time
import random
import math
import argparse
from rpi_ws281x import PixelStrip

# LED strip configuration:
LED_COUNT = 100  # Number of LED pixels.
LED_PIN = 18  # GPIO pin connected to the pixels (18 uses PWM!).
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10  # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 255  # Set to 0 for darkest and 255 for brightest
LED_INVERT = False  # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL = 0  # set to '1' for GPIOs 13, 19, 41, 45 or 53

class Color:
    def __init__(self, red=0, green=0, blue=0):
        self.red = red
        self.green = green
        self.blue = blue
        self.black = self.red == 0 and self.green == 0 and self.blue == 0

    def __iadd__(self, other):
        if other.black:
            return self
        if self.black is False:
            self.red += other.red
            self.green += other.green
            self.blue += other.blue
        else:
            self.black = False
            self.red = other.red
            self.green = other.green
            self.blue = other.blue
        return self

    def __imul__(self, other):
        if self.black:
            return self
        if other < 0:
            other = 0
        self.red *= other
        self.green *= other
        self.blue *= other
        return self

    def get(self):
        if self.black:
            return 0
        if self.red > 255:
            self.red = 255
        if self.green > 255:
            self.green = 255
        if self.blue > 255:
            self.blue = 255
        return (round(self.red) << 8) | (round(self.green) << 16) | round(self.blue)

def wheel(pos):
    """Generate rainbow colors across 0-255 positions."""
    if pos < 85:
        return Color(pos * 3, 255 - pos * 3, 0)
    elif pos < 170:
        pos -= 85
        return Color(255 - pos * 3, 0, pos * 3)
    else:
        pos -= 170
        return Color(0, pos * 3, 255 - pos * 3)

def fixcolor(pos):
    if pos == 0:
        return Color(255, 0, 0)
    elif pos == 1:
        return Color(0, 255, 0)
    elif pos == 2:
        return Color(0, 0, 255)
    elif pos == 3:
        return Color(128, 128, 0)
    elif pos == 4:
        return Color(0, 128, 128)
    elif pos == 5:
        return Color(128, 0, 128)
    return Color(255, 255, 255)

class LightFunc:
    def __init__(self):
        self.state = 0

    def get(self, i) -> Color:
        return Color()

    def next_frame(self):
        self.state += 1

class LightFuncN:
    def __init__(self):
        self.state = [0] * LED_COUNT

    def get(self, i) -> Color:
        return Color()

    def next_frame(self):
        for i in range(LED_COUNT):
            if self.state[i]:
                self.state[i] -= 1

class FuncRainbow(LightFunc):
    def __init__(self):
        super().__init__()
        self.wave = random.randrange(2, 5) / 10
        self.pos = 0
        self.shift = random.randrange(20, 100) / 200

    def get(self, i) -> Color:
        c = wheel((self.state + i) & 255)
        c *= math.sin(i * self.wave + self.pos) * 0.4 + 0.6
        return c

    def next_frame(self):
        self.state += 1
        self.state &= 255
        self.pos += self.shift

class FuncMoveingDots1(LightFunc):
    def __init__(self, brighness=1.00, speed=1.00):
        super().__init__()
        self.brighness = brighness
        self.color = wheel(random.randrange(256))
        self.wave = random.randrange(2, 5) / 10
        self.shift = random.randrange(-100, 100) / 200 * speed

    def get(self, i) -> Color:
        m = math.sin(i * self.wave + self.state) * self.brighness
        if m < 0.1:
            c = Color()
        else:
            c = copy.copy(self.color)
            c *= m
        return c

    def next_frame(self):
        self.state += self.shift

class FuncMoveingDots2(LightFunc):
    def __init__(self):
        super().__init__()
        self.color = wheel(random.randrange(256))
        self.wave = 2 * math.pi * (random.randrange(3) + 1) / LED_COUNT
        self.speed = random.randrange(-100, 100) / 200

    def get(self, i) -> Color:
        m = math.sin(i * self.wave + self.state) * 4 - 3
        if m < 0.1:
            c = Color()
        else:
            c = copy.copy(self.color)
            c *= m
        return c

    def next_frame(self):
        self.state += self.speed

class FuncMoveCombine(LightFunc):
    def __init__(self):
        super().__init__()
        self.f1 = FuncMoveingDots1(0.2, 0.1)
        self.f2 = FuncMoveingDots2()

    def get(self, i) -> Color:
        c = self.f1.get(i)
        c += self.f2.get(i)
        return c

    def next_frame(self):
        self.f1.next_frame()
        self.f2.next_frame()

class FuncRGBSinWave(LightFunc):
    def __init__(self):
        super().__init__()
        self.wave = []
        self.speed = []
        self.pos = []
        for i in range(3):
            self.wave.append(2 * math.pi * (random.randrange(3) + 1) / LED_COUNT)
            self.speed.append(random.randrange(-100, 100) / 500)
            self.pos.append(random.randrange(-314, 314) / 100)

    def get(self, i) -> Color:
        c = []
        for ci in range(3):
            c.append(3 ** (math.sin(i * self.wave[ci] + self.pos[ci]) * 5 - 5) * 255)
        r, g, b = c
        return Color(r, g, b)

    def next_frame(self):
        for i in range(3):
            self.pos[i] += self.speed[i]

class FuncRGBSawWave(LightFunc):
    def __init__(self):
        super().__init__()
        self.wave = []
        self.speed = []
        self.pos = []
        for i in range(3):
            self.wave.append((random.randrange(3) + 1) / LED_COUNT)
            self.speed.append(random.randrange(-100, 100) / 4000)
            self.pos.append(random.randrange(100) / 100)

    def get(self, i) -> Color:
        c = []
        for ci in range(3):
            y = i * self.wave[ci] + self.pos[ci]
            c.append(3 ** ((y - math.floor(y)) * 5 - 5) * 255)
        r, g, b = c
        return Color(r, g, b)

    def next_frame(self):
        for i in range(3):
            self.pos[i] += self.speed[i]

class FuncFade1(LightFuncN):
    def __init__(self):
        super().__init__()
        self.color = wheel(random.randrange(256))

    def get(self, i) -> Color:
        s = self.state[i]
        if s == 0:
            return Color()
        ret = copy.copy(self.color)
        if s < 20:
            ret *= s / 20
        else:
            ret *= (25 - s) / 5
        return ret

    def next_frame(self):
        super().next_frame()
        if random.randrange(5) == 0:
            i = random.randrange(LED_COUNT)
            if self.state[i] == 0:
                self.state[i] = 24

class FuncFade2(LightFuncN):
    def __init__(self):
        super().__init__()
        self.fast = 20
        self.slow = 50
        self.slow2 = self.slow * 2
        self.color1 = wheel(random.randrange(256))
        self.color2 = fixcolor(random.randrange(7))
        self.color2 *= 0.08
        for i in range(LED_COUNT):
            self.state[i] = random.randrange(self.slow * 2)

    def get(self, i) -> Color:
        s = self.state[i]
        ret = copy.copy(self.color2)
        if s <= self.slow2:
            if s < self.slow:
                ret *= (self.slow - s) / self.slow
            else:
                ret *= (s - self.slow) / self.slow
            return ret
        chigh = copy.copy(self.color1)
        if s < self.slow2 + self.fast:
            chigh *= (s - self.slow2) / self.fast
            ret += chigh
        else:
            chigh *= (self.slow2 + self.fast + 5 - s) / 5
            return chigh
        return ret

    def next_frame(self):
        for i in range(LED_COUNT):
            if self.state[i]:
                self.state[i] -= 1
            else:
                self.state[i] = self.slow2
        if random.randrange(10) == 0:
            i = random.randrange(LED_COUNT)
            if self.state[i] <= self.slow2:
                self.state[i] = self.slow2 + self.fast + 4

class FuncSparkling1(LightFuncN):
    def __init__(self):
        super().__init__()
        self.slow = 50
        self.slow2 = self.slow * 2
        self.color1 = wheel(random.randrange(256))
        self.color2 = fixcolor(random.randrange(7))
        self.color2 *= 0.08
        for i in range(LED_COUNT):
            self.state[i] = random.randrange(self.slow * 2)

    def get(self, i) -> Color:
        s = self.state[i]
        if random.randrange(LED_COUNT * 10) == 0:
            ret = copy.copy(self.color1)
        else:
            ret = copy.copy(self.color2)
            if s <= self.slow2:
                if s < self.slow:
                    ret *= (self.slow - s) / self.slow
                else:
                    ret *= (s - self.slow) / self.slow
        return ret

    def next_frame(self):
        for i in range(LED_COUNT):
            if self.state[i]:
                self.state[i] -= 1
            else:
                self.state[i] = self.slow2

class Tree:
    def __init__(self, arguments):
        self.args = arguments
        self.strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        self.strip.begin()
        self.func1 = None  # typing.Optional[LightFunc, LightFuncN]
        self.func2 = None  # typing.Optional[LightFunc, LightFuncN]
        self.mix = 0
        self.funclist = [FuncRainbow, FuncMoveingDots1, FuncMoveingDots2, FuncMoveCombine, FuncRGBSinWave,
                         FuncRGBSawWave, FuncFade1, FuncFade2, FuncSparkling1]
        self.fixfunc = None
        if self.args.action is not None and self.args.action < len(self.funclist):
            self.fixfunc = self.funclist[self.args.action]
        if self.args.wait < 0:
            self.args.wait = 0
        random.seed()

    def _random_func(self):
        choice = self.fixfunc if self.fixfunc is not None else random.choice(self.funclist)
        if self.args.v:
            print(f"Next scene: {choice.__name__}")
        return choice()

    def run(self):
        self.func1 = self._random_func()
        t = time.time()
        t_next_scene = t + self.args.wait
        t_next = t + 0.04
        t_fps = t
        fps = 0
        try:
            while True:
                for i in range(LED_COUNT):
                    c = self.func1.get(i)
                    if self.func2 is not None:
                        c *= (1 - self.mix)
                        c2 = self.func2.get(i)
                        c2 *= self.mix
                        c += c2
                    try:
                        self.strip.setPixelColor(i, c.get())
                    except OverflowError:
                        print(c)
                        print(c.get())
                self.strip.show()
                self.func1.next_frame()
                t = time.time()
                if self.func2 is None:
                    if t_next_scene < t:
                        self.func2 = self._random_func()
                        self.mix = 0
                else:
                    self.mix += 0.02
                    if self.mix >= 1:
                        self.func1 = self.func2
                        self.func2 = None
                        t_next_scene = t + self.args.wait
                    else:
                        self.func2.next_frame()
                if self.args.fps:
                    fps += 1
                    if t_fps + 1 <= t:
                        t_fps += 1
                        print(f"FPS: {fps}")
                        fps = 0
                t = time.time()
                w = t_next - t
                if w >= 0.01:
                    t_next += 0.04
                else:
                    w = 0.01
                    t_next = t + 0.05
                time.sleep(w)
        except KeyboardInterrupt:
            pass
        if self.args.clear:
            for i in range(LED_COUNT):
                self.strip.setPixelColor(i, 0)
            self.strip.show()

if __name__ == '__main__':
    print('Press Ctrl-C to quit.')
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--action", type=int, help="selected action", default=None)
    parser.add_argument("-w", "--wait", type=int, help="wait per screen", default=20)
    parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
    parser.add_argument('-f', '--fps', action='store_true', help='display FPS')
    parser.add_argument('-v', action='store_true', help='Verbose')
    args = parser.parse_args()
    tree = Tree(args)
    tree.run()


"""
GMM Accuracy with 200 features 0.33 with k fold
GMM Accuracy with 400 features 0.24 with k fold

Bayes GMM with 200 features 0.23
Bayes GMM with 400 features 0.24

"""

from sklearn.mixture import GaussianMixture
from sklearn.mixture import BayesianGaussianMixture
from sklearn.model_selection import train_test_split
import pandas
import numpy as np
import sklearn
from sklearn.model_selection import StratifiedKFold

file_path_200f = "/home/k_mathin/PycharmProjects/DataMiningClass/datasets/classification/object_classification/yin_airpl_m_sun/target_6_4_101_91_MICC_F220_bow_200.csv"

caltech_binary = '/Users/Srikanth/PycharmProjects/COMP551_Projects/DataMiningClass_v4/datasets/classification/aero_bike/with_targets/MICC_F220_bow_200.csv'
#
# data = pandas.read_csv("/home/k_mathin/PycharmProjects/DataMiningClass/datasets/classification/heart.csv",
#                        header=None,
#                        skiprows=1)
data = pandas.read_csv(caltech_binary, header=None, skiprows=1)

X = data.iloc[:, 0:len(data.keys()) - 1]  # slicing: all rows and 1 to 4 cols
# store response vector in "y"
y = data.iloc[:, len(data.keys()) - 1]
k = len(np.unique(y))
X = np.asarray(X)
y = np.asarray(y)
skf = StratifiedKFold(n_splits=4)
skf.get_n_splits(X, y)
accuracy_list = []

for train_index, test_index in skf.split(X, y):
    # print("TRAIN:", train_index, "TEST:", test_index)

    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

    # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

    X_train = np.asarray(X_train)
    X_test = np.asarray(X_test)
    y_train = np.asarray(y_train)
    y_test = np.asarray(y_test)

    # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1)

    # mixture_model = GaussianMixture(n_components=k)
    mixture_model = BayesianGaussianMixture(n_components=k)
    mixture_model.fit(X_train, y_train)
    predictions = mixture_model.predict(X_test)

    accuracy_list.append(sklearn.metrics.accuracy_score(y_test, predictions))
print(accuracy_list)
print("Final acc: ", np.asarray(accuracy_list).mean())


from dataset import MangoDataset,Dataloader,make_dataset
from options import opt
from pathlib import Path
import torch
import torch.nn as nn
from torch.autograd import Variable
from torchvision import transforms
import numpy as np
from PIL import Image

label_dict={
    'A':0,
    'B':1,
    'C':2
}

def evaluation():
	eval_set=MangoDataset(Path(opt.data_root).joinpath('C1-P1_Dev'))
	# data_loader=Dataloader(dataset=eval_set,batch_size=opt.eval_batch_size,shuffle=False,num_workers=opt.eval_num_workers)
	weight_path = Path(opt.checkpoint_dir).joinpath(opt.weight_path)

	model = torch.load(weight_path)
	model = model.cuda(opt.cuda_devices)
	model.eval()

	criterion = nn.CrossEntropyLoss()

	evaluation_loss = 0.0
	evaluation_corrects = 0

	for i,(image,label) in enumerate(eval_set):
		image_1, image_2, image_3 = eval_data_transform(image)
		label=np.asarray([label])
		label=torch.from_numpy(label)

		input_1 = Variable(image_1.cuda(opt.cuda_devices))
		input_2 = Variable(image_2.cuda(opt.cuda_devices))
		input_3 = Variable(image_3.cuda(opt.cuda_devices))
		label=Variable(label.cuda(opt.cuda_devices))

		output_1 = model(input_1)
		output_2 = model(input_2)
		output_3 = model(input_3)

		output = output_1+output_2+output_3

		_, preds = torch.max(output.data, 1)
		output/=3
		loss = criterion(output/3, label)

		evaluation_loss += loss.item() * input_1.size(0)
		evaluation_corrects += torch.sum(preds == label.data)

	evaluation_loss = evaluation_loss / len(eval_set)
	evaluation_acc = float(evaluation_corrects) / len(eval_set)

	print(f'Evaluation loss: {evaluation_loss:.4f}\taccuracy: {evaluation_acc:.4f}\n')


from requests import get
from lib.auth import Authentication
from lib.config import server
from json import loads, dumps
from ipaddress import ip_address
from time import sleep

class GetData(object):

    def __init__(self, username, password):
        self.token = Authentication(username, password).logon()
        self.headers = {'Authorization': 'Bearer {}'.format(self.token)}

    def get_groups(self):
        list_groups = {}
        response = get(server + '/sepm/api/v1/groups', headers=self.headers, verify=False)
        group_list = loads(response.text)['content']
        for x in group_list:
            list_groups[x['name']] = x['id']
        f = open('list_group.json','w+')
        f.write(dumps(list_groups))
        f.close()
        return group_list

    def get_computers_from_group(self, group_id):
        response = get(server + '/sepm/api/v1/groups/{}/computers'.format(group_id), headers=self.headers, verify=False)
        computer_list = loads(response.text)['content']
        f = open('computers_from_group.json','w+')
        f.write(dumps(computer_list))
        f.close()
        return computer_list

    def get_computers(self, pageIndex=1):
        response = get(server + '/sepm/api/v1/computers/?pageSize=100&pageIndex={}'.format(pageIndex), headers=self.headers, verify=False)
        return loads(response.text)

    def get_all_computers(self):
        hosts = {}
        response = self.get_computers()
        for i in range(1,response['totalPages']+1):
            response = self.get_computers(i)
            for x in response['content']:
                hosts[x['computerName']] = {'macAddress': x['macAddresses'][0], 'hardwareKey': x['hardwareKey'],
                                            'ipAddress': []}
                for k in x['ipAddresses']:
                    if ip_address(k).version == 4:
                        hosts[x['computerName']]['ipAddress'].append(k)
            sleep(3)
        f = open('list_computers.json','w+')
        f.write(str(dumps(hosts)))
        f.close()

    def get_all_computers_pendent_reboot(self):
        hosts = {}
        response = self.get_computers()
        for i in range(1, response['totalPages'] + 1):
            response = self.get_computers(i)
            for x in response['content']:
                if x['rebootRequired'] == 1:
                    hosts[x['computerName']] = {'ipAddresses':x['ipAddresses']}
            sleep(3)
        return hosts

    def get_servers(self):
        response = get(server + '/sepm/api/v1/admin/servers', headers=self.headers, verify=False)
        return response.text

    def get_version(self):
        response = get(server + '/sepm/api/v1/version', headers=self.headers, verify=False)
        return response.text

    def get_computer_info(self, computer_name):
        response = get(server + '/sepm/api/v1/computers/?computerName={}'.format(computer_name), headers=self.headers, verify=False)
        return response.text


import os
import pandas as pd
import numpy as np
import argparse

import baxus
from baxus.util.behaviors import BaxusBehavior
from baxus.util.behaviors.gp_configuration import GPBehaviour
from baxus.baxus import BAxUS
from baxus.util.parsing import embedding_type_mapper, acquisition_function_mapper, mle_optimization_mapper

from envs.spark import SparkParameters
from models.utils import get_logger, get_foldername, get_filename
from models.bench import SparkBench
from models.configs import baxus_params as bp
import models.configs as cfg

parser = argparse.ArgumentParser()
parser.add_argument('-b', '--bo', type=str, default='baxus')
# parser.add_argument('-t', '--test', type=str, default='test', help='description for this parameter')
# parser.add_argument('-i', '--ints', type=int, default=5, help='description for this parameter')
# parser.add_argument('-f', '--floats', type=float, default=0.5, help='description for this parameter')
logger = get_logger()
os.system('clear')
opt = parser.parse_args()
logger.info("## ARGUMENT INFORMATION ##")
for _ in vars(opt):
    logger.info(f"{_}: {vars(opt)[_]}")

os.makedirs(cfg.INCUMBENTS_RESULTS_PATH, exist_ok=True)

def main():
    bin_sizing_method = embedding_type_mapper[bp['embedding_type']]
    acquisition_function = acquisition_function_mapper[bp['acquisition_function']]
    mle_optimization_method = mle_optimization_mapper[bp['mle_optimization']]

    behavior = BaxusBehavior(n_new_bins=bp['new_bins_on_split'],
                            initial_base_length=bp['l_init'],
                            min_base_length=bp['l_min'],
                            max_base_length=bp['l_max'],
                            acquisition_function=acquisition_function,
                            embedding_type=bin_sizing_method,
                            adjust_initial_target_dim=bp['adjust_initial_target_dim'],
                            noise=bp['noise_std'],
                            budget_until_input_dim=bp['budget_until_input_dim']
                            )

    gp_behaviour = GPBehaviour(
        mll_estimation=mle_optimization_method,
        n_initial_samples=bp['multistart_samples'],
        n_best_on_lhs_selection=bp['multistart_after_samples'],
        n_mle_training_steps=bp['mle_training_steps'],
    )

    sp = SparkParameters()

    input_dim = len(sp) # args.input_dim
    ub = sp.ub
    lb = sp.lb

    f = SparkBench(dim=input_dim, ub=ub, lb=lb, sp=sp)

    optim = BAxUS(f=f,
                n_init=bp['n_init'],
                max_evals=bp['max_evals'],
                target_dim=bp['target_dim'],
                behavior=behavior,
                gp_behaviour=gp_behaviour,
                run_dir=get_foldername(os.path.join('bo-results', opt.bo))
                )

    optim.optimize()

    incumbent_configs, incumbent_results = optim.optimization_results_incumbent()
    np.save(get_filename(cfg.INCUMBENTS_RESULTS_PATH,'tuned_configs', '.npy'), incumbent_configs)
    np.save(get_filename(cfg.INCUMBENTS_RESULTS_PATH,'tuned_results', '.npy'), incumbent_results)

    # np.save(os.path.join(cfg.INCUMBENTS_RESULTS_PATH, 'tuned_configs.npy'), incumbent_configs)
    # np.save(os.path.join(cfg.INCUMBENTS_RESULTS_PATH, 'tuned_results.npy'), incumbent_results)

if __name__ == '__main__':
    try:
        main()
    except:
        logger.exception("ERROR!!")
    else:
        logger.handlers.clear()


import streamlit as st
import pandas as pd
from model import load_model, predict
import time

# Load your trained model (make sure the model file 'svm_model_OPT.pkl' is in the same directory)
# status_model_filename = 'model\status\svm_model_OPT.pkl'
status_model = load_model('model/status/DT_model.joblib')

# salary_model_filename = 'model/salary/random_forest_regression_model.joblib'
salary_model = load_model('model/salary/random_forest_regression_model.joblib')

# Create a Streamlit web app
st.title('Campus Recruitment Prediction')
st.write('This app predicts campus recruitment status and salary based on selected features.')
st.markdown("""

""", unsafe_allow_html=True)
st.markdown('
Enter your name
', unsafe_allow_html=True)
name = st.text_input("")
# Define input fields for user input
user_input_container = st.container()

with user_input_container:
    st.markdown('
Please Enter correct details
',unsafe_allow_html=True)

    # Gender
    gender = st.selectbox('Select Gender', ['Male', 'Female'])

    # Group SSC Details
    st.subheader('SSC Details')
    col1, col2 = st.columns(2)
    with col1:
        ssc_p = st.number_input('Enter Percentage', min_value=0.0, max_value=100.0, key='ssc_p')
    with col2:
        ssc_b = st.selectbox('Select Board', ['Central', 'Others'], key='ssc_b')

    # Group HSC Details
    st.subheader('HSC Details')
    col1, col2, col_3 = st.columns(3)
    with col1:
        hsc_p = st.number_input('Enter Percentage', min_value=0.0, max_value=100.0, key='hsc_p')
    with col2:
        hsc_b = st.selectbox('Select Board', ['Central', 'Others'], key='hsc_b')
    with col_3:
        hsc_s = st.selectbox('Select HSC Stream', ['Science', 'Commerce', 'Arts'])

    # Group Degree Details
    st.subheader('Degree Details')
    col1, col2 = st.columns(2)
    with col1:
        degree_p = st.number_input('Enter Percentage', min_value=0.0, max_value=100.0, key='degree_p')
    with col2:
        degree_t = st.selectbox('Select Type', ['Comm&Mgmt', 'Sci&Tech', 'Others'], key='degree_t')

        # Work Experience
    workex = st.selectbox('Work Experience', ['Yes', 'No'])

    # E-test Percentage
    etest_p = st.number_input('Enter E-test Percentage', min_value=0.0, max_value=100.0)

    # Specialization
    specialisation = st.selectbox('Select Specialization', ['Mkt&HR', 'Mkt&Fin'])

    # MBA Percentage
    mba_p = st.number_input('Enter MBA Percentage', min_value=0.0, max_value=100.0)

if degree_t == 'Others':
    degree_t = 'Others1'

# Create a dictionary with user inputs
user_input = {
    'gender': gender,
    'ssc_p': ssc_p,
    'ssc_b': ssc_b,
    'hsc_p': hsc_p,
    'hsc_b': hsc_b,
    'hsc_s': hsc_s,
    'degree_t':degree_t,
    'workex': workex,
    'etest_p': etest_p,
    'specialisation': specialisation,
    'mba_p': mba_p,
    'degree_p': degree_p,

}

# Define a function to preprocess user input
def preprocess_user_input(input_data):
    # Create a dictionary to map user input to label-encoded values for categorical features
    label_encoding_mapping = {
        'Male': 0,
        'Female': 1,
        'Central': 0,
        'Others': 1,
        'Science': 0,
        'Commerce': 1,
        'Arts': 2,
        'Yes': 1,
        'No': 0,
        'Mkt&HR': 0,
        'Mkt&Fin': 1,
        'Comm&Mgmt':0,
        'Sci&Tech':1,
        'Others1':2
    }

    # Label encode categorical features
    for feature in ['gender', 'ssc_b', 'hsc_b', 'hsc_s', 'degree_t','workex', 'specialisation']:
        input_data[feature] = label_encoding_mapping.get(input_data[feature])

    return input_data

# Create a button to make predictions
if st.button("Make Prediction"):
    # Preprocess user input
    preprocessed_input = preprocess_user_input(user_input)

    # Extract the values from the dictionary
    input_values = list(preprocessed_input.values())

    # Call the make_prediction function with the input values
    recruitment_status = predict(status_model, [input_values])
    if recruitment_status==1:
        # Calculate salary only if status is "Placed"
        salary_prediction = predict(salary_model,[input_values])
        rounded_salary = round(salary_prediction / 1000) * 1000
        lower_range = rounded_salary - 1000
        upper_range = rounded_salary + 1000
        st.balloons()
        succes = st.success(f"ðŸŽ‰Congratulations! {name} has high chances of getting PLACED! ðŸŽ‰")
        time.sleep(3)
        succes.empty()
        # Display the prediction
        st.write("Result Predicted: SUCCESSFULL")

        st.write(f"Salary Prediction: {lower_range} to {upper_range}")
    else:
        st.write("Result Predicted: NOT SUCCESSFULL")
        st.write("ðŸ˜” Sorry, you are not placed.")
else:
    # Display a neutral message when the button is not clicked
    st.write("Click the 'Make Prediction' button to check your placement status.")


#
# https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/
# Medium
# Topics: Hash Table, Tree, Depth-First Search, Breadth-First Search, Counting
#
# This is a graph traversal problem. We'll choose Depth-First Search as the search to use. A key detail to note
# is that these are undirected graphs. This becomes important because a graph with edges defined as follows:
#
# {{0, 2}, {0, 3}, {1, 2}}
#
# if one was ignoring the unidirection, would look like
#
# 1   0
#  \ / \
#   2   3
#
# which is wrong, it actually looks like this
#
#     0
#    / \
#   2   3
#  /
# 1
#
# As we build our adjacency list, we need to add both edges to the adjacency list.
#
# Time Complexity: O(n), O(26n) -> O(n)
# Space Complexity: O(n), O(26n) -> O(n)
#
# Breadth-First Search may also be employed here. When used, we will be moving bottom up, as opposed to top to bottom, as we traditionally do.
# This way, as we move upwards, we can populate the results. To do this, we need to isolate all leafs. As we work upwards, we will be pruning our
# leafs, which in turn will create more leafs that we will need to process.
#
# Time Complexity: O(n), O(26n) -> O(n)
# Space Complexity: O(n), O(26n) -> O(n)
#

from collections import Counter
from collections import defaultdict
from typing import Dict
from typing import List

import unittest

BRUTE = False

if BRUTE:
    class Solution:
        def dfs(self, node: int, parent: int, adj: Dict[int, List[int]], labels: str, results: List[int]):
            counts: List[int] = [0] * 26
            counts[ord(labels[node]) - ord('a')] = 1
            for child in adj[node]:
                if child == parent:
                    continue
                totals = self.dfs(child, node, adj, labels, results)
                for i in range(26):
                    counts[i] += totals[i]
            results[node] = counts[ord(labels[node]) - ord('a')]
            return counts

        def countSubTrees(self, n: int, edges: List[List[int]], labels: str):
            adj: Dict[int, List[int]] = defaultdict(list)
            for e in edges:
                adj[e[0]].append(e[1])
                adj[e[1]].append(e[0])

            results = [0] * n
            self.dfs(0, -1, adj, labels, results)
            return results
else:
    class Solution:
        def dfs(self, node: int, parent: int, adj: Dict[int, List[int]], labels: str, results: List[int]):
            counts = Counter()
            for child in adj[node]:
                if child == parent:
                    continue
                counts += self.dfs(child, node, adj, labels, results)
            counts[labels[node]] += 1
            results[node] = counts[labels[node]]
            return counts

        def countSubTrees(self, n: int, edges: List[List[int]], labels: str):
            adj: Dict[int, List[int]] = defaultdict(list)
            for e in edges:
                adj[e[0]].append(e[1])
                adj[e[1]].append(e[0])

            results = [0] * n
            self.dfs(0, -1, adj, labels, results)
            return results

class TestSolution(unittest.TestCase):
    def setUp(self):
        self.soln = Solution()

    def test_case0(self):
        edges0: List[List[int]] = [[0, 1], [0, 2], [1, 4], [1, 5], [2, 3], [2, 6]]
        labels0 = "abaedcd"
        self.assertEqual(self.soln.countSubTrees(7, edges0, labels0), [2, 1, 1, 1, 1, 1, 1])

    def test_case1(self):
        edges1: List[List[int]] = [[0, 1], [1, 2], [0, 3]]
        labels1 = "bbbb"
        self.assertEqual(self.soln.countSubTrees(4, edges1, labels1), [4, 2, 1, 1])

    def test_case2(self):
        edges2: List[List[int]] = [[0, 2], [0, 3], [1, 2]]
        labels2 = "aeed"
        self.assertEqual(self.soln.countSubTrees(4, edges2, labels2), [1, 1, 2, 1])


#!/usr/bin/env python3

from ..day05.intCode import Processor
from collections import defaultdict, deque, namedtuple
from os import path

Point = namedtuple('Point', ['x', 'y'])

LEFT  = 0
RIGHT = 1

BLACK = 0
WHITE = 1

NORTH = 0
WEST  = 1
SOUTH = 2
EAST  = 3

class Robot:
  def __init__(self, code):
    self.brains = Processor(code, [])
    self.cells = defaultdict(int)
    self.orientation = NORTH

  def start(self):
    unique_cells_painted, x, y, first_run = 0, 0, 0, True
    res = self.brains.process()
    try:
      while True:
        cell_color = self.cells[(x,y)]
        self.brains.add_input(1 if first_run else cell_color)
        paint, rotate = next(res), next(res)
        self.cells[(x,y)] = paint
        self.orientation = (self.orientation + rotate * 2 - 1) % 4
        x += (0, 1, 0, -1)[self.orientation]
        y += (-1, 0, 1, 0)[self.orientation]
    except StopIteration:
      pass
    return len(self.cells.keys())

  def paint(self):
    min_x, min_y, max_x, max_y = 0, 0, 0, 0
    for x, y in self.cells.keys():
      min_x, min_y, max_x, max_y = min(min_x, x), min(min_y, y), max(max_x, x), max(max_y, y)

    width, height = max_x - min_x + 1, max_y - min_y + 1
    grid = [[' ' for i in range(width)] for j in range(height)]

    for x in range(width):
      for y in range(height):
        grid[abs(min_y-y)][abs(min_x-x)] = '#' if self.cells[(x,y)] == 1 else ' '

    for r in grid:
      print(''.join(r))

def get_inputs(file='testinput11.txt'):
  with open(path.join(path.dirname(__file__), file), 'r+') as f:
    return [int(c) for c in f.readline().rstrip('\r').rstrip('\n').split(',') ]

if __name__ == '__main__':
  r = Robot(get_inputs('input11.txt'))
  print(f'Unique cells painted: {r.start()}')
  r.paint()


from models.layers import mean_pooling, BiAttention, LSTMWrapper, GatedAttention
from jdmodels.jdlayers import GraphBlock, encoder_graph_node_feature, PredictionLayer, ParaSentEntPredictionLayer
from torch import nn

class HierarchicalGraphNetwork(nn.Module):
    """
    Packing Query Version
    """
    def __init__(self, config):
        super(HierarchicalGraphNetwork, self).__init__()
        self.config = config
        self.max_query_length = self.config.max_query_length

        self.bi_attention = BiAttention(input_dim=config.input_dim,
                                        memory_dim=config.input_dim,
                                        hid_dim=config.hidden_dim,
                                        dropout=config.bi_attn_drop)
        self.bi_attn_linear = nn.Linear(config.hidden_dim * 4, config.hidden_dim)
        self.hidden_dim = config.hidden_dim
        self.sent_lstm = LSTMWrapper(input_dim=config.hidden_dim,
                                     hidden_dim=config.hidden_dim,
                                     n_layer=1,
                                     dropout=config.lstm_drop) ### output: 2 * self.hidden_dim

        q_dim = self.hidden_dim if config.q_update else config.input_dim
        self.q_map = nn.Linear(in_features=q_dim, out_features=self.hidden_dim * 2)
        if self.q_map:
            nn.init.xavier_uniform_(self.q_map.weight, gain=1.414)

        self.graph_blocks = nn.ModuleList()
        self.graph_blocks.append(GraphBlock(self.config.q_attn, config, input_dim=self.hidden_dim * 2, hidden_dim=self.hidden_dim))
        for _ in range(self.config.num_gnn_layers-1):
            self.graph_blocks.append(GraphBlock(self.config.q_attn, config, input_dim=self.hidden_dim, hidden_dim=self.hidden_dim))

        self.ctx_attention = GatedAttention(input_dim=config.hidden_dim*2,
                                            memory_dim=config.hidden_dim,
                                            hid_dim=self.config.ctx_attn_hidden_dim,
                                            dropout=config.bi_attn_drop,
                                            gate_method=self.config.ctx_attn)
        self.para_sent_ent_predict_layer = ParaSentEntPredictionLayer(self.config, hidden_dim=self.hidden_dim)
        self.predict_layer = PredictionLayer(self.config)

    def forward(self, batch, return_yp):
        query_mapping = batch['query_mapping']
        context_encoding = batch['context_encoding']
        # extract query encoding
        trunc_query_mapping = query_mapping[:, :self.max_query_length].contiguous()
        trunc_query_state = (context_encoding * query_mapping.unsqueeze(2))[:, :self.max_query_length, :].contiguous()
        # bert encoding query vec
        query_vec = mean_pooling(trunc_query_state, trunc_query_mapping)
        attn_output, trunc_query_state = self.bi_attention(context_encoding,
                                                           trunc_query_state,
                                                           trunc_query_mapping)
        input_state = self.bi_attn_linear(attn_output) # N x L x d
        input_state = self.sent_lstm(input_state, batch['context_lens'])
        if self.config.q_update:
            query_vec = mean_pooling(trunc_query_state, trunc_query_mapping)

        query_vec = self.q_map(query_vec)
        ################################################################################################################
        graph_state_dict = encoder_graph_node_feature(batch=batch, input_state=input_state, hidden_dim=self.hidden_dim)
        graph_state, graph_mask = None, None
        ################################################################################################################
        for l in range(self.config.num_gnn_layers):
            graph_state, graph_state_dict, graph_mask, query_vec = self.graph_blocks[l](batch=batch,
                                                                                graph_state_dict=graph_state_dict,
                                                                                query_vec=query_vec)
        input_state, _ = self.ctx_attention(input_state, graph_state, graph_mask.squeeze(-1))
        para_logit, sent_logit, ent_logit = self.para_sent_ent_predict_layer.forward(batch=batch,
                                                                                graph_state_dict=graph_state_dict,
                                                                                query_vec=query_vec)
        predictions = self.predict_layer(batch, input_state, sent_logit, packing_mask=query_mapping,
                                         return_yp=return_yp)
        if return_yp:
            start, end, q_type, yp1, yp2 = predictions
            return start, end, q_type, para_logit, sent_logit, ent_logit, yp1, yp2
        else:
            start, end, q_type = predictions
            return start, end, q_type, para_logit, sent_logit, ent_logit


# Сериализация класса
#
# Ваша задача научить классы конвертиться к json-строке
# при помощи миксина под названием JsonSerializableMixin,
# который добавляет метод to_json() в любой класс,
# использующий этот миксин. Метод to_json() конвертирует
# словарь атрибутов экземпляра в строку JSON, используя
# стандартную библиотеку json в Python.

import json

class JsonSerializableMixin:

    def to_json(self):

        return json.dumps(self.__dict__)

# Ниже код для проверки миксина JsonSerializableMixin
class Car(JsonSerializableMixin):
    def __init__(self, make: str, color: str):
        self.make = make
        self.color = color

class Book(JsonSerializableMixin):
    def __init__(self, title: str, author: str):
        self.title = title
        self.author = author

class Person(JsonSerializableMixin):
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

car = Car("Toyota", "red")
assert car.to_json() == '{"make": "Toyota", "color": "red"}'

book = Book("The Catcher in the Rye", "J.D. Salinger")
assert book.to_json() == '{"title": "The Catcher in the Rye", "author": "J.D. Salinger"}'
book.ratings = [5, 4, 5, 4, 5]
book.is_bestseller = True
book.to_json() == '{"title": "The Catcher in the Rye", "author": "J.D. Salinger", "ratings": [5, 4, 5, 4, 5], "is_bestseller": true}'

person = Person("John", 30)
assert person.to_json() == '{"name": "John", "age": 30}'
print('Good')