import sys
input = sys.stdin.readline

i_formula = list(input().replace("\n", ""))

gwal_lst = []
gwal_tuple_lst = []
for i in range(len(i_formula)):
    character = i_formula[i]
    ch_ind = i
    if character == "(":
        gwal_lst.append(ch_ind)
    elif character == ")":
        gwal_tuple_lst.append((gwal_lst.pop(), ch_ind))

main_lst = []

for i in range(2**len(gwal_tuple_lst)):
    if i == 0:
        continue
    t_ind = int(bin(i).replace('0b', ""))
    t_ind = format(t_ind, '0'+str(len(gwal_tuple_lst)))
    print(t_ind)
    remove_ind_lst = []
    for t in range(len(t_ind)):
        if t_ind[t] == '1':
            remove_ind_lst.append(gwal_tuple_lst[t][0])
            remove_ind_lst.append(gwal_tuple_lst[t][1])
    remove_ind_lst.sort()
    new_formula = ""
    for s in range(len(i_formula)):
        if s in remove_ind_lst:
            continue
        else:
            new_formula += i_formula[s]
    main_lst.append(new_formula)

for i in main_lst:
    print(i)


from __future__ import (absolute_import, division, print_function)

import os
import os.path
import unittest

from PIL import Image

import imagehash

class TestImageHash(unittest.TestCase):
    @staticmethod
    def get_data_image(fname=None):
        if fname is None:
            fname = 'imagehash.png'
        dname = os.path.abspath(os.path.dirname(__file__))
        target = os.path.join(dname, 'data', fname)
        if not os.path.isfile(target):
            emsg = 'Unknown test image file: {!r}'
            raise ValueError(emsg.format(target))
        return Image.open(target)

    def check_hash_algorithm(self, func, image):
        original_hash = func(image)
        rotate_image = image.rotate(-1)
        rotate_hash = func(rotate_image)
        distance = original_hash - rotate_hash
        emsg = ('slightly rotated image should have '
                'similar hash {} {} {}'.format(original_hash, rotate_hash,
                                               distance))
        self.assertTrue(distance <= 10, emsg)
        rotate_image = image.rotate(-90)
        rotate_hash = func(rotate_image)
        emsg = ('rotated image should have different '
                'hash {} {}'.format(original_hash, rotate_hash))
        self.assertNotEqual(original_hash, rotate_hash, emsg)
        distance = original_hash - rotate_hash
        emsg = ('rotated image should have larger different '
                'hash {} {} {}'.format(original_hash, rotate_hash,
                                       distance))
        self.assertTrue(distance > 10, emsg)

    def check_hash_length(self, func, image, sizes=range(2,21)):
        for hash_size in sizes:
            image_hash = func(image, hash_size=hash_size)
            emsg = 'hash_size={} is not respected'.format(hash_size)
            self.assertEqual(image_hash.hash.size, hash_size**2, emsg)

    def check_hash_stored(self, func, image, sizes=range(2,21)):
        for hash_size in sizes:
            image_hash = func(image, hash_size)
            other_hash = imagehash.hex_to_hash(str(image_hash))
            emsg = 'stringified hash {} != original hash {}'.format(other_hash,
                                                                    image_hash)
            self.assertEqual(image_hash, other_hash, emsg)
            distance = image_hash - other_hash
            emsg = ('unexpected hamming distance {}: original hash {} '
                    '- stringified hash {}'.format(distance, image_hash,
                                                   other_hash))
            self.assertEqual(distance, 0, emsg)

    def check_hash_size(self, func, image, sizes=range(-1,2)):
        for hash_size in sizes:
            with self.assertRaises(ValueError):
                func(image, hash_size)


# -*- coding: utf-8 -*-
import sys
sys.path.append('../')

from structured_data import index_excels_normalTable

excel = "excels_sanidad_oit/sanidad_oit.xlsx"
sheet = 0
name_index = "index_oficinas_turismo"
type_index = "structured"

table_start_and_end = {
    "start_row": 1,
    "start_col": 0,
    "end_row": 3,
    "end_col":6,
    "start_value_row": 2,
    "start_value_col": 0
}

type_items = {
    "name" : str,
    "address" : str,
    "lat" : float,
    "lng" : float,
    "phone" : str,
    "email" : str,
    "schedule" : str,
}

name_items = ["name", "address","lat","lng","phone","email","schedule"]

attributes_to_fixed={
    "place": "Puerto de la Cruz"
}

index_excels_normalTable.main(excel, sheet, name_index, type_index, table_start_and_end, type_items, name_items, attributes_to_fixed = attributes_to_fixed)


import xml.etree.ElementTree as ET
from pprint import pprint
from collections import Counter
from itertools import chain

def coint_in_xml():
    tree = ET.parse('newsafr.xml')
    root = tree.getroot()
    items = root.findall('channel/item')
    news_description = []
    for n_d in items:
        news_description.append(n_d.find('description').text)
    words_news = str(news_description).lower().split()
    long_word = []
    for word in words_news:
        if len(word) > 6:
            long_word.append(word)
    words_news_count = Counter(chain.from_iterable(map(str.split, long_word)))
    pprint(words_news_count.most_common(10))

coint_in_xml()


from django.shortcuts import render, redirect

from main.models import *
from django.views.generic import DetailView
from django.http import JsonResponse

def Home(request):
    context = {
        'product':Product.objects.all(),
        'blogs':Blog.objects.all(),
        'foydali':Foydali.objects.all(),
        'client':Clients.objects.all(),
    }
    return render(request, 'index.html', context)

def Blogs(request):
    return render(request, 'blog.html')

def About(request):
    return render(request, 'about.html')

class ProductDetail(DetailView) :
    model = Blog

    template_name = 'blog-details.html'
    context_object_name = 'blog'

def AddToCart(request, id):
    user = request.user

    try:
        shop = Shop.objects.create(client=user, status=0)
    except:
        shop = Shop.objects.create(client = user)
    product = Product.objects.get(id=id)
    if product.discount:
        ShopItem.objects.create(shop=shop, product=product, quantity=1, total=product.discount)
        shop.total += product.discount
    else:
        ShopItem.objects.create(shop=shop, product=product, quantity=1, total=product.price)
        shop.total += product.price
    shop.save()
    return redirect('/')

def Cart(request):
    shop = Shop.objects.filter(status=0)
    products = ShopItem.objects.filter(shop__client=request.user, shop__status=0 )
    context = {
        'products':products,
        'shop':shop[0],
    }
    return render (request, 'cart.html', context)

def CountSavatcha(request):
    count = ShopItem.objects.filter(shop__client=request.user, shop__status=0)
    s = 0
    for c in count:
        s += c.total

    data = {
        'count': count.count(),
        'total': s
    }

    return JsonResponse(data)

def BuyurtmaBerish(request, id):
    shop = Shop.objects.get(id=id)
    shop.status=1
    shop.save()

    return redirect('/')

def DeleteCart(request, id):

    item = ShopItem.objects.get(id=id)
    item.delete()

    return redirect('/cart/')


import json

from app.models import *
def salvar(data):
    try:
        evento = Eventos(
            data['id'] if data['id'] != '' else None,
            data['data'],
            data['descricao'],
            1,
            (session['user_id'] if session['type'] == 'servidor' else None),
            data['privacidade'] if data['privacidade'] != '' else None,
        )
        idEvento = evento.save()
        ServidorEvento.deleteByEvent(idEvento)

        if len(json.loads(data['servidoresVinculados'])) > 0:
            for idServidor in json.loads(data['servidoresVinculados']):
                servidorEvento = ServidorEvento(None, idEvento, idServidor)
                servidorEvento.save()

        return {'success': True}
    except Exception as e:
        return {'success': False, 'error': e}

def delete(id):
    ServidorEvento.deleteByEvent(id)
    evento = Eventos.query.get_or_404(id)
    db.session.delete(evento)
    db.session.commit()
    return {'success': True}


#!/usr/bin/env python
#pylint: disable=no-member

"""
Sell a particular trade immediately
"""

import sys
import time
from greencandle.lib.binance import Binance
from greencandle.lib.common import arg_decorator
from greencandle.lib import config
from greencandle.lib.order import Trade

@arg_decorator
def main():
    """
    Close a long trade immediately
    Trade must belong to strategy in current config scope/container

    Usage: sell_now <pair> <interval> <test_trade> <test_data>
    """
    if len(sys.argv) < 4:
        print(f"Usage {sys.argv[0]} [pair] [interval] [test_trade] [test_data]")
        sys.exit(1)

    pair = sys.argv[1]
    interval = sys.argv[2]

    config.create_config()
    test_trade = bool(len(sys.argv) > 3 and sys.argv[3] == "test")
    test_data = bool(len(sys.argv) > 3 and sys.argv[4] == "test")
    current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
    client = Binance()
    current_price = client.prices()[pair]
    print(current_time, current_price)

    sells = []
    trade = Trade(interval=interval, test_data=test_data, test_trade=test_trade, config=config)
    sells.append((pair, current_time, current_price, "manual_sell"))
    trade.close_trade(sells, drawdowns={pair:0}, drawups={pair:0})

if __name__ == "__main__":
    main()


import os

import numpy as np
import skopt
import torch
import torchvision
from matplotlib import pyplot as plt
import tabulate

import scripts.plot as plot
from curvature.lenet5 import lenet5
from curvature.resnet import resnet18
from curvature.utils import setup, get_eigenvalues, accuracy, get_eigenvectors, expected_calibration_error

import matplotlib
matplotlib.use("agg")

def load_data(args, model, data='imagenet', estimator="kfac", ood=False):
    if estimator in ["swag", "swa"] and data == 'imagenet':
        data_path = os.path.join(args.results_dir, model, "data", "swag", f"ood_{estimator}" if ood else estimator)
        data = np.load(data_path + ".npz")
        return data['targets'], None, data['predictions']

    filename = f"{args.prefix}{model}_{data}{args.suffix}"
    data_path = os.path.join(args.results_dir, model, "data", estimator, filename)
    data = np.load(data_path + ".npz")
    if ood:
        return data['labels'], data['ood_predictions'], data['bnn_ood_predictions']
    return data['labels'], data['predictions'], data['bnn_predictions']

def ecdf(args):
    fig, ax = plt.subplots(figsize=(12, 7), tight_layout=True)

    labels, predictions, bnn_predictions = load_data(args, args.model, args.data, args.estimator)
    labels, ood_predictions, bnn_ood_predictions = load_data(args, args.model, args.data, args.estimator, ood=True)

    plot.inv_ecdf_vs_pred_entropy(predictions, color='dodgerblue', linestyle='--', axis=ax)
    plot.inv_ecdf_vs_pred_entropy(ood_predictions, color='crimson', linestyle='--', axis=ax)
    plot.inv_ecdf_vs_pred_entropy(bnn_predictions, color='dodgerblue', axis=ax)
    plot.inv_ecdf_vs_pred_entropy(bnn_ood_predictions, color='crimson', axis=ax)
    ax.legend([f"NN {args.data.upper()} | Acc.: {accuracy(predictions, labels):.2f}%",
               f"NN OOD",
               f"BNN {args.data.upper()} | Acc.: {accuracy(bnn_predictions, labels):.2f}%",
               f"BNN OOD"], fontsize=16, frameon=False)
    filename = f"{args.prefix}{args.model}_{args.data}{args.suffix}"
    plt.savefig(args.results_dir + f"/figures/ecdf_{filename}.pdf", format='pdf', dpi=1200)

