##___________________Library_____________________##

import telebot
import time
import json
import requests
import pandas as pd
from datetime import datetime
import random
import numpy as np
import os
import sys
from flask import Flask, request

##___________________Bot_Confirmation______________________##

token = "1349348866:AAG3VD_SkxlHIltZl0gRw4LHd6hnmpla15o"

bot = telebot.TeleBot(token)
server = Flask(__name__)

##____________________User_Details_________________________##

user_details = {}
feedback_reply = {}

class Job:
    def __init__(self, job_field):
        self.job_field = job_field
        self.location = None
        self.company = None

##_____________________Job_Search__________________________##

def search_jobs(job, location_given, company_given, id):
    if job.lower() == "na":
        job = ""
    if location_given.lower() == "na":
        location_given = ""
    if company_given.lower() == "na":
        company_given = ""
    job=job.replace(" ", "%20")
    location_given=location_given.replace(" ", "%20")
    company_given=company_given.replace(" ", "%20")
    urls = f"http://15.206.63.193:5000/db/main?tsearch={job}&lsearch={location_given}&csearch={company_given}&dept=&"
    req = requests.get(urls)
    job_list = json.loads(req.content)
    job_details(job_list, id)

def job_details(job_list, id):
    if len(job_list["result"]) == 0:
        bot.send_message(id, "Sorry no new jobs available, please try again later.")
    else:
        try:
            bot.send_message(id, "Here are latest jobs for you!")
            for i in range(0, 15):
                try:
                    comp = job_list["result"][i]["Company"]
                    loc = job_list["result"][i]["Location"]
                    title = job_list["result"][i]["Title"]
                    indus = job_list["result"][i]["Industry"]
                    link = job_list["result"][i]["URL"]
                    bot.send_message(id, f"ðŸŸ  *Company*: {comp}\n*ðŸŸ¡ Title*: {title}\n*ðŸŸ¢ Industry*: {indus}\n*ðŸ”µ Location*: {loc}\n"
                    f"\n\n*ðŸŸ£ Link*:\n{link}", parse_mode="Markdown")
                except:
                    pass
        except:
            pass
        bot.send_message(id, "Type *Update* to update jobs.", parse_mode="Markdown")
    return True

##___________________________/start____________________________##

@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.reply_to(message, "Welcome to the Job searching bot! \nðŸ”´ Type */start* to start again.\nðŸ”´ Type *Update* to update jobs.\n"
    "ðŸ”´ Type *About* to know about this bot.\nðŸ”´ Type *Help* for help.\nðŸ”´ Type *Feedback* to give a feedback.\nðŸ”´ Type *Donate* to donate and show your support ðŸ˜Š"
    "\nðŸ”´ For advertisement or commercial purpose send mail to: job.finding.bot@gmail.com", parse_mode="Markdown")
    owner_id = 872448274
    chat_id = message.chat.id
    now = datetime.now()
    dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
    df_read = pd.read_csv(os.path.join(sys.path[0],"customer_list.csv"))
    user_id = df_read.to_dict("records")
    nme = [message.from_user.first_name]
    if message.from_user.username==None:
        usrnme = ["Na"]
    else:
        usrnme = [message.from_user.username]
    chtid = [chat_id]
    rgst_on = [dt_string]
    lst_usd = [0]
    lst_job = ["Na"]
    lst_loc = ["Na"]
    lst_comp = ["Na"]
    subs = [1]
    dic = {"Name": nme, "Username": usrnme, "Chat_ID": chtid, "Registered_On": rgst_on, "Last_Used": lst_usd,
    "Last_Job": lst_job, "Last_Location": lst_loc, "Last_Company": lst_comp, "Subscription": subs}
    temp_list=[]
    for i in range(len(user_id)):
        temp_list.append(user_id[i]["Chat_ID"])
    for i in chtid:
        if i not in temp_list:
            print("Added")
            df = pd.DataFrame(dic)
            df.to_csv(os.path.join(sys.path[0],"customer_list.csv"), mode= 'a', header=False, index = False)
            bot.send_message(owner_id, f"New data added\nName: {message.from_user.first_name}\nUser name: {message.from_user.username}\nChat ID: {chat_id}"
            "\n\nCheck list: /customer_list\n\nSend ad: /send_ad\nAnnouncement: /announce")
    bot.send_message(chat_id, "*Note*: You can pause your subscription by typing /off.", parse_mode="Markdown")

##______________________/list_____________________________##

@bot.message_handler(commands=["list"])
def list_command(message):
    owner_id = 872448274
    chat_id = message.chat.id
    if chat_id == owner_id:
        bot.send_message(owner_id, "List of commands:\n/start: For start menu\n/off: To pause subscription\n/on: To resume subscription\n"
        "/send_ad: To send ad\n/announce: For announcement\n/customer_list: For customer list\n/reply_feedback: To reply a feedback\nKey: 58789")
    else:
        bot.send_message(chat_id, "Access Denied!")

##_______________________/off_____________________________##

@bot.message_handler(commands=["off"])
def off_subs(message):
    chat_id = message.chat.id
    df_read = pd.read_csv(os.path.join(sys.path[0],"customer_list.csv"))
    li = df_read.loc[df_read["Chat_ID"]== chat_id, "Subscription"]
    if li.array[0] != 0:
        bot.send_message(chat_id, "ðŸ”´ We have *paused* your subscription that means you will not recieve any notificaion, update or notice from us. You will not be able to update jobs too. "
        "If possible please state your reason to pause subscription by typing *Feedback*, that will help us a lot. You can resume your subscription any time by typing /on.", parse_mode="Markdown")
        df_read.loc[df_read["Chat_ID"]== chat_id, "Subscription"] = 0
        df_read.to_csv(os.path.join(sys.path[0],"customer_list.csv"), index=False)
    else:
        bot.send_message(chat_id, "Your subscription is already paused, resume it anytime by typing /on")

##_______________________/on___________________________##

@bot.message_handler(commands=["on"])
def on_subs(message):
    chat_id = message.chat.id
    df_read = pd.read_csv(os.path.join(sys.path[0],"customer_list.csv"))
    li = df_read.loc[df_read["Chat_ID"]== chat_id, "Subscription"]
    if li.array[0] != 1:
        bot.send_message(chat_id, "ðŸ”´ Welcome back! We are glad to see you again. We have *resumed* your subscription. You are now able to recieve lastest "
        "job updates by typing *Update*. Type /start to see menu.", parse_mode="Markdown")
        df_read.loc[df_read["Chat_ID"]== chat_id, "Subscription"] = 1
        df_read.to_csv(os.path.join(sys.path[0],"customer_list.csv"), index=False)
    else:
        bot.send_message(chat_id, "Your subscription is already active!")

##_________________________/send_ad__________________________##

@bot.message_handler(commands=["send_ad"])
def ask_ad(message):
    owner_id = 872448274
    msg = bot.send_message(owner_id, "Enter the *key* value", parse_mode="Markdown")
    bot.register_next_step_handler(msg, ad_key)

def ad_key(message):
    owner_id = 872448274
    key = message.text
    if key == "58789":
        msg = bot.send_message(owner_id, "Enter the number of people you want to send ad(write *All* if you want to send message to everyone), "
        "advertisement image location(with '\\' instead of '\') and advertisement "
        "text/link separated by *#*", parse_mode="Markdown")
        bot.register_next_step_handler(msg, send_adv)
    else:
        chat_id = message.chat.id
        bot.send_message(chat_id, "Wrong key!", parse_mode="Markdown")
        bot.send_message(owner_id, f"Advertisement access denied to: {message.from_user.first_name}\n{message.from_user.username}\n{chat_id}")

def send_adv(message):
    owner_id = 872448274
    try:
        ad = message.text
        ad_list=ad.split("#")
        df_read = pd.read_csv(os.path.join(sys.path[0],"customer_list.csv"))
        user_id = df_read.to_dict("records")
        temp_list=[]
        for i in range(len(user_id)):
            temp_list.append(int(user_id[i]["Chat_ID"]))
        if str(ad_list[0]).lower()=="all":
            for i in temp_list:
                photo = open(ad_list[1], "rb")
                li = df_read.loc[df_read["Chat_ID"]== i, "Subscription"]
                if li.array[0] == 1:
                    bot.send_photo(i, photo, caption= ad_list[2])
        else:
            random.shuffle(temp_list)
            for i in range(int(ad_list[0])):
                try:
                    photo = open(ad_list[1], "rb")
                    li = df_read.loc[df_read["Chat_ID"]== temp_list[i], "Subscription"]
                    if li.array[0] == 1:
                        bot.send_photo(temp_list[i], photo, caption= ad_list[2])
                        bot.send_message(owner_id, temp_list[i])
                except:
                    pass
        bot.send_message(owner_id, "Process of sending ad: Complete")
    except Exception as e:
        bot.send_message(owner_id, e)

##______________________/announce_____________________________##

@bot.message_handler(commands=['announce'])
def send_announcement(message):
    owner_id = 872448274
    msg = bot.send_message(owner_id, "Enter the *key* value", parse_mode="Markdown")
    bot.register_next_step_handler(msg, announce_key)

def announce_key(message):
    owner_id = 872448274
    key = message.text
    if key == "58789":
        msg = bot.send_message(owner_id, "Enter your announcement. This message will be sent to everyone.", parse_mode="Markdown")
        bot.register_next_step_handler(msg, announce)
    else:
        chat_id = message.chat.id
        bot.send_message(chat_id, "Wrong key!", parse_mode="Markdown")
        bot.send_message(owner_id, f"Announcement denied to: {message.from_user.first_name}\n{message.from_user.username}\n{chat_id}")

def announce(message):
    owner_id = 872448274
    try:
        ann = message.text
        df_read = pd.read_csv(os.path.join(sys.path[0],"customer_list.csv"))
        user_id = df_read.to_dict("records")
        temp_list=[]
        for i in range(len(user_id)):
            temp_list.append(int(user_id[i]["Chat_ID"]))
        for i in temp_list:
            li = df_read.loc[df_read["Chat_ID"]== i, "Subscription"]
            if li.array[0] == 1:
                bot.send_message(i, ann)
        bot.send_message(owner_id, "Process of announcement: Complete")
    except Exception as e:
        bot.send_message(owner_id, e)

##_______________________/customer_list_____________________________##

@bot.message_handler(commands=['customer_list'])
def check_customer(message):
    owner_id = 872448274
    msg = bot.send_message(owner_id, "Enter the *key* value", parse_mode="Markdown")
    bot.register_next_step_handler(msg, list_key)

def list_key(message):
    owner_id = 872448274
    key = message.text
    if key == "58789":
        bot.send_document(owner_id, open(os.path.join(sys.path[0],"customer_list.csv"), "rb"))
    else:
        chat_id = message.chat.id
        bot.send_message(chat_id, "Wrong key!", parse_mode="Markdown")
        bot.send_message(owner_id, f"Customer list access denied to: {message.from_user.first_name}\n{message.from_user.username}\n{chat_id}")

##__________________________/reply_feedback__________________________##

@bot.message_handler(commands=['reply_feedback'])
def replyfeedback(message):
    owner_id = 872448274
    msg = bot.send_message(owner_id, "Enter the *key* value", parse_mode="Markdown")
    bot.register_next_step_handler(msg, feedback_key)

def feedback_key(message):
    owner_id = 872448274
    key = message.text
    if key == "58789":
        msg = bot.send_message(owner_id, "Enter the chat id and feedback separated by *#*", parse_mode="Markdown")
        bot.register_next_step_handler(msg, feedback_message)
    else:
        chat_id = message.chat.id
        bot.send_message(chat_id, "Wrong key!", parse_mode="Markdown")
        bot.send_message(owner_id, f"Feedback access denied to: {message.from_user.first_name}\n{message.from_user.username}\n{chat_id}")

def feedback_message(message):
    feedback = message.text
    feedback_list=feedback.split("#")
    bot.send_message(feedback_list[0], feedback_list[1])

##________________________Hi__________________________##

@bot.message_handler(func=lambda msg: msg.text is not None and ("hi" in msg.text.lower() or "hey" in msg.text.lower() or "hei" in msg.text.lower() or "hello" in msg.text.lower()))
def send_hi(message):
    chat_id = message.chat.id
    df_read = pd.read_csv(os.path.join(sys.path[0],"customer_list.csv"))
    li = df_read.loc[df_read["Chat_ID"]== chat_id, "Subscription"]
    if li.array[0] == 1:
        bot.reply_to(message, "Welcome to the Job searching bot! \nðŸ”´ Type */start* to start again.\nðŸ”´ Type *Update* to update jobs.\n"
        "ðŸ”´ Type *About* to know about this bot.\nðŸ”´ Type *Help* for help.\nðŸ”´ Type *Feedback* to give a feedback.\nðŸ”´ Type *Donate* to donate and show your support ðŸ˜Š", parse_mode="Markdown")
    else:
        bot.send_message(chat_id, "You have paused your subscription, please type /on to resume it.")

##____________________Feedback__________________________##

@bot.message_handler(func=lambda msg: msg.text is not None and "feedback" in msg.text.lower())
def send_feedback(message):
    chat_id = message.chat.id
    msg = bot.send_message(chat_id, "Please start writing your feedback. Try to write your feedback in a single message.* The bot will accept only one single message"
    " as a feedback.*", parse_mode="Markdown")
    bot.register_next_step_handler(msg, feedback_thanks)

def feedback_thanks(message):
    chat_id = message.chat.id
    try:
        owner_id = 872448274
        feedback = message.text
        bot.send_message(owner_id, f"Name: {message.from_user.first_name}\nUsername: {message.from_user.username}\nChat ID: {chat_id}\n\nFeedback: {feedback}\nType: /reply_feedback")
        bot.send_message(chat_id, "Thank you for your feedback ðŸ˜Š. We have recorded your feedback and will surely check it and work on it.")
    except:
        bot.send_message(chat_id, "Something went wrong, please try again later.")

##______________________Help________________________##

@bot.message_handler(func=lambda msg: msg.text is not None and "help" in msg.text.lower())
def send_help(message):
    bot.reply_to(message, "To use this bot type *Update*. The bot will ask about your prefered Job title, Location and Company. "
    "Type *Na* if you don't have any preferable Job title, Location or Company."
    "For any complain or suggestion please write a feedback by typing *Feedback*.", parse_mode="Markdown")

##________________________About______________________##

@bot.message_handler(func=lambda msg: msg.text is not None and "about" in msg.text.lower())
def send_about(message):
    bot.reply_to(message, "This is a telegram bot to give latest job update created by me (I'm not going to disclose my name here ðŸ˜…). "
    "It searches jobs from following websites: \nLinkedin, Naukari, Monster India, Internshala, Time Jobs and Indeed \nand show best jobs here. The user can compare and apply to these jobs"
    " through the links. *Please don't Copyright this bot.* The sole purpose of this bot is to provide information about jobs and source link is provided with the jobs. "
    "Sometimes bot might not show results, this might occur due to some technical fault. In cases like this please inform us by writing a feedback. "
    "Write a feedback by typing *Feedback* if you have any question or complain.", parse_mode="Markdown")

##____________________Thanks_____________________##

@bot.message_handler(func=lambda msg: msg.text is not None and ("thank" in msg.text.lower() or "thanks" in msg.text.lower() or "thankyou" in msg.text.lower()))
def send_greetings(message):
    bot.reply_to(message, "Welcome ðŸ˜Š. You can update jobs again by typing *Update*.", parse_mode="Markdown")

##_________________Donation_______________________##
##Work_Left

@bot.message_handler(func=lambda msg: msg.text is not None and ("donation" in msg.text.lower() or "donate" in msg.text.lower() or "pay" in msg.text.lower()))
def send_donation(message):
    owner_id = 872448274
    bot.reply_to(message, "Thank you for your support, we will add a donation link soon. ðŸ˜ŠðŸ˜Š", parse_mode="Markdown")
    bot.send_message(owner_id, f"Donation: {message.from_user.first_name}")

##_________________Update___________________##

@bot.message_handler(func=lambda msg: msg.text is not None and ("update" in msg.text.lower() or "new" in msg.text.lower() or "jobs" in msg.text.lower() or "job" in msg.text.lower() or "updated" in msg.text.lower()))
def send_update(message):
    chat_id = message.chat.id
    df_read = pd.read_csv(os.path.join(sys.path[0],"customer_list.csv"))
    li = df_read.loc[df_read["Chat_ID"]== chat_id, "Subscription"]
    if li.array[0] == 1:
        msg = bot.send_message(chat_id, "Please write your prefered Job field.\nExample: *Teaching*\n "
        "\nðŸ”´ If you don't have any prefarable Job field type *Na*", parse_mode="Markdown")
        bot.register_next_step_handler(msg, location)
    else:
        bot.send_message(chat_id, "You have paused your subscription, please type /on to resume it.")

def location(message):
    chat_id = message.chat.id
    try:
        jf = message.text
        try:
            if jf.lower() == "/start":
                send_welcome
        except:
            bot.send_message(chat_id, "Invalid input please try again.")
        user = Job(jf)
        user_details[chat_id] = user
        msg = bot.send_message(chat_id, "Please write your prefered Location.\nExample: *Kolkata*\n "
        "\nðŸ”´ If you don't have any prefarable Location type *Na*", parse_mode="Markdown")
        bot.register_next_step_handler(msg, company)
    except:
        bot.send_message(chat_id,"Something went wrong please try again.")

def company(message):
    chat_id = message.chat.id
    try:
        loc = message.text
        try:
            if loc.lower() == "/start":
                send_welcome
        except:
            bot.send_message(chat_id, "Invalid input please try again.")
        user = user_details[chat_id]
        user.location = loc
        msg = bot.send_message(chat_id, "Please write your prefered Company.\nExample: *Amazon*\n "
        "\nðŸ”´ If you don't have any prefarable Company type *Na*", parse_mode="Markdown")
        bot.register_next_step_handler(msg, at_answer)
    except:
        bot.send_message(chat_id,"Something went wrong please try again.")

def at_answer(message):
    chat_id = message.chat.id
    try:
        com = message.text
        try:
            if com.lower() == "/start":
                send_welcome
        except:
            bot.send_message(chat_id, "Invalid input please try again.")
        user = user_details[chat_id]
        user.company = com
        bot.send_message(chat_id, "Please wait I'm searching best jobs for you.")
        now = datetime.now()
        dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
        df_read = pd.read_csv(os.path.join(sys.path[0],"customer_list.csv"))
        df_read.loc[df_read["Chat_ID"]== chat_id, "Last_Used"] = dt_string
        df_read.loc[df_read["Chat_ID"]== chat_id, "Last_Job"] = user.job_field
        df_read.loc[df_read["Chat_ID"]== chat_id, "Last_Location"] = user.location
        df_read.loc[df_read["Chat_ID"]== chat_id, "Last_Company"] = user.company
        df_read.to_csv(os.path.join(sys.path[0],"customer_list.csv"), index = False)

        search_jobs(user.job_field, user.location, user.company, chat_id)
    except Exception as e:
        bot.send_message(chat_id, e)

##________________Bot_Run____________##

@server.route('/' + token, methods=['POST'])
def getMessage():
    bot.process_new_updates([telebot.types.Update.de_json(request.stram.read().decode("utf-8"))])
    return "!", 200

@server.route("/")
def webhook():
    bot.remove_webhook()
    bot.set_webhook(url="https://fast-brook-37232.herokuapp.com/" + token)
    return "!", 200

if __name__ == "__main__":
    server.run(host="0.0.0.0", port= int(os.environ.get("PORT", 5000)))


#!/usr/bin/env python3
"""
Convex Hull

@authors: Roman Yasinovskyy
@version: 2021.11
"""

def get_convex(filename: str) -> list:
    """
    Find points on the convex hull

    Calculate the result with p0 as the lowest-rightmost

    :param filename: name of a file with all all points
    :return: list of point in the correct order (starting with the rightmost-lowest)
    """
    with open(filename) as f:
        data = f.read().splitlines()

    idx = 0
    li = list()

    while idx < len(data):
        test = data[idx].split()
        if test[2] != "N":
            li.append(test[0:2])
        idx += 1

    for i in range(0, len(li)):
        for j in range(0, len(li[i])):
            li[i][j] = int(li[i][j])
    # print(li)
    li.sort()

    convex = list()
    convex.append(li[0])
    convex.append(li[1])

    def z(p1,p2,p3):
        return ((p2[0] - p1[0]) * (p3[1]-p1[1]))  - ((p2[1]-p1[1]) * (p3[0]-p1[0]))

    idx2 = 2

    while idx2 < len(li):
        while len(convex) > 1 and z(convex[-2], convex[-1], li[idx2]) < 0:
            li.append(convex.pop())
        convex.append(li[idx2])
        idx2 += 1

    return convex

def measure_convex(hull_points: list) -> float:
    """
    Calculate the length of the convex hull

    :param hull_points: all points on the convex hull in counter-clockwise order
    :return: length of the convex hull
    """
    idx = 0
    totaldistance = 0

    while idx < len(hull_points):
        first = hull_points[idx]

        if idx+1 >= len(hull_points):
            second = hull_points[0]

        else:
            second = hull_points[idx+1]

        totaldistance += (((second[0]-first[0])**2)+((second[1]-first[1])**2)) ** 0.5

        idx += 1

    # print(totaldistance)
    return totaldistance

def main():
    """Entry point"""
    print(f"{'file':20s}{'points':10s}{'length'}")
    for i in [1, 2, 3]:
        filename = f"convexhull{i}.in"
        hull_points = get_convex("data/projects/convexhull/" + filename)
        hull_length = measure_convex(hull_points)
        print(f"{filename:20s}{len(hull_points):<10d}{hull_length}")

if __name__ == "__main__":
    main()


import data
import question_model
import quiz_brain

question_bank = []

for question in data.question_data:
    q = question_model.Question(question["question"], question["correct_answer"])
    question_bank.append(q)

quiz = quiz_brain.QuizBrain(question_bank)

while quiz.still_has_questions():
    quiz.next_question()

print(
    f"You completed the quiz, your final score is: {quiz.score}/{quiz.total_questions}"
)


# coding: utf8
import csv
from datetime import datetime, timedelta
import os

class Plant:
    """Plant actions"""
    def __init__(self, db_entry, log_filename="Default"):
        self.log_filename = log_filename
        self.id = db_entry[0]
        self.type = db_entry[1]
        self.temperature = db_entry[2]
        self.location = db_entry[3]
        self.frequency = int(db_entry[4])
        self.webhook = db_entry[5]

    def log(self, data):
        with open(self.log_filename, "a+") as f:
                f.write("{}\n".format(data))

    def watering_need(self, current_date):
        """ Return last watering time if plant deserve water or None"""
        with open(self.log_filename, 'rb') as fh:
            for line in fh:
                pass
            last_watering = datetime.strptime(line.decode().rstrip(), "%Y-%m-%d")
            if (last_watering + timedelta(days=self.frequency)) < current_date:
                # Here we suppose that plants are gonna be watering ...
                # but we can't think about a better solution to check they are.
                # maybe Qrcode.
                self.log(datetime.strftime(current_date, "%Y-%m-%d"))
                return last_watering
        return None


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('conteudo', '0003_imagem_title'),
    ]

    operations = [
        migrations.AlterField(
            model_name='new',
            name='texto',
            field=models.TextField(null=True, verbose_name='Texto', blank=True),
        ),
    ]


from countryinfo import CountryInfo

from openstix.toolkit.filters.presets import LOCATION_FILTER
from openstix.objects import Relationship, Location
from openstix.toolkit.filters import Filter
from openstix.datasets._base import Dataset

REGION_FILTER = Filter("x_location_type", "=", "region")
SUBREGION_FILTER = Filter("x_location_type", "=", "sub-region")
COUNTRY_FILTER = Filter("x_location_type", "=", "country")
CITY_FILTER = Filter("x_location_type", "=", "city")

COMMON_PROPERTIES_VALUES = {
    "confidence": 100,
    "revoked": False,
    "allow_custom": True,
}

class GeoLocationsDataset(Dataset):

    source = "geolocations"
    files = None

    def regions(self):
        return self._query([LOCATION_FILTER, REGION_FILTER])

    def region(self, region):
        region_filter = [LOCATION_FILTER, REGION_FILTER, Filter("region", "=", region)]
        return self._query_one(region_filter)

    def subregions(self):
        return self._query([LOCATION_FILTER, SUBREGION_FILTER])

    def subregion(self, subregion):
        subregion_filter = [LOCATION_FILTER, SUBREGION_FILTER, Filter("region", "=", subregion)]
        return self._query_one(subregion_filter)

    def countries(self):
        return self._query([LOCATION_FILTER, COUNTRY_FILTER])

    def country(self, country):
        country_filter = [LOCATION_FILTER, COUNTRY_FILTER, Filter("country", "=", country)]
        return self._query_one(country_filter)

    def cities(self):
        return self._query([LOCATION_FILTER, CITY_FILTER])

    def city(self, city):
        city_filter = [LOCATION_FILTER, CITY_FILTER, Filter("city", "=", city)]
        return self._query_one(city_filter)

    def load(self):
        for key in CountryInfo().all():

            item = CountryInfo(key).info()

            region = None
            subregion = None
            country = None
            capital = None

            if "region" in item and item["region"] != "":
                region = self.workspace.create(
                    Location,
                    name=item["region"],
                    region=item["region"],
                    x_location_type="region",
                    **COMMON_PROPERTIES_VALUES,
                )

            if "subregion" in item and item["subregion"] != "":
                subregion = self.workspace.create(
                    Location,
                    name=item["subregion"],
                    region=item["subregion"],
                    x_location_type="sub-region",
                    **COMMON_PROPERTIES_VALUES,
                )

            if region and subregion:
                self.workspace.create(
                    Relationship,
                    relationship_type="located-at",
                    source_ref=subregion.id,
                    target_ref=region.id,
                    **COMMON_PROPERTIES_VALUES,
                )

            if "name" in item and item["name"] != "" and "ISO" in item and item["ISO"]["alpha2"] != "":
                latitude, longitude = None, None
                if "latlng" in item:
                    latitude = item["latlng"][0]
                    longitude = item["latlng"][1]

                # WORKAROUND: https://github.com/oasis-open/cti-python-stix2/issues/572
                if latitude == 0:
                    latitude = 0.01
                if longitude == 0:
                    longitude = 0.01

                country = self.workspace.create(
                    Location,
                    name=item["name"],
                    country=item["ISO"]["alpha2"],
                    latitude=latitude,
                    longitude=longitude,
                    x_location_type="country",
                    **COMMON_PROPERTIES_VALUES,
                )

            if country and region:
                self.workspace.create(
                    Relationship,
                    relationship_type="located-at",
                    source_ref=country.id,
                    target_ref=region.id,
                    **COMMON_PROPERTIES_VALUES,
                )

            if country and subregion:
                self.workspace.create(
                    Relationship,
                    relationship_type="located-at",
                    source_ref=country.id,
                    target_ref=subregion.id,
                    **COMMON_PROPERTIES_VALUES,
                )

            if "capital" in item and item["capital"] != "":
                latitude, longitude = None, None
                if "capital_latlng" in item:
                    latitude = item["capital_latlng"][0]
                    longitude = item["capital_latlng"][1]

                # WORKAROUND: https://github.com/oasis-open/cti-python-stix2/issues/572
                if latitude == 0:
                    latitude = 0.01
                if longitude == 0:
                    longitude = 0.01

                capital = self.workspace.create(
                    Location,
                    name=item["capital"],
                    city=item["capital"],
                    latitude=latitude,
                    longitude=longitude,
                    country=item["ISO"]["alpha2"],
                    x_location_type="city",
                    **COMMON_PROPERTIES_VALUES,
                )

            if country and capital:
                self.workspace.create(
                    Relationship,
                    relationship_type="located-at",
                    source_ref=capital.id,
                    target_ref=country.id,
                    **COMMON_PROPERTIES_VALUES,
                )

            if "provinces" in item:
                for _province in item["provinces"]:

                    if _province == "":
                        continue

                    province = self.workspace.create(
                        Location,
                        name=_province,
                        city=_province,
                        country=item["ISO"]["alpha2"],
                        x_location_type="city",
                        **COMMON_PROPERTIES_VALUES,
                    )

                    if not country:
                        continue

                    self.workspace.create(
                        Relationship,
                        relationship_type="located-at",
                        source_ref=province.id,
                        target_ref=country.id,
                        **COMMON_PROPERTIES_VALUES,
                    )


from aiogram import Bot, Dispatcher, types
from config import Config

bot = Bot(Config.TOKEN)
dp = Dispatcher(bot)

@dp.message_handler()
async def echo(message: types.Message):
    await message.answer(message.text)


import gc
import os
import shutil
from pathlib import Path
from typing import Dict

import torch
from tqdm import tqdm

# code taken from  https://github.com/Lightning-AI/lit-llama
def convert_state_dict(state_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
    converted = {}
    converted["transformer.wte.weight"] = state_dict["tok_embeddings.weight"]
    converted["lm_head.weight"] = state_dict["output.weight"]
    converted["transformer.ln_f.scale"] = state_dict["norm.weight"]

    for key in [k for k in state_dict if k.startswith("layers")]:
        layer_idx = key.split(".")[1]

        # attention
        # the wq, wk, wv from the FB model are stacked in our model as c_attn
        converted[f"transformer.h.{layer_idx}.attn.c_attn.weight"] = torch.cat(
            (
                state_dict[f"layers.{layer_idx}.attention.wq.weight"],
                state_dict[f"layers.{layer_idx}.attention.wk.weight"],
                state_dict[f"layers.{layer_idx}.attention.wv.weight"],
            )
        )
        converted[f"transformer.h.{layer_idx}.attn.c_proj.weight"] = state_dict[
            f"layers.{layer_idx}.attention.wo.weight"
        ]
        # mlp
        converted[f"transformer.h.{layer_idx}.mlp.c_fc1.weight"] = state_dict[
            f"layers.{layer_idx}.feed_forward.w1.weight"
        ]
        converted[f"transformer.h.{layer_idx}.mlp.c_proj.weight"] = state_dict[
            f"layers.{layer_idx}.feed_forward.w2.weight"
        ]
        converted[f"transformer.h.{layer_idx}.mlp.c_fc2.weight"] = state_dict[
            f"layers.{layer_idx}.feed_forward.w3.weight"
        ]
        # rms norm
        converted[f"transformer.h.{layer_idx}.rms_1.scale"] = state_dict[f"layers.{layer_idx}.attention_norm.weight"]
        converted[f"transformer.h.{layer_idx}.rms_2.scale"] = state_dict[f"layers.{layer_idx}.ffn_norm.weight"]
    return converted

shard_dims = {
    "lm_head.weight": 0,
    "wte.weight": 1,
    "attn.c_attn.weight": 0,
    "attn.c_proj.weight": 1,
    "mlp.c_fc1.weight": 0,
    "mlp.c_fc2.weight": 0,
    "mlp.c_proj.weight": 1
}

def meta_weights_for_nano_model(
    *,
    output_dir: Path = Path("checkpoints/lit-llama"),
    ckpt_dir: Path = Path("checkpoints/llama/"),
    tokenizer_path: Path = Path("checkpoints/llama/tokenizer.model"),
    model_size: str = "7B",
) -> None:
    output_dir = output_dir / model_size
    ckpt_dir = ckpt_dir
    os.makedirs(output_dir, exist_ok=True)

    # the tokenizer is the same for all model sizes, so we store it in the parent dir
    if "tokenizer.model" not in os.listdir(output_dir.parent):
        shutil.copy(tokenizer_path, output_dir.parent)

    checkpoint_files = sorted(ckpt_dir.glob("*.pth"))
    checkpoint_files.sort()
    n_checkpoints = len(checkpoint_files)

    # for the bigger models, there are multiple model-parallel checkpoints
    # and we combine them into one single file
    combined = None
    for file in tqdm(checkpoint_files, total=n_checkpoints):
        checkpoint = torch.load(file, map_location="cpu")
        converted = convert_state_dict(checkpoint)
        if combined is None:
            combined = converted
            continue
        for name, param in converted.items():
            dim = None
            for k, d in shard_dims.items():
                if k in name:
                    dim = d
                    break
            if dim is None:
                # Extra check: assert that tensors are the same if not sharded
                # assert torch.allclose(combined[name], param)
                continue
            combined[name] = torch.cat((combined[name], param), dim=dim)

        del checkpoint
        del converted
        gc.collect()

    for name, param in combined.items():
        if "c_attn" not in name:
            continue

        # Turn [Q1, K1, V1, Q2, K2, V2, ...] into [Q1, Q2, ..., K1, K2, .., V1, V2, ...]

        src_chunk_len = param.shape[0] // n_checkpoints
        mat_len = src_chunk_len // 3
        dst_chunk_len = mat_len * n_checkpoints
        attn = torch.clone(param)
        for i in range(n_checkpoints):
            for j in range(3):
                param[j * dst_chunk_len + i * mat_len: j * dst_chunk_len + (i+1) * mat_len] = \
                    attn[i * src_chunk_len + j * mat_len: i * src_chunk_len + (j+1) * mat_len]

        del attn
        gc.collect()

    torch.save(combined, Path(output_dir, "state_dict.pth"))


from discord import Embed, message

from SnsInfo import SnsInfo

DOMAIN_TWITTER = "twitter.com"
DOMAIN_X = "x.com"
DOMAIN_INSTAGRAM = "instagram.com"
DOMAIN_WEVERSE = "weverse.io"
DOMAIN_H1KEY = "h1key-official.com"
DOMAIN_YEEUN = "yeeun.bstage.in"
DOMAIN_PURPLE_KISS = "purplekiss.co.kr"
DOMAIN_BSTAGE = [DOMAIN_H1KEY, DOMAIN_YEEUN, DOMAIN_PURPLE_KISS]

def post_source(url: str):
    if DOMAIN_TWITTER in url or DOMAIN_X in url:
        return "X", "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/X_icon_2.svg/2048px-X_icon_2.svg.png"
    elif DOMAIN_INSTAGRAM in url:
        return "Instagram", "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Instagram_icon.png/600px-Instagram_icon.png"
    elif DOMAIN_WEVERSE in url:
        return "Weverse", "https://image.winudf.com/v2/image1/Y28uYmVueC53ZXZlcnNlX2ljb25fMTY5NjQwNDE0MF8wMTM/icon.webp?w=140&fakeurl=1&type=.webp"

def generate_embeds(username: str, sns_info: SnsInfo):
    embeds = []
    # 圖片訊息，Embed 的 url 如果一樣，最多可以 4 張以下的合併在一個區塊
    for index, image_url in enumerate(sns_info.images[slice(4)]):
        if index == 0:
            source = post_source(sns_info.post_link)
            embed = (
                Embed(title=sns_info.title, description=sns_info.content, url=sns_info.post_link).set_author(
                    name=sns_info.profile.name, icon_url=sns_info.profile.url)
                .set_image(url=image_url)
                .insert_field_at(index=0, name="使用者", value=username))
            if source is not None:
                embed.set_footer(text=post_source(sns_info.post_link)[0],
                                 icon_url=post_source(sns_info.post_link)[1])
            embeds.append(embed)
        else:
            embeds.append(Embed(url=sns_info.post_link)
                          .set_author(name=sns_info.profile.name, url=sns_info.profile.url)
                          .set_image(url=image_url))
    else:
        embeds.append(Embed(title=sns_info.title, description=sns_info.content, url=sns_info.post_link).set_author(
                    name=sns_info.profile.name, icon_url=sns_info.profile.url)
                .insert_field_at(index=0, name="使用者", value=username))

    return embeds

def mentions(message: message, bot_id: int):
    if bot_id in message.raw_mentions:
        return True
    else:
        for role in message.role_mentions:
            for member in role.members:
                if member.id == bot_id:
                    return True
    return False


#supermercado

lista = []

qtd = int(input())

for i in range(qtd):

    entrada = input().split()
    preco = float(entrada[0])
    kg = float(entrada[1])

    kg = 1000 / kg                    #1kg tem mil gramas

    resultado = round(preco * kg, 3)          #arredondando agora p 3 casas decimais

    lista.append(resultado)                     #apendando

lista = sorted(lista)

print("{}".format(lista[0]))


import wizwalker
import asyncio
from threading import Event
from wizwalker import Keycode, HotkeyListener, ModifierKeys

xyz_list = []
run = True
async def startup():
    listener = HotkeyListener()

    p = wizwalker.WizWalker().get_new_clients()[0]

    async def add_xyz():
        global xyz_list
        print('Added a location')
        xyz_list += [await p.body.position()]
    async def end():
        global run
        print('Ending and writing')
        run = False

    await listener.add_hotkey(Keycode.K, add_xyz, modifiers=ModifierKeys.NOREPEAT)
    await listener.add_hotkey(Keycode.L, end, modifiers=ModifierKeys.NOREPEAT)
    listener.start()
    try:

        await p.activate_hooks()
        filename = await p.zone_name()
        # your program here
        global run
        while run:
            await asyncio.sleep(1)

    finally:
        global xyz_list
        await listener.stop()
        await p.close()
        with open(f'Zones\{filename}.txt'.replace('/','-'), 'w') as file:
            for xyz in xyz_list:
                line = str(xyz).replace('<XYZ (','').replace(')>','')
                file.write(f'{line}\n')

if __name__ == "__main__":
        asyncio.run(startup())


def solution(prices):
    answer = []
    for index in range(len(prices)):
        cnt = 0
        # basic_count = len(prices) - 1 - index
        for index2 in range(index + 1, len(prices)):
            cnt += 1
            if (prices[index] > prices[index2]):
                break

        answer.append(cnt)

    return answer


#!/usr/bin/env python
import os
activate_this = os.path.expanduser("~/PycharmProjects/DefensicsAutomation/venv/bin/activate_this.py")
execfile(activate_this, dict(__file__=activate_this))

from DefensicsScript import *
from threading import Thread
from datetime import datetime
import GlobalVariables
import GlobalFunctions
import ReadEXCEL
import os

def add_ports():
    # ip-DUT,mac-DUT,ip-LP.mac-LP,name_device-LP,ipv6-DUT,ipv6-LP,10G
    #GlobalFunctions.add_port("10.100.10.100", "00:00:00:00:03:14", "10.100.10.200", "00:00:00:00:01:00", "cvl0_0",
    #                         "3001:1:3::1:10", "3001:1:3::1:20", "10G")
    GlobalFunctions.add_port("10.100.10.100", "00:00:00:00:03:14", "10.100.10.200", "00:00:00:00:01:00", "cvl0_0",
                             "fe80::200:ff:fe00:314", "fe80::200:ff:fe00:100", "10G")
    #GlobalFunctions.add_port("10.100.10.101", "00:02:00:01:03:15", "10.100.10.201", "00:00:00:00:01:01", "cvl0_1",
    #                         "fe80::202:ff:fe01:315", "fe80::200:ff:fe00:101", "10G")
    #GlobalFunctions.add_port("10.100.10.102", "00:03:00:02:03:16", "10.100.10.202", "00:00:00:00:01:02", "cvl0_2",
    #                         "fe80::203:ff:fe02:316", "fe80::200:ff:fe00:102", "10G")
    #GlobalFunctions.add_port("10.100.10.103", "00:04:00:03:03:17", "10.100.10.203", "00:00:00:00:01:03", "cvl0_3",
    #                         "fe80::204:ff:fe03:317", "fe80::200:ff:fe00:103", "10G")

    # lizysha: for MH tests
    #GlobalFunctions.add_port("133.133.10.10", "00:00:00:00:03:14", "133.133.10.20", "00:00:00:00:01:00", "cvl0_0",
      #                       "3001:1:3::1:10", "3001:1:3::1:20", "10G")

    #GlobalFunctions.add_port("10.100.10.101", "00:00:00:00:03:14", "10.100.10.201", "00:00:00:00:01:01", "cvl0_1",
     #                        "fe80::200:ff:fe00:101", "fe80::200:ff:fe00:201", "10G")

def init():

    # allow ssh to DUT machine
    GlobalFunctions.allow_ssh()

    add_ports()

    GlobalVariables.logger.info("Num of port: " + str(len(GlobalVariables.ports_list)))

    # ping all ports to see device aliveness
    GlobalFunctions.ping_all_ports(GlobalVariables.ports_list)

    # create background in order to run
    create_path_to_list_runs()

def run_regular_defensics_automation():
    # update date and time
    update_date()
    GlobalVariables.start_time = datetime.now()

    # create file to fill output log
    GlobalVariables.path_to_lists_runs_details = GlobalVariables.part_of_path_to_results + GlobalVariables.date + '_'\
                                                 + GlobalVariables.project

    if not os.path.exists(GlobalVariables.path_to_lists_runs_details):
        os.makedirs(GlobalVariables.path_to_lists_runs_details)

    # if run this script sign the run is regular run (not reproducing) - will take suites to run from XL
    message = "++++++++ REGULAR RUN - Running testplans from excel ++++++++\n"

    GlobalFunctions.enable_logging(message)

    # call init to initialize the run
    init()

    # create .txt files of CMDs from XL list of testplans to run
    ReadEXCEL.create_files_from_excel(GlobalVariables.path_to_XL, GlobalVariables.path_to_lists_runs_details
                                      + '/ListOfTestplans.txt', GlobalVariables.path_to_cmds_files,
                                      GlobalVariables.path_to_server_cmds_files)
    create_testplans_queue()
    create_threads_queue()

    # start the run by threads
    thread_run_regular_ports = Thread(target=start_run_regular_ports)
    thread_run_regular_ports.start()

    # Wait to all the running threads
    thread_run_regular_ports.join()
    for running_thread in GlobalVariables.running_threads_dic.values():
        running_thread.join()
        GlobalVariables.logger.info("did join to thread: " + str(running_thread.thread_id) + "-> "
                                    + str(running_thread.port.device_name))
        GlobalVariables.logger.info("all threads finished")

    # update and print status of run
    GlobalFunctions.print_status_of_run()

    # end - updates about the run and send results if need
    end_run("Regular Run")

def run_reproduce_defensics_automation(dics_cmd_device_reproduce):
    # update date and time
    update_date()
    GlobalVariables.start_time = datetime.now()

    # call init to initialize the run
    init()

    GlobalVariables.num_tests = len(dics_cmd_device_reproduce)
    GlobalVariables.logger.info("Tests to reproduce queue size is: " + str(GlobalVariables.num_tests) + "\n")

    # create a dictionary of available devices for reproducing of failures
    create_status_device_dic()

    # create threads queue to reproduce failures- every item is thread for one test
    create_reproduce_test_thread_queue(dics_cmd_device_reproduce)

    # start the run by threads
    thread_run_reproduce_runs = Thread(target=start_run_reproduce_runs)
    thread_run_reproduce_runs.start()
    # Wait to all the running threads
    thread_run_reproduce_runs.join()

    for running_thread in GlobalVariables.running_threads_dic.values():
        running_thread.join()
        GlobalVariables.logger.info("did join to thread: " + str(running_thread.thread_id) + "-> "
                                    + str(running_thread.port.device_name))
        GlobalVariables.logger.info("all threads finished")

    # update and print status of run
    GlobalFunctions.print_status_of_run()

    # end - updates about the run and send results if need
    end_run("Reproduce Failures")

if __name__ == '__main__':
    run_regular_defensics_automation()


# coding: utf-8
"""
Replace string columns with JSON columns in locations table.
"""

import os

import flask_sqlalchemy

MIGRATION_INDEX = 54
MIGRATION_NAME, _ = os.path.splitext(os.path.basename(__file__))

def run(db: flask_sqlalchemy.SQLAlchemy) -> bool:
    # Skip migration by condition
    column_info = db.session.execute(db.text("""
        SELECT column_name, data_type
        FROM information_schema.columns
        WHERE table_name = 'locations'
    """)).fetchall()
    if ('name', 'json') in column_info:
        return False

    # Perform migration
    existing_data = [
        location_data
        for location_data in db.session.execute(db.text("""
            SELECT id, name, description
            FROM locations
        """)).fetchall()
    ]

    db.session.execute(db.text("""
        ALTER TABLE locations
        DROP COLUMN name;
    """))
    db.session.execute(db.text("""
        ALTER TABLE locations
        DROP COLUMN description;
    """))
    db.session.execute(db.text("""
        ALTER TABLE locations
        ADD name JSON NOT NULL DEFAULT '{}'::json;
    """))
    db.session.execute(db.text("""
        ALTER TABLE locations
        ADD description JSON NOT NULL DEFAULT '{}'::json;
    """))
    for id, name, description in existing_data:
        location_data = {
            'id': id,
            'name': name,
            'description': description
        }
        db.session.execute(db.text("""
            UPDATE locations
            SET name = json_build_object('en', :name), description = json_build_object('en', :description)
            WHERE id = :id;
        """), params=location_data)
    return True


"""
方法三: 广度优先搜索(BFS)
https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xefb4e/
https://leetcode-cn.com/problems/invert-binary-tree/solution/dong-hua-yan-shi-liang-chong-shi-xian-226-fan-zhua/

解题思路：
首先我们引入一个队列，这是把递归程序改写成迭代程序的常用方法。
1. 根节点先入队
2. 交换其左右节点
3. 如果左节点不为空，入队；如果右节点不为空，入队
4. 重复步骤 2 - 3，直到队列为空

时间复杂度：O(n)，其中 n 为二叉树节点的个数。每个节点只会被遍历一次。
空间复杂度：取决于队列中存储的最大元素个数，其在最坏情况下会达到 O(n)。
"""

# 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 invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return root

        que = [root]  # 创建队列，根节点先进入队列
        while que:  # 如果队列不为空，说明还没有遍历完整棵树
            cur = que.pop(0)  # 依次出队
            cur.left, cur.right = cur.right, cur.left  # 交换左、右节点
            if cur.left:
                que.append(cur.left)  # 左子节点入队
            if cur.right:
                que.append(cur.right)  # 右子节点入队

        return root


from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext_lazy as _

class User(AbstractUser):
    class Role_choices(models.TextChoices):
        USER = 'user', _('Пользователь')
        ADMINISTRATOR = 'admin', _('Администратор')
    username = models.CharField(
        verbose_name='Уникальный юзернейм',
        max_length=150,
        unique=True)
    first_name = models.CharField(
        verbose_name='Имя',
        max_length=150,
    )
    last_name = models.CharField(
        verbose_name='Фамилия',
        max_length=150
    )
    email = models.EmailField(
        verbose_name='Почтовый адрес',
        blank=False,
        unique=True,
        max_length=254,
        null=False,
    )

    @property
    def is_user(self):
        return self.role == User.Role_choices.USER

    @property
    def is_admin(self):
        return self.role == User.Role_choices.ADMINISTRATOR

    class Meta:
        ordering = ('username',)
        verbose_name = 'Пользователь'
        verbose_name_plural = 'Пользователи'

    def __str__(self):
        return self.email


import scrapy
from datetime import datetime
import locale

locale.setlocale(locale.LC_ALL, 'esp_esp')

class MalditaBulosSpdier(scrapy.Spider):
    name = 'malditaBulosSpider'

    start_urls = [
        'https://maldita.es/malditobulo/1'
    ]

    def parse(self, response):
        for titularbulo in response.xpath("//div[@class='section-card flex flex-col md:flex-row']"):
            titular = titularbulo.xpath(".//div[@class='section-card-headline']/a/text()").get()
            detalletitular = titularbulo.xpath(".//div[@class='section-card-headline']/a/@href").get()
            yield scrapy.Request(
                url=response.urljoin(detalletitular),
                callback=self.parse_detalle_titular,
                cb_kwargs={
                    'titular': titular,
                    'link_titular': response.urljoin(detalletitular)
                }
            )

        next_page = response.xpath(
            "//span[@class='bg-white text-gray-800 px-3 py-2 text-lg border-r border-gray-400']/a/@href").get()
        if next_page is not None:
            next_page_link = response.urljoin(next_page)
            yield scrapy.Request(url=next_page_link, callback=self.parse)

    def parse_detalle_titular(self, response, titular, link_titular):
        fecha = response.xpath("//div[@id='article-date']/span[@class='meta-value']/text()").get()
        origen = response.xpath("//img[@id='article-featured-image']/@src").get()
        fecha = fecha.split(sep=",", maxsplit=2)
        fecha_formateada = datetime.strptime(fecha[1].strip(), "%d %B %Y")
        yield {
            'titular': titular,
            'link_titular': link_titular,
            'fecha': fecha_formateada,
            'origen': origen,
        }


from flask import Flask, request
from flask_cors import CORS

import sys
import StoreManager
app = Flask(__name__)
CORS(app)

@app.route('/stores/',methods=['GET'])
def GetStores():
    query = ''
    alt = request.args.get("alt", '32.0879122')
    lng = request.args.get("lng", '34.7724783')
    chain= request.args.get("chain", 'supersal')
    storeManager = StoreManager.StoreManeger()
    print('Input: ' + alt + ' ' + lng + ' ' + chain)
    query = storeManager.getFromGoogle(alt, lng, chain)
    print(query)
    return query

if __name__ == '__main__':
    app.run(port='5003')


base_enum = {'A':1,'a':1,'T':2,'t':2, 'U':2, 'u':2, 'G':3,'g':3,'C':4,'c':4,
            '':5, '-':5,'*':5, 'N':5, 'n':5, 'X':5, 'x':5, '.':5,
            's':6,'start':6,'e':7,'end':7, 'noinsert':8, 'pad':0,
            'unk':9, '?':9, 'M':9, 'm':9, 'K':9, 'k':9, 'R':9, 'r':9, 'Y':9, 'y':9,
            'S':9, 's':9, 'W':9, 'w':9, 'B':9, 'b':9, 'V':9, 'v':9, 'H':9, 'h':9, 'D':9, 'd':9}
real_bases_set = set([base_enum['a'], base_enum['t'], base_enum['g'], base_enum['c']])
enum_base = {0:'p', 1:'A', 2:'T', 3:'G', 4:'C', 5:'-', 6:'s', 7:'e', 8:'noinsert', 9:'?'}
# Encode strand direction -- aatt (lower 1) AATT (upper 2)
STRAND_PAD = 0
STRAND_LOWER = 1
STRAND_UPPER = 2
strand_enum =  {'A':STRAND_UPPER,'a':STRAND_LOWER,'T':STRAND_UPPER,'t':STRAND_LOWER,
                'G':STRAND_UPPER,'g':STRAND_LOWER,'C':STRAND_UPPER,'c':STRAND_LOWER,
                '':STRAND_PAD, '-':STRAND_PAD,'*':STRAND_PAD, 'N':STRAND_UPPER, 'n':STRAND_LOWER,
                's':STRAND_PAD,'start':STRAND_PAD,'e':STRAND_PAD,'end':STRAND_PAD,
                'noinsert':STRAND_PAD, 'pad':STRAND_PAD, 'M':STRAND_UPPER, 'm':STRAND_LOWER,
                'unk':STRAND_PAD, '?':STRAND_PAD}

real_bases_set = set(['A', 'a', 'T', 't', 'C', 'c', 'G', 'G'])
real_base_keys_set = set([base_enum[k] for k in ['A','T','C','G','-','M','noinsert']])
mutation_type_enum = {'SNP':1, 'Insert':2, 'Delete':3, 'ins': 2, 'del':3, 'unk':0, 'error':0}


import sqlite3

data = [('Yphe', 'Yphe@compote.com', 0),
        ('Zirak', 'Zirak34@hibou.fr', 100),
        ('Tikal', 'twouini@music.fr', 50),
        ('Nyse', 'Niz@patate.com', 0)]

def main():
    conn = sqlite3.connect('baseDonnees.db')
    cur = conn.cursor()
    cur.execute(
        "CREATE TABLE IF NOT EXISTS Joueurs(id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, pseudo TEXT, mail TEXT, score FLOAT)")
    zirac350 = (350, 'Zirak')
    cur.execute("UPDATE Joueurs SET score = ? WHERE pseudo = ?", zirac350)

    conn.commit()
    cur.close()
    conn.close()

def main_exo1():
    conn = sqlite3.connect('baseDonnees.db')
    cur = conn.cursor()
    cur.execute(
        "CREATE TABLE IF NOT EXISTS Joueurs(id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, pseudo TEXT, mail TEXT, score FLOAT)")
    cur.executemany("INSERT INTO Joueurs (pseudo, mail, score) VALUES (?, ?, ?)", data)
    conn.commit()
    cur.close()
    conn.close()

def main_exo2():
    conn = sqlite3.connect('baseDonnees.db')
    cur = conn.cursor()
    modif = (9999, 'Yphe')
    cur.execute("UPDATE Joueurs SET score = ? WHERE pseudo = ?", modif)
    suppr = ('Yphe',)
    cur.execute("DELETE FROM Joueurs WHERE pseudo = ?", suppr)
    conn.commit()
    cur.close()
    conn.close()

def main_exo3():
    conn = sqlite3.connect('baseDonnees.db')
    cur = conn.cursor()
    cur.execute("SELECT * FROM Joueurs")
    conn.commit()
    listeResultat = cur.fetchall()
    print(listeResultat)
    recherche = ('Zirak',)
    cur.execute("SELECT score FROM Joueurs WHERE pseudo = ?", recherche)
    conn.commit()
    listeResultat = cur.fetchall()
    print(listeResultat)
    cur.close()
    conn.close()

if __name__ == '__main__':
    main()


import numpy as np
import tensorflow as tf
from datetime import datetime
import os
import sys
import json
sys.path.append('../')
import retriever

cdnd_dir = os.path.dirname(os.path.realpath(__file__))
vocab_file =  cdnd_dir+'/data/metadata/w2v_vocab.json'
embed_path =  cdnd_dir+'/data/metadata/w2v.bin'

class Model():
    def __init__(self,
                 batch_size=200,
                 num_hidden=200,

                 #Image's vector size.
                 img_dims=4096,

                 #Spaital features length.
                 bbox_dims=8,
                 lr=0.5, # learning rate.
                 decay_steps=10000,
                 decay_rate=0.9,
                 embed_size=100,
                 params_dir=cdnd_dir+'/CDNDParams/',

                 # Whether to uses prefix levlel attention or not.
                 use_wordAttn=False,

                 # Whther to use bidirectional rnn
                 useBidirectionalRnn=False,

                 # We scale the VGG16 LN outputs by IMGscale
                 IMGscale=0.023,
                 # We scale the language LN outputs by Qscale
                 Qscale=0.16
                 ):

        self.batch_size = batch_size
        self.img_dims = img_dims
        self.bbox_dims = bbox_dims
        self.num_hidden = num_hidden
        self.embed_size = embed_size
        self.lr = lr
        self.IMGscale=IMGscale
        self.Qscale=Qscale
        self.params_dir = params_dir
        self.vocab, embed_vecs = self.load_datasets()

        self.queries = tf.placeholder(tf.int32, [None, None], name='queries')
        self.img  = tf.placeholder(tf.float32, [None, None, self.img_dims], name='img')# VGG output vectors
        self.bboxes = tf.placeholder(tf.float32, [None, None, self.bbox_dims], name='bboxes')# spatial bbox's features.

        # attn_idx: inicates whether attention box is a pad (0) or not (1).
        self.attn_idx = tf.placeholder(tf.float32, [None, None], name='attn_idx')
        self.labels = tf.placeholder(tf.float32, [None, None], name='labels')

        # Dropout ratio for rnn's inputs and outpouts
        self.dropout_in = tf.placeholder(tf.float32, name='dropoutIn_holder')
        self.dropout_out = tf.placeholder(tf.float32, name='dropoutOut_holder')

        # Dropout ratio for attention vector (for the final attention layer before the loss function)
        self.dropout_img = tf.placeholder(tf.float32, name='dropoutImg_holder')
        # Dropout ratio for query vector (for the final attention layer before the loss function)
        self.dropout_q = tf.placeholder(tf.float32, name='dropoutImg_holder')

        self.isTrain = tf.placeholder(tf.bool, name='isTrain_holder')
        self.queries_lens = self.length(self.queries) # list of all the lengths of the batch's queriey

        # Concatinate images vectors and their spaital features.
        # These vectors wlll be used for attenionn when
        # we calculate the loss function.
        attn_vecs = tf.concat([self.img, self.bboxes], 2)
        voc_size = len(self.vocab)

        # Load pre-trained word imaddings.
        # w2v_embed is not trainable.
        with tf.variable_scope('w2v'):
            w2v_embed = tf.get_variable('w2v_embed', initializer=embed_vecs, trainable=False)
            w2v_queries = tf.nn.embedding_lookup(w2v_embed, self.queries, name='w2v_queries')

        with tf.variable_scope('embed'):
            embed = tf.get_variable('embed', shape=[voc_size, self.embed_size],
                                    initializer=tf.random_uniform_initializer(minval=-0.1, maxval=0.1))
            embed_queries_tmp = tf.nn.embedding_lookup(embed, self.queries, name='embed_queries')

        embed_queries = embed_queries_tmp+w2v_queries

        with tf.variable_scope('rnn'):
            if use_wordAttn:
                normed_image = self.IMGscale*tf.contrib.layers.layer_norm(self.img, begin_norm_axis=2)
                attn_vecs = tf.concat([normed_image, self.bboxes], 2)
                cell = ALSTM(num_units=self.num_hidden,
                            img_attn_dim=self.img_dims+self.bbox_dims,
                            img_attn_states=attn_vecs,
                            img_attn_idx=self.attn_idx,
                            batch_size=self.batch_size,
                            dropout_in=self.dropout_in, dropout_out=self.dropout_out)
            else:
                tmp = tf.nn.rnn_cell.LSTMCell(self.num_hidden, state_is_tuple=True)
                cell = tf.contrib.rnn.DropoutWrapper(
                    tmp,
                    input_keep_prob=self.dropout_in,
                    output_keep_prob=self.dropout_out
                )

            if useBidirectionalRnn:
                if use_wordAttn:
                    cell_bw = ALSTM(num_units=self.num_hidden,
                            img_attn_dim=self.img_dims+self.bbox_dims,
                            img_attn_states=attn_vecs,
                            img_attn_idx=self.attn_idx,
                            batch_size=self.batch_size,
                            dropout_in=self.dropout_in, dropout_out=self.dropout_out)
                else:
                    tmp_bw = tf.nn.rnn_cell.LSTMCell(self.num_hidden, state_is_tuple=True)
                    cell_bw = tf.contrib.rnn.DropoutWrapper(
                        tmp,
                        input_keep_prob=self.dropout_in,
                        output_keep_prob=self.dropout_out
                    )

                self.outputs, self.last_states = tf.nn.bidirectional_dynamic_rnn(
                    cell_fw=cell,
                    cell_bw=cell_bw,
                    dtype=tf.float32,
                    sequence_length=self.queries_lens,
                    inputs=embed_queries)

                state = tf.concat([self.last_states[0][1], self.last_states[1][1]], -1)

            else:
                self.outputs, self.last_states = tf.nn.dynamic_rnn(
                    cell=cell,
                    dtype=tf.float32,
                    sequence_length=self.queries_lens,
                    inputs=embed_queries)
                state = self.last_states[1]

        self.scores = self.CDN_attention(state)

        # Cross entophy loss for each of the queries in the batch.
        self.loss = tf.reduce_mean(-tf.reduce_sum(
                        self.labels*tf.log(self.scores+0.00000001)+
                            (1-self.labels)*tf.log((1-self.scores)+0.00000001),
                        axis=-1))

        ##############
        # Optimizers #
        ##############

        starter_learning_rate = self.lr
        self.global_step = tf.Variable(0, name='global_step', trainable=False)
        self.learning_rate = tf.train.exponential_decay(starter_learning_rate,
                                                        self.global_step,
                                                        decay_steps=decay_steps,
                                                        decay_rate=decay_rate,
                                                        staircase=True)

        self.optimizer =  tf.train.GradientDescentOptimizer(
                    learning_rate=self.learning_rate).minimize(self.loss, global_step=self.global_step)

        if not os.path.exists(self.params_dir):
                os.makedirs(self.params_dir)
        self.saver = tf.train.Saver()

    def load_datasets(self):
        # loading vocabulary
        with open(vocab_file, 'r') as f:
            vocab = json.loads(f.read())
        vocab['<unk>'] = len(vocab)

        # Words vectors
        embed_vecs = np.load(open(embed_path, 'rb'))
        embed_vecs = np.concatenate([embed_vecs, np.zeros((1, 100))], 0).astype(np.float32)

        return vocab, embed_vecs

    def length(self, seq):
        '''
        Retruns real lengths (before addings) of all queries in seq  .
        '''
        return tf.cast(tf.reduce_sum(tf.sign(tf.abs(seq)), reduction_indices=1), tf.int32)

    def linear(self, inputs, output_dim, scope='linear', bias=True, reuse=False):

        with tf.variable_scope(scope, reuse=reuse):
            W1 = tf.get_variable('W1', initializer=tf.contrib.layers.xavier_initializer(),
                                shape=(inputs.get_shape()[-1], output_dim))
            if bias:
                b = tf.get_variable('b', initializer=tf.constant_initializer(0.1),
                               shape=[1, output_dim])
                return tf.matmul(inputs, W1) + b

            return tf.matmul(inputs, W1)

    def CDN_attention(self, q_embed):
        '''
        Given the queries embeddings, calculate the attention over all the query's
        bounding boxes vectors using CDN, That is, calculate:

        probs = softmax(relu(context(Sq+Satt+b)))

        Where:
        Sq = <Wq, queries_states>
        Sattn = <Wattn, attention_bboxes_vectors>

        The  bounding box with the highest attention score will be chosen as the correct bounding box.

        Params:
            q_embed: Tensor of shape (batch size x num_hidden), queries embeddings.

        Returns:
            probs: Tensor of shape (batch_size x max bbox number for query).
                   Attention score for each bbox.
        '''

        # Shape: (batch size x num_hidden)
        self.Urnn = self.Qscale*tf.contrib.layers.layer_norm(q_embed)
        UattTmp = self.IMGscale*tf.contrib.layers.layer_norm(self.img, begin_norm_axis=2)
        self.Uatt = tf.concat([UattTmp, self.bboxes], 2)
        with tf.variable_scope('bnorm_l1') as scope:
            b = tf.get_variable(
                    'b',
                    initializer=tf.constant_initializer(0.1),
                    shape=[1, self.num_hidden])

            context = tf.get_variable(
                    'context',
                    initializer=tf.random_uniform_initializer(minval=-0.1, maxval=0.1),
                    shape=[self.num_hidden, 1])

            Sq = tf.nn.dropout(
                self.linear(self.Urnn, self.num_hidden, bias=False, scope='Sq'),
                self.dropout_q)

            Sattn = tf.nn.dropout(
                        tf.reshape(
                            self.linear(
                                tf.reshape(self.Uatt, (-1, self.img_dims+self.bbox_dims)),
                                self.num_hidden,
                                bias=False, scope='Sattn'),
                             [self.batch_size, -1, self.num_hidden]),
                        self.dropout_img)

            out = tf.nn.relu(tf.expand_dims(Sq, 1) + Sattn + b)
            logits = tf.reshape(tf.matmul(tf.reshape(out, (-1, tf.shape(out)[-1])),  context), (tf.shape(out)[0], -1))

            # Calculate logits's masked softmax. We use self.attn_idx for
            # masking the padded BBOXes.
            max_logits = tf.reduce_max(logits*self.attn_idx, axis=-1, keepdims=True)
            masked_logits = tf.exp(logits-max_logits)*self.attn_idx
            probs = masked_logits/tf.reduce_sum(masked_logits, axis=-1, keepdims=True)

            return probs

    def q_padding(self, seq, max_length):
        '''
        Pad  seq with vocab['<pad>'] (0) to max_length length.
        '''
        return seq + [self.vocab['<pad>']]*(max_length-len(seq))

    def build_data(self, data, start, end):
        '''
        Build batch.
        ------------

        Params:
            data: each entry in this list has the following structure:
                  [query indexes, [bounding box vector (VGG), bounding box spaital features], ...,
                  [bounding box vector (VGG), bounding box spaital features], index of the true label]

            start/end: batch data is built from data[start:end]

        Returns:
            attn_idx: attn_idx[i, j]=1 if the j'th bbox in the i'th query is not padding, else equals to 0.

            padded_queries: list of queries, padded to the length of the longest query in the batch.
                            Note: vocab['p<pad>']=0

            padded_im: list of bounding boxes vectors, padded to the maximum number of bbox per query.
                       Note: padded vector is vector of zeros.

            padded_bbox: list of bounding boxes spatial features, padded to the maximum number of bbox per query.
                         Note: padded vector is vector of zeros.

            dist_labels: dist_labels[i][j]=1 if j is the true bbox for query i, else dist_labels[i][j]=0

        '''

        qlen = max([len(data[i][0]) for i in range(start, end)]) # Length fo the longest query
        imlen = max([len(data[i]) for i in range(start, end)])-2 # Maximum number of bbox per query.
        padded_queries, padded_im, padded_bbox, attn_idx = [], [], [], []

        # Build one hot labels from the labels index, given in the data.
        labels = [item[-1] for item in data[start:end]] # data[i][-1]=index of the true bbox of query i
        dist_labels = np.zeros((end-start, imlen)) #label distribution
        dist_labels[[i for i in np.arange(end-start)], [l for l in labels]]=1

        im_dim, bbox_dim = data[0][1][0].shape[1], data[0][1][1].shape[1]
        for i in range(start, end):
            padded_queries.append(self.q_padding(data[i][0], qlen))

            attn_idx.append([1 for _ in range(len(data[i])-2)]+[0 for _ in range(imlen-(len(data[i])-2))])

            padded_im.append(np.concatenate([data[i][j][0] for j in range(1, len(data[i])-1)] +
                                       [np.full((imlen-(len(data[i])-2), im_dim), self.vocab['<pad>'], dtype=np.float32)], axis=0))

            padded_bbox.append(np.concatenate([data[i][j][1] for j in range(1, len(data[i])-1)] +
                                       [np.full((imlen-(len(data[i])-2),bbox_dim), self.vocab['<pad>'], dtype=np.float32)], axis=0))

        return np.array(attn_idx), np.array(padded_queries, dtype=np.int32), np.array(padded_im), np.array(padded_bbox), np.array(dist_labels)

    def ground(self, data=None, start=None, end=None,
               sess=None, feed_dict = None, scores=[]):
        '''
        Given a query and a list of bboxes, the function returns the index of the chosen bbox and the ground truth bbox.

        Params:
            data: A numpy array with datasat's data points
            start/end: The function only take data points from data[start:end]
            imScale: whether to scale the images vectors
        '''
        isSess = (sess==None)
        if isSess:
            sess = tf.Session()
        with sess.as_default():
            if isSess:
                tf.global_variables_initializer().run()
                ckpt = tf.train.get_checkpoint_state(self.params_dir)
                if ckpt and ckpt.model_checkpoint_path:
                    self.saver.restore(sess, ckpt.model_checkpoint_path) # restore all variables
                else:
                    print('Initializing variables')
            if feed_dict is None:
                attn_idx, padded_queries, padded_im, padded_bbox, labels = self.build_data(
                    data, start, end)

                feed_dict = {
                        self.queries:padded_queries,
                        self.img:padded_im,
                        self.bboxes:padded_bbox,
                        self.labels:labels,
                        self.attn_idx:attn_idx}

            if len(scores)==0:
                feed_dict[self.isTrain]=False
                feed_dict[self.dropout_in]=1.
                feed_dict[self.dropout_out]=1.
                feed_dict[self.dropout_img]=1.
                feed_dict[self.dropout_q]=1.
                scores = sess.run(self.scores, feed_dict=feed_dict) # get score for each bbox

        return np.argmax(scores, axis=1), np.argmax(feed_dict[self.labels], axis=1)

    def iou_accuracy(self, data=None, start=None, end=None, sess=None,
                     feed_dict=None, threshold=0.5, test=False, scores=[]):
        '''
        Calculate the IOU score between the Model bbox and the true bbox.

         Params:
            data: A numpy array with datasat's data points
            start/end: The function only take data points from data[start:end]
            imScale: whether to scale the images vectors
            threshold: If IOU>0.5 this is a true positive
        '''

        # Get score for each bbox (labels) and th true bbox index (gt_idx)
        labels, gt_idx = self.ground(data, start, end, sess=sess, feed_dict=feed_dict, scores=scores)
        acc = 0

        for i in range(start, end):
            gt = data[i][gt_idx[i-start]+1][1][0] # ground truth bbox. Note that len(data)!=len(gt_idx)=batch_size
            crops = np.expand_dims(data[i][labels[i-start]+1][1][0], axis=0) #Model chosen bbox. Note that len(data)!=len(labels)=batch_size
            acc += (retriever.compute_iou(crops, gt)[0]>threshold) #IOU for the i sample.

        return acc/(end-start)

    def accuracy(self, data=None, start=None, end=None, sess=None,
                 feed_dict=None, scores=[]):
        isSess = (sess==None)
        if isSess:
            print('Building sess')
            sess = tf.Session()
        with sess.as_default():
            if isSess:
                print('Building sess used')
                tf.global_variables_initializer().run()
                ckpt = tf.train.get_checkpoint_state(self.params_dir)
                if ckpt and ckpt.model_checkpoint_path:
                    print('3')
                    self.saver.restore(sess, ckpt.model_checkpoint_path) # restore all variables
                else:
                    print('Initializing variables')
            if feed_dict is None:
                print('Building feed_dict')
                attn_idx, padded_queries, padded_im, padded_bbox, labels = self.build_data(data, start, end)
                feed_dict = {
                        self.queries:padded_queries,
                        self.img:padded_im,
                        self.bboxes:padded_bbox,
                        self.attn_idx:attn_idx,
                        self.labels:labels,
                    }

            loss = 0
            if len(scores)==0:
                feed_dict[self.isTrain]=False
                feed_dict[self.dropout_in]=1.
                feed_dict[self.dropout_out]=1.
                feed_dict[self.dropout_img]=1.
                feed_dict[self.dropout_q]=1.
                loss, scores = sess.run([self.loss, self.scores], feed_dict=feed_dict)

            acc = sum(
                np.equal(
                    np.argmax(scores, axis=1),
                    np.argmax(feed_dict[self.labels], axis=1))/len(feed_dict[self.labels])
            )

        return loss, scores, acc

    def predict(self, queries, img, bboxes, attn_idx):
        sess = tf.Session()
        with sess.as_default():
            tf.global_variables_initializer().run()
            ckpt = tf.train.get_checkpoint_state(self.params_dir)
            if ckpt and ckpt.model_checkpoint_path:
                print('Loading parameters from', ckpt.model_checkpoint_path)
                self.saver.restore(sess, ckpt.model_checkpoint_path) # restore all variables
            else:
                print('Initializing variables')

            feed_dict = {
                    self.queries:queries,
                    self.img:img,
                    self.bboxes:bboxes,
                    self.dropout_in:1.,
                    self.dropout_out:1.,
                    self.dropout_img:1.,
                    self.dropout_q:1.,
                    self.isTrain:False,
                    self.attn_idx:attn_idx,
                    self.labels:[[]]
            }

            scores = sess.run(self.scores, feed_dict=feed_dict)
        return scores

    def train(self, trn_data, tst_data, ephocs_num,  start_ephoc=0, dropout_in=0.5,
              dropout_out=0.5, dropout_img=1., dropout_q=1.):

        '''
        Params:
             trn_data: list, train set.

             tst_data: list, test set.

             ephocs_num: number of ephocs

             start_ephoc: number of first ephoc.

            dropout_in: dropout ratio of rnn inputs.

            dropout_output: dropout ratio of rnn output.

            dropout_img: dropout ratio of images vectors before the last attention layer .

            onlyB: boolean, Wheter to train only B. By setting startA and acctivation_ephoc larger than ephocs_num
                   and setting onlyB to True, we get A out of the game

        '''

        trn_nbatch = len(trn_data)//self.batch_size
        tst_nbatch = len(tst_data)//self.batch_size

        sess = tf.Session()
        with sess.as_default():
            tf.global_variables_initializer().run()
            ckpt = tf.train.get_checkpoint_state(self.params_dir)
            if ckpt and ckpt.model_checkpoint_path:
                print('Loading parameters from', ckpt.model_checkpoint_path)
                self.saver.restore(sess, ckpt.model_checkpoint_path) # restore all variables
            else:
                print('Initializing variables')

            for ephoc in range(start_ephoc, ephocs_num):

                ############
                # Training #
                ############

                startTime = datetime.now().replace(microsecond=0)
                print('='*50,'\nTrain, ephoc:',ephoc)
                np.random.shuffle(trn_data)
                trn_loss, trn_acc, trn_iou = 0, 0, 0
                qMean, qSTD, qRange, imgMean, imgSTD, imgRange = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
                g_img, g_rnn = 0.0, 0.0

                for b in range(trn_nbatch):
                    attn_idx, padded_queries, padded_im, padded_bbox, labels = self.build_data(trn_data,
                                                                                b*self.batch_size,
                                                                                (b+1)*self.batch_size)

                    feed_dict = {
                        self.queries:padded_queries,
                        self.img:padded_im,
                        self.bboxes:padded_bbox,
                        self.attn_idx:attn_idx,
                        self.labels: labels,
                        self.dropout_in:dropout_in,
                        self.dropout_out:dropout_out,
                        self.dropout_img:dropout_img,
                        self.dropout_q:dropout_q,
                        self.isTrain:True
                    }

                    scores, loss, lr, gs,  _ = sess.run([self.scores,
                                                        self.loss, self.learning_rate,
                                                        self.global_step, self.optimizer], feed_dict=feed_dict)

                    loss, scores, acc = self.accuracy(sess=sess, feed_dict=feed_dict)
                    iou_acc = self.iou_accuracy(trn_data, b*self.batch_size, (b+1)*self.batch_size,
                                                sess=sess, feed_dict=feed_dict, scores=scores)

                    trn_acc += acc/trn_nbatch
                    trn_loss += loss/trn_nbatch
                    trn_iou += iou_acc/trn_nbatch

                    if b%50==0:
                        print('b:%d'%(b),
                                ';lr:%.3f'%(lr),
                                ';loss:%.2f'%(loss), ';acc:%.2f'%(acc),
                                ';iou:%.2f'%(iou_acc),
                                ';time:', datetime.now().replace(microsecond=0)-startTime)

                print('\n*Tr loss: %.3f'%(trn_loss),';Tr acc: %.3f'%(trn_acc),
                        ';IOU acc: %.3f'%(trn_iou),  ';Time:', datetime.now().replace(microsecond=0)-startTime, '\n')

                self.saver.save(sess, self.params_dir + "/model.ckpt", global_step=ephoc)

                ###########
                # Testing #
                ###########

                print('Testing, ephoc:',ephoc)
                tstTime = datetime.now().replace(microsecond=0)
                tst_loss, tst_acc, tst_iou = 0, 0, 0
                for b in range(tst_nbatch):
                    attn_idx, padded_queries, padded_im, padded_bbox, labels = self.build_data(tst_data,
                                                                                b*self.batch_size,
                                                                                (b+1)*self.batch_size)
                    feed_dict = {
                        self.queries:padded_queries,
                        self.img:padded_im,
                        self.bboxes:padded_bbox,
                        self.attn_idx:attn_idx,
                        self.labels: labels,
                        self.dropout_in:1.,
                        self.dropout_out:1.,
                        self.dropout_img:1.,
                        self.dropout_q:1.,
                        self.isTrain:False
                    }
                    scores, loss = sess.run([self.scores, self.loss], feed_dict=feed_dict)
                    _,_, acc = self.accuracy(sess=sess, feed_dict=feed_dict, scores=scores)
                    iou_acc = self.iou_accuracy(
                        tst_data, b*self.batch_size, int(b+1)*self.batch_size, sess=sess,
                        feed_dict=feed_dict, scores=scores)

                    tst_acc += acc/tst_nbatch
                    tst_loss += loss/tst_nbatch
                    tst_iou += iou_acc/tst_nbatch
                    if b%50==0:
                        print('batch:', b, ';loss: %.3f'%(loss), ';acc: %.3f'%(acc),
                               ';iou_acc: %.3f'%(iou_acc), ';time:',
                              datetime.now().replace(microsecond=0)-startTime)

                print('\n*Test loss: %.3f'%(tst_loss), ';Test accuracy %.3f'%(tst_acc),
                      ';Test IOU: %.3f'%(tst_iou), ';Time:', datetime.now().replace(microsecond=0)-startTime)
            print('='*50,'\n')


#  MiniLight Python : minimal global illumination renderer
#
#  Harrison Ainsworth / HXA7241 and Juraj Sukop : 2007-2008, 2013.
#  http://www.hxa.name/minilight

from .spatialindex import SpatialIndex
from .triangle import Triangle
from .vector3f import Vector3f, ZERO, ONE, MAX

import re
SEARCH = re.compile('(\(.+\))\s*(\(.+\))').search

MAX_TRIANGLES = 0x1000000

class Scene(object):

    def __init__(self, in_stream, eye_position):
        for l in in_stream:
            if type(l) == type(""):
                line = l.encode('ascii','ignore')
            else:
                line = l
            if not line.isspace():
                s, g = SEARCH(line.decode('utf-8')).groups()
                self.sky_emission = Vector3f(s).clamped(ZERO, MAX)
                self.ground_reflection = Vector3f(g).clamped(ZERO, ONE)
                self.triangles = []
                try:
                    for i in range(MAX_TRIANGLES):
                        self.triangles.append(Triangle(in_stream))
                except StopIteration:
                    pass
                self.emitters = [triangle for triangle in self.triangles
                    if not triangle.emitivity.is_zero() and triangle.area > 0.0]
                self.index = SpatialIndex(eye_position, self.triangles)
                self.get_intersection = self.index.get_intersection
                break

    ##def get_intersection(self, ray_origin, ray_direction, last_hit):
    ##    return self.index.get_intersection(ray_origin, ray_direction,
    ##        last_hit)

    def get_emitter(self, random):
        emitter = None if len(self.emitters) == 0 else self.emitters[
            min(len(self.emitters) - 1,
                int(random.real64() * len(self.emitters))) ]
        return [(emitter.get_sample_point(random) if emitter else ZERO),
            emitter]

    def emitters_count(self):
        return len(self.emitters)

    def get_default_emission(self, back_direction):
        return self.sky_emission if back_direction.y < 0.0 else \
            self.sky_emission * self.ground_reflection


a, v = map(int, input().split(" "))
t = 1
while(a+v != 0):
	total = [0]*a
	r = []
	m = 0
	for i in range(v):
		entrada = [int(x) for x in input().split(" ")]
		total[entrada[0]-1] += 1
		total[entrada[1]-1] += 1
	print("Teste", t)
	for j in range(a):
		if total[j] > m:
			m = total[j]
			r = [j+1]
		elif total[j] == m:
			r.append(j+1)
	print(*r, sep=" ", end=" \n")
	print("")
	t += 1
	a, v = map(int, input().split(" "))


from PIL import ImageFont, ImageDraw, Image

hangulJamosRange = (0x1100, 0x11ff)
hangulSyllablesRange = (0xAC00, 0xD7AF)
# germanUmlauts = [0x00C4, 0x00E4, 0x00D6, 0x00F6, 0x00DX, 0x00FC, 0x1E9E, 0x00DF]
print("""Amazfit Bip(米动手表 青春版) 한글 비트맵 이미지 생성기\n
      ©2018 Youngbin Han(sukso96100@gmail.com)\n
      이 스크립트는 한글 자모(U+1100~U+11FF) 와 한글 글자마디(U+AC00~U+D7AF) 에 헤당하는 파일만 생성합니다.""")
fontPath = input("사용할 글꼴 파일(*.ttf/*.otf) 경로 또는 이름 입력:")
destPath = input("""생성된 비트맵 이미지를 저장할 경로 입력. 마지막에 '/' 포함하여 입력. \n
                (이 스크립트 파일과 같은 경로에 저장하려면 비워두기)\n
                ~>""")
marginLeft = int(input("글자 왼쪽 간격 정수로 입력.(기본값:0)") or "0")
marginTop = int(input("글자 위쪽 간격 정수로 입력.(기본값:0)") or "0")

def printInRange(charRange, font):
    for i in range(charRange[0], charRange[1]):
        image = Image.new('1', (16, 16), "black")
        draw = ImageDraw.Draw(image)
        draw.text((marginLeft, marginTop), chr(i), font=font, fill="white")
        image.save("{}{:04x}4.bmp".format(destPath, i), "bmp")

def printInArray(charArray, font):
    for i in charArray:
        image = Image.new('1', (16, 16), "black")
        draw = ImageDraw.Draw(image)
        draw.text((marginLeft, marginTop), chr(i), font=font, fill="white")
        image.save("{}{:04x}4.bmp".format(destPath, i), "bmp")

print("글꼴 불러오는 중...")
font = ImageFont.truetype(fontPath, 15)

print("처리중...")
printInRange(hangulJamosRange, font)
printInRange(hangulSyllablesRange, font)
# printInArray(germanUmlauts, font)

print("작업 완료.")


from ctypes import *
from ctypes.wintypes import HWND, LPCSTR, UINT, INT, LPSTR, LPDWORD, DWORD, HANDLE, BOOL

MessageBoxA = windll.user32.MessageBoxA
MessageBoxA.argtypes = (HWND, LPSTR, LPCSTR, UINT)
MessageBoxA.restype = INT

print(MessageBoxA)

lpText = LPCSTR(b'World')
lpCaption = LPCSTR(b'Hello')
MB_OK = 0x00000000
MB_OKCANCEL = 0x00000001

#MessageBoxA(None, lpText, lpCaption, MB_OKCANCEL)

GetUserNameA = windll.advapi32.GetUserNameA
GetUserNameA.argtypes = (LPCSTR, LPDWORD)
GetUserNameA.restype = INT

buffer_size = DWORD(2)
buffer = create_string_buffer(buffer_size.value)

GetUserNameA(buffer, byref(buffer_size))
print(buffer.value)

error = GetLastError()

if error:
    print(error)
    print(WinError(error))

class RECT(Structure):
    _fields_ = [('left', c_long),
                ('top', c_long),
                ('right', c_long),
                ('bottom', c_long)]

rect = RECT()
print(rect.left)
print(rect.top)
print(rect.right)
print(rect.bottom)

rect.left = 1
print(rect.left)

GetWindowRect = windll.user32.GetWindowRect
GetWindowRect.argtypes = (HANDLE, POINTER(RECT))
GetWindowRect.restype = BOOL

hwnd = windll.user32.GetForegroundWindow()
GetWindowRect(hwnd, byref(rect))

rect = RECT()
print(rect.left)
print(rect.top)
print(rect.right)
print(rect.bottom)


n = int(input())

# AMAZING SOLUTION OF FIBONACCI

def fib(n):
    pre = [1, 1]
    curr = ""
    i = 0
    j = 1
    while len(curr) != n:
        pre.append(pre[i]+pre[j])

        if len(str(pre[-1])) == n:
            print(pre[-1])
            break
        else:
            i += 1
            j += 1

if n == 1:
    print(1)
else:
    fib(n)


import cv2
import keyboard

# haar files (face and smile)
face_detector_file = r"haarcascade_frontalface_default.xml"
face_detector = cv2.CascadeClassifier(face_detector_file)

smile_detector_file = r"haarcascade_smile.xml"
smile_detector = cv2.CascadeClassifier(smile_detector_file)

# access the webcam.
webcam= cv2.VideoCapture(0, cv2.CAP_DSHOW)

# get the current frame
while True:
    # Read the current frame
    successful_frame_read, frame = webcam.read()

    # end if there's an error
    if not successful_frame_read:
        break
    else:
        # if frame read was successful  convert frame to grayscale
        grayscaled_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        faces = face_detector.detectMultiScale(grayscaled_frame)
        for (x,y,w,h) in faces:
            cv2.rectangle(frame, (x,y), (x+w, y+h),(0,255,0), 2)

            # crop the frame to just contain the face and put smile on it
            the_face = frame[y:y+h, x:x+w]
            # convert the face into grayscale
            grayscaled_face = cv2.cvtColor(the_face, cv2.COLOR_BGR2GRAY)

            smiles = smile_detector.detectMultiScale(grayscaled_face, scaleFactor=1.7, minNeighbors=30)

            # Label the face as smiling
            if len(smiles) > 0:
                cv2.putText(frame, "SMILING", (x,y+h+40), fontFace= cv2.FONT_HERSHEY_PLAIN, fontScale=2, color=(0,255,0))

        # display frame
        cv2.imshow("Smile Detector", frame)

        # Exit if 'SPACE-BAR' is pressed
        if keyboard.is_pressed(" "):
            break
        else:
            # read next frame every 1 millisecond
            cv2.waitKey(1)

# release the webcam after done
webcam.release()
# destroy/close all windows
cv2.destroyAllWindows()


heights = [170, 200, 165, 152, 183, 176, 162, 158]
total = 0

lenheights = len(heights)

for i in range(lenheights):
    total += heights[i]

average = round(total / lenheights)

print(f"The total height is: {total}\nThe average height is {average}")

Beginner/Day 5 (5 Projects PW Gen)/Average Height.py