# Посчитать общее количество определенных цифр в числах
# Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел.
# Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры.
#
# 1. Запросить у пользователя количество вводимых чисел (n) и цифру для подсчета (d).
# 2. Присвоить счетчику цифр значение 0.
# 3. Выполнить n раз цикл, в теле которого
#   1. запрашивать очередное число,
#   2. пока это число не сократиться до нуля
#       1. извлекать последнюю его цифру и сравнивать с цифрой, которую надо посчитать,
#       2. увеличивать значение счетчика цифр на 1, если сравниваемые цифры совпадают,
#       3. избавляться от последней цифры числа.
# 4. В конце программы вывести количество посчитанных цифр на экран.

n = int(input("Сколько будет чисел? "))
d = int(input("Какую цифру считать? "))
count = 0
for i in range(1, n + 1):
    m = int(input("Число " + str(i) + ": "))
    while m > 0:
        if m % 10 == d:
            count += 1
        m = m // 10

print("Было введено %d цифр %d" % (count, d))


import torch
import torch.nn as nn
import torch.nn.functional as F

class CNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
        self.pool = nn.MaxPool2d(2, 2)
        self.dropout = nn.Dropout(0.3)
        self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
        self.conv4 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)
        self.conv5 = nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1)
        self.conv6 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
        self.fc1 = nn.Linear(18432, 1024)
        self.fc2 = nn.Linear(1024, 512)
        self.fc3 = nn.Linear(512, 75)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = self.pool(F.relu(self.conv3(x)))
        x = self.pool(F.relu(self.conv4(x)))
        #x = (F.relu(self.conv5(x)))
        #x = self.pool(F.relu(self.conv6(x)))
        x = self.dropout(x)
        x = torch.flatten(x, 1)  # flatten all dimensions except batch

        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        # x = F.softmax(x, dim=1)
        return x


# Names: Bailey Carr, Tony Drouillard, Aishwareeya Rath
# FSUID: bfc19, tld19b, ar19c
# Due Date: December 3, 2021
# This project was completed on the group efforts of Bailey Carr, Tony Drouillar, and Aishwareeya Rath

# These are various libraries we needed for the project
# flask gives us ability to interact with the user through HTML
# sqlite3 gives us interaction with the database
# datetime allows us to get the current date and time
# randint allows us to get the number of the day of the week
from flask import Flask, render_template, request, url_for
import sqlite3 as sql
import datetime
from random import randint

app = Flask(__name__)

# a function we wrote to streamline inserts into the database
def dbInsert(table, kind, name, amount, cost, tax=-1):
    con = sql.connect("groceryData.db")
    cur = con.cursor()
    alreadyExists = cur.execute("SELECT Amount FROM %s WHERE Name=?" % table, (name,)).fetchone()
    if(alreadyExists):
        cur.execute("UPDATE {0} SET Amount={1} WHERE Name='{2}'".format(table, int(alreadyExists[0])+int(amount), name))
    else:
        if(tax == -1):
            cur.execute("INSERT INTO %s (Kind,Name,Amount,Cost) VALUES (?,?,?,?)" % table, (kind, name, amount, cost))
        else:
            cur.execute("INSERT INTO %s (Kind,Name,Amount,Cost,Tax) VALUES (?,?,?,?,?)" % table, (kind, name, amount, cost, tax))
    con.commit()
    con.close()

# a function written to assist with grabbing things from the inventory we have, if it is not the total inventory
# if it is the total inventory, we just grab the whole entire inventory
def get_X_inventory(kind):
    con = sql.connect("groceryData.db")
    con.row_factory = sql.Row
    cur = con.cursor()
    query = "SELECT Kind,Cost,Amount,Name FROM Inventory"
    query += " WHERE Kind='%s'" % kind if (kind != "TotalInventory") else ""
    cur.execute(query)
    rows = cur.fetchall()
    con.close()
    return rows

# renders the homepage
@app.route("/")
def home():
    return render_template("index.html")

# renders the main inventory page, from here the user can go to different inventories based off of what kind of
# product they would like to buy. They can also view all products in one list through a link on this page
@app.route("/Inventory.html")
def get_inventory():
    return render_template("Inventory.html")

# renders the produce inventory
@app.route("/Produce.html")
def get_produce_inventory():
    return render_template("Produce.html", rows=get_X_inventory("Produce"))

# renders the household inventory
@app.route("/Household.html")
def get_household_inventory():
    return render_template("Household.html", rows=get_X_inventory("Household"))

# renders the electronics inventory
@app.route("/Electronics.html")
def get_electronics_inventory():
    return render_template("Electronics.html", rows=get_X_inventory("Electronics"))

# renders the seafood inventory
@app.route("/Seafood.html")
def get_seafood_inventory():
    return render_template("Seafood.html", rows=get_X_inventory("Seafood"))

# renders all products in the inventory
@app.route("/TotalInventory.html")
def get_total_inventory():
    return render_template("TotalInventory.html", rows=get_X_inventory("TotalInventory"))

# this grabs all the products the user currently has sitting inside of their shopping cart and displays it
# to them on the shopping cart page
@app.route("/ShoppingCart.html")
def get_shopping_cart():
    con = sql.connect("groceryData.db")
    con.row_factory = sql.Row
    cur = con.cursor()
    cur.execute("SELECT Kind,Cost,Amount,Name FROM ShoppingCart")
    rows = cur.fetchall()
    con.close()
    return render_template("ShoppingCart.html", rows=rows)

# This page displays the checkout totals of everything the user has in their cart
# we have also added "sales" for each day of the week. This day of the week is generated
# by a random number generator from 1 to 7. The corresponding day and sale amount is shown
@app.route("/Checkout.html")
def get_checkout():
# we have to make randnum from the randnum est in main, so it is the global randnum
    global randnum
    print(randnum)
    print("just got randnum")
# decides the sale and the day of the week
    if randnum == 1:
       day = "Sunday"
       sale = 0.95
    elif randnum == 2:
       day = "Monday"
       sale = 0.85
    elif randnum == 3:
       day = "Tuesday"
       sale = 0.90
    elif randnum == 4:
       day = "Wednesday"
       sale = 0.75
    elif randnum == 5:
       day = "Thursday"
       sale = 0.80
    elif randnum == 6:
       day = "Friday"
       sale = 0.90
    elif randnum == 7:
       day = "Saturday"
       sale = 0.95
    else:
        day = "A Normal Day"
        sale = 1
# grabs the sale amount as a percent
    discount = 1 - sale
    discount = round(discount, 2)
    con = sql.connect("groceryData.db")
    con.row_factory = sql.Row
    cur = con.cursor()
    cur.execute("SELECT Kind,Name,Amount,Cost,Tax FROM ShoppingCart")
    sub = tax = total = 0
    rows = cur.fetchall()
# calculates the cost with the sale factored in
    for row in rows:
        sub += row["Cost"] * row["Amount"] * sale
        tax += row["Cost"] * row["Amount"] * row["Tax"]
    total += sub + tax
    totals = (sub, tax, total)
    con.close()
    return render_template("Checkout.html", day=day, sale=discount*100,rows=rows, totals=totals)

# users can request products through this page
@app.route("/RequestProduct.html")
def add_request():
    return render_template("RequestProduct.html")

# users can see other users' requests through this page
@app.route("/ShowRequests.html")
def show_requests():
    con = sql.connect("groceryData.db")
    con.row_factory = sql.Row
    cur = con.cursor()
    cur.execute("SELECT * FROM Requests")
    rows = cur.fetchall()
    con.close()
    return render_template("ShowRequests.html", rows=rows)

# if a user wants to add their review, this page will show
@app.route("/AddReview.html")
def add_review():
    return render_template("AddReview.html")

# users can see everyone's review from this page
@app.route("/ShowReviews.html")
def show_reviews():
    con = sql.connect("groceryData.db")
    con.row_factory = sql.Row
    cur = con.cursor()
    cur.execute("SELECT * FROM Reviews")
    rows = cur.fetchall()
    con.close()
    return render_template("ShowReviews.html", rows=rows)

# this page generates the receipt for the products that the user has purchased
# once again the random number is chose through that global randnum
@app.route("/Receipt.html")
def get_receipt():
    global randnum
    print(randnum)
    print("just got randnum")
    if randnum == 1:
        sale = 0.95
    elif randnum == 2:
        sale = 0.85
    elif randnum == 3:
        sale = 0.90
    elif randnum == 4:
        sale = 0.75
    elif randnum == 5:
        sale = 0.80
    elif randnum == 6:
        sale = 0.90
    elif randnum == 7:
        sale = 0.95
    else:
        sale = 1
    con = sql.connect("groceryData.db")
    con.row_factory = sql.Row
    cur = con.cursor()
    cur.execute("SELECT Kind,Name,Amount,Cost,Tax FROM Receipt")
    rows = cur.fetchall()
    sub = tax = total = 0
    for row in rows:
        sub += row["Cost"] * row["Amount"] * sale
        tax += row["Cost"] * row["Amount"] * row["Tax"]
    total += sub + tax
    totals = (sub, tax, total)
    con.close()
    return render_template("Receipt.html", rows=rows, totals=totals)

# this grabs the data the user submitted from the add review page and just adds it
# to the appropirate table in the database
@app.route("/addReview", methods=["POST", "GET"])
def addReview():
    if request.method == "POST":
        try:
            name = request.form["Name"]
            rating = request.form["Rating"]
            review = request.form["Review"]
            with sql.connect("groceryData.db") as con:
                cur = con.cursor()
                cur.execute("INSERT INTO Reviews (Name,Rating,Review) VALUES (?,?,?)", (name, rating, review))
                con.commit()
        except:
            con.rollback()
            con.close()
            return render_template("index.html")
        else:
            con.close()
            return show_reviews()

# same as above, grabs the users wishes and adds it to the right tabel
@app.route("/requestProduct", methods=["POST", "GET"])
def requestProduct():
    if request.method == "POST":
        try:
            name = request.form["Name"]
            kind = request.form["Kind"]
            with sql.connect("groceryData.db") as con:
                cur = con.cursor()
                cur.execute("INSERT INTO Requests (Name,Kind) VALUES (?,?)", (name, kind))
                con.commit()
        except:
            con.rollback()
            con.close()
            return render_template("index.html")
        else:
            con.close()
            return show_requests()

# if a user has complaints :( they can add their complaints and the approrpiate page is rendered
@app.route("/Complaints.html")
def get_complaint_form():
    con = sql.connect("groceryData.db")
    cur = con.cursor()
    cur.execute("SELECT Kind FROM Inventory")
    rows = cur.fetchall()
    return render_template("Complaints.html",rows=rows)

# grabs data from the complaints page and add it to the table
@app.route("/file_complaint", methods=["POST", "GET"])
def file_complaint():
    if request.method == "POST":
        try:
            print("entering try")
            complaint = request.form["Complaint"]
            print("complaint is ", complaint)
            issue = request.form["Issue"]
            print("time is ", issue)
            with sql.connect("groceryData.db") as con:
                print("entering connect")
                cur = con.cursor()
                cur.execute("INSERT INTO Complaints (Complaint,Issue) VALUES (?,?)", (complaint, issue))
                con.commit()
        except:
            print("except")
            con.rollback()
        finally:
            return render_template("index.html")

# we have hard coded 40 products, 10 per kind
def load_inventory():
    dbInsert("Inventory", "Produce", "Avocados", 1000, 1.00)
    dbInsert("Inventory", "Produce", "Bananas", 1000, 0.10)
    dbInsert("Inventory", "Produce", "Broccoli", 1000, 1.50)
    dbInsert("Inventory", "Produce", "Mangoes", 1000, 0.70)
    dbInsert("Inventory", "Produce", "Mushrooms", 1000, 0.05)
    dbInsert("Inventory", "Produce", "Bok Choy", 1000, 3.00)
    dbInsert("Inventory", "Produce", "Plantains", 1000, 1.75)
    dbInsert("Inventory", "Produce", "Oranges", 1000, 0.20)
    dbInsert("Inventory", "Produce", "Strawberries", 1000, 0.50)
    dbInsert("Inventory", "Produce", "Beans", 1000, 2.00)
    dbInsert("Inventory", "Electronics", "Laptop", 100, 599.99)
    dbInsert("Inventory", "Electronics", "Television", 100, 299.99)
    dbInsert("Inventory", "Electronics", "Smartphone", 100, 799.99)
    dbInsert("Inventory", "Electronics", "Printer", 100, 50.00)
    dbInsert("Inventory", "Electronics", "Charger Cables", 100, 9.99)
    dbInsert("Inventory", "Electronics", "Lightning Ports", 100, 19.99)
    dbInsert("Inventory", "Electronics", "Mouse Pads", 100, 9.99)
    dbInsert("Inventory", "Electronics", "Keyboard", 100, 69.99)
    dbInsert("Inventory", "Electronics", "Game System", 100, 359.99)
    dbInsert("Inventory", "Electronics", "Electronic Cleaner", 100, 29.99)
    dbInsert("Inventory", "Household", "Pillows", 250, 15.99)
    dbInsert("Inventory", "Household", "Blankets", 250, 29.99)
    dbInsert("Inventory", "Household", "Paintings", 250, 99.99)
    dbInsert("Inventory", "Household", "Plates", 250, 40.00)
    dbInsert("Inventory", "Household", "Rugs", 250, 75.50)
    dbInsert("Inventory", "Household", "Curtains", 250, 43.00)
    dbInsert("Inventory", "Household", "Blinds", 50, 99.99)
    dbInsert("Inventory", "Household", "Mirror", 250, 25.00)
    dbInsert("Inventory", "Household", "Statue", 250, 3000.00)
    dbInsert("Inventory", "Household", "Couch", 250, 600.00)
    dbInsert("Inventory", "Seafood", "Shrimp", 25, 10.00)
    dbInsert("Inventory", "Seafood", "Salmon", 25, 25.00)
    dbInsert("Inventory", "Seafood", "Tilapia", 25, 15.00)
    dbInsert("Inventory", "Seafood", "Caviar Bottle", 10, 250.00)
    dbInsert("Inventory", "Seafood", "Seafood Rub", 250, 5.00)
    dbInsert("Inventory", "Seafood", "Mussels", 200, 12.00)
    dbInsert("Inventory", "Seafood", "Oysters", 200, 34.00)
    dbInsert("Inventory", "Seafood", "Fish Sticks", 100, 1.99)
    dbInsert("Inventory", "Seafood", "Fish Sauce", 25, 9.99)
    dbInsert("Inventory", "Seafood", "Eel", 20, 47.00)
    print("load_inventory committed")

# this is how the products actually get added into the table
# we have drop downs next to each thing inside of the table they can see when trying to purchase something
# they can go to the appropriate button, add however much they want, and then it'll be added to
# their shopping cart and that much is removed from the inventory
@app.route("/addToCart", methods=["POST", "GET"])
def addToCart():
    if request.method == "POST":
        try:
            with sql.connect("groceryData.db") as con:
                dept = request.form["addToCart"]
                rows = get_X_inventory(dept)
                for row in rows:
                    if(request.form[row["Name"]] == "0"):
                        continue
                    # Add to Cart
                    dbInsert("ShoppingCart", row["Kind"], row["Name"], request.form[row["Name"]],
                             row["Cost"], 0.075 if (dept != "Produce" and dept != "Seafood") else 0)
                    # Update Inventory
                    dbInsert("Inventory", row["Kind"], row["Name"], -int(request.form[row["Name"]]), row["Cost"],
                             0.075 if (dept != "Produce" and dept != "Seafood") else 0)
                print("addedToCart")
        except:
            print("Could not addToCart")
            con.rollback()
        finally:
            con.close()
            return get_shopping_cart()

# when the user wants to checkout, this page will get them their sale amount and
# render the appropriate page after performing the calculations necessary
@app.route("/Checkout.html", methods=["POST", "GET"])
def checkout():
    if request.method == "POST":
        global randnum
        if randnum == 1:
            sale = 0.95
        elif randnum == 2:
            sale = 0.85
        elif randnum == 3:
            sale = 0.90
        elif randnum == 4:
            sale = 0.75
        elif randnum == 5:
            sale = 0.80
        elif randnum == 6:
            sale = 0.90
        elif randnum == 7:
            sale = 0.95
        else:
            sale = 1
        try:
            with sql.connect("groceryData.db") as con:
                con.row_factory = sql.Row
                cur = con.cursor()
                cur.execute("DELETE FROM Receipt")
                cur.execute("INSERT INTO Receipt SELECT * FROM ShoppingCart")
                cur.execute("DELETE FROM ShoppingCart")
                con.commit()
                print("checkout Committed")
        except:
            print("Could not checkout")
            con.rollback()
            con.close()
            return render_template("index.html")
        else:
            cur.execute("SELECT * FROM Receipt")
            rows = cur.fetchall()
            sub = tax = total = 0
            for row in rows:
                # Calculate Receipt values
                sub += row["Cost"] * row["Amount"] * sale
                tax += row["Cost"] * row["Amount"] * row["Tax"]
            total += sub + tax
            totals = (sub, tax, total)
            return render_template("Receipt.html", rows=rows, totals=totals)

# just a main to actually get the program running
if __name__ == "__main__":
    # If db empty, load_inventory()
    if not sql.connect("groceryData.db").cursor().execute("SELECT * FROM Inventory").fetchone():
        load_inventory()
    randnum = randint(1, 7)
    print(randnum)
    app.run(host="0.0.0.0")


import os
import sys
__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(__dir__)
sys.path.append(os.path.abspath(os.path.join(__dir__, '..')))

import cv2
import copy
import numpy as np
import math
import time
import torch
import paddle.fluid as fluid

import predict.predict_utility as utility
logger = utility.initial_logger()

from src.utils.input_utility import get_image_file_list, check_and_read_gif
from src.postprocess.crnn_postprocess import CharacterOps

from ctcdecode import CTCBeamDecoder
from spellchecker import SpellChecker
from nltk.tokenize import word_tokenize

class TextRecognizer(object):
    def __init__(self, args):
        if args.use_pdserving is False:
            self.predictor, self.input_tensor, self.output_tensors =\
                utility.create_predictor(args, mode="rec")
            self.use_zero_copy_run = args.use_zero_copy_run
        self.rec_image_shape = [int(v) for v in args.rec_image_shape.split(",")]
        self.rec_render = args.rec_render
        self.character_type = args.rec_char_type
        self.rec_batch_num = args.rec_batch_num
        self.rec_algorithm = args.rec_algorithm
        self.rec_whitelist = args.rec_whitelist
        self.rec_blacklist = args.rec_blacklist
        self.text_len = args.max_text_length

        char_ops_params = {
            "character_type": args.rec_char_type,
            "character_dict_path": args.rec_char_dict_path,
            "use_space_char": args.use_space_char,
            "max_text_length": args.max_text_length
        }
        if self.rec_algorithm in ["CRNN", "Rosetta", "STAR-Net"]:
            char_ops_params['loss_type'] = 'ctc'
            self.loss_type = 'ctc'
        elif self.rec_algorithm == "RARE":
            char_ops_params['loss_type'] = 'attention'
            self.loss_type = 'attention'
        elif self.rec_algorithm == "SRN":
            char_ops_params['loss_type'] = 'srn'
            self.loss_type = 'srn'
        self.char_ops = CharacterOps(char_ops_params)
        self.len_chars = self.char_ops.len_characters()

        # If both blacklist and whitelist are provided, whitelist is only used
        if self.rec_whitelist=='' and self.rec_blacklist!='':
            self.mod_chars = np.arange(start=0, stop=self.len_chars+1, step=1)
            black_list = self.char_ops.encode(self.rec_blacklist)
            self.mod_chars = np.setdiff1d(self.mod_chars, black_list)
        elif self.rec_whitelist!='':
            white_list = self.char_ops.encode(self.rec_whitelist)
            self.mod_chars = np.append(white_list, [self.len_chars])
        elif self.rec_whitelist=='' and self.rec_blacklist=='':
            self.mod_chars = []

        self.use_beam_search = args.use_beam_search
        if self.use_beam_search:
            self.beam_width = args.beam_width
            self.beam_lm_dir = args.beam_lm_dir if args.beam_lm_dir != '' else None
            self.beam_alpha = args.beam_alpha
            self.beam_beta = args.beam_beta
            self.beam_cutoff_top = args.beam_cutoff_top
            self.beam_cutoff_prob = args.beam_cutoff_prob
            # self.labels = self.char_ops.decode(np.arange(0,self.len_chars,1)) + '_'
            self.labels = list(self.char_ops.decode(self.mod_chars) + '_')
            self.blank_id = len(self.mod_chars)

            self.decoder = CTCBeamDecoder(
                labels = self.labels,
                model_path=self.beam_lm_dir,
                alpha=self.beam_alpha,
                beta=self.beam_beta,
                cutoff_top_n=self.beam_cutoff_top,
                cutoff_prob=self.beam_cutoff_prob,
                beam_width=self.beam_width,
                num_processes=os.cpu_count(),
                blank_id=self.blank_id,
                log_probs_input=False
            )

        self.use_spell_check = args.use_spell_check
        if self.use_spell_check:
            self.spell_case_sensitive = args.spell_case_sensitive
            self.spell_language = "" if self.spell_case_sensitive else args.spell_language
            self.spell_tokenizer = word_tokenize if args.spell_tokenizer == 'NLTK' else None
            self.spell_word_freq = args.spell_word_freq if args.spell_word_freq !='' else None
            self.spell_text_corpus = args.spell_text_corpus

            self.spell = SpellChecker(
                language=self.spell_language,
                local_dictionary=self.spell_word_freq,
                tokenizer=self.spell_tokenizer,
                case_sensitive=self.spell_case_sensitive,
            )

            if self.spell_text_corpus != '':
                self.spell.word_frequency.load_text_file(self.spell_text_corpus)

    def resize_norm_img(self, img, max_wh_ratio):
        imgC, imgH, imgW = self.rec_image_shape
        assert imgC == img.shape[2]
        if self.character_type == "ch":
            imgW = int((32 * max_wh_ratio))
        h, w = img.shape[:2]
        ratio = w / float(h)
        if math.ceil(imgH * ratio) > imgW:
            resized_w = imgW
        else:
            resized_w = int(math.ceil(imgH * ratio))
        resized_image = cv2.resize(img, (resized_w, imgH))
        resized_image = resized_image.astype('float32')
        resized_image = resized_image.transpose((2, 0, 1)) / 255
        resized_image -= 0.5
        resized_image /= 0.5
        padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
        padding_im[:, :, 0:resized_w] = resized_image
        return padding_im

    def resize_norm_img_srn(self, img, image_shape):
        imgC, imgH, imgW = image_shape

        img_black = np.zeros((imgH, imgW))
        im_hei = img.shape[0]
        im_wid = img.shape[1]

        if im_wid <= im_hei * 1:
            img_new = cv2.resize(img, (imgH * 1, imgH))
        elif im_wid <= im_hei * 2:
            img_new = cv2.resize(img, (imgH * 2, imgH))
        elif im_wid <= im_hei * 3:
            img_new = cv2.resize(img, (imgH * 3, imgH))
        else:
            img_new = cv2.resize(img, (imgW, imgH))

        img_np = np.asarray(img_new)
        img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
        img_black[:, 0:img_np.shape[1]] = img_np
        img_black = img_black[:, :, np.newaxis]

        row, col, c = img_black.shape
        c = 1

        return np.reshape(img_black, (c, row, col)).astype(np.float32)

    def srn_other_inputs(self, image_shape, num_heads, max_text_length,
                         char_num):

        imgC, imgH, imgW = image_shape
        feature_dim = int((imgH / 8) * (imgW / 8))

        encoder_word_pos = np.array(range(0, feature_dim)).reshape(
            (feature_dim, 1)).astype('int64')
        gsrm_word_pos = np.array(range(0, max_text_length)).reshape(
            (max_text_length, 1)).astype('int64')

        gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
        gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
            [-1, 1, max_text_length, max_text_length])
        gsrm_slf_attn_bias1 = np.tile(
            gsrm_slf_attn_bias1,
            [1, num_heads, 1, 1]).astype('float32') * [-1e9]

        gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
            [-1, 1, max_text_length, max_text_length])
        gsrm_slf_attn_bias2 = np.tile(
            gsrm_slf_attn_bias2,
            [1, num_heads, 1, 1]).astype('float32') * [-1e9]

        encoder_word_pos = encoder_word_pos[np.newaxis, :]
        gsrm_word_pos = gsrm_word_pos[np.newaxis, :]

        return [
            encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
            gsrm_slf_attn_bias2
        ]

    def process_image_srn(self,
                          img,
                          image_shape,
                          num_heads,
                          max_text_length,
                          char_ops=None):
        norm_img = self.resize_norm_img_srn(img, image_shape)
        norm_img = norm_img[np.newaxis, :]
        char_num = char_ops.get_char_num()

        [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \
            self.srn_other_inputs(image_shape, num_heads, max_text_length, char_num)

        gsrm_slf_attn_bias1 = gsrm_slf_attn_bias1.astype(np.float32)
        gsrm_slf_attn_bias2 = gsrm_slf_attn_bias2.astype(np.float32)

        return (norm_img, encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
                gsrm_slf_attn_bias2)

    def __call__(self, img_list):
        img_num = len(img_list)
        # Calculate the aspect ratio of all text bars
        width_list = []
        for img in img_list:
            width_list.append(img.shape[1] / float(img.shape[0]))
        # Sorting can speed up the recognition process
        indices = np.argsort(np.array(width_list))

        #rec_res = []
        rec_res = [['', 0.0]] * img_num
        batch_num = self.rec_batch_num
        predict_time = 0
        for beg_img_no in range(0, img_num, batch_num):
            end_img_no = min(img_num, beg_img_no + batch_num)
            norm_img_batch = []
            max_wh_ratio = 0
            for ino in range(beg_img_no, end_img_no):
                # h, w = img_list[ino].shape[0:2]
                h, w = img_list[indices[ino]].shape[0:2]
                wh_ratio = w * 1.0 / h
                max_wh_ratio = max(max_wh_ratio, wh_ratio)
            for ino in range(beg_img_no, end_img_no):
                if self.loss_type != "srn":
                    norm_img = self.resize_norm_img(img_list[indices[ino]],
                                                    max_wh_ratio)
                    norm_img = norm_img[np.newaxis, :]
                    norm_img_batch.append(norm_img)
                else:
                    norm_img = self.process_image_srn(img_list[indices[ino]],
                                                      self.rec_image_shape, 8,
                                                      25, self.char_ops)
                    encoder_word_pos_list = []
                    gsrm_word_pos_list = []
                    gsrm_slf_attn_bias1_list = []
                    gsrm_slf_attn_bias2_list = []
                    encoder_word_pos_list.append(norm_img[1])
                    gsrm_word_pos_list.append(norm_img[2])
                    gsrm_slf_attn_bias1_list.append(norm_img[3])
                    gsrm_slf_attn_bias2_list.append(norm_img[4])
                    norm_img_batch.append(norm_img[0])

            norm_img_batch = np.concatenate(norm_img_batch, axis=0)
            norm_img_batch = norm_img_batch.copy()

            if self.loss_type == "srn":
                starttime = time.time()
                encoder_word_pos_list = np.concatenate(encoder_word_pos_list)
                gsrm_word_pos_list = np.concatenate(gsrm_word_pos_list)
                gsrm_slf_attn_bias1_list = np.concatenate(
                    gsrm_slf_attn_bias1_list)
                gsrm_slf_attn_bias2_list = np.concatenate(
                    gsrm_slf_attn_bias2_list)
                starttime = time.time()

                norm_img_batch = fluid.core.PaddleTensor(norm_img_batch)
                encoder_word_pos_list = fluid.core.PaddleTensor(
                    encoder_word_pos_list)
                gsrm_word_pos_list = fluid.core.PaddleTensor(gsrm_word_pos_list)
                gsrm_slf_attn_bias1_list = fluid.core.PaddleTensor(
                    gsrm_slf_attn_bias1_list)
                gsrm_slf_attn_bias2_list = fluid.core.PaddleTensor(
                    gsrm_slf_attn_bias2_list)

                inputs = [
                    norm_img_batch, encoder_word_pos_list,
                    gsrm_slf_attn_bias1_list, gsrm_slf_attn_bias2_list,
                    gsrm_word_pos_list
                ]

                self.predictor.run(inputs)
            else:
                starttime = time.time()
                if self.use_zero_copy_run:
                    self.input_tensor.copy_from_cpu(norm_img_batch)
                    self.predictor.zero_copy_run()
                else:
                    norm_img_batch = fluid.core.PaddleTensor(norm_img_batch)
                    self.predictor.run([norm_img_batch])

            if len(self.mod_chars)!=0:
                mod_onehot = np.zeros((self.len_chars + 1))
                mod_onehot[self.mod_chars] = 1

            if self.loss_type == "ctc":
                rec_idx_batch = self.output_tensors[0].copy_to_cpu()
                rec_idx_lod = self.output_tensors[0].lod()[0]
                predict_batch = self.output_tensors[1].copy_to_cpu()
                predict_lod = self.output_tensors[1].lod()[0]

                if len(self.mod_chars)!=0:
                    predict_batch = np.multiply(predict_batch, mod_onehot) #* Implemented blacklist and whitelist here!

                for rno in range(len(rec_idx_lod) - 1):

                    beg = predict_lod[rno]
                    end = predict_lod[rno + 1]
                    probs = predict_batch[beg:end, :]
                    ind = np.argmax(probs, axis=1)
                    valid_ind = range(ind.shape[0])
                    preds_text = self.char_ops.decode(ind[valid_ind], is_remove_duplicate=True)
                    if len(valid_ind) == 0:
                        continue
                    score = np.mean(probs[valid_ind, ind[valid_ind]])

                    # use_spell_check results are the final results if both beam search and spell check is true!
                    if self.use_beam_search:
                        mod_probs = probs[:,self.mod_chars]
                        mod_probs = torch.Tensor(mod_probs).unsqueeze(0)
                        beams,scores,_,out_lens = self.decoder.decode(mod_probs)
                        res_beam = beams[0][0][:out_lens[0][0]]
                        res_list = [self.mod_chars[i] for i in res_beam]
                        res_text = self.char_ops.decode(res_list)
                        score_beam = 1/np.exp(scores[0][0])
                        if preds_text != res_text:
                            print(f'original: {preds_text} || beam_search_corrected: {res_text}')
                        rec_res[indices[beg_img_no + rno]] = [res_text, score_beam]

                        if self.use_spell_check:
                            corrected = self.spell.correction(res_text)
                            if preds_text != corrected:
                                print(f'original: {preds_text} || spell_check_corrected: {corrected}')
                            rec_res[indices[beg_img_no + rno]] = [corrected, score_beam]

                    elif self.use_spell_check:
                        corrected = self.spell.correction(preds_text)
                        if preds_text != corrected:
                            print(f'original: {preds_text} || spell_check_corrected: {corrected}')
                        rec_res[indices[beg_img_no + rno]] = [corrected, score]

                    else:
                        rec_res[indices[beg_img_no + rno]] = [preds_text, score]

            elif self.loss_type == 'srn':
                rec_idx_batch = self.output_tensors[0].copy_to_cpu()
                probs = self.output_tensors[1].copy_to_cpu()

                # TODO: implement whitelist and blacklist for srn loss

                char_num = self.char_ops.get_char_num()
                preds = rec_idx_batch.reshape(-1)
                elapse = time.time() - starttime
                predict_time += elapse
                total_preds = preds.copy()
                for ino in range(int(len(rec_idx_batch) / self.text_len)):
                    preds = total_preds[ino * self.text_len:(ino + 1) *
                                        self.text_len]
                    ind = np.argmax(probs, axis=1)
                    valid_ind = np.where(preds != int(char_num - 1))[0]
                    if len(valid_ind) == 0:
                        continue
                    score = np.mean(probs[valid_ind, ind[valid_ind]])
                    preds = preds[:valid_ind[-1] + 1]
                    preds_text = self.char_ops.decode(preds)

                    rec_res[indices[beg_img_no + ino]] = [preds_text, score]
            else:
                rec_idx_batch = self.output_tensors[0].copy_to_cpu()
                predict_batch = self.output_tensors[1].copy_to_cpu()

                # TODO: implement whitelist and blacklist for srn loss

                elapse = time.time() - starttime
                predict_time += elapse
                for rno in range(len(rec_idx_batch)):
                    end_pos = np.where(rec_idx_batch[rno, :] == 1)[0]
                    if len(end_pos) <= 1:
                        preds = rec_idx_batch[rno, 1:]
                        score = np.mean(predict_batch[rno, 1:])
                    else:
                        preds = rec_idx_batch[rno, 1:end_pos[1]]
                        score = np.mean(predict_batch[rno, 1:end_pos[1]])
                    preds_text = self.char_ops.decode(preds)
                    # rec_res.append([preds_text, score])
                    rec_res[indices[beg_img_no + rno]] = [preds_text, score]

        # *TODO: COMPLETE (if self.rec_render:)

        return rec_res, predict_time

def main(args):
    image_file_list = get_image_file_list(args.image_dir)
    text_recognizer = TextRecognizer(args)
    valid_image_file_list = []
    img_list = []
    for image_file in image_file_list:
        img, flag = check_and_read_gif(image_file)
        if not flag:
            img = cv2.imread(image_file)
        if img is None:
            logger.info("error in loading image:{}".format(image_file))
            continue
        valid_image_file_list.append(image_file)
        img_list.append(img)

    try:
        rec_res, predict_time = text_recognizer(img_list)
    except Exception as e:
        print(e)
        logger.info(
            "ERROR!!!! \n"
            "Please read the FAQ: https://github.com/PaddlePaddle/PaddleOCR#faq \n"
            "If your model has tps module:  "
            "TPS does not support variable shape.\n"
            "Please set --rec_image_shape='3,32,100' and --rec_char_type='en' ")
        exit()
    for ino in range(len(img_list)):
        print("Predicts of %s:%s" % (valid_image_file_list[ino], rec_res[ino]))
    print("Total predict time for %d images:%.3f" %
          (len(img_list), predict_time))

if __name__ == "__main__":
    main(utility.parse_args())


import json
from datetime import datetime, timedelta

TODAY = datetime.now().date()
TOMORROW = TODAY + timedelta(days=1)

class Locations:
    def __init__(self, locations_file):
        self.locations = self.load_locations(locations_file)

    def load_locations(self, locations_file):
        with open(locations_file, "r") as locations_list:
            available_locations = json.load(locations_list)
        return available_locations

class SaveLocations:
    def __init__(self, locations_file, available_locations):
        self.save = self.save_locations(locations_file, available_locations)

    def save_locations(self, locations_file, available_locations):
        with open(locations_file, "w") as locations_list:
            json.dump(available_locations, locations_list)

available_locations = Locations("locations.json")
available_locations = available_locations.locations

def try_float(message):
    input_check = False
    while not input_check:
        try:
            user_input = float(input(f"{message}").replace(",", "."))
            return user_input
        except ValueError:
            print("Błąd. Spróbuj ponownie")

def print_available_locations():
    location_name_list = []
    for location_name, data in available_locations.items():
        location_name_list.append(location_name)
    print(f"Dostępne lokacje: {location_name_list}")

def select_location():
    print_available_locations()
    location_name = None
    while not location_name:
        location_name = input("Podaj nazwę miasta: ").upper()
        if len(location_name) == 0:
            print("Błąd. Spróbuj ponownie")
            location_name = None
    if location_name not in available_locations:
        print("Nie wykryto miasta.")
        add_new_city(location_name)
    latitude = available_locations[location_name].get("latitude")
    longitude = available_locations[location_name].get("longitude")
    return latitude, longitude, location_name

def add_new_city(location_name):
    location_latitude = try_float("Podaj szerokość geograficzną: ")
    location_longitude = try_float("Podaj długość geograficzną: ")
    available_locations[location_name] = {
        "latitude": location_latitude,
        "longitude": location_longitude
    }
    save_locations = SaveLocations("locations.json", available_locations)
    save_locations.save

def get_date():
    date_correct = False
    while not date_correct:
        global TODAY, TOMORROW
        print(
            f"Podaj date (YYYY-MM-DD). Pozostaw pole puste, aby wyświetlić dla jutra, tj.: {TOMORROW}")
        date = input(": ")
        if len(date) == 0:
            return TOMORROW
        try:
            date = datetime.strptime(date, "%Y-%m-%d").date()
            return date
        except ValueError:
            print("Niepoprawny format daty.\n Spróbuj ponownie")

def bad_attribute_value(attribute):
    print(
        f"Podana wartość: \"{attribute}\" jest niepoprawna. Spóbuj ponownie.")
    return None

def attribute_type_check(attribute_type, message):
    if attribute_type == str:
        print(message)
        user_input = None
        while not isinstance(user_input, str):
            try:
                user_input = str(input(":>>> "))
                return user_input
            except ValueError:
                user_input = bad_attribute_value(user_input)

def continue_request():
    print("Czy kontynować?")
    user_confirm = False
    while not user_confirm:
        user_confirm = attribute_type_check(str, ">>>TAK/NIE").upper()
        if user_confirm == "TAK":
            return True
        elif user_confirm == "NIE":
            return False
        else:
            user_confirm = bad_attribute_value(user_confirm)
            user_confirm = False


import numpy as np
from math import factorial
import matplotlib.pyplot as plt
import cv2
import logging
import os

cs = ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00']

def savitzky_golay(y, window_size, order, deriv=0, rate=1):
    r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter.
    The Savitzky-Golay filter removes high frequency noise from data.
    It has the advantage of preserving the original shape and
    features of the signal better than other types of filtering
    approaches, such as moving averages techniques.
    Parameters
    ----------
    y : array_like, shape (N,)
        the values of the time history of the signal.
    window_size : int
        the length of the window. Must be an odd integer number.
    order : int
        the order of the polynomial used in the filtering.
        Must be less then `window_size` - 1.
    deriv: int
        the order of the derivative to compute (default = 0 means only smoothing)
    Returns
    -------
    ys : ndarray, shape (N)
        the smoothed signal (or it's n-th derivative).
    ----------
    .. [1] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of
       Data by Simplified Least Squares Procedures. Analytical
       Chemistry, 1964, 36 (8), pp 1627-1639.
    .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing
       W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery
       Cambridge University Press ISBN-13: 9780521880688
    """

    try:
        window_size = np.abs(np.int(window_size))
        order = np.abs(np.int(order))
    except:
        print('wrong types')
    # except ValueError, msg:
    #     raise ValueError("window_size and order have to be of type int")
    if window_size % 2 != 1 or window_size < 1:
        raise TypeError("window_size size must be a positive odd number")
    if window_size < order + 2:
        raise TypeError("window_size is too small for the polynomials order")
    order_range = range(order + 1)
    half_window = (window_size - 1) // 2
    # precompute coefficients
    b = np.mat([[k ** i for i in order_range] for k in range(-half_window, half_window + 1)])
    m = np.linalg.pinv(b).A[deriv] * rate ** deriv * factorial(deriv)
    # pad the signal at the extremes with
    # values taken from the signal itself
    firstvals = y[0] - np.abs(y[1:half_window + 1][::-1] - y[0])
    lastvals = y[-1] + np.abs(y[-half_window - 1:-1][::-1] - y[-1])
    y = np.concatenate((firstvals, y, lastvals))
    return np.convolve(m[::-1], y, mode='valid')

def hist(data):
    d = np.diff(np.unique(data)).min()
    left_of_first_bin = data.min() - float(d) / 2
    right_of_last_bin = data.max() + float(d) / 2
    plt.hist(data, np.arange(left_of_first_bin, right_of_last_bin + d, d))

def order_points(pts):
    # initialzie a list of coordinates that will be ordered
    # such that the first entry in the list is the top-left,
    # the second entry is the top-right, the third is the
    # bottom-right, and the fourth is the bottom-left
    rect = np.zeros((4, 2), dtype="float32")

    # the top-left point will have the smallest sum, whereas
    # the bottom-right point will have the largest sum
    s = pts.sum(axis=1)
    rect[0] = pts[np.argmin(s)]
    rect[2] = pts[np.argmax(s)]

    # now, compute the difference between the points, the
    # top-right point will have the smallest difference,
    # whereas the bottom-left will have the largest difference
    diff = np.diff(pts, axis=1)
    rect[1] = pts[np.argmin(diff)]
    rect[3] = pts[np.argmax(diff)]

    # return the ordered coordinates
    return rect

def four_point_transform(image, pts):
    # obtain a consistent order of the points and unpack them
    # individually
    rect = order_points(pts)
    (tl, tr, br, bl) = rect

    # compute the width of the new image, which will be the
    # maximum distance between bottom-right and bottom-left
    # x-coordiates or the top-right and top-left x-coordinates
    widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
    widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
    maxWidth = max(int(widthA), int(widthB))

    # compute the height of the new image, which will be the
    # maximum distance between the top-right and bottom-right
    # y-coordinates or the top-left and bottom-left y-coordinates
    heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
    heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
    maxHeight = max(int(heightA), int(heightB))

    # now that we have the dimensions of the new image, construct
    # the set of destination points to obtain a "birds eye view",
    # (i.e. top-down view) of the image, again specifying points
    # in the top-left, top-right, bottom-right, and bottom-left
    # order
    dst = np.array([
        [0, 0],
        [maxWidth - 1, 0],
        [maxWidth - 1, maxHeight - 1],
        [0, maxHeight - 1]], dtype="float32")

    # compute the perspective transform matrix and then apply it
    M = cv2.getPerspectiveTransform(rect, dst)
    warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))

    # return the warped image
    return warped

def annotate_vid_with_frame_num(fname, out_file="out", NUM_FRAMES=None):
    # open video and create background subtractors
    logging.info('tracking %s', fname)
    cap = cv2.VideoCapture(fname)

    # initialize loop
    frame_num = 0
    if NUM_FRAMES is None:
        NUM_FRAMES = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    logging.info('num_frames %d', NUM_FRAMES)

    # make out_dir
    if not os.path.exists(os.path.dirname(os.path.abspath(out_file))):
        os.makedirs(os.path.dirname(os.path.abspath(out_file)))

    # remove file if it exists
    if os.path.exists(out_file):
        os.remove(out_file)

    # tube dimensions
    width, height = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    video = cv2.VideoWriter(out_file, -1, 7, (width, height))

    # loop over frames
    ret, frame = cap.read()
    while ret and frame_num < NUM_FRAMES:
        if frame_num % 100 == 0:
            logging.info('frame_num %d', frame_num)
        # read next frame
        frame_num += 1
        ret, frame = cap.read()

        cv2.putText(frame, "frame_num: %d" % (frame_num),
                    (20, 40), cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, color=(0, 255, 0))
        video.write(frame)

    video.release()


# jsb.plugs.socket/kickban.py
#
#

""" kickban functionality for IRC. """

## jsb imports

from jsb.utils.generic import getwho
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.callbacks import callbacks

## basic imports

import Queue
import time
import logging

## defines

bans      = {}
cachetime = 300
timeout   = 10

## callbacks

def handle_367(bot, ievent):
    logging.debug('kickban - 367 - %s' % str(ievent))
    channel = ievent.arguments[1].lower()
    if not bot.name in bans or not channel in bans[bot.name]:
        return # not requested by this plugin
    bans[bot.name][channel].append(ievent.txt.split()[0])

def handle_mode(bot, ievent):
    logging.debug('kick-ban - mode - %s' % str(ievent))
    # [18 Jan 2008 13:41:29] (mode) cmnd=MODE prefix=maze!wijnand@2833335b.cc9dd561.com.hmsk postfix=#eth0-test +b *!*@je.moeder.ook arguments=[u'#eth0-test', u'+b', u'*!*@je.moeder.ook'] nick=maze user=wijnand userhost=wijnand@2833335b.cc9dd561.com.hmsk channel=#eth0-test txt= command= args=[] rest= speed=5 options={}

## functions

def get_bans(bot, channel):
    # :ironforge.sorcery.net 367 basla #eth0 *!*@71174af5.e1d1a3cf.net.hmsk eth0!eth0@62.212.76.127 1200657224
    # :ironforge.sorcery.net 367 basla #eth0 *!*@6ca5f0a3.14055a38.89.123.imsk eth0!eth0@62.212.76.127 1200238584
    # :ironforge.sorcery.net 368 basla #eth0 :End of Channel Ban List
    channel = channel.lower()
    if not bot.name in bans:
        bans[bot.name] = {}
    bans[bot.name][channel] = []
    queue368 = Queue.Queue()
    if not bot.wait:
        return
    bot.wait.register('368', channel, queue368)
    bot.sendraw('MODE %s +b' % (channel, ))
    # wait for End of Channel Ban List
    try:
        res = queue368.get(1, timeout)
    except Queue.Empty:
        return None
    return bans[bot.name][channel]

def get_bothost(bot):
    return getwho(bot, bot.nick).split('@')[-1].lower()

## commands

def handle_ban_list(bot, ievent):
    banslist = get_bans(bot, ievent.channel)
    if not banslist:
        ievent.reply('the ban list for %s is empty' % ievent.channel)
    else:
        ievent.reply('bans on %s: ' % ievent.channel, banslist, nr=True)

def handle_ban_remove(bot, ievent):
    channel = ievent.channel.lower()
    if len(ievent.args) != 1 or not ievent.args[0].isdigit():
        ievent.missing('<banlist index>')
        return
    if not bot.name in bans or not channel in bans[bot.name]:
        banslist = get_bans(bot, ievent.channel)
    else:
        banslist = bans[bot.name][channel]
        index = int(ievent.args[0])-1
        if len(banslist) <= index:
            ievent.reply('ban index out of range')
        else:
            unban = banslist[index]
            banslist.remove(unban)
            bot.sendraw('MODE %s -b %s' % (channel, unban))
            ievent.reply('unbanned %s' % (unban, ))

def handle_ban_add(bot, ievent):
    if not ievent.args:
        ievent.missing('<nick>')
        return
    if ievent.args[0].lower() == bot.nick.lower():
        ievent.reply('not going to ban myself')
        return
    userhost = getwho(bot, ievent.args[0])
    if userhost:
        host = userhost.split('@')[-1].lower()
        if host == get_bothost(bot):
            ievent.reply('not going to ban myself')
            return
        bot.sendraw('MODE %s +b *!*@%s' % (ievent.channel, host))
        ievent.reply('banned %s' % (host, ))
    else:
        ievent.reply('can not get userhost of %s' % ievent.args[0])

def handle_kickban_add(bot, ievent):
    if not ievent.args:
        ievent.missing('<nick> [<reason>]')
        return
    if ievent.args[0].lower() == bot.nick.lower():
        ievent.reply('not going to kickban myself')
        return
    userhost = getwho(bot, ievent.args[0])
    reason = len(ievent.args) > 1 and ' '.join(ievent.args[1:]) or 'Permban requested, bye'
    if userhost:
        host = userhost.split('@')[-1].lower()
        if host == get_bothost(bot):
            ievent.reply('not going to kickban myself')
            return
        bot.sendraw('MODE %s +b *!*@%s' % (ievent.channel, host))
        bot.sendraw('KICK %s %s :%s' % (ievent.channel, ievent.args[0], reason))
    else:
        ievent.reply('can not get userhost of %s' % ievent.args[0])

callbacks.add('367', handle_367)
callbacks.add('MODE', handle_mode)

cmnds.add('ban-add', handle_ban_add, 'OPER')
examples.add('ban-add', 'adds a host to the ban list', 'ban-add *!*@lamers.are.us')
cmnds.add('ban-list', handle_ban_list, 'OPER', threaded=True)
cmnds.add('ban-remove', handle_ban_remove, 'OPER', threaded=True)
examples.add('ban-remove', 'removes a host from the ban list', 'ban-remove 1')
cmnds.add('ban-kickban', handle_kickban_add, 'OPER')
examples.add('ban-kickban', 'kickbans the given nick', 'kickban Lam0r Get out of here')


import unittest

from typing import List

import ansi

class TestAnsi(unittest.TestCase):

  def test_print_colors(self) -> None:
    for function in [
        ansi.red,
        ansi.green,
        ansi.yellow,
        ansi.gray,
        ansi.bright_green,
    ]:
      print('Printing in %s...' % function(function.__name__))

if __name__ == '__main__':
  unittest.main()


import kivy
import db

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.config import Config
kivy.require('1.10.1')

class AppBoxLayout(BoxLayout):
    @staticmethod
    def send_greetings(name, greeting):
        db.send_greetings(name, greeting)

class GreetingApp(App):

    def build(self):
        Config.set('graphics', 'width', '500')
        Config.set('graphics', 'height', '400')
        Config.write()

        return AppBoxLayout()

if __name__ == '__main__':
    GreetingApp().run()


#making the necessary imports
import nltk
import re
import pandas as pd
import heapq

#import the dataset
dataset = pd.read_csv('data.csv',nrows=9)
big_texts = dataset.iloc[:,-1]

#some helping functions
#------------------------------------------------------------------------------
def clean_text(unclean_text):
    unclean_text = re.sub(r'\[[0-9]*\]',' ',unclean_text)
    unclean_text = re.sub(r'\s+',' ',unclean_text)
    clean_text = unclean_text.lower()
    clean_text = re.sub(r'\W',' ',clean_text)
    clean_text = re.sub(r'\d',' ',clean_text)
    clean_text = re.sub(r'\s+',' ',clean_text)
    return clean_text

def generate_word2count(ct,sp):
    word2count = {}
    for word in nltk.word_tokenize(ct):
        if word not in sp:
            if word not in word2count.keys():
                word2count[word] = 1
            else:
                word2count[word] += 1
    for key in word2count.keys():
        word2count[key] = word2count[key]/max(word2count.values())
    return word2count

def score_sentences(s,w):
    sent2score = {}
    for sentence in s:
        for word in nltk.word_tokenize(sentence.lower()):
            if word in w.keys():
                if len(sentence.split(' ')) < 25:
                    if sentence not in sent2score.keys():
                        sent2score[sentence] = w[word]
                    else:
                        sent2score[sentence] += w[word]
    return sent2score
#------------------------------------------------------------------------------

#take in the paragraph for summarizing
text = str(big_texts[1])
sents = nltk.sent_tokenize(text)

#calling the preprocessing function
clean_text = clean_text(text)
stop_words = nltk.corpus.stopwords.words('english')

#creating word2count table
word2count = {}
word2count = generate_word2count(clean_text,stop_words)

#give score to the sentences
sent2score = {}
sent2score = score_sentences(sents,word2count)

#summarize the text according to scored sentences and print the result
average_score = sum(list(sent2score.values()))/len(list(sent2score.values()))
best_sentences2 = []
for i in list(sent2score.keys()):
    if sent2score[i] >= average_score:
        best_sentences2.append(i)
#second approach
best_sentences = heapq.nlargest(5, sent2score, key=sent2score.get)
print('---------------------------------------------------------')
for sentence in best_sentences2:
    print(sentence)


import numpy as np
import const as cst
from scipy.integrate import solve_ivp
#pour minimaliser la charge de calcul repetitive on définit une méta-constante
c=(cst.rho*np.pi*cst.d**2)/(8*cst.m)
def oderhs(t,y):
    v = np.array(y[3:6], dtype=cst.dtype)
    w=np.array(y[6:9],dtype=cst.dtype)
    normv=np.linalg.norm(v)
    normw=np.linalg.norm(w)
    if(normw>0 and normv>0 ):
        cm=1/(2+(1.96*normv)/(normw*cst.d))
        Fm=(cm*c*normv**2)*np.cross(w/normw,v/normv)
    else:
        Fm=0.0
    if(normv>0):
        Ft=(-1*cst.cd*c*normv**2)*(v/normv)
    else:
        Ft=0
    Fd=np.array([0,0,cst.g])
    a=Fd+Ft+Fm
    alpha=np.zeros(3)
    return np.concatenate((v,a,alpha))

def euler(f,t_span,y,events = None ):
    t=t_span[0]
    step=int(t_span[1]/cst.precision)
    # on alloue un tableau vide que l on remplira au fur et a mesure
    yt=np.empty((step+1,9),dtype=cst.dtype)
    yt[0][:]=y
    for i in range(step):
        dy=f(t,y)
        y=y+dy*cst.precision
        t=t+cst.precision
        if events(t,y):
            yt=np.resize(yt,(i+1,9))# on sépare la partie écrite de la partie empty
            break
        yt[i+1][:]=y
    return yt
def  trajectoirecomplete(yInit,T,bouncing=True):
    pos=euler(oderhs,[0,T],yInit,events=evenement)
    for i in range(pos.shape[0]):
        if(pos[i][0]*pos[0][0]<0 and pos[i][5]>0 and pos[i][2]>cst.hf  ):
            return(0,0,0)
    if bouncing:
        pos[-1][5]=pos[-1][5]*cst.e
        return np.append(pos,trajectoirecomplete(pos[-1][:],T-(pos.shape[0]-1)*cst.precision,bouncing=False),axis=0)
    return pos
def  trajectoireFiletHorizontal(yInit,T,bouncing=True):
    pos=euler(oderhs,[0,T],yInit,events=evenement)
    for i in range(pos.shape[0]):
        # si on n as pas encore passé le filet(la balle est du meme coté que la pos init)
        # et si la posz de la balle est plus petite que le filet et que la balle descend
        # cela ne sert a rien , la balle ne passera pas le filet
        if(pos[i][0]*pos[0][0]<0 and pos[i][5]>0 and pos[i][2]>cst.hf  ):
            return(0,0,0)
        #dans le cas d un deuxieme rebond,il suffit de repartir de la dernière position et de redéfinir la vitesse verticale comme multiplié par e
    if bouncing:
        pos[-1][5]=pos[-1][5]*cst.e
        #pos shape donne la taile du tableau or le premier element contient la pos initale donc on a
        return trajectoireFiletHorizontal(pos[-1][:],T-(pos.shape[0]-1)*cst.precision,bouncing=False)
    return tuple(pos[-1][:3])
def evenement(t,y):
    return 0>y[2]
evenement.terminal=True
y=np.array([-11.89, 0, 2 , 50, 1, 0,30, 15, 0])
T=np.array([0,1])
print(euler(oderhs,T,y,evenement))


import time
start_time = time.perf_counter()

def binarySearch(arr, target, first, last):
    if first > last:
        return 1
    mid = int((first+last)/2)
    if arr[mid]==target:
        return mid
    elif arr[mid] > target:
        return binarySearch(arr, target, first, mid-1)
    else:
        return binarySearch(arr, target, mid+1, last)

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

for i in range(n):
    print(binarySearch(result, lst[i], 0, n-1), end=' ')

end_time = time.perf_counter()
print(f"\ntime elapsed : {int(round((end_time - start_time) * 1000))}ms")


import socket
import json

class SocketClient():

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

    def get_request(self, ids):
        """return json type"""
        if isinstance(ids, str):
            coil_ids = [ids]
        else:
            coil_ids = ids

        request = {}
        request["requests"] = []
        for coil_id in coil_ids:
            req = {}
            req["coilId"] = coil_id
            req["curDir"] = self.ctx.records.get_cur_dir(coil_id)
            req["factors"] = self.ctx.factor.get_factors()
            request["requests"].append(req)

        return json.dumps(request)

    def get_response(self, coil_ids):

        client = socket.socket()
        # 连接到localhost主机的8999端口上去
        client.connect(('localhost', 8999))
        # 把编译成utf-8的数据发送出去
        client.send(self.get_request(coil_ids).encode('utf-8'))
        # 接收数据
        resp = client.recv(10000000)
        coils = json.loads(resp.decode())
        client.close()
        return coils


from .apitask import APITask

from thing import queries
from thing.models import PriceHistory

HISTORY_PER_REQUEST = 50
HISTORY_URL = 'http://goonmetrics.com/api/price_history/?region_id=10000002&type_id=%s'

class HistoryUpdater(APITask):
    name = 'thing.history_updater'

    def run(self):
        if self.init() is False:
            return

        # Get a list of all item_ids
        cursor = self.get_cursor()
        cursor.execute(queries.all_item_ids)

        item_ids = [row[0] for row in cursor]

        cursor.close()

        # Collect data
        new = []
        for i in range(0, len(item_ids), 50):
            # Fetch the XML
            url = HISTORY_URL % (','.join(str(z) for z in item_ids[i:i + 50]))
            data = self.fetch_url(url, {})
            if data is False:
                return

            root = self.parse_xml(data)

            # Do stuff
            for t in root.findall('price_history/type'):
                item_id = int(t.attrib['id'])

                data = {}
                for hist in t.findall('history'):
                    data[hist.attrib['date']] = hist

                # Query that shit
                for ph in PriceHistory.objects.filter(region=10000002, item=item_id, date__in=data.keys()):
                    del data[str(ph.date)]

                # Add new ones
                for date, hist in data.items():
                    new.append(PriceHistory(
                        region_id=10000002,
                        item_id=item_id,
                        date=hist.attrib['date'],
                        minimum=hist.attrib['minPrice'],
                        maximum=hist.attrib['maxPrice'],
                        average=hist.attrib['avgPrice'],
                        movement=hist.attrib['movement'],
                        orders=hist.attrib['numOrders'],
                    ))

        if new:
            PriceHistory.objects.bulk_create(new)

        return True


import os
import glob
from skimage import io
import tqdm
from osgeo import gdal
import numpy as np
import shutil

img_piece_size = (2048, 1024)
img_parent_path = r'M:\Tiny_Ship\temp_uncompress'
img_format = 'tiff'
pieces_save_path = r'M:\Tiny_Ship\20211006_Patches'

def get_file(in_path_list, img_format):
    file_list = []
    for file in in_path_list:
        if os.path.isdir(file):
            files = glob.glob(file + '/*')
            file_list.extend(get_file(files, img_format))
        else:
            if file.split('.')[-1] == img_format:
                file_list += [file]
    return file_list

def get_pieces(img_parent_path, pieces_path, img_format, is_1_level_need_convert=False):
    file_list = get_file([img_parent_path], img_format)
    file_list_names = [os.path.basename(x).replace('.tiff', '') for x in file_list]
    already_exist_files = [os.path.basename(x) for x in glob.glob(pieces_path + '/GF*')]

    file_list = [img_parent_path + '/' + x.split('-')[0] + f'/{x}.tiff' for x in (set(file_list_names) - set(already_exist_files))]
    for img_path in tqdm.tqdm(file_list):
        pieces_save_path = pieces_path + '/' + os.path.basename(img_path).replace('.' + img_format, '').split("-")[0]
        os.makedirs(pieces_save_path, exist_ok=True)
        try:
            cut_img_to_pieces(img_path, pieces_save_path, img_format, is_1_level_need_convert=False)
        except Exception as e:
            shutil.rmtree(pieces_save_path)
            with open("error.txt", 'a') as f:
                f.write(repr(e) + img_path)
                f.write('\n')

def cut_img_to_pieces(img_file: str, save_folder, img_format, is_1_level_need_convert=False):
    tiff_dataset_temp = gdal.Open(img_file, gdal.GA_ReadOnly)
    # 1级产品到2级产品
    # sr = osr.SpatialReference()
    # sr.SetWellKnownGeogCS('WGS84')
    if is_1_level_need_convert and "L1" in img_file:
        img_file = img_file.replace('.' + img_format, '_GEO.' + img_format)
        tiff_dataset = gdal.Warp(img_file, tiff_dataset_temp, format='GTiff',
                                 resampleAlg=gdal.GRIORA_Bilinear, outputType=gdal.GDT_Int16, rpc=True)
    else:
        tiff_dataset = tiff_dataset_temp
    nBand, height, width = tiff_dataset.RasterCount, tiff_dataset.RasterYSize, tiff_dataset.RasterXSize
    h_list = list(range(0, height, img_piece_size[1]))
    h_list[-1] = height - img_piece_size[1]
    w_list = list(range(0, width, img_piece_size[0]))
    w_list[-1] = width - img_piece_size[0]
    for h_step in h_list:
        for w_step in w_list:
            img_data = tiff_dataset.ReadAsArray(w_step, h_step, img_piece_size[0], img_piece_size[1])[:3][::-1]
            img_data = np.transpose(img_data, (1, 2, 0))
            if "GF6" in os.path.basename(img_file):
                normalize_factor = 16
            elif "GF1" in os.path.basename(img_file):
                normalize_factor = 4
            else:
                raise Exception("Un Implement")
            img_piece = (img_data / normalize_factor).astype(np.uint8)
            io.imsave(save_folder + '/%s_%d_%d.tiff' %
                              (os.path.basename(img_file).replace('.' + img_format, ''), w_step, h_step), img_piece, check_contrast=False)

if __name__ == "__main__":
    get_pieces(img_parent_path, pieces_save_path, img_format, is_1_level_need_convert=False)


class Solution(object):
    def findPeakElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # # method 1: Linear O(n)
        # for i in range(0, len(nums)-1):
        #     if nums[i]>nums[i+1]:
        #         return i
        # return len(nums) - 1

        # method 2: Binary Search O(logn)
        left, right = 0, len(nums)-1
        while left<right:
            mid = (left+right)/2
            print(mid)
            if nums[mid] < nums[mid + 1]:
                left = mid + 1
            else:
                right = mid
        return left

Algorithms/Binary Search/162. Find Peak Element.py


def fizzbuzz(num):
    for i in range(1, num+1):
        if i % 15 == 0:
            print('fizzbuzz')
        elif i % 5 == 0:
            print('buzz')
        elif i % 3 == 0:
            print('fizz')
        else:
            print(f'{i}')

if __name__=='__main__':
    fizzbuzz(15)


from queue import PriorityQueue

G = [[-1, 6,-1, 5, 2],
[-1,-1, 1, 2,-1],
[-1,-1,-1,-1,-1],
[-1,-1, 4,-1,-1],
[-1,-1, 8,-1,-1]]

P = [0,1,3]

def Relax(dist, parent, fuel_left, P, u, v, w, d):
    if dist[v] > dist[u] + w:
        dist[v] = dist[u] + w
        parent[v] = u
        for i in range(len(P)):
            if P[i] == v:
                fuel_left[v] = d
                return
        fuel_left[v] = fuel_left[u] - w

def PrintResult(parent, t, result):
    if parent[t] == None:
        return None
    if parent[t] == -1:
        result.append(t)
        return result
    PrintResult(parent, parent[t], result)
    result.append(t)
    return result

def jak_dojade(G, P, d, a, b):
    n = len(G)
    visited = [False]*n
    fuel_left =[0]*n
    dist = [float("inf")]*n
    parent = [None]*n

    Q = PriorityQueue()
    Q.put((0, a))
    dist[a] = 0
    fuel_left[a] = d
    parent[a] = -1

    while not Q.empty():
        u = Q.get()[1]
        visited[u] = True

        for i in range(n):
            if G[u][i] > 0:
                if visited[i] == False and G[u][i] <= fuel_left[u]:
                    Relax(dist, parent, fuel_left, P, u, i, G[u][i], d)
                    Q.put((dist[i], i))
    result = []
    result = PrintResult(parent, b, result)
    return result

print(jak_dojade(G, P, 5, 0, 2))


import warnings
from abc import ABC
from collections import OrderedDict
from copy import copy
from typing import (
    Any,
    Dict,
    Hashable,
    Iterable,
    Iterator,
    List,
    Optional,
    Sequence,
    Tuple,
    Union,
    cast,
)

import torch

from pystiche.meta import is_scalar_tensor
from pystiche.misc import (
    build_complex_obj_repr,
    build_deprecation_message,
    build_fmtstr,
    format_dict,
)

__all__ = ["ComplexObject", "LossDict", "TensorKey"]

class ComplexObject(ABC):
    _STR_INDENT = 2

    def _properties(self) -> Dict[str, Any]:
        return OrderedDict()

    def extra_properties(self) -> Dict[str, Any]:
        return OrderedDict()

    def properties(self) -> Dict[str, Any]:
        dct = self._properties()
        dct.update(self.extra_properties())
        return dct

    def _named_children(self) -> Iterator[Tuple[str, Any]]:
        return iter(())

    def extra_named_children(self) -> Iterator[Tuple[str, Any]]:
        return iter(())

    def named_children(self) -> Iterator[Tuple[str, Any]]:
        yield from self._named_children()
        yield from self.extra_named_children()

    def _build_repr(
        self,
        name: Optional[str] = None,
        properties: Optional[Dict[str, str]] = None,
        named_children: Optional[Sequence[Tuple[str, Any]]] = None,
    ) -> str:
        if name is None:
            name = self.__class__.__name__

        if properties is None:
            properties = self.properties()

        if named_children is None:
            named_children = tuple(self.named_children())

        return build_complex_obj_repr(
            name,
            properties=properties,
            named_children=named_children,
            num_indent=self._STR_INDENT,
        )

    def __repr__(self) -> str:
        return self._build_repr()

class Object(ComplexObject):
    def __init__(self) -> None:
        msg = build_deprecation_message(
            "The class Object", "0.4", info="It was renamed to ComplexObject."
        )
        warnings.warn(msg)

class LossDict(OrderedDict):
    def __init__(
        self, losses: Sequence[Tuple[str, Union[torch.Tensor, "LossDict"]]] = (),
    ) -> None:
        super().__init__()
        for name, loss in losses:
            self[name] = loss

    def __setitem__(self, name: str, loss: Union[torch.Tensor, "LossDict"]) -> None:
        if isinstance(loss, torch.Tensor):
            if not is_scalar_tensor(loss):
                # FIXME
                raise TypeError
            super().__setitem__(name, loss)
        elif isinstance(loss, LossDict):
            for child_name, child_loss in loss.items():
                super().__setitem__(f"{name}.{child_name}", child_loss)
        else:
            # FIXME
            raise TypeError

    def aggregate(self, max_depth: int) -> Union[torch.Tensor, "LossDict"]:
        def sum_partial_losses(partial_losses: Iterable[torch.Tensor]) -> torch.Tensor:
            return cast(torch.Tensor, sum(partial_losses))

        if max_depth == 0:
            return sum_partial_losses(self.values())

        splits = [name.split(".") for name in self.keys()]
        if not any([len(split) >= max_depth for split in splits]):
            return copy(self)

        agg_names = [".".join(split[:max_depth]) for split in splits]
        key_map = dict(zip(self.keys(), agg_names))
        agg_losses: Dict[str, List[torch.Tensor]] = {
            name: [] for name in set(agg_names)
        }
        for name, loss in self.items():
            agg_losses[key_map[name]].append(loss)

        return LossDict(
            [(name, sum_partial_losses(agg_losses[name])) for name in agg_names]
        )

    def total(self) -> torch.Tensor:
        return cast(torch.Tensor, self.aggregate(0))

    def backward(self, *args: Any, **kwargs: Any) -> None:
        self.total().backward(*args, **kwargs)

    def item(self) -> float:
        return self.total().item()

    def __float__(self) -> float:
        return self.item()

    def __mul__(self, other: Any) -> "LossDict":
        other = float(other)
        return LossDict([(name, loss * other) for name, loss in self.items()])

    # TODO: can this be moved in __str__?
    def format(self, max_depth: Optional[int] = None, **format_dict_kwargs: Any) -> str:
        if max_depth is not None:
            if max_depth == 0:
                return str(self.total())
            dct = cast(LossDict, self.aggregate(max_depth))
        else:
            dct = self

        fmt = build_fmtstr(precision=3, type="e")
        values = [fmt.format(value.item()) for value in dct.values()]
        return format_dict(OrderedDict(zip(dct.keys(), values)), **format_dict_kwargs)

    def __str__(self) -> str:
        return self.format()

class TensorKey:
    def __init__(self, x: torch.Tensor, precision: int = 4) -> None:
        x = x.detach()
        self._key = (*self._extract_meta(x), *self._calculate_stats(x, precision))

    @staticmethod
    def _extract_meta(x: torch.Tensor) -> Tuple[Hashable, ...]:
        return (x.device, x.dtype, x.size())

    @staticmethod
    def _calculate_stats(x: torch.Tensor, precision: int) -> List[str]:
        stat_fns = (torch.min, torch.max, torch.norm)
        return [f"{stat_fn(x):.{precision}e}" for stat_fn in stat_fns]

    @property
    def key(self) -> Tuple[Hashable, ...]:
        return self._key

    def __eq__(self, other: Any) -> bool:
        if isinstance(other, torch.Tensor):
            other = TensorKey(other)
        if isinstance(other, TensorKey):
            return self.key == other.key

        # FIXME
        raise TypeError

    def __hash__(self) -> int:
        return hash(self.key)

    def __repr__(self) -> str:
        return str(self.key)


import re, json, semaver
from os import walk, path, system
from setuptools import setup, find_packages, Command

with open(path.join(path.dirname(__file__), 'pytsite', 'pytsite.json')) as f:
    data = json.load(f)
    pkg_name = data['name'].lower()
    pkg_version = data['version']
    pkg_description = data['description']['en']
    pkg_url = data['url']
    pkg_author = data['author']['name']
    pkg_author_email = data['author']['email']
    pkg_license = data['license']['name']
    pkg_requires_packages = data['requires']['packages']  # type: dict

ASSET_FNAME_RE = re.compile('\.(png|jpg|jpeg|gif|svg|ttf|woff|woff2|eot|otf|map|js|css|less|txt|md|yml|jinja2|json)$')

class CleanCommand(Command):
    """Custom clean command to tidy up the project root.
    """
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        system('rm -vrf ./build ./dist')

def find_package_data():
    r = {}

    for pkg in find_packages():
        pkg_path = path.sep.join(pkg.split('.'))
        for root, dir_name, files in walk(pkg_path):
            for file_name in files:
                if ASSET_FNAME_RE.search(file_name):
                    if pkg not in r:
                        r[pkg] = []
                    file_ext = path.splitext(file_name)[1]
                    path_glob = re.sub('^{}{}'.format(pkg_path, path.sep), '', path.join(root, '*' + file_ext))
                    if path_glob not in r[pkg]:
                        r[pkg].append(path_glob)

    return r

setup(
    name=pkg_name,
    version=pkg_version,
    description=pkg_description,
    url=pkg_url,
    author=pkg_author,
    author_email=pkg_author_email,
    license=pkg_license,
    download_url='https://github.com/pytsite/pytsite/archive/{}.tar.gz'.format(pkg_version),
    install_requires=[f'{k}{semaver.VersionRange(v)}' for k, v in pkg_requires_packages.items()],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Console',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Natural Language :: Russian',
        'Natural Language :: Ukrainian',
        'Operating System :: POSIX',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: JavaScript',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Software Development :: Libraries :: Application Frameworks',
    ],
    packages=find_packages(),
    package_data=find_package_data(),
    cmdclass={
        'clean': CleanCommand,
    }
)


# -*- coding: utf-8 -*-

"""	Title: Edad Empleados Función
"""

def calculaPuesto(edad):
	# puesto = ""
	if edad >= 15 and edad <= 18:
		puesto = "Call center"
	elif edad >= 19 and edad <= 25:
		puesto = "Administrador"
	elif edad >= 25 and edad <= 45:
		puesto = "Jefe de piso"
	else:
		puesto = "No hay chamba para mayores de 45 :("
	return puesto

def principal():

	nombre = input("Ingresa tu nombre: ")
	edad = int(input("Ingresa tu edad: "))

	print("\nNombre: ", nombre, "\nEdad: ", edad, "\nPuesto: ", calculaPuesto(edad))
	return

principal()

Ejercicios UAM-A/Practica 5. Funciones/EdadEmpleadosFunc/edadEmpleadosFunc.py


import logging
import logging.config
import logging.handlers
from path import Path
import multiprocessing_logging
multiprocessing_logging.install_mp_handler()

import sys

class ColorPrint:

    @staticmethod
    def print_fail(message, end = '\n'):
        sys.stderr.write('\x1b[1;31m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_pass(message, end = '\n'):
        sys.stdout.write('\x1b[1;32m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_warn(message, end = '\n'):
        sys.stderr.write('\x1b[1;33m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_info(message, end = '\n'):
        sys.stdout.write('\x1b[1;34m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_bold(message, end = '\n'):
        sys.stdout.write('\x1b[1;37m' + message.strip() + '\x1b[0m' + end)

class Logger():
    def __init__(self, level, log_dir, log_name, filename):
        self.logger = logging.getLogger(log_name)

        # logging to file
        # fh = logging.handlers.RotatingFileHandler(
        #     Path(log_dir) / 'main_logger_{:%H%M%S}.log'.format(datetime.now()),
        #     'w', 20 * 1024 * 1024, 5)
        fh = logging.handlers.RotatingFileHandler(
            Path(log_dir) / filename, 'w', 20 * 1024 * 1024, 5)
        formatter = logging.Formatter('%(asctime)s %(levelname)5s - %(name)s '
                                      '[%(filename)s line %(lineno)d] - %(message)s',
                                      datefmt='%m-%d %H:%M:%S')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)

        # logging to screen
        fh = logging.StreamHandler()
        formatter = logging.Formatter('[%(levelname)s] %(message)s', )
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)

        self.logger.setLevel(level)
        self.logger.info("Start training")

    def info(self, id, input):
        id_str = " [" + str(id) + "] "
        self.logger.info(id_str + input)

    def warning(self, id, input):
        id_str = " [" + str(id) + "] "
        self.logger.warning(id_str + input)

    def error(self, id, input):
        id_str = " [" + str(id) + "] "
        self.logger.error(id_str + input)

def init_logger(level='INFO', log_dir='./', log_name='main_logger', filename='main.log'):
    return Logger(level, log_dir, log_name, filename)


from dataclasses import dataclass
from decimal import Decimal
from typing import Union

from web3 import Web3

from core.blockchain.connections import connect_to_blockchain, send_transaction
from core.core_types.dex import load_dex, Dex
from core.core_types.network import load_network, Network
from core.core_types.tokens import ERC20Token
from core.core_types.wallet import load_wallet, Wallet
from core.printers import cprint, PrintColor

@dataclass
class SwapConfig:
    wallet: Wallet
    dex: Dex
    network: Network
    amount: Union[int, float]
    gas_price_gwei: Union[int, float]

    token_to_sell: ERC20Token
    token_to_buy: ERC20Token

def swap_exact_tokens_for_tokens(config: SwapConfig):
    w3 = connect_to_blockchain(config.network)
    config.dex.init_router(w3)

    swap_tx = config.dex.router.functions.swapExactTokensForTokens(
        config.token_to_sell.to_wei(config.amount),
        1,
        [config.token_to_sell.address, config.token_to_buy.address],
        config.wallet.address,
        3249824084
    ).buildTransaction({'gasPrice': Web3.toWei(config.gas_price_gwei, 'gwei'),
                        'gas': 300000,
                        'nonce': w3.eth.get_transaction_count(config.wallet.address)})

    sent_tx = send_transaction(w3, swap_tx, config.wallet.private_key)

    w3.eth.wait_for_transaction_receipt(sent_tx.hash)
    cprint(PrintColor.GREEN, "Got receipt")

if __name__ == '__main__':
    avax_network = load_network('avax')
    _config = SwapConfig(
        wallet=load_wallet('main'),
        dex=load_dex('avax.pangolin'),
        network=avax_network,

        amount=80,
        gas_price_gwei=30,

        token_to_sell=avax_network.get_token_by_symbol('USDC'),
        token_to_buy=ERC20Token('????????????'),
    )


import os

from dotenv import load_dotenv
from discord.ext import commands

load_dotenv()
bot = commands.Bot(command_prefix = "!")
bot.remove_command('help')
TOKEN = os.getenv('DISCORD_TOKEN')

initial_extension = ['cogs.voice_bot', 'cogs.storage_bot', 'cogs.resources_bot', 'cogs.helper_bot']

@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')
    for ext in initial_extension:
        bot.load_extension(ext)

@bot.command()
async def shutdown(ctx):
    await ctx.bot.logout()

bot.run(TOKEN)


import sys
from collections import defaultdict
from pathlib import Path

import numpy as np
import pandas as pd
import scipy

def mean_confidence_interval(data, confidence=0.95):
    a = 1.0 * np.array(data)
    n = len(a)
    m, se = np.mean(a), scipy.stats.sem(a)
    i = se * scipy.stats.t.ppf((1 + confidence) / 2., n - 1)
    return m, i

if __name__ == '__main__':
    data_dir = Path(sys.argv[1])

    if data_dir.name.find('test') >= 0:
        dataset = 'test'
    else:
        dataset = 'validation'

    print(f'Dataset: {dataset}')

    urls = pd.read_csv(f'data/{dataset}.tsv', sep='\t')['image_url']
    captions = pd.read_csv(f'data/{dataset}_caption_list.csv')['caption_title_and_reference_description']

    k = 10

    evaluated_submissions = defaultdict(list)
    for file in data_dir.iterdir():
        if not file.is_file() or not file.name.endswith('.csv'):
            continue

        submission = pd.read_csv(file)
        submission_name = file.name[:-4]

        last_id = -1
        position = 0
        for row in submission.iterrows():
            id = row[1]['id']
            caption = row[1]['caption_title_and_reference_description']
            if last_id != id:
                position = 1
            else:
                position += 1
            if position <= k:
                rel = 'N'
                if captions.iloc[id] == caption:
                    rel = 'R'
                evaluated_submissions[submission_name].append(
                    (id, position, rel, submission_name, caption))
            last_id = id

    last_id = -1
    with open('comparison.txt', mode='wt', encoding='utf-8') as outfile:
        for values in zip(*evaluated_submissions.values()):
            last_position = -1
            for row in values:
                id = row[0]
                position = row[1]
                if id != last_id:
                    print(file=outfile)
                    print(f'Query: {id}', urls.iloc[id], file=outfile)
                    last_id = id
                if position != last_position:
                    print(f' Rank: {position}',file=outfile)
                    last_position = position
                print('  '+'\t'.join([str(x) for x in row][2:]), file=outfile)


import csv
from pprint import pprint

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    def handle(self, *args, **options):
        with open(args[0]) as csvfile:
            reader = csv.DictReader(csvfile)
            weights = []
            for row in reader:
                row['Twitter'] = 1
                weights.append(row)
            pprint(weights)


from flask import Flask

from acondbs.models import Product, ProductRelation, ProductRelationType

def test_example_how_to_query(app: Flask) -> None:
    #                              +--------+
    #               --(child)-->   |        |
    #                    |         | child1 |
    #  +---------+  <-(parent)--   |        |
    #  |         |                 +--------+
    #  | parent1 |
    #  |         |                 +--------+
    #  +---------+  --(child)-->   |        |
    #                    |         | child2 |
    #               <-(parent)--   |        |
    #                              +--------+

    with app.app_context():
        parent1 = Product.query.filter_by(name='parent1').first()
        child1 = Product.query.filter_by(name='child1').first()
        child2 = Product.query.filter_by(name='child2').first()

        # Product relations with the type name 'child'
        relations = (
            ProductRelation.query.join(ProductRelationType)
            .filter(ProductRelationType.name == 'child')
            .all()
        )
        assert ['child', 'child'] == [r.type_.name for r in relations]

        # Products with 'parent'
        products = (
            Product.query.join(
                ProductRelation,
                (Product.product_id == ProductRelation.self_product_id),
            )
            .join(ProductRelationType)
            .filter(ProductRelationType.name == 'parent')
            .all()
        )
        assert [child1, child2] == products

        # Products with 'child'
        products = (
            Product.query.join(
                ProductRelation,
                (Product.product_id == ProductRelation.self_product_id),
            )
            .join(ProductRelationType)
            .filter(ProductRelationType.name == 'child')
            .all()
        )
        assert [parent1] == products


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from models import MyData

# Create your views here.

def main_page(request):
	return render(request, 'main.html')

def forms_option(request):
	option = str(request.GET.get('forms_opt'))

	if option == 'fill':
		return HttpResponseRedirect('http://127.0.0.1:8000/forms/fill_form/')
	elif option == 'show':
		return HttpResponseRedirect('http://127.0.0.1:8000/forms/show_all/')

def fill_form(request):
	return render(request, 'fill_form.html')

def show_all(request):

	fname = request.GET.get('firstname')
	lname = request.GET.get('lastname')

	if not (fname == None and lname == None):
		dict = {
			'firstname' : fname,
			'lastname' : lname
		}

		new_ele = MyData(firstname = fname, lastname = lname)
		new_ele.save()

	all_data = MyData.objects.all()

	ctx = {
		'data' : all_data
	}

	return render(request, 'show_all.html', ctx)


import random

# setting defaults
player_values = []

# //----API----

def get_int_input(out: str) -> int:
    try:
        return int(input(f"{out}\n"))
    except ValueError:
        return get_int_input(out=out)

# //------Game------
def calculate_from_list() -> list:
    results = []

    for player_index in range(player_count):
        sum = 0
        for play_set in range(play_rounds):
            sum += (player_values[play_set + player_index * play_rounds]) * play_set + 1
        results.append(sum)
    return results

def roll_the_dice() -> int:
    return random.randint(1, dice_size)

def play_round(player: int) -> None:
    roll = roll_the_dice()
    print("------------[Offene Werte]------------")
    print(player_values)
    for i in range(play_rounds):
        if player_values[(player * play_rounds) + i] == 0:
            print(f"{i + 1} ist frei")

    print(f"Du hast eine {roll} gewürfelt")

    tmp = get_int_input("Welchen Multiplikator möchtest du wählen?") - 1
    while player_values[(player * play_rounds) + tmp] != 0:
        print("Der Wert ist belegt bitte nutze einen anderen Wert!")
        tmp = get_int_input("Welchen Multiplikator möchtest du wählen?") - 1

    player_values[player * play_rounds + tmp] = roll

def game_manage() -> None:
    for round_index in range(play_rounds):
        for player_index in range(player_count):
            print(f"Runde {round_index + 1} - Player {player_index + 1}")
            play_round(player_index)
    results = calculate_from_list()
    print("------------[Ergebnisse]------------")
    for i in range(player_count):
        print(f"Player {i + 1} hat {results[i]} Punkte")

    print(f"Gewonnen hat Player {results.index(max(results)) + 1}")

    exit(0)

def setup_game() -> tuple[int, int, int]:
    dice = get_int_input("Wie groß soll der Würfel sein? (Standart = 6)")
    rounds = get_int_input("Wie viele Runden sollen gespielt werden?")
    count = get_int_input("Wie viele Spieler sollen mit spielen?")

    """
    setting up a list with deafults for all players in one list
    playervalues stays behind the other players
    calculeted by: playerindex * play_rounds + ??
    """
    for i in range(count * rounds):
        player_values.append(0)
    return dice, rounds, count

dice_size, play_rounds, player_count = setup_game()

game_manage()