def entropy_histogram(args):
    if args.estimator in ['swa', 'swag']:
        labels, _, predictions = load_data(args, args.model, args.data, args.estimator)
        _, _, ood_predictions = load_data(args, args.model, args.data, args.estimator, ood=True)
    elif args.estimator == 'sgd':
        labels, predictions, _ = load_data(args, args.model, args.data, 'kfac')
        _, ood_predictions, _ = load_data(args, args.model, args.data, 'kfac', ood=True)
    else:
        labels, _, predictions = load_data(args, args.model, args.data, args.estimator)
        _, _, ood_predictions = load_data(args, args.model, args.data, args.estimator, ood=True)
    acc = accuracy(predictions, labels)
    ece = expected_calibration_error(predictions, labels)[0]
    label = f"In Class | Acc.: {acc:.2f}% | ECE: {100 * ece:.2f}%"

    fig_path = os.path.join(args.results_dir, args.model, "figures", args.estimator)
    os.makedirs(fig_path, exist_ok=True)

    filename = f"{args.prefix}{args.model}_{args.data}{args.suffix}"
    plot.entropy_hist(predictions, ood_predictions, path=os.path.join(fig_path, f"{filename}_entropy.pdf"), label=label)

def calibration(args):
    fig, ax = plt.subplots(figsize=(12, 7), tight_layout=True)

    c1 = next(ax._get_lines.prop_cycler)['color']
    c2 = next(ax._get_lines.prop_cycler)['color']
    c3 = next(ax._get_lines.prop_cycler)['color']
    c4 = next(ax._get_lines.prop_cycler)['color']
    c5 = next(ax._get_lines.prop_cycler)['color']
    c6 = next(ax._get_lines.prop_cycler)['color']
    c7 = next(ax._get_lines.prop_cycler)['color']

    try:
        labels, predictions, kfac_predictions = load_data(args, args.model, args.data, "kfac")
        plot.calibration(predictions, labels, color=c1, label=f"SGD", axis=ax)
        plot.calibration(kfac_predictions, labels, color=c2, label="KFAC-Laplace", axis=ax)
    except FileNotFoundError:
        print(f"Data for model {args.model} and estimator SGD/KFAC not available.")
    try:
        diag_labels, _, diag_predictions = load_data(args, args.model, args.data, "diag")
        plot.calibration(diag_predictions, diag_labels, color=c3, label="Diag-Laplace", axis=ax)
    except FileNotFoundError:
        print(f"Data for model {args.model} and estimator DIAG not available.")
    try:
        efb_labels, _, efb_predictions = load_data(args, args.model, args.data, "efb")
        plot.calibration(efb_predictions, efb_labels, color=c4, label="EFB-Laplace", axis=ax)
    except FileNotFoundError:
        print(f"Data for model {args.model} and estimator EFB not available.")
    try:
        inf_labels, _, inf_predictions = load_data(args, args.model, args.data, "inf")
        plot.calibration(inf_predictions, inf_labels, color=c5, label="INF-Laplace", axis=ax)
    except FileNotFoundError:
        print(f"Data for model {args.model} and estimator INF not available.")
    try:
        swag_labels, _, swag_predictions = load_data(args, args.model, args.data, "swag")
        swa_labels, _, swa_predictions = load_data(args, args.model, args.data, "swa")
        plot.calibration(swa_predictions, swa_labels, color=c6, label="SWA", axis=ax)
        plot.calibration(swag_predictions, swag_labels, color=c7, label="SWAG", axis=ax)
    except FileNotFoundError:
        print(f"Data for model {args.model} and estimator SWAG/SWA not available.")

    filename = f"{args.prefix}{args.model}_{args.data}{args.suffix}"
    plt.savefig(args.results_dir + f"/figures/calibration_{filename}.pdf", format='pdf', dpi=1200)

def calibration_overview(args):
    fig, ax = plt.subplots(figsize=(12, 7), tight_layout=True)

    all_nets = ['resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152',
                'densenet121', 'densenet161', 'densenet169', 'densenet201',
                'googlenet_x', 'inception_v3', 'wide_resnet50_2', 'vgg16', 'alexnet_x']

    nets = all_nets
    det_list = tuple(all_nets) if args.estimator != 'none' else all_nets
    bnn_list = all_nets if args.estimator != 'none' else []
    for name in nets:
        try:
            labels, predictions, bnn_predictions = load_data(args, name, args.data,
                                                             args.estimator if args.estimator != 'none' else 'kfac')
            color = next(ax._get_lines.prop_cycler)['color']

            if name in det_list and isinstance(det_list, list):
                plot.calibration(predictions, labels, color=color, label=name, axis=ax)
            elif name in bnn_list and isinstance(bnn_list, list):
                plot.calibration(bnn_predictions, labels, color=color, label=name, axis=ax)

            if name in det_list and isinstance(det_list, tuple):
                plot.calibration(predictions, labels, axis=ax, alpha=0.3, color=color, linestyle='--')
            elif name in bnn_list and isinstance(bnn_list, tuple):
                plot.calibration(bnn_predictions, labels, axis=ax, alpha=0.3, color=color, linestyle='--')
        except FileNotFoundError:
            print(f"Data for model {name} not available.")
    plt.savefig(
        args.results_dir + f"/figures/calibration_overview_{args.estimator if args.estimator != 'none' else ''}.pdf",
        format='pdf', dpi=1200)

def out_of_domain(args):
    fig, ax = plt.subplots(figsize=(12, 7), tight_layout=True)

    c1 = next(ax._get_lines.prop_cycler)['color']
    c2 = next(ax._get_lines.prop_cycler)['color']
    c3 = next(ax._get_lines.prop_cycler)['color']
    c4 = next(ax._get_lines.prop_cycler)['color']
    c5 = next(ax._get_lines.prop_cycler)['color']
    c6 = next(ax._get_lines.prop_cycler)['color']
    c7 = next(ax._get_lines.prop_cycler)['color']

    try:
        labels, predictions, kfac_predictions = load_data(args, args.model, args.data, "kfac")
        ood_labels, ood_predictions, ood_kfac_predictions = load_data(args, args.model, args.data, "kfac", ood=True)
        plot.inv_ecdf_vs_pred_entropy(ood_predictions, "SGD", c1, axis=ax)
        plot.inv_ecdf_vs_pred_entropy(ood_kfac_predictions, "KFAC-Laplace", c2, axis=ax)
        plot.inv_ecdf_vs_pred_entropy(predictions, color=c1, linestyle='--', axis=ax)
        plot.inv_ecdf_vs_pred_entropy(kfac_predictions, color=c2, linestyle='--', axis=ax)
    except FileNotFoundError:
        print(f"Data for model {args.model} and estimator SGD/KFAC not available.")
    try:
        diag_labels, _, diag_predictions = load_data(args, args.model, args.data, "diag")
        ood_diag_labels, _, ood_diag_predictions = load_data(args, args.model, args.data, "diag", ood=True)
        plot.inv_ecdf_vs_pred_entropy(ood_diag_predictions, "Diag-Laplace", c3, axis=ax)
        plot.inv_ecdf_vs_pred_entropy(diag_predictions, color=c3, linestyle='--', axis=ax)
    except FileNotFoundError:
        print(f"Data for model {args.model} and estimator DIAG not available.")
    try:
        efb_labels, _, efb_predictions = load_data(args, args.model, args.data, "efb")
        ood_efb_labels, _, ood_efb_predictions = load_data(args, args.model, args.data, "efb", ood=True)
        plot.inv_ecdf_vs_pred_entropy(ood_efb_predictions, "EFB-Laplace", c4, axis=ax)
        plot.inv_ecdf_vs_pred_entropy(efb_predictions, color=c4, linestyle='--', axis=ax)
    except FileNotFoundError:
        print(f"Data for model {args.model} and estimator EFB not available.")
    try:
        inf_labels, _, inf_predictions = load_data(args, args.model, args.data, "inf")
        ood_inf_labels, _, ood_inf_predictions = load_data(args, args.model, args.data, "inf", ood=True)
        plot.inv_ecdf_vs_pred_entropy(ood_inf_predictions, "INF-Laplace", c5, axis=ax)
        plot.inv_ecdf_vs_pred_entropy(inf_predictions, color=c5, linestyle='--', axis=ax)
    except FileNotFoundError:
        print(f"Data for model {args.model} and estimator INF not available.")
    try:
        swag_labels, _, swag_predictions = load_data(args, args.model, args.data, "swag")
        swa_labels, _, swa_predictions = load_data(args, args.model, args.data, "swa")
        ood_swag_labels, _, ood_swag_predictions = load_data(args, args.model, args.data, "swag", ood=True)
        ood_swa_labels, _, ood_swa_predictions = load_data(args, args.model, args.data, "swa", ood=True)
        plot.inv_ecdf_vs_pred_entropy(ood_swa_predictions, "SWA", c6, axis=ax)
        plot.inv_ecdf_vs_pred_entropy(ood_swag_predictions, "SWAG", c7, axis=ax)
        plot.inv_ecdf_vs_pred_entropy(swa_predictions, color=c6, linestyle='--', axis=ax)
        plot.inv_ecdf_vs_pred_entropy(swag_predictions, color=c7, linestyle='--', axis=ax)
    except FileNotFoundError:
        print(f"Data for model {args.model} and estimator SWA/SWAG not available.")

    solid, = ax.plot([], [], c="black", ls='-')
    dashed, = ax.plot([], [], c="black", ls='--')

    lines = plt.legend(fontsize=16, loc="upper right", frameon=False)
    plt.legend([solid, dashed], ["out-of-domain", "in-domain"], fontsize=14, loc="lower left", frameon=False)
    ax.add_artist(lines)

    plt.savefig(args.results_dir + f"/figures/out_of_domain_{args.model}.pdf", format='pdf', dpi=1200)

def out_of_domain_overview(args):
    fig, ax = plt.subplots(figsize=(12, 7), tight_layout=True)

    nets = ['resnet18', 'resnet50', 'resnet152', 'densenet121', 'densenet161']

    for name in nets:
        color = next(ax._get_lines.prop_cycler)['color']
        try:
            if args.estimator in ['swa', 'swag']:
                _, _, predictions = load_data(args, name, args.data, args.estimator)
                _, _, ood_predictions = load_data(args, name, args.data, args.estimator, ood=True)
            elif args.estimator == 'sgd':
                _, predictions, _ = load_data(args, name, args.data, 'kfac')
                _, ood_predictions, _ = load_data(args, name, args.data, 'kfac', ood=True)
            else:
                _, _, predictions = load_data(args, name, args.data, args.estimator)
                _, _, ood_predictions = load_data(args, name, args.data, args.estimator, ood=True)
            plot.inv_ecdf_vs_pred_entropy(ood_predictions, name.capitalize(), color=color, axis=ax)
            plot.inv_ecdf_vs_pred_entropy(predictions, color=color, linestyle='--', axis=ax)
        except FileNotFoundError:
            print(f"Data for model {name} not available.")

    solid, = ax.plot([], [], c="black", ls='-')
    dashed, = ax.plot([], [], c="black", ls='--')

    lines = plt.legend(fontsize=16, loc="upper right", frameon=False)
    plt.legend([solid, dashed], ["out-of-domain", "in-domain"], fontsize=14, loc="lower left", frameon=False)
    ax.add_artist(lines)

    plt.savefig(args.results_dir + f"/figures/out_of_domain_{args.estimator}.pdf", format='pdf', dpi=1200)

def eigenvalues(args):
    print("Loading factors")
    factors_path = os.path.join(args.root_dir, "factors",
                                f"{args.prefix}{args.model}_{args.data}_{args.estimator}{args.suffix}.pth")
    factors = torch.load(factors_path, map_location='cpu')

    filename = f"{args.prefix}{args.model}_{args.data}{args.suffix}"
    fig_path = os.path.join(args.results_dir, args.model, "figures", args.estimator, filename)

    print("Computing eigenvalues")
    eigvals = get_eigenvalues(factors, verbose=True)
    plot.eigenvalue_histogram(eigvals.numpy(), show_stats=args.verbose, path=fig_path + "_eigenvalue_histogram.pdf")

def print_hyperparameters(args):
    hyper_list = list()
    for name in ['resnet18', 'resnet50', 'resnet152',
                 'densenet121', 'densenet161']:
        tmp = [name.capitalize()]
        for est in ['diag', 'kfac', 'efb', 'inf']:
            filename = f"{args.prefix}{name}_{args.data}{args.suffix}"
            results_path = os.path.join(args.results_dir, name, "data", est, filename)
            try:
                norm, scale = np.load(results_path + "_best_params.npy")
                tmp.append(round(norm))
                tmp.append(round(scale))
            except FileNotFoundError:
                pass
        hyper_list.append(tmp)
    print(tabulate.tabulate(hyper_list,
                            headers=['Model', 'DIAG Norm', 'DIAG Scale', 'KFAC Norm', 'KFAC Scale',
                                     'EFB Norm', 'EFB Scale', 'INF Norm', 'INF Scale'], tablefmt='rst',
                            numalign='right', floatfmt=".0f"))

def hyperparameters(args, plot_3d=False, plot_time=True):
    filename = f"{args.prefix}{args.model}_{args.data}_{args.estimator}{args.suffix}"
    if not plot_time:
        results_path = os.path.join(args.results_dir, args.model, "data", args.estimator, args.optimizer, filename)
        try:
            data = np.load(results_path + "_hyperopt_stats.npy", allow_pickle=True).item()
            metrics = ['score', 'acc', 'ent', 'nll', 'ece']
        except FileNotFoundError:
            data = dict()
            metrics = ['score']
        res = skopt.load(results_path + "_hyperopt_dump.pkl")
        data['norm'] = np.array(res.x_iters)[:, 0]
        data['scale'] = np.array(res.x_iters)[:, 1]
        data['score'] = np.array(res.func_vals)

    if plot_3d:
        plot.hyper_results_3d(data)
    elif plot_time:
        fig, ax = plt.subplots(figsize=(12, 7), tight_layout=True)
        c1 = next(ax._get_lines.prop_cycler)['color']
        c2 = next(ax._get_lines.prop_cycler)['color']
        gp_data = list()
        random_data = list()
        for i in range(10):
            random_path = os.path.join(args.results_dir, args.model, "data", args.estimator, 'random', str(i), filename)
            gp_path = os.path.join(args.results_dir, args.model, "data", args.estimator, 'gp', str(i), filename)
            try:
                data = np.load(random_path + f"_hyperopt_stats{'_layer.npy' if args.layer else '.npy'}", allow_pickle=True).item()
                #ax.scatter(np.arange(len(random_data['cost'])), random_data['cost'], c=c1, marker='x')
                random_data.append([np.nanmin(data['cost'][:i + 1]) for i in range(len(data['cost']))])
                #ax.plot(random_data, c=c1, lw=0.5, ls='--')
            except FileNotFoundError:
                print(f"Data for experiment {i} (random) not available.")
            try:
                data = np.load(gp_path + f"_hyperopt_stats{'_layer.npy' if args.layer else '.npy'}", allow_pickle=True).item()
                #ax.scatter(np.arange(len(gp_data['cost'])), gp_data['cost'], c=c2, marker='+')
                gp_data.append([np.nanmin(data['cost'][:i + 1]) for i in range(len(data['cost']))])
                #ax.plot(gp_data, c=c2, lw=0.5, ls='--')
            except FileNotFoundError:
                print(f"Data for experiment {i} (gp) not available.")

        random_data = np.array(random_data)
        random_mean = np.nanmean(random_data, axis=0)
        random_std = np.nanstd(random_data, axis=0)
        ax.plot(random_mean, c=c1, lw=2, label='Random Search')
        plt.fill_between(np.arange(random_mean.shape[0]), random_mean - random_std, random_mean + random_std, color=c1, alpha=0.2)

        gp_data = np.array(gp_data)
        gp_mean = np.nanmean(gp_data, axis=0)
        gp_std = np.nanstd(gp_data, axis=0)
        ax.plot(gp_mean, c=c2, lw=2, label='Bayesian Optimization')
        plt.fill_between(np.arange(gp_mean.shape[0]), gp_mean - gp_std, gp_mean + gp_std, color=c2, alpha=0.2)
        plt.legend(fontsize=16)
        plt.xlabel('Iteration', fontsize=14)
        plt.ylabel('Error + ECE', fontsize=14)
        plt.show()
    else:
        for metric in metrics:
            data[metric] = np.array(data[metric])
            fig_path = results_path.replace("data", "figures") + f"_hyper_results_{metric}.pdf"
            plot.hyper_results(data, metric, annotate=True, path=fig_path)

def adversarial_attack(args):
    for metric in ['ent', 'acc']:
        fig, ax = plt.subplots(figsize=(9, 9), tight_layout=True)
        filename = f"{args.prefix}{args.model}_{args.data}_fgsm{args.suffix}.npz"

        for estimator in ['kfac', 'diag', 'efb', 'inf']:
            results_path = os.path.join(args.results_dir, args.model, "data", estimator, filename)
            try:
                data = np.load(results_path, allow_pickle=True)
                stats, bnn_stats = data['stats'].item(), data['bnn_stats'].item()
                epsilons = stats['eps']
                color = next(ax._get_lines.prop_cycler)['color']

                if estimator == 'kfac':
                    plt.plot(epsilons, stats[metric], color=color, linewidth=3, label='SGD')
                    color = next(ax._get_lines.prop_cycler)['color']
                label = estimator.upper()
                plt.plot(epsilons, bnn_stats[metric], color=color, linewidth=3, label=f"{label}-Laplace")
                ax.spines['top'].set_visible(False)
                ax.spines['right'].set_visible(False)
                ax.grid(linestyle='dashed')
                ax.tick_params(direction='out', labelsize=14, right=False, top=False)
                ax.set_ylabel('Predictive Entropy' if metric == 'ent' else 'Accuracy', fontsize=16)
                ax.set_xlabel('Step size', fontsize=16)
                ax.set_xlim(0, 1)
                ax.legend(fontsize=16)

            except FileNotFoundError:
                print(f"Data for model {args.model} and estimator {estimator.upper()} not available.")
        plt.savefig(args.results_dir + f"/figures/adv_{metric}_{args.model}_{args.data}.pdf", format='pdf', dpi=1200)

def summary(args):
    if args.model == 'lenet5':
        model = lenet5(pretrained=args.data, device=args.device)
    elif args.model == 'resnet18' and args.data != 'imagenet':
        model = resnet18(pretrained=os.path.join(args.root_dir, 'weights', f"{args.model}_{args.data}.pth"),
                         device=args.device)
    else:
        model_class = getattr(torchvision.models, args.model)
        if args.model in ['googlenet', 'inception_v3']:
            model = model_class(pretrained=True, aux_logits=False)
        else:
            model = model_class(pretrained=True)

    module_classes = list()
    for module in model.modules():
        module_class = module.__class__.__name__
        if module_class in ['Linear', 'Conv2d']:
            module_classes.append(module_class)

    diag_list = list()
    kfac_list = list()
    efb_list = list()
    inf_list = list()
    for est in ['diag', 'kfac', 'efb', 'inf']:
        if est == 'diag':
            factors_list = diag_list
        elif est == 'kfac':
            factors_list = kfac_list
        elif est == 'efb':
            factors_list = efb_list
        else:
            factors_list = inf_list

        factors_path = os.path.join(args.root_dir, "factors", f"{args.model}_{args.data}_{est}")
        if est in ["diag", "kfac"]:
            factors = torch.load(factors_path + '.pth', map_location='cpu')
        elif est == 'efb':
            kfac_factors = torch.load(factors_path.replace("efb", "kfac") + '.pth')
            lambdas = torch.load(factors_path + '.pth', map_location='cpu')

            factors = list()
            eigvecs = get_eigenvectors(kfac_factors)

            for eigvec, lambda_ in zip(eigvecs, lambdas):
                factors.append((eigvec[0], eigvec[1], lambda_))
        elif est == 'inf':
            try:
                factors = torch.load(f"{factors_path}{args.rank}.pth", map_location='cpu')
            except FileNotFoundError:
                factors = np.load(factors_path + f"{args.rank}.npz", allow_pickle=True)['sif_list']  # Todo: Remove

        numel_sum = 0
        for index, (cls, factor) in enumerate(zip(module_classes, factors)):
            numel = np.sum([f.numel() for f in factor]).astype(int)
            if est == 'diag':
                factors_list.append([f"{cls} {index}", numel, (numel * 32) / (8 * 1024 ** 2)])
            else:
                factors_list.append([numel, (numel * 32) / (8 * 1024 ** 2)])
            numel_sum += numel
        if est == 'diag':
            factors_list.append(["Total", numel_sum, (numel_sum * 32) / (8 * 1024 ** 2)])
        else:
            factors_list.append([numel_sum, (numel_sum * 32) / (8 * 1024 ** 2)])

    factors_list = np.concatenate([diag_list, kfac_list, efb_list, inf_list], axis=1)

    print(tabulate.tabulate(factors_list, headers=['Layer #', '#Parameters', 'Size (MB)', '#Parameters', 'Size (MB)', '#Parameters', 'Size (MB)', '#Parameters', 'Size (MB)'], floatfmt=".1f",
                            numalign='right', tablefmt='latex'))

def landscapes(args, from2d='x'):
    filename = f"{args.prefix}{args.model}_{args.data}{args.suffix}"
    results_path = os.path.join(args.results_dir, "loss1d" if args.loss1d else "loss2d", filename)

    if args.loss1d:
        if from2d == 'x':
            results_path += "_2dx"
        elif from2d == 'y':
            results_path += "_2dy"
        plot.plot_loss1d(data=np.load(results_path + ".npy"), path=results_path)
    elif args.loss2d:
        plot.plot_surfaces(data=np.load(results_path + ".npy"), show_samples=True, path=results_path)

def main():
    args = setup()
    if args.calibration:
        calibration(args)
    elif args.networks:
        out_of_domain_overview(args)
        calibration_overview(args)
    elif args.ood:
        out_of_domain(args)
    elif args.eigvals:
        eigenvalues(args)
    elif args.hyper:
        hyperparameters(args)
    elif args.fgsm:
        adversarial_attack(args)
    elif args.ecdf:
        ecdf(args)
    elif args.entropy:
        entropy_histogram(args)
    elif args.summary:
        summary(args)
    elif args.landscapes:
        landscapes(args)
    else:
        print_hyperparameters(args)

if __name__ == "__main__":
    main()


from mythic_container.MythicCommandBase import *
from mythic_container.MythicRPC import *
import json, sys, base64

class UploadArguments(TaskArguments):
    def __init__(self, command_line, **kwargs):
        super().__init__(command_line, **kwargs)
        self.args = [
            CommandParameter(
                name="file",
                type=ParameterType.File,
                description="file to upload"
            ),
            CommandParameter(
                name="remote_path",
                type=ParameterType.String,
                description="/remote/path/on/victim.txt",
            ),
        ]

    async def parse_arguments(self):
        if len(self.command_line) == 0:
            raise ValueError("Must supply arguments")
        raise ValueError("Must supply named arguments or use the modal")

    async def parse_dictionary(self, dictionary_arguments):
        self.load_args_from_dictionary(dictionary_arguments)

class UploadCommand(CommandBase):
    cmd = "upload"
    needs_admin = False
    help_cmd = "upload"
    description = (
        "Upload a file to the target machine by selecting a file from your computer. "
    )
    version = 1
    supported_ui_features = ["file_browser:upload"]
    author = "@its_a_feature_"
    attackmapping = ["T1132", "T1030", "T1105"]
    argument_class = UploadArguments
    attributes = CommandAttributes(
        supported_python_versions=["Python 2.7", "Python 3.8"],
        supported_os=[SupportedOS.MacOS, SupportedOS.Windows, SupportedOS.Linux ],
    )

    async def create_go_tasking(self, taskData: MythicCommandBase.PTTaskMessageAllData) -> MythicCommandBase.PTTaskCreateTaskingMessageResponse:
        response = MythicCommandBase.PTTaskCreateTaskingMessageResponse(
            TaskID=taskData.Task.ID,
            Success=True,
        )
        try:
            file_resp = await SendMythicRPCFileSearch(MythicRPCFileSearchMessage(
                TaskID=taskData.Task.ID,
                AgentFileID=taskData.args.get_arg("file")
            ))
            if file_resp.Success:
                if len(file_resp.Files) > 0:
                    original_file_name = file_resp.Files[0].Filename
                    if len(taskData.args.get_arg("remote_path")) == 0:
                        taskData.args.add_arg("remote_path", original_file_name)
                    elif taskData.args.get_arg("remote_path")[-1] == "/":
                        taskData.args.add_arg("remote_path", taskData.args.get_arg("remote_path") + original_file_name)
                    response.DisplayParams = f"{original_file_name} to {taskData.args.get_arg('remote_path')}"
                else:
                    raise Exception("Failed to find that file")
            else:
                raise Exception("Error from Mythic trying to get file: " + str(file_resp.Error))
        except Exception as e:
            raise Exception("Error from Mythic: " + str(sys.exc_info()[-1].tb_lineno) + " : " + str(e))
        return response

    async def process_response(self, task: PTTaskMessageAllData, response: any) -> PTTaskProcessResponseMessageResponse:
        resp = PTTaskProcessResponseMessageResponse(TaskID=task.Task.ID, Success=True)
        return resp


import json

# Removes validator set and staking information from emoney2.genesis.json and replaces it with the validator set of testnet.genesis.json.

def mergeSupply(mainnet, testnet):
    total={}
    for balance in mainnet["supply"] + testnet["supply"]:
        amount, denom = balance["amount"], balance["denom"]

        if denom in total:
            newAmount = int(total[denom]) + int(amount)
            total[denom] = str(newAmount)
        else:
            total[denom] = amount

    supply = []

    for denom, balance in total.items():
        supply.append( { "denom" : denom, "amount" : amount })

    mainnet["supply"] = supply

with open('emoney2.export.json') as emoney2g, open('testnet.export.json') as testnetg:
    mainnet = json.load(emoney2g)
    testnet = json.load(testnetg)

    # Transplant testnet staking state to the new net.
    mainnet["app_state"]["auth"]["accounts"].extend(testnet["app_state"]["auth"]["accounts"])
    mainnet["app_state"]["staking"] = testnet["app_state"]["staking"]
    mainnet["app_state"]["distribution"] = testnet["app_state"]["distribution"]
    del mainnet["validators"]

    # "supply" module state
    mergeSupply(mainnet["app_state"]["supply"], testnet["app_state"]["supply"])

    with open('output.json', 'w', encoding='utf-8') as f:
        json.dump(mainnet, f, ensure_ascii=False, indent=4)


from app.models import articles
from flask import render_template
from app import app
from .request import get_articles, get_sources

# Views
@app.route('/')
def index():

    '''
    View root page function that returns the index page and it's data
    '''
    general_sources = get_sources('general')
    news_business = get_sources('business')
    technology_sources = get_sources('technology')
    entertainment_sources = get_sources('entertainment')
    science_sources =get_sources('science')
    health_sources = get_sources('health')
    sports_sources = get_sources('sports')
    # print(general_news)
    title = 'Home - Welcome to The best News Review Website Online'
    return render_template('index.html', title = title,general = general_sources,business=news_business,technology =technology_sources,enternainment= entertainment_sources,sports =sports_sources,science = science_sources,health= health_sources)

@app.route('/source/<source_id>')
def artcicles(source_id):

    '''
    View news page function that returns the news details page and its data
    '''

    return render_template('index.html',id = source_id)

@app.route('/source/<int:id>')
def source(id):

    '''
    View source page function that returns the movie details page and its data
    '''
    source = get_sources(id)
    title = f'{source.title}'

    return render_template('news.html',title = title,source= source)

@app.route('/articles/<id>')
def article(id):

    '''
    View news page function that returns the news details page and its data
    '''
    article = get_articles(id)
    title = f'{id}'

    return render_template('news.html',title = title,article= article)


#Program shows if the word is a palindrome or not

def isPalindrome(word:str) -> None:
    '''define if word is a palindrome or not'''
    word = word.lower()
    reverse = ""

    #loop to revert to word
    for charac in word:
        reverse = charac + reverse

    #output
    if (reverse == word):
        print(word, "is a palindrome")
    else:
        print(word, "is not a palindrome")

def main():
    countWords = int(input("How many words do you want to check? "))

    #define how many words you want to test
    for words in range(countWords):
        print()
        word = input("Enter a String: ")
        isPalindrome(word)

if __name__=="__main__":
    main()

# case 1
# How many words do you want to check? 4

# Enter a String: noon
# noon is a palindrome

# Enter a String: print
# print is not a palindrome

# Enter a String: racecar
# racecar is a palindrome

# Enter a String: speed
# speed is not a palindrome

# case 2
# How many words do you want to check? 3

# Enter a String: Dad
# dad is a palindrome

# Enter a String: dead
# dead is not a palindrome

# Enter a String: did
# did is a palindrome

# case 3
# How many words do you want to check? 3

# Enter a String: Mom
# mom is a palindrome

# Enter a String: man
# man is not a palindrome

# Enter a String: main
# main is not a palindrome

# case 4
# How many words do you want to check? 0
# >>>

# case 5
# How many words do you want to check? 3

# Enter a String: arara
# arara is a palindrome

# Enter a String: Hannah
# hannah is a palindrome

# Enter a String: rotator
# rotator is a palindrome


import socket

def send_file_2_client(new_client_socket, client_addr):
    # 1. 接收客户端发送过来的要下载的文件名
    file_name = new_client_socket.recv(1024).decode("utf-8")
    print("客户端(%s)需要下载文件是(%s)" % (str(client_addr), file_name))

    # 2.打开这个文件，读取数据
    # with的前提三能把文件打开，就一定能调用close，但如果文件根本不能打开，就不推荐使用close
    file_content = None
    # 打开这个文件，读取数据
    try:
        f = open(file_name, "rb")
        file_content = f.read()
        f.close()
    except Exception as ret:
        print("没有要下载的文件(%s)" % file_name)
    # 3. 发送文件的数据给客户端
    # new_client_socket.send("This is a String send to client to test".encode("utf-8"))
    if file_content:
       new_client_socket.send(file_content)

def main():

    # 创建socket
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 绑定 bind
    tcp_server_socket.bind(("", 7890))
    # 被动 listen
    tcp_server_socket.listen(128)
    while True:
        # 等待 accept
        new_client_socket, client_addr = tcp_server_socket.accept()
        # 调用发送文件函数，完成为客户端服务
        send_file_2_client(new_client_socket, client_addr)

        # 关闭套接字
        new_client_socket.close()
    tcp_server_socket.close()

if __name__ == "__main__":
    main()


import json

import psycopg2
import requests
import telebot
from telebot import types

from book_recommendation_system import find_similar_books
from configs import DATABASE_URL, BOT_TOKEN, GOOGLE_MAP_API_TOKEN
from exceptions import IncorrectBookIndex

connection = psycopg2.connect(DATABASE_URL)

cursor = connection.cursor()

bot = telebot.TeleBot(token=BOT_TOKEN)

main_menu_keyboard = types.ReplyKeyboardMarkup(row_width=2)
btn1 = types.KeyboardButton(text='Порадити книгу')
btn2 = types.KeyboardButton(text='Додати книгу в улюблені')
btn3 = types.KeyboardButton(text='Видалити книгу з улюблених')
btn4 = types.KeyboardButton(text='Переглянути список улюблених книг')
btn5 = types.KeyboardButton(text='Переглянути найближчі книжкові магазини')
main_menu_keyboard.add(btn1, btn2, btn3, btn4, btn5)

@bot.message_handler(commands=['start'])
def send_welcome(message):
    user_name = message.from_user.first_name
    chat_id = message.chat.id
    cursor.execute(f'CREATE TABLE IF NOT EXISTS ratings_{str(chat_id)}  '
                   '(id serial PRIMARY KEY, book_title VARCHAR(50), book_author VARCHAR(50), book_rating REAL)')
    bot.send_message(message.chat.id, f'Привіт, {user_name}! 👋\n\n'
                                      f'Я бот для рекомендацій книжок. 📚\n\n'
                                      f'Поділися своїми вподобаннями, і я порекомендую тобі цікаву книгу, '
                                      f'використовуючи нейромережу. 💫\n\n'
                                      f'Ти можеш обрати одну з моїх функцій у меню внизу. 👇\n\n'
                                      f'Щоб отримати детальнішу інформацію про мене, використай команду /help ℹ',
                     reply_markup=main_menu_keyboard)

@bot.message_handler(commands=['help'])
def send_help_info(message):
    bot.send_message(message.chat.id, f'1) Щоб скористатися однією з моїх можливостей, використовуй *меню знизу*, або '
                                      f'вводь відповідні команди вручну;\n'
                                      f'2) Щоб отримати поради книжок на основі раніше вподобаної скористайся функцією '
                                      f'*"Порадити книгу"*. Після цього нейрона мережа підбере 7 найбільш схожих книг '
                                      f'до вказаної;\n'
                                      f'3) В боті доступний власний список улюблених книг. За допомогою команд '
                                      f'*"Додати книгу в улюблені"* та *"Видалити книгу з улюблених"* ти можеш додавати'
                                      f' та видаляти книжки відповідно у свій топ. Щоб переглянути сформований список '
                                      f'використай команду *"Переглянути список улюблених книг"*;\n'
                                      f'4) Щоб дізнатися, які поблизу тебе є книжкові магазини, ти можеш скористатися '
                                      f'командою *"Переглянути найближчі книжкові магазини"*, та після того, як ти '
                                      f'поділишся своєю локацію, я виведу список усіх книжкових магазинів в радіусі 3 '
                                      f'кілометрів;\n',
                     parse_mode='Markdown')

@bot.message_handler(func=lambda message: message.text == 'Додати книгу в улюблені')
def add_book_to_favourite(message):
    bot_message = bot.send_message(message.chat.id,
                                   '👌 Окей! 👌\nВкажи назву книги, автора та оцінку від 0.0 до 5.0.\n'
                                   'Напр: Гарі Потер, Дж. К. Ролінг, 4.7')
    bot.register_next_step_handler(bot_message, add_book_to_db)

def add_book_to_db(message):
    try:
        book_title, book_author, book_rating = message.text.split(',')
    except ValueError:
        bot.send_message(message.chat.id, "🛑 Упс, не той формат... 🛑\nСпробуй ще раз, дотримуючись формату через кому.")
    else:
        chat_id = message.chat.id
        cursor.execute(f"SELECT * FROM ratings_{str(chat_id)} "
                       f"WHERE book_title = '{book_title}' AND book_author = '{book_author}'")
        book_in_list = cursor.fetchall()
        if not book_in_list:
            cursor.execute(
                f"INSERT INTO ratings_{str(chat_id)} (book_title, book_author, book_rating) "
                f"VALUES ('{book_title}', '{book_author}', {book_rating})")
            connection.commit()
            bot.send_message(message.chat.id, f'✅ Готово! ✅\nКнигу *"{book_title}"* додано до списку '
                                              f'улюблених.', parse_mode='Markdown')
        else:
            bot.send_message(message.chat.id,
                             f'🛑 Ану, щось не те... 🛑\nКнига *"{book_title}" з автором *{book_author}* вже є в твоєму '
                             f'списку улюблених.')

@bot.message_handler(func=lambda message: message.text == 'Видалити книгу з улюблених')
def remove_book_from_favourite(message):
    bot_message = bot.send_message(message.chat.id,
                                   '👌 Окей! 👌\nВкажи назву книги, яку хочеш видалити із списку улюблених')
    bot.register_next_step_handler(bot_message, remove_book_from_db)

def remove_book_from_db(message):
    book_name_to_remove = message.text
    chat_id = message.chat.id
    cursor.execute(f"SELECT * FROM ratings_{str(chat_id)} WHERE book_title = '{book_name_to_remove}'")
    book_exists = cursor.fetchall()
    if book_exists:
        cursor.execute(f"DELETE FROM ratings_{str(chat_id)} WHERE book_title = '{book_name_to_remove}'")
        connection.commit()
        bot.send_message(message.chat.id, f'✅ Готово! ✅\nКнигу *"{book_name_to_remove}"* видалено списку '
                                          f'улюблених.', parse_mode='Markdown')
    else:
        bot.send_message(message.chat.id,
                         f'🛑 Ой... 🛑\nКниги *"{book_name_to_remove}"* немає в твоєму списку улюблених, '
                         f'спробуй ще раз.', parse_mode='Markdown')

@bot.message_handler(func=lambda message: message.text == 'Переглянути список улюблених книг')
def get_favourite_books(message):
    chat_id = message.chat.id
    cursor.execute(f"SELECT * FROM ratings_{str(chat_id)} ORDER BY book_rating DESC LIMIT 10")
    top_books = cursor.fetchall()
    if top_books:
        response = "*🫶 Мої улюблені книги:*\n\n"
        counter = 1
        for book in top_books:
            response += f"{counter}) 📖 *{book[1]}*\n    🤵{book[2]}\n    ⭐ {book[3]}\n\n"
            counter += 1
        # with open('images/istockphoto-1370405901-612x612.jpg', 'rb') as photo:
        #     bot.send_photo(message.chat.id, photo, caption=response, parse_mode='Markdown')
    else:
        response = '⚠ Щось ніц нема... ⚠\nПоки твій список улюблених книг порожній. ' \
                   'Скористайся командою "Додати книгу в улюблені", щоб додати першу книгу.'
    bot.send_message(message.chat.id, response, parse_mode='Markdown')

@bot.message_handler(func=lambda message: message.text == 'Порадити книгу')
def recommend_book(message):
    bot_message = bot.send_message(message.chat.id,
                                   '💪 Легко! 💪\nВкажи назву книги (англійською), яка тобі сподобалася і я підберу '
                                   'для тебе схожі 🪄')
    bot.register_next_step_handler(bot_message, get_recommendation)

def get_recommendation(message):
    book_name = message.text
    try:
        recommended_books = find_similar_books(book_name)
    except IncorrectBookIndex:
        bot.send_message(message.chat.id,
                         "🛑 Ой, а що трапилось... 🛑\nНазва книги неправильна, спробуй ще раз", parse_mode='Markdown')
    else:
        response = "*🔝 Ось 7 найбільш схожих книг:*\n\n"
        counter = 1
        for key, value in recommended_books.items():
            response += f"{counter}) 📖 *{key}*\n ⭐ Схожість: {value}\n\n"
            counter += 1
        bot.send_message(message.chat.id, response, parse_mode='Markdown')

@bot.message_handler(func=lambda message: message.text == 'Переглянути найближчі книжкові магазини')
def get_user_location(message):
    bot_message = bot.send_message(message.chat.id, '👽 Питань нема 👽\nПоділися своєю локацією 📍')
    bot.register_next_step_handler(bot_message, get_nearest_book_stores)

def get_nearest_book_stores(message):
    try:
        user_lat = message.location.latitude
        user_lng = message.location.longitude
        google_map_api_url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json" \
                             f"?location={user_lat},{user_lng}" \
                             f"&radius=3000" \
                             f"&type=book_store" \
                             f"&language=uk" \
                             f"&key={GOOGLE_MAP_API_TOKEN}"
        google_map_api_response = requests.get(google_map_api_url)
        result = json.loads(google_map_api_response.text)
        bookstores = result["results"]
        bot_response = "*👇 Ось найближчі книжкові магазини:*\n\n"
        for bookstore in bookstores:
            name = bookstore["name"]
            address = bookstore["vicinity"]
            rating = bookstore["rating"] if "rating" in bookstore else "-"
            if "opening_hours" in bookstore:
                open_now = '🔓 Відчинено' if bookstore["opening_hours"]["open_now"] else '🔓 Зачинено'
            else:
                open_now = '🔓 -'
            bot_response += f"📚 Магазин: {name}\n 📍 Адреса: {address}\n ⭐ Рейтинг: {rating}\n {open_now}\n\n"
        bot.send_message(message.chat.id, bot_response, parse_mode='Markdown')
    except AttributeError:
        bot.send_message(message.chat.id,
                         f"🛑 Ойой, не те нам треба... 🛑\nСпробуй ще раз поділитися локацією.")

bot.polling(none_stop=True, interval=0)


"""Support for circadian white sensor."""
import logging
from datetime import datetime, timedelta
import voluptuous as vol

from homeassistant.core import callback
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
    CONF_NAME,
    EVENT_CORE_CONFIG_UPDATE,
    EVENT_STATE_CHANGED,
)
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_point_in_time
from homeassistant.components.sun import (
    ENTITY_ID as SUN_ENTITY_ID,
    STATE_ATTR_NEXT_DAWN,
    STATE_ATTR_NEXT_DUSK,
    STATE_ATTR_NEXT_NOON,
)

SCAN_INTERVAL = timedelta(minutes=1)

_LOGGER = logging.getLogger(__name__)

ATTR_MAX = "max"
ATTR_MIN = "min"
ATTR_MID = "mid"
ATTR_TOP_EXPONENT = "top_exponent"
ATTR_BOTTOM_EXPONENT = "bottom_exponent"

STATE_ATTR_DAY_START = "day_start"
STATE_ATTR_DAY_MIDDLE = "day_middle"
STATE_ATTR_DAY_END = "day_end"
STATE_ATTR_CURRENTLY = "time_of_day"

DEFAULT_NAME = "Circadian White"

ICON = "mdi:web-clock"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
        vol.Optional(ATTR_MAX, default=6500): cv.positive_int,
        vol.Optional(ATTR_MIN, default=2500): cv.positive_int,
        vol.Optional(ATTR_MID, default=4500): cv.positive_int,
        vol.Optional(ATTR_TOP_EXPONENT, default=2): vol.All(vol.Coerce(int), vol.Range(min=1, min_included=False)),
        vol.Optional(ATTR_BOTTOM_EXPONENT, default=2.2): vol.All(vol.Coerce(int), vol.Range(min=1, min_included=False)),
    }
)

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up the Circadian White Entity."""
    async_add_entities([CircadianWhiteSensor(config.get(CONF_NAME),
                                             config.get(ATTR_MIN),
                                             config.get(ATTR_MID),
                                             config.get(ATTR_MAX),
                                             config.get(ATTR_TOP_EXPONENT),
                                             config.get(ATTR_BOTTOM_EXPONENT),
                                            )], True)

class CircadianWhiteSensor(Entity):
    """Update a sensor with a circadian white level"""

    def __init__(self, name, minimum, middle, maximum, top_exponent, bottom_exponent):
        """Initialize the Random sensor."""
        self._name = name
        self._overnight = 1500
        self._minimum = minimum
        self._middle = middle
        self._maximum = maximum
        self._unit_of_measurement = 'kelvins'
        self._day_start = None
        self._day_middle = None
        self._day_end = None
        self._currently = None
        self._last_sun_update = None
        self._state = self._maximum
        self._available = False

        # Math Variables. Only the exponent is exposed to the user
        # But they could all be changed for varied results.
        # Utilised do_math to see the results.
        self._x_limit = 2
        self._top_exponent = top_exponent
        self._bottom_exponent = bottom_exponent
        self._update_formula()

    async def async_added_to_hass(self):

        @callback
        def update_config(event):
            self.update_sun_events(dt_util.now())
        update_config(None)
        self.hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, update_config)

    @property
    def name(self):
        """Return the name of the device."""
        return self._name

    @property
    def available(self):
        """Not available if we don't have Sun data"""
        return self._available

    @property
    def state(self):
        """Return the state of the device."""
        return self._state

    @property
    def unit_of_measurement(self):
        return self._unit_of_measurement

    @property
    def icon(self):
        """Return the icon to use in the frontend, if any."""
        return ICON

    @property
    def device_state_attributes(self):
        """Return the attributes of the sensor."""
        return {STATE_ATTR_DAY_START: self._day_start.isoformat(),
                STATE_ATTR_DAY_MIDDLE: self._day_middle.isoformat(),
                STATE_ATTR_DAY_END: self._day_end.isoformat(),
                ATTR_MAX: self._maximum,
                ATTR_MIN: self._minimum,
                ATTR_MID: self._middle,
                ATTR_TOP_EXPONENT: self._top_exponent,
                ATTR_BOTTOM_EXPONENT: self._bottom_exponent,
                STATE_ATTR_CURRENTLY: self._currently}

    async def async_update(self):
        """Calculate where we are in the current day, the day follows the following sequence:
              - Night
              - Early Morning
              - Late Morning
              - Early Afternoon
              - Late Afternoon
              - Night
        """
        if self._last_sun_update is None:
            self._available = False
            _LOGGER.info("Circadian White is still waiting for an update from the Sun")
            return

        now = dt_util.now()
        # If we haven't been updated for more than 24 hours -> bail
        if (now - self._last_sun_update).days > 0:
            self._available = False
            _LOGGER.warn("Astral data is out of date")
            return

        self._calculate_kelvins(now)
        _LOGGER.info("Day is currently: {}".format(self._currently))

    def _calculate_kelvins(self, now):
        self._state = self._minimum
        if now < self._predawn:
            self._currently = 'Night'
            self._state = self._overnight
        elif now < self._day_start:
            self._currently = 'Pre-Dawn'
            progress = (now - self._predawn).seconds/3600  # Currently predawn is hardcoded for 1 hour
            curve = self._predawn_a * self._predawn_exponent ** (self._x_limit - (progress * self._x_limit * 2)) + self._predawn_c
            self._state = int(curve)
        elif now < self._mid_morning:
            self._currently = 'Early Morning'
            progress = (now - self._day_start)/self._morning_length
            curve = self._bottom_a * self._bottom_exponent ** ((progress * self._x_limit * 2) - self._x_limit) + self._bottom_c
            self._state = int(curve)
        elif now < self._day_middle:
            self._currently = 'Late Morning'
            progress = (now - self._mid_morning)/self._morning_length
            curve = self._top_a * self._top_exponent ** (self._x_limit - (progress * self._x_limit * 2)) + self._top_c
            self._state = int(curve)
        elif now < self._mid_afternoon:
            self._currently = 'Early Afternoon'
            progress = (now - self._day_middle)/self._afternoon_length
            curve = self._top_a * self._top_exponent ** ((progress * self._x_limit * 2) - self._x_limit) + self._top_c
            self._state = int(curve)
        elif now < self._day_end:
            self._currently = 'Late Afternoon'
            progress = (now - self._mid_afternoon)/self._afternoon_length
            curve = self._bottom_a * self._bottom_exponent ** (self._x_limit - (progress * self._x_limit * 2)) + self._bottom_c
            self._state = int(curve)
        elif now < self._late_evening:
            self._currently = 'Evening'
            progress = (now - self._day_end)/self._evening_length
            curve = self._evening_a * self._evening_exponent ** ((progress * self._x_limit * 2) - self._x_limit) + self._evening_c
            self._state = int(curve)
        elif now < self._nighttime:
            self._currently = 'Late Evening'
            progress = (now - self._day_end)/self._evening_length
            curve = self._evening_a * self._evening_exponent ** ((progress * self._x_limit * 2) - self._x_limit) + self._evening_c
            self._state = int(curve)
        else:
            self._currently = 'Night'
            self._state = self._overnight

    def _update_formula(self):
        """We use the general formula
                a*b^x + c = y
        Where y ends up being the kelvins and x is normalsed from the _x_limit to a percentage of the time
        in the window we are calculating.
        ie. if _x_limit = 2 then the x goes from -2 -> 2 across the time window.

        b is the exponent. By default we use 3 for the early morning and late afternoon (bottom_exponent)
        and 2 for the noon window (top exponent).
        This gives a gentle wake up curve and then spends less time at the bluest at noon time
        """
        x = self._x_limit
        b = self._bottom_exponent
        y2 = self._middle
        y1 = self._minimum
        # Calculate the bottom vars first
        self._bottom_a = ( y2 - y1 )/(b ** x - b ** -x)
        self._bottom_c = (( b ** x ) * y1 - (b ** -x) * y2) / ( b ** x - b ** -x)

        # Now the Top vars
        y2 = self._maximum
        y1 = self._middle
        b = self._top_exponent
        self._top_a = ( y2 - y1 )/(b ** -x - b ** x)
        self._top_c = (( b ** -x ) * y1 - (b ** x) * y2) / ( b ** -x - b ** x)

        # Now the predawn vars
        y2 = self._minimum
        y1 = self._overnight
        b = self._predawn_exponent = 2
        self._predawn_a = ( y2 - y1 )/(b ** -x - b ** x)
        self._predawn_c = (( b ** -x ) * y1 - (b ** x) * y2) / ( b ** -x - b ** x)

        # Now the evening vars
        y2 = self._minimum
        y1 = self._overnight
        b = self._evening_exponent = 8
        self._evening_a = ( y2 - y1 )/(b ** -x - b ** x)
        self._evening_c = (( b ** -x ) * y1 - (b ** x) * y2) / ( b ** -x - b ** x)

    @callback
    def update_sun_events(self, point_in_time):
        _LOGGER.debug("Updating Astral Events from Sun Entity")
        sun = self.hass.states.get(SUN_ENTITY_ID)
        if sun is None:
            _LOGGER.warn("Can't access the Sun Entity, try again in 5 minutes")
            async_track_point_in_time(
                self.hass, self.update_sun_events, point_in_time + timedelta(minutes=5)
            )
            return

        self._calculate_day_events(
            point_in_time,
            dt_util.as_local(dt_util.parse_datetime(sun.attributes[STATE_ATTR_NEXT_DAWN])),
            dt_util.as_local(dt_util.parse_datetime(sun.attributes[STATE_ATTR_NEXT_NOON])),
            dt_util.as_local(dt_util.parse_datetime(sun.attributes[STATE_ATTR_NEXT_DUSK])),
            )

        self._last_sun_update = point_in_time
        self._available = True
        self.async_write_ha_state()

        schedule = self._nighttime + timedelta(minutes=15)
        if point_in_time > schedule:
            schedule = self._nighttime + timedelta(minutes=15)

        _LOGGER.debug("Scheduling next astral for: {}".format(schedule))
        async_track_point_in_time(self.hass, self.update_sun_events, schedule)

    def _calculate_day_events(self, now, day_start, day_middle, day_end):
        # If we're bootstrapping for any reason, ie, a restart/reload
        # the times will be in the future, small error, but we'll just set them to today
        # unless we are already past the day_end
        today = now.date()
        # Co-erce them all to today.
        self._day_start = datetime.combine(today, day_start.time(), day_start.tzinfo)
        self._day_middle = datetime.combine(today, day_middle.time(), day_middle.tzinfo)
        self._day_end = datetime.combine(today, day_end.time(), day_end.tzinfo)

        self._predawn = self._day_start - timedelta(hours=1)
        self._morning_length = (self._day_middle - self._day_start)/2
        self._mid_morning = self._day_start + self._morning_length

        self._late_evening = self._day_end + timedelta(hours=1)
        # We don't want late_night to be very far past 10PM
        ten_pm = self._day_end.replace(hour=22, minute=0, second=0)
        while self._late_evening < ten_pm:
            self._late_evening = self._late_evening + timedelta(minutes=15)

        self._nighttime = self._late_evening + timedelta(hours=1)

        # This is a bit of a fallacy. But if dusk is more than 4 hours before late evening
        # We're just going to push it later 1/2 an hour. So that "Evening" is't quite as long a part of the day.
        if (self._late_evening - self._day_end) > timedelta(hours=4):
            self._day_end += timedelta(minutes=30)

        self._evening_length = self._nighttime - self._day_end
        self._afternoon_length = (self._day_end - self._day_middle)/2
        self._mid_afternoon = self._day_middle + self._afternoon_length


"""
Simple demo
===========
This demo shows the following steps:
- use oteapi-asmod to load an atomistic structure (a C3H6 molecule)
- use ase to calculate the energy and the forces on each atom
- describe the structure and results as instances of two data models
  (ASEAtoms and CalcResults)
- populate an minimal triplestore with mappings
- instantiate a Molecule datamodel via ontological mappings from the
  existing data

Steps to install the requirements (preferrably in a virtual environment):

```shell
git clone git@github.com:EMMC-ASBL/oteapi-asmod.git
cd oteapi-asmod
pip install -U -e .
pip install oteapi-dlite
```

Run the demo:

```shell
python simple.py
```

"""
import sys
sys.path.append("C:\\Users\\alexc\\Desktop\\Universita\\Ricerca\\OpenModel\\OntoFlow")
print(sys.path)

from pathlib import Path

import ase
import dlite
import numpy as np
import pint
from ase.calculators.emt import EMT
from ase.symbols import Symbols, symbols2numbers
from tripper import DM, EMMO, Triplestore, Literal
from tripper.mappings import MappingStep, Value, mapping_routes
from oteapi.datacache import DataCache
from oteapi.models.resourceconfig import ResourceConfig
from oteapi.plugins import load_strategies
from oteapi_asmod.strategies.parse import AtomisticStructureParseStrategy
from ontoflow.engine import OntoFlowDMEngine
from ontoflow.mco_strategies.minimumCostStrategy import MinimumCostStrategy

thisdir = Path(__file__).absolute().parent
datadir = thisdir / "data"
entitydir = thisdir / "entities"

load_strategies()

# Load atoms object with oteapi
# -----------------------------
structure = "C3H6"
print((datadir / f"{structure}.xyz").as_uri())
print((datadir / f"{structure}.xyz"))
config = ResourceConfig(
    downloadUrl=(datadir / f"{structure}.xyz").as_uri(),
    mediaType="chemical/x-xyz",
)

cache = DataCache()
parser = AtomisticStructureParseStrategy(config)
parser.initialize()

key = parser.get().cached_atoms_key
atoms = cache.get(key)  # ase.Atoms object
# print(atoms)

# Convert the atoms object to a DLite instance
# --------------------------------------------

# Add entity definitions to the metadata search path - not nessesary when we
# get a proper centralised entity storage
dlite.storage_path.append(f"{entitydir}/*.json")

# Use dlite.objectfactory to do the conversion
# Consider to add a convenient function for this to dlite.factory
ASEAtoms = dlite.get_instance("http://onto-ns.com/meta/0.1/ASEAtoms")
aseatoms = dlite.objectfactory(atoms, meta=ASEAtoms)
inst = aseatoms.dlite_inst
# print(ASEAtoms)
# print(aseatoms)
# print(inst)

# Perform calculation
# -------------------

# First, recreate an ase.Atoms object from the DLite instance
at = ase.Atoms(**inst.properties)

# Assign simple EMT calculator
at.calc = EMT()

# Create result instance, perform calculation and populate result instance
Result = dlite.get_instance("http://onto-ns.com/meta/0.1/CalcResults")
result = Result(inst.dimensions)
result.potential_energy = at.get_potential_energy()  # Trigger simulation
result.forces = at.get_forces()

# print(at)
# print(Result)
# print(result)

# Instantiate new entity via ontological mappings
# -----------------------------------------------
# Lets assume that we need a Molecule instance for the next simulation.
# We instantiate this instance from existing data via ontological mappings.

# Register missing units
#
# Right now we are using pint, but the ambition is to either add
# functionality for populating an empty pint unit registry from
# e.g. QUDT, implement our own ontology-driven Quantity class with the
# same functionality as pint.Quantity.
#
# A nice thing about pint.Quantity is that it handles both units and
# shapes a simple and transparent way (supporting all standard mathematical
# operations as well as numpy ufuncs).
ureg = pint.UnitRegistry()
ureg.define("Angstrom  = 1e-10 * m")

Molecule = dlite.get_instance("http://onto-ns.com/meta/0.1/Molecule")

def get_formula(symbols):
    """Convert a list of atomic symbols to a chemical formula."""
    # Note that `symbols` is a Quantity object.  Use `symbols.m` to
    # get only the magnitude without unit.
    s = Symbols(symbols2numbers(symbols.m))
    return s.get_chemical_formula()

def get_maxforce(forces):
    """Returns the magnitude of the largest force in forces."""
    # Note that `forces` is a Quantity object.  The returned value
    # will also be a Quantity object with the same unit.  Hence, the
    # unit is always handled explicitly.  This makes it possible for
    # conversion function to change unit as well.
    return np.sqrt(np.sum(forces**2, axis=1).max())

# ts = Triplestore(backend="rdflib")
Triplestore.remove_database(backend="stardog", database="ontoflow", base_iri="http://localhost:5820")
Triplestore.create_database(backend="stardog", database="ontoflow", base_iri="http://localhost:5820")

ts = Triplestore(backend="stardog", base_iri="http://localhost:5820", database="ontoflow")
# ts = Triplestore(name="rdflib", base_iri="http://example.com/demo-ontology#")
DON = ts.bind("don", "http://example.com/demo-ontology#")
ASE = ts.bind("ase", "http://onto-ns.com/meta/0.1/ASEAtoms#")

# Add mappings

# Add mappings
func1_iri = ts.add_function(
    get_formula,
    expects=[DON.Symbols],
    returns=[DON.Formula],
)
ts.add_function(
    get_maxforce,
    expects=[EMMO.Force],
    returns=[DON.MaxForce],
)
ts.add_mapsTo(EMMO.PotentialEnergy, Result, "potential_energy")
ts.add_mapsTo(EMMO.PotentialEnergy, Molecule, "energy")
ts.add_mapsTo(DON.Symbols, ASEAtoms, "symbols")
ts.add_mapsTo(DON.Formula, Molecule, "formula")
ts.add_mapsTo(EMMO.Force, Result, "forces")
ts.add_mapsTo(DON.MaxForce, Molecule, "maxforce")
ts.add([ASE.symbols, DON.hasReference, "http://aseatomdb.com/data/aseatom.json"])
ts.add([DON.Formula, DON.hasAccuracy, DON.Low])
ts.add([DON.Formula, DON.hasComputationalEffort, DON.Low])
# ts.add([DON.Symbols, DM.hasCost, "\"15\""])
print(ts.serialize())

## Add second route
def get_formula_complex(symbols):
    """Convert a list of atomic symbols to a chemical formula."""
    # Note that `symbols` is a Quantity object.  Use `symbols.m` to
    # get only the magnitude without unit.
    s = Symbols(symbols2numbers(symbols.m))
    return s.get_chemical_formula()

func2_iri = ts.add_function(
    get_formula_complex,
    expects=[DON.SymbolsComplex],
    returns=[DON.Formula_Complex],
)
ts.add_mapsTo(DON.Formula_Complex, Molecule, "formula")
ts.add_mapsTo(DON.SymbolsComplex, ASEAtoms, "symbols")
ts.add([DON.Formula_Complex, DON.hasAccuracy, DON.High])
ts.add([DON.Formula_Complex, DON.hasComputationalEffort, DON.High])

mco_strategy = MinimumCostStrategy()

engine = OntoFlowDMEngine(triplestore = ts, cost_file = r"C:\Users\alexc\Desktop\Universita\Ricerca\OpenModel\OntoFlow\examples\datamodel_generation\cost_definitions.yaml", mco_interface = mco_strategy)

molecule_routes = engine.getmappingroute(
    meta=Molecule,
    instances=[inst, result],  # Available data
    quantity=ureg.Quantity,  # Quantity class with our extended unit registry
)

# print("-----------ROUTES--------------")
# print(molecule_routes)
print("-------------------------")
print("-------------FORMULA FINAL------------")
print(molecule_routes["formula"].show())
print("------------WORKFLOW-------------")
print(molecule_routes["formula"].get_workflow_yaml(0))
# # print(molecule_routes["formula"].visualise(0))

# print("-------------------------")
# print("-------------------------")
# print(molecule_routes["formula"].show())
# print("-------------------------")
# el = copy.copy(molecule_routes["formula"])
# el.input_routes = []
# print(el.show())


import select
import socket
import pyautogui

def main() -> None:
    host = ""
    port = 12345

    # create a TCP/IP socket
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setblocking(0)
        # bind the socket to the port
        sock.bind((host, port))
        # listen for incoming connections
        sock.listen(5)
        print("Server started...")

        # sockets from which we expect to read
        inputs = [sock]
        outputs = []

        while inputs:
            # wait for at least one of the sockets to be ready for processing
            readable, writable, exceptional = select.select(inputs, outputs, inputs)

            for s in readable:
                if s is sock:
                    conn, addr = s.accept()
                    inputs.append(conn)
                else:
                    data = s.recv(1024)
                    if data:
                        decoded = data.decode()
                        if decoded == 'right':
                            print("right pressed")
                            pyautogui.press('right')
                        elif decoded == 'left':
                            print("left pressed")
                            pyautogui.press('left')
                    else:
                        inputs.remove(s)
                        s.close()

if __name__ == "__main__":
    main()


from tkinter import *

root = Tk()
star=""
# N = 10

for i in range(1, 10):
    star += "*" * i + "\n"

label = Label(root, text = star, justify = "right", font = ("Monospace", 20, "bold"))
label.pack()

root.mainloop()


from typing import List
import os
import time
from os import listdir
from os.path import isfile, join

class FolderScanner:
    ignore_file_extensions = ['.crdownload', '.tmp']  # this needs to be hardcoded
    stop_scan = False
    max_file_size = 32  # MB

    def __init__(self, download_folder_path: str) -> None:
        self.download_folder_path = download_folder_path

    def check_directory_changes(self) -> str:
        print(f"excluded_file_extensions: {self.ignore_file_extensions}")
        files_in_download_directory = self._scan_directory()
        while True and not self.stop_scan:
            time.sleep(2)
            new_scan = self._scan_directory()
            for new_file in new_scan:
                ignored_file = self._check_if_file_in_ignore_list(new_file)
                if not ignored_file and new_file not in files_in_download_directory:
                    file_size = os.stat(f"{self.download_folder_path}\{new_file}").st_size
                    if file_size == 0:
                        print(f'size of file 0')
                        files_in_download_directory.append(new_file)
                    valid_file_size = int(f"{file_size / float(1 << 20):,.0f}") <= self.max_file_size
                    absolute_file_path = self.download_folder_path + '\\' + new_file
                    if '.part' in new_file and valid_file_size:
                        if self._file_downloaded_from_firefox(new_file) and \
                                files_in_download_directory[-1][:3] == new_file[:3]:
                            print(f"found file downloaded from firefox")
                            return self.download_folder_path + '\\' + files_in_download_directory[-1]
                    elif valid_file_size and file_size > 1 and '.part' not in new_file:
                        return absolute_file_path
                    else:
                        print(f"passing", new_file)

    def _scan_directory(self) -> List:
        """Scan directory & return all file names"""
        directory = [f for f in listdir(self.download_folder_path) if
                     isfile(join(self.download_folder_path, f))]
        return directory

    @classmethod
    def stop_scanning(cls, stop: bool) -> None:
        cls.stop_scan = stop

    @classmethod
    def add_file_ext_to_ignore_list(cls, ext: str) -> None:
        file_extensions = ext.split(' ')
        for file_ext in file_extensions:
            if file_ext not in cls.ignore_file_extensions:
                cls.ignore_file_extensions.append(file_ext)

    def _check_if_file_in_ignore_list(self, file_name: str) -> bool:
        for tmp_file_ext in self.ignore_file_extensions:
            if tmp_file_ext in file_name:
                return True
        return False

    def _file_downloaded_from_firefox(self, file_name: str) -> bool:
        """Firefox create temporary file with .part ending when file is not present
         we can assume file was successfully downloaded"""
        abs_file_path = self.download_folder_path + '\\' + file_name
        for _ in range(20):
            # We can assume file is bigger than 32MB if it hasn't been downloaded in 20 sec
            if not os.path.exists(abs_file_path):
                return True
            time.sleep(1)
        return False


def bin_search(test, key):
    left = 0
    right = len(test)
    while left < right:
        middle = (left + right) // 2
        if test[middle] >= key:
            right = middle
        else:
            left = middle + 1
    return left

file_input = open("binsearch.in", 'r')
file_output = open("binsearch.out", 'w')

_ = int(file_input.readline())
list_of_nums = [int(i) for i in file_input.readline().split()]
num_of_keys = file_input.readline()
keys = [int(i) for i in file_input.readline().split()]

for key in keys:
    left_index = bin_search(list_of_nums, key)
    right_index = bin_search(list_of_nums, key + 1)

    if left_index >= len(list_of_nums):
        print('-1', '-1', file=file_output)
    elif list_of_nums[left_index] != key:
        print('-1', '-1', file=file_output)
    else:
        print(left_index + 1, right_index, file=file_output)


# --------------------------------------------------------
# Deep Iterative Matching Network
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Written by Yi Li, Gu Wang
# --------------------------------------------------------
from __future__ import print_function, division
import numpy as np
from glumpy import app, gl, gloo, data, log
import logging

log.setLevel(logging.WARNING)  # ERROR, WARNING, DEBUG, INFO
from lib.pair_matching.RT_transform import quat2mat

vertex = """
uniform mat4   u_model;         // Model matrix
uniform mat4   u_view;          // View matrix
uniform mat4   u_projection;    // Projection matrix
attribute vec3 position;
attribute vec3 normal;
attribute vec2 texcoord;
varying vec3   v_normal;
varying vec3   v_position;
varying vec2   v_texcoord;
void main()
{
    // Assign varying variables
    v_normal   = normal;
    v_position = position;
    v_texcoord = texcoord;
    // Final position
    gl_Position = u_projection * u_view * u_model * vec4(position, 1.0);
}
"""

def get_fragment(brightness_ratio=0.4):
    fragment = """
    uniform mat4      u_model;           // Model matrix
    uniform mat4      u_view;            // View matrix
    uniform mat4      u_normal;          // Normal matrix
    uniform mat4      u_projection;      // Projection matrix
    uniform sampler2D u_texture;         // Texture
    uniform vec3      u_light_position;  // Light position
    uniform vec3      u_light_intensity; // Light intensity

    varying vec3      v_normal;          // Interpolated normal (in)
    varying vec3      v_position;        // Interpolated position (in)
    varying vec2      v_texcoord;        // Interpolated fragment texture coordinates (in)
    void main()
    {{
        // Calculate normal in world coordinates
        vec3 normal = normalize(u_normal * vec4(v_normal,1.0)).xyz;

        // Calculate the location of this fragment (pixel) in world coordinates
        vec3 position = vec3(u_view*u_model * vec4(v_position, 1));
        //vec3 light_position = vec3(u_view*u_model * vec4(u_light_position, 1));
        // Calculate the vector from this pixels surface to the light source
        vec3 surfaceToLight = u_light_position - position;

        // Calculate the cosine of the angle of incidence (brightness)
        float brightness = dot(normal, surfaceToLight) /
                          (length(surfaceToLight) * length(normal));
        brightness = max(min(brightness,1.0),0.0);

        // Calculate final color of the pixel, based on:
        // 1. The angle of incidence: brightness
        // 2. The color/intensities of the light: light.intensities
        // 3. The texture and texture coord: texture(tex, fragTexCoord)

        // Get texture color
        vec4 t_color = vec4(texture2D(u_texture, v_texcoord).rgb, 1.0);

        // Final color
        gl_FragColor = t_color * ({} + {}*brightness * vec4(u_light_intensity, 1));
    }}
    """.format(
        1 - brightness_ratio, brightness_ratio
    )
    return fragment

class Render_Py_Light:
    def __init__(self, model_folder, K, width=640, height=480, zNear=0.25, zFar=6.0, brightness_ratios=[0.4, 0.3, 0.2]):
        self.width = width
        self.height = height
        self.zNear = zNear
        self.zFar = zFar
        self.K = K
        self.model_folder = model_folder

        log.info("Loading mesh")
        vertices, indices = data.objload("{}/textured.obj".format(model_folder), rescale=False)
        self.render_kernels = []
        for brightness_ratio in brightness_ratios:
            fragment = get_fragment(brightness_ratio=brightness_ratio)
            render_kernel = gloo.Program(vertex, fragment)
            render_kernel.bind(vertices)

            log.info("Loading texture")
            render_kernel["u_texture"] = np.copy(data.load("{}/texture_map.png".format(model_folder))[::-1, :, :])

            render_kernel["u_model"] = np.eye(4, dtype=np.float32)
            u_projection = self.my_compute_calib_proj(K, width, height, zNear, zFar)
            render_kernel["u_projection"] = np.copy(u_projection)

            render_kernel["u_light_intensity"] = 1, 1, 1
            self.render_kernels.append(render_kernel)
        self.brightness_k = 0  # init

        self.window = app.Window(width=width, height=height, visible=False)

        @self.window.event
        def on_draw(dt):
            self.window.clear()
            gl.glDisable(gl.GL_BLEND)
            gl.glEnable(gl.GL_DEPTH_TEST)
            self.render_kernels[self.brightness_k].draw(gl.GL_TRIANGLES)

        @self.window.event
        def on_init():
            gl.glEnable(gl.GL_DEPTH_TEST)

    def render(self, r, t, light_position, light_intensity, brightness_k=0, r_type="quat", K=None):
        """
        :param r:
        :param t:
        :param light_position:
        :param light_intensity:
        :param brightness_k: choose which brightness in __init__
        :param r_type:
        :return:
        """
        if r_type == "quat":
            R = quat2mat(r)
        elif r_type == "mat":
            R = r
        self.brightness_k = brightness_k
        self.render_kernels[brightness_k]["u_view"] = self._get_view_mtx(R, t)
        self.render_kernels[brightness_k]["u_light_position"] = light_position
        self.render_kernels[brightness_k]["u_normal"] = np.array(
            np.matrix(
                np.dot(
                    self.render_kernels[brightness_k]["u_view"].reshape(4, 4),
                    self.render_kernels[brightness_k]["u_model"].reshape(4, 4),
                )
            ).I.T
        )
        self.render_kernels[brightness_k]["u_light_intensity"] = light_intensity

        if K is not None:
            u_projection = self.my_compute_calib_proj(K, self.width, self.height, self.zNear, self.zFar)
            self.render_kernels[brightness_k]["u_projection"] = np.copy(u_projection)

        app.run(framecount=0)
        rgb_buffer = np.zeros((self.height, self.width, 4), dtype=np.float32)
        gl.glReadPixels(0, 0, self.width, self.height, gl.GL_RGBA, gl.GL_FLOAT, rgb_buffer)

        rgb_gl = np.copy(rgb_buffer)
        rgb_gl.shape = 480, 640, 4
        rgb_gl = rgb_gl[::-1, :]
        rgb_gl = np.round(rgb_gl[:, :, :3] * 255).astype(np.uint8)  # Convert to [0, 255]
        bgr_gl = rgb_gl[:, :, [2, 1, 0]]

        depth_buffer = np.zeros((self.height, self.width), dtype=np.float32)
        gl.glReadPixels(0, 0, self.width, self.height, gl.GL_DEPTH_COMPONENT, gl.GL_FLOAT, depth_buffer)
        depth_gl = np.copy(depth_buffer)
        depth_gl.shape = 480, 640
        depth_gl = depth_gl[::-1, :]
        depth_bg = depth_gl == 1
        depth_gl = 2 * self.zFar * self.zNear / (self.zFar + self.zNear - (self.zFar - self.zNear) * (2 * depth_gl - 1))
        depth_gl[depth_bg] = 0
        return bgr_gl, depth_gl

    def __del__(self):
        self.window.close()

    def my_compute_calib_proj(self, K, w, h, zNear, zFar):
        u0 = K[0, 2] + 0.5
        v0 = K[1, 2] + 0.5
        fu = K[0, 0]
        fv = K[1, 1]
        L = +(u0) * zNear / -fu
        T = +(v0) * zNear / fv
        R = -(w - u0) * zNear / -fu
        B = -(h - v0) * zNear / fv
        proj = np.zeros((4, 4))
        proj[0, 0] = 2 * zNear / (R - L)
        proj[1, 1] = 2 * zNear / (T - B)
        proj[2, 2] = -(zFar + zNear) / (zFar - zNear)
        proj[2, 0] = (R + L) / (R - L)
        proj[2, 1] = (T + B) / (T - B)
        proj[2, 3] = -1.0
        proj[3, 2] = -(2 * zFar * zNear) / (zFar - zNear)
        return proj

    def _get_view_mtx(self, R, t):
        u_view = np.eye(4, dtype=np.float32)
        u_view[:3, :3], u_view[:3, 3] = R, t.squeeze()
        yz_flip = np.eye(4, dtype=np.float32)
        yz_flip[1, 1], yz_flip[2, 2] = -1, -1
        u_view = yz_flip.dot(u_view)  # OpenCV to OpenGL camera system
        u_view = u_view.T  # OpenGL expects column-wise matrix format
        return u_view

if __name__ == "__main__":
    import cv2
    import os
    import sys
    from pprint import pprint

    cur_path = os.path.abspath(os.path.dirname(__file__))
    sys.path.insert(1, os.path.join(cur_path, "../.."))

    def mat2quat(M):
        # Qyx refers to the contribution of the y input vector component to
        # the x output vector component.  Qyx is therefore the same as
        # M[0,1].  The notation is from the Wikipedia article.
        Qxx, Qyx, Qzx, Qxy, Qyy, Qzy, Qxz, Qyz, Qzz = M.flat
        # Fill only lower half of symmetric matrix
        K = (
            np.array(
                [
                    [Qxx - Qyy - Qzz, 0, 0, 0],
                    [Qyx + Qxy, Qyy - Qxx - Qzz, 0, 0],
                    [Qzx + Qxz, Qzy + Qyz, Qzz - Qxx - Qyy, 0],
                    [Qyz - Qzy, Qzx - Qxz, Qxy - Qyx, Qxx + Qyy + Qzz],
                ]
            )
            / 3.0
        )
        # Use Hermitian eigenvectors, values for speed
        vals, vecs = np.linalg.eigh(K)
        # Select largest eigenvector, reorder to w,x,y,z quaternion
        q = vecs[[3, 0, 1, 2], np.argmax(vals)]
        # Prefer quaternion with positive w
        if q[0] < 0:
            q *= -1
        return q

    class_name = "002_master_chef_can"

    model_dir = os.path.join(cur_path, "../../data/LOV/models/{}".format(class_name))
    pose_path = os.path.join(cur_path, "../../data/render_v5/data/render_real/%s/0001/{}-pose.txt" % (class_name))
    color_path = os.path.join(cur_path, "../../data/render_v5/data/render_real/%s/0001/{}-color.png" % (class_name))
    width = 640
    height = 480
    K = np.array([[1066.778, 0, 312.9869], [0, 1067.487, 241.3109], [0, 0, 1]])
    ZNEAR = 0.25
    ZFAR = 6.0
    idx = "000001"

    brightness_ratios = [0.3, 0.4]
    render_machine = Render_Py_Light(model_dir, K, width, height, ZNEAR, ZFAR, brightness_ratios=brightness_ratios)
    pose_real_est = np.loadtxt(pose_path.format(idx), skiprows=1)
    r_quat = mat2quat(pose_real_est[:, :3])
    t = pose_real_est[:, 3]
    # warm up
    rgb_gl, _ = render_machine.render((0.5, 0.5, 0.5, 0.5), t, light_position=[0, 0, 1], light_intensity=[1, 1, 1])
    import time

    start_t = time.time()
    rgb_gl_1, _ = render_machine.render(r_quat, t, light_position=[0, 0, -1], light_intensity=[1, 1, 1], brightness_k=0)
    rgb_gl_2, _ = render_machine.render(
        r_quat, t, light_position=[0, 0, -1], light_intensity=[1 * 1.5, 1 * 1.5, 1.2 * 1.5], brightness_k=1
    )
    rgb_gl_3, _ = render_machine.render(
        r_quat, t, light_position=[0, 0, -1], light_intensity=np.array([1, 1.2, 1]) * 2, brightness_k=0
    )
    rgb_gl_4, _ = render_machine.render(
        r_quat, t, light_position=[0, 0, -1], light_intensity=np.array([1.2, 1, 1]) * 3, brightness_k=1
    )
    rgb_gl_5, _ = render_machine.render(r_quat, t, light_position=[0, 0, -1], light_intensity=[1, 0, 1], brightness_k=0)
    rgb_gl_6, _ = render_machine.render(r_quat, t, light_position=[0, 0, -1], light_intensity=[0, 1, 1], brightness_k=0)
    rgb_gl_7, _ = render_machine.render(
        r_quat, t, light_position=[0, 0, -1], light_intensity=[10, 10, 10], brightness_k=0
    )
    print("using {} seconds".format(time.time() - start_t))
    rgb_pa = cv2.imread(color_path.format(idx), cv2.IMREAD_COLOR)

    pprint(rgb_gl_1[rgb_gl_1.nonzero()])
    pprint(rgb_gl_2[rgb_gl_2.nonzero()])
    pprint(rgb_gl_3[rgb_gl_3.nonzero()])
    pprint(rgb_gl_4[rgb_gl_3.nonzero()])
    pprint(rgb_gl_5[rgb_gl_3.nonzero()])
    pprint(rgb_gl_6[rgb_gl_3.nonzero()])
    pprint(rgb_gl_7[rgb_gl_3.nonzero()])

    import matplotlib.pyplot as plt

    fig = plt.figure()
    plt.axis("off")
    fig.add_subplot(2, 4, 1)
    plt.imshow(rgb_pa)
    fig.add_subplot(2, 4, 2)
    plt.imshow(rgb_gl_1)
    fig.add_subplot(2, 4, 3)
    plt.imshow(rgb_gl_2)
    fig.add_subplot(2, 4, 4)
    plt.imshow(rgb_gl_3)
    fig.add_subplot(2, 4, 5)
    plt.imshow(rgb_gl_4)
    fig.add_subplot(2, 4, 6)
    plt.imshow(rgb_gl_5)
    fig.add_subplot(2, 4, 7)
    plt.imshow(rgb_gl_6)
    fig.add_subplot(2, 4, 8)
    plt.imshow(rgb_gl_7)
    fig.suptitle("brightness_ratio: {}".format(brightness_ratios[0]))

    plt.show()


from __future__ import annotations

import math

from cctbx.crystal import symmetry
from libtbx.phil import parse

from dials.array_family import flex
from dials.util import tabulate

"""
Class to find a reasonable cutoff for integration based on work in LABELIT.
Bins the reflection table by resolution, then finds the first bin that goes
under a given I/sigI limit.  Cuts the data at that point.
"""

phil_scope = parse(
    """
significance_filter
  .expert_level=1
{
  enable = False
    .type=bool
    .help=If enabled, the significance filter will, for every experiment, find \
          the highest resolution where the I/sigI remains above a certain point\
          (controlled by isigi_cutoff).
  d_min = None
    .type = float
    .help = High resolution cutoff for binning. If None, use the highest \
            resolution reflection as d_min.
  n_bins = 20
    .type = int
    .help = Number of bins to use when examining resolution falloff
  isigi_cutoff = 1.0
    .type = float
    .help = I/sigI cutoff. Reflections in and past the first bin that falls \
            below this cutoff will not be retained
}
"""
)

class SignificanceFilter:
    def __init__(self, params):
        self.params = params.significance_filter
        self.best_d_min = None

    def __call__(self, experiments, reflections):
        results = flex.reflection_table()
        table_header = ["", "", "", "I", "IsigI", "N >", "RMSD", "Cutoff"]
        table_header2 = [
            "Bin",
            "Resolution Range",
            "Completeness",
            "",
            "",
            "cutoff",
            "(um)",
            "",
        ]

        for exp_id in range(len(experiments)):
            print("*" * 80)
            print("Significance filtering experiment", exp_id)
            table_data = []
            table_data.append(table_header)
            table_data.append(table_header2)
            experiment = experiments[exp_id]

            # Find the bins for this experiment
            crystal = experiment.crystal
            refls = reflections.select(reflections["id"] == exp_id)
            sym = symmetry(
                unit_cell=crystal.get_unit_cell(), space_group=crystal.get_space_group()
            )
            d = crystal.get_unit_cell().d(refls["miller_index"])
            mset = sym.miller_set(indices=refls["miller_index"], anomalous_flag=False)
            binner = mset.setup_binner(
                n_bins=self.params.n_bins, d_min=self.params.d_min or 0
            )
            acceptable_resolution_bins = []

            # Iterate through the bins, examining I/sigI at each bin
            for i in binner.range_used():
                d_max, d_min = binner.bin_d_range(i)
                if d_max < 0:
                    sel = d > d_min
                else:
                    sel = (d <= d_max) & (d > d_min)
                sel &= refls["intensity.sum.value"] > 0
                bin_refls = refls.select(sel)
                n_refls = len(bin_refls)
                avg_i = (
                    flex.mean(bin_refls["intensity.sum.value"]) if n_refls > 0 else 0
                )
                avg_i_sigi = (
                    flex.mean(
                        bin_refls["intensity.sum.value"]
                        / flex.sqrt(bin_refls["intensity.sum.variance"])
                    )
                    if n_refls > 0
                    else 0
                )
                acceptable_resolution_bins.append(
                    avg_i_sigi >= self.params.isigi_cutoff
                )

                bright_refls = bin_refls.select(
                    (
                        bin_refls["intensity.sum.value"]
                        / flex.sqrt(bin_refls["intensity.sum.variance"])
                    )
                    >= self.params.isigi_cutoff
                )
                n_bright = len(bright_refls)

                rmsd_obs = (
                    1000
                    * math.sqrt(
                        (
                            bright_refls["xyzcal.mm"] - bright_refls["xyzobs.mm.value"]
                        ).sum_sq()
                        / n_bright
                    )
                    if n_bright > 0
                    else 0
                )

                table_row = []
                table_row.append("%3d" % i)
                table_row.append(
                    "%-13s"
                    % binner.bin_legend(
                        i_bin=i,
                        show_bin_number=False,
                        show_bin_range=False,
                        show_d_range=True,
                        show_counts=False,
                    )
                )
                table_row.append(
                    "%13s"
                    % binner.bin_legend(
                        i_bin=i,
                        show_bin_number=False,
                        show_bin_range=False,
                        show_d_range=False,
                        show_counts=True,
                    )
                )

                table_row.append(f"{avg_i:.2f}")
                table_row.append(f"{avg_i_sigi:.2f}")
                table_row.append("%3d" % n_bright)
                table_row.append(f"{rmsd_obs:.2f}")
                table_data.append(table_row)

            # Throw out bins that go back above the cutoff after the first non-passing bin is found
            acceptable_resolution_bins = [
                acceptable_resolution_bins[i]
                for i in range(len(acceptable_resolution_bins))
                if False not in acceptable_resolution_bins[: i + 1]
            ]

            for b, row in zip(acceptable_resolution_bins, table_data[2:]):
                if b:
                    row.append("X")
            print(tabulate(table_data, headers="firstrow"))

            # Save the results
            if any(acceptable_resolution_bins):
                best_index = acceptable_resolution_bins.count(True) - 1
                best_row = table_data[best_index + 2]
                d_min = binner.bin_d_range(binner.range_used()[best_index])[1]
                self.best_d_min = d_min
                print("best row:", " ".join(best_row))
                if self.params.enable:
                    results.extend(refls.select(d >= d_min))
            else:
                print("Data didn't pass cutoff")
                self.best_d_min = None
        if self.params.enable:
            return results
        else:
            return reflections