import os
import progressbar
from glob import glob
import pickle
import numpy as np

from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn import metrics

import cv2
import mahotas as mt
from skimage import feature
from numpy.lib import stride_tricks

from settings import image_dir, label_dir, model_dir, cache_dir
from settings import scaler_fn, model_fn
from settings import palette_bgr, palette_rgb
from settings import oversample, random_state
from settings import classes, class_sep
from settings import h_neigh, h_ind, lbp_radius, lbp_points
from settings import test_size

from tools import onehot2int, int2onehot, load_pickle, dump2pickle

def test_model(X, y, model):
    pred = model.predict(X)
    precision = metrics.precision_score(
        y, pred, average='weighted', labels=np.unique(pred))
    recall = metrics.recall_score(
        y, pred, average='weighted', labels=np.unique(pred))
    f1 = metrics.f1_score(y, pred, average='weighted', labels=np.unique(pred))
    accuracy = metrics.accuracy_score(y, pred)

    print('--------------------------------')
    print('[RESULTS] Accuracy: %.2f' % accuracy)
    print('[RESULTS] Precision: %.2f' % precision)
    print('[RESULTS] Recall: %.2f' % recall)
    print('[RESULTS] F1: %.2f' % f1)
    print('--------------------------------')
    return

def train_model(X, y):
    print('[INFO] Training MLP model.')
    model = MLPClassifier(solver='lbfgs', alpha=1e-5, warm_start=True,
                          hidden_layer_sizes=(30), learning_rate='adaptive', early_stopping=True, max_iter=200, random_state=random_state)
    model.fit(X, y)

    print('[INFO] Model training complete.')
    print('[INFO] Training Accuracy: %.2f' % model.score(X, y))
    return model

def calc_haralick(roi):
    feature_vec = []

    texture_features = mt.features.haralick(roi)
    mean_ht = texture_features.mean(axis=0)

    [feature_vec.append(i) for i in mean_ht[0:9]]
    return np.array(feature_vec)

def harlick_features(img, h_neigh):

    print('[INFO] Computing haralick features.')
    size = h_neigh
    shape = (img.shape[0] - size + 1, img.shape[1] - size + 1, size, size)
    strides = 2 * img.strides
    patches = stride_tricks.as_strided(img, shape=shape, strides=strides)
    patches = patches.reshape(-1, size, size)

    bar = progressbar.ProgressBar(maxval=img.size,
                                  widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])

    bar.start()

    h_features = []

    for i, p in enumerate(patches):
        bar.update(i+1)
        h_features.append(calc_haralick(p))

    return np.array(h_features)

def create_binary_pattern(img, p, r):

    print('[INFO] Computing local binary pattern features.')
    lbp = feature.local_binary_pattern(img, p, r)
    return (lbp-np.min(lbp))/(np.max(lbp)-np.min(lbp))

def create_features(img):
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    feature_img = np.zeros((img.shape[0], img.shape[1], 4))
    feature_img[:, :, :3] = img

    hsv = np.zeros((img.shape[0], img.shape[1], 3))
    hsv[:, :, :3] = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    hsv = hsv[h_ind:-h_ind, h_ind:-h_ind]

    feature_img[:, :, 3] = create_binary_pattern(
        img_gray, lbp_points, lbp_radius)
    feature_img = feature_img[h_ind:-h_ind, h_ind:-h_ind]
    features = feature_img.reshape(
        feature_img.shape[0]*feature_img.shape[1], feature_img.shape[2])
    hsv = hsv.reshape(
        feature_img.shape[0]*feature_img.shape[1], 3)

    features = np.hstack((hsv, features))

    h_features = harlick_features(img_gray, h_neigh)

    features = np.hstack((features, h_features))

    return features

def create_dataset(image_dict, label_dict):
    print('[INFO] Creating training dataset on %d image(s).' %
          len(image_dict.keys()))

    X = []
    y = []

    for fn in image_dict.keys():
        img = image_dict[fn]
        label = label_dict[fn]

        cached_fn = os.path.join(cache_dir, fn.split(
            os.path.sep)[-1].split('.')[0]+".pkl")
        if os.path.isfile(cached_fn):
            features = load_pickle(cached_fn)
        else:
            features = create_features(img)
            dump2pickle(features, cached_fn)

        label = label[h_ind:-h_ind, h_ind:-h_ind]
        labels = label.reshape(label.shape[0]*label.shape[1], -1)
        X.append(features)
        y.append(labels)
    X = np.array(X)
    X = X.reshape(X.shape[0]*X.shape[1], -1)

    y = np.array(y)
    y = (y > 0) * 1
    y = y.astype(dtype=np.uint8)
    y = y.reshape(y.shape[0]*y.shape[1], -1)

    # delete ambigous samples
    indices = np.where(y.sum(axis=1) != 1)
    y = np.delete(y, indices, axis=0)
    X = np.delete(X, indices, axis=0)

    # unused
    def add_background_label(y):
        expanded = np.c_[y, np.zeros(y.shape[0])].astype(np.uint8)
        bg_label = np.zeros(len(classes)+1, dtype=np.uint8)
        bg_label[-1] = 1
        expanded[np.where(~expanded.any(axis=1))] = bg_label
        return expanded

    y_int = onehot2int(y)

    from collections import Counter
    print("Original dataset shape {}".format(Counter(y_int)))
    if oversample:
        from imblearn.over_sampling import RandomOverSampler
        ros = RandomOverSampler(random_state=random_state)
        X, y_int = ros.fit_resample(X, y_int)
        print("Resampled dataset shape {}".format(Counter(y_int)))
        y = int2onehot(y_int)

    scaler = MinMaxScaler()
    scaler.fit(X)
    X = scaler.transform(X)

    dump2pickle(scaler, os.path.join(model_dir, scaler_fn))

    return X, y

def read_data(image_dir, label_dir):

    print('[INFO] Reading image data.')

    filelist = glob(os.path.join(image_dir, '*.jpg'))
    image_dict = dict()
    label_dict = dict()

    for fn in filelist:
        image_dict[fn] = cv2.imread(fn, cv2.IMREAD_COLOR)
        label_fn = os.path.join(label_dir, fn.split(
            os.path.sep)[-1].split('.')[0]+".png")
        label_map = cv2.imread(label_fn, cv2.IMREAD_COLOR)
        label_layers = []
        if not os.path.isfile(label_fn):
            raise ValueError(
                "Label file {} does not exist".format(label_fn))
        for i in classes:
            indices = np.where(label_map == palette_bgr[i])[:2]
            ones = np.zeros((label_map.shape[0], label_map.shape[1]), np.uint8)
            ones[indices] = 1
            label_layers.append(ones)
        label_dict[fn] = np.stack([layer
                                   for layer in label_layers], axis=-1)
    return image_dict, label_dict

if __name__ == "__main__":
    cache_dir = os.path.join(cache_dir, "store")

    image_dict, label_dict = read_data(image_dir, label_dir)
    a = label_dict['data\\images\\pots_block_2_27.jpg']
    X, y = create_dataset(image_dict, label_dict)
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=test_size, random_state=random_state)
    print('[INFO] Feature vector size:', X_train.shape)
    model = train_model(X_train, y_train)
    test_model(X_test, y_test, model)
    dump2pickle(model, os.path.join(model_dir, model_fn))


product1 = input()
product2 = input()

product1_list = product1.split()
product2_list = product2.split()

which_pay_prod1 = int(product1_list[1]) * round(float(product1_list[2]), 2)
which_pay_prod2 = int(product2_list[1]) * round(float(product2_list[2]), 2)

total_to_pay = round(which_pay_prod1 + which_pay_prod2, 2)

print(f"VALOR A PAGAR: R$ {total_to_pay:.2f}")


from pycountry import countries

from webapp.services.import_services.models import LocationUpdate, BusinessUpdate, EvseUpdate, ConnectorUpdate, RegularHoursUpdate, \
    ExceptionalPeriodUpdate, ImageUpdate
from webapp.services.import_services.ocpi.ocpi_validators import LocationInput, EvseInput, ConnectorInput, BusinessDetailsInput, ImageInput

class OcpiMapper:

    def map_location(self, location_input: LocationInput, source: str) -> LocationUpdate:
        location_update = LocationUpdate(
            uid=location_input.id,
            source=source,
            name=location_input.name,
            address=location_input.address,
            postal_code=location_input.postal_code,
            city=location_input.city,
            state=location_input.state,
            country=countries.get(alpha_3=location_input.country).alpha_2,
            lat=location_input.coordinates.latitude,
            lon=location_input.coordinates.longitude,
            directions=location_input.directions,
            parking_type=location_input.parking_type,
            time_zone=location_input.time_zone,
            last_updated=location_input.last_updated,
            evses=[],
        )
        for evse_input in location_input.evses:
            location_update.evses.append(self.map_evse(evse_input))

        for business_type in ('operator', 'suboperator', 'owner'):
            if not getattr(location_input, business_type):
                continue

            setattr(location_update, business_type, self.map_business(business_input=getattr(location_input, business_type)))

        if location_input.opening_times:
            location_update.twentyfourseven = location_input.opening_times.twentyfourseven
            if location_input.opening_times.regular_hours:
                location_update.regular_hours = []
                for regular_hour_input in location_input.opening_times.regular_hours:
                    location_update.regular_hours.append(RegularHoursUpdate(**regular_hour_input.to_dict()))

            if location_input.opening_times.exceptional_openings:
                location_update.exceptional_openings = []
                for exceptional_opening_input in location_input.opening_times.exceptional_openings:
                    location_update.exceptional_openings.append(ExceptionalPeriodUpdate(**exceptional_opening_input.to_dict()))

            if location_input.opening_times.exceptional_closings:
                location_update.exceptional_closings = []
                for exceptional_closings_input in location_input.opening_times.exceptional_closings:
                    location_update.exceptional_closings.append(ExceptionalPeriodUpdate(**exceptional_closings_input.to_dict()))

        return location_update

    def map_evse(self, evse_input: EvseInput) -> EvseUpdate:
        evse_update = EvseUpdate(
            uid=evse_input.evse_id,
            status=evse_input.status,
            floor_level=evse_input.floor_level,
            physical_reference=evse_input.physical_reference,
            last_updated=evse_input.last_updated,
            capabilities=evse_input.capabilities,
            parking_restrictions=evse_input.parking_restrictions,
            # TODO: directions
            connectors=[],
        )

        if evse_input.coordinates:
            evse_update.lat = evse_input.coordinates.latitude
            evse_update.lon = evse_input.coordinates.longitude

        for connector_input in evse_input.connectors:
            evse_update.connectors.append(self.map_connector(connector_input))

        return evse_update

    @staticmethod
    def map_connector(connector_input: ConnectorInput) -> ConnectorUpdate:
        connector_update = ConnectorUpdate(
            uid=connector_input.id,
            standard=connector_input.standard,
            format=connector_input.format,
            power_type=connector_input.power_type,
            max_voltage=connector_input.max_voltage,
            max_amperage=connector_input.max_amperage,
            max_electric_power=connector_input.max_electric_power,
            last_updated=connector_input.last_updated,
            terms_and_conditions=connector_input.terms_and_conditions,
        )

        return connector_update

    def map_business(self, business_input: BusinessDetailsInput) -> BusinessUpdate:
        business_update = BusinessUpdate(
            name=business_input.name,
            website=business_input.website,
        )
        if business_input.logo:
            business_update.logo = self.map_image(business_input.logo)

        return business_update

    @staticmethod
    def map_image(image_input: ImageInput) -> ImageUpdate:
        image_update = ImageUpdate(
            external_url=image_input.url,
            width=image_input.width,
            category=image_input.category,
            type=image_input.type,
            height=image_input.height,
        )
        return image_update


"""
const $ = new Env("统计东哥历史红包");
统计东哥历史红包
"""

import requests
import sys
import re
import time
import os

def gettimestamp():
    return str(int(time.time() * 1000))

def printf(text):
    print(text)
    sys.stdout.flush()

def getinfo(ck):
    isNext = True
    page = 1
    sum = 0
    usedsum = 0
    count = 0
    while isNext:
        url = "https://wq.jd.com/user/info/QueryUserRedEnvelopesV2?type=2&orgFlag=JD_PinGou_New&page=%s&cashRedType=1&redBalanceFlag=0&channel=3&_=%s&sceneval=2&g_login_type=1&g_ty=ls" % (
            page, gettimestamp())
        headers = {
            'accept': '*/*',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.9',
            'dnt': '1',
            'referer': 'https://wqs.jd.com/',
            'sec-fetch-dest': 'script',
            'sec-fetch-mode': 'no-cors',
            'sec-fetch-site': 'same-site',
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
            'cookie': ck
        }
        r = requests.get(url, headers=headers).json()
        # print(r)
        if r['data']['unUseRedInfo']['redList'] == None:
            print('累计红包总数', count, '累计红包总额 %.2f' % sum, '已使用红包总额 %.2f' % usedsum)
            isNext = False
        else:
            page += 1
            count = r['data']['unUseRedInfo']['count']
            for i in r['data']['unUseRedInfo']['redList']:
                sum += float(i['discount'])
                usedsum += (float(i['discount']) - float(i['balance']))

if __name__ == '__main__':
    try:
        printf("--------[212796668]群管理贡献--------")
        cks = os.environ["JD_COOKIE"].split("&")
    except:
        f = open("/jd/config/config.sh", "r", encoding='utf-8')
        cks = re.findall(r'Cookie[0-9]*="(pt_key=.*?;pt_pin=.*?;)"', f.read())
        f.close()
    for ck in cks:
        ptpin = re.findall(r"pt_pin=(.*?);", ck)[0]
        printf("--------开始京东账号" + ptpin + "--------")
        try:
            getinfo(ck)
        except:
            print("发生异常错误")


from cmath import inf

class Hungarian:
    def __init__(self, matrix):
        self.matrix = matrix  # matrix[task][machine] = cost
        self.theta = 0  # total matrix reduction
        self.ind_zeros = []  # współrzędne zer niezależnych
        self.dep_zeros = []  # współrzędne zer zależnych
        self.cross_row = []  # wiersze do przekreślenia
        self.cross_col = []  # kolumny do przekreślenia

    def reduce_matrix(self):  # Metoda odejmująca najmniejszą wartość od wierszy i kolumn
        # wiersze:
        for i, _ in enumerate(self.matrix):
            self.theta += min(self.matrix[i])  # zwiększenie total matrix reduction
            self.matrix[i] = [elem - min(self.matrix[i])
                              for elem in self.matrix[i]]
        # kolumny:
        for j, _ in enumerate(self.matrix):
            min_col_val = inf
            for i, _ in enumerate(self.matrix[j]):
                if self.matrix[i][j] < min_col_val:
                    min_col_val = self.matrix[i][j]

            self.theta += min_col_val  # zwiększenie total matrix reduction

            for i, _ in enumerate(self.matrix[j]):
                self.matrix[i][j] -= min_col_val

    def assign(self):
        ind_zeros = []  # współrzędne zer niezależnych
        dep_zeros = []  # współrzędne zer zależnych
        size = len(self.matrix)  # rozmiar macierzy

        for number in range(1, size + 1):  # Dla liczby zer w wierszu
            for idx, row in enumerate(self.matrix):  # dla każdego wiersza macierzy
                if row.count(0) == number:  # jeśli liczba zer w wierszu wynosi number
                    added = False  # zmienna do sprawdzania czy znaleziono zero niezalezne
                    for idy, col in enumerate(row):  # dla każdej kolumny
                        # jeśli znaleziono zero, nie jest to zero niezależne i kolumna nie jest już w innym zerze
                        if col == 0 and not added and idy not in [el[1] for el in ind_zeros]:
                            another_zero_in_col = False  # zmiienna do spradzania większej ilości zer w kolumnie
                            for row_in_col in range(size):  # dla każdego wiersza w kolumnie
                                # jeśli znaleziono zero i nie jest to wiersz row
                                if self.matrix[row_in_col][idy] == 0 and row_in_col != row:
                                    another_zero_in_col = True  # znaleziono zero
                            if not another_zero_in_col:  # jeśli nie znaleziono więcej zer
                                added = True  # znaleziono zero niezalezne
                                ind_zeros.append((idx, idy))  # dodaj współrzędną do zer niezależnych

                    if not added:  # jeśli nie znaleziono zera niezależnego
                        for idy, col in enumerate(row):  # dla każdej kolumny macierzy
                            #  znajdź pierwsze zero, którego kolumna nie jest już w zerach niezaleznych
                            if col == 0 and idy not in [el[1] for el in ind_zeros]:
                                ind_zeros.append((idx, idy))  # dodaj do zer niezależnych
                                break

        # dodanie zer zależnych
        for row in range(size):  # dla każdego wiersza
            for col in range(size):  # dla każdej kolumny
                # jeśli znaleziono zero i nie jest to zero niezależne lub niezależne
                if self.matrix[row][col] == 0 and (row, col) not in ind_zeros:
                    dep_zeros.append((row, col))  # znaleziono zero zależne

        self.ind_zeros = ind_zeros
        self.dep_zeros = dep_zeros

    def zero_crossing(self):
        select_row = [i for i in range(len(self.matrix))]  # tablica na zaznaczone wiersze
        select_col = []  # tablica na zaznaczone kolumny
        # Oznaczyć symbolem x każdy wiersz nie posiadający niezależnego zera
        for el in self.ind_zeros:  # dla każdego elementu w tablicy zer niezależnych
            select_row.remove(el[0])  # usuń wiersz z tablicy zaznaczonych, w którym jest zero niezależne

        while True:  # do póki znajdowane są nowe zaznaczenia
            selected = False  # zmienna do sprawdzania czy znaleziono nowe zaznaczenia

            # Oznaczyć symbolem x każda kolumnę mającą zero zależne 0 w oznaczonym wierszu
            for row in select_row:  # dla każdego wiersza w zaznaczonych wierszach
                for col in range(len(self.matrix[row])):  # dla każdej kolumny macierzy
                    # for zero in self.dep_zeros:  # dla każdego zera zależnego
                    #     if zero[0] == row and zero[1] == col:
                    if (row, col) in self.dep_zeros:  # jeśli współrzędne są równe współrzędnym zera zależnego
                        if col not in select_col:  # jeśli kolumna nie jest w zaznaczonych kolumnach
                            select_col.append(col)  # dodaj do zaznaczonych kolumn
                            selected = True  # zaznaczono

            # Oznaczyć symbolem x każdy wiersz mający w oznakowanej kolumnie niezależne zero
            for col in select_col:  # dla każdej kolumny w zaznaczonych kolumnach
                for row in range(len(self.matrix)):  # dla każdego wiersza macierzy
                    # for zero in self.ind_zeros:
                    #     if zero[0] == row and zero[1] == col:
                    if (row, col) in self.ind_zeros:  # jeśli współrzędne są równe współrzędnym zera niezależnego
                        if row not in select_row:  # jeśli wiersz nie jest w zaznaczonych wierszach
                            select_row.append(row)  # dodaj do zaznaczonych wierszy
                            selected = True  # zaznaczono
            if not selected:  # jeśli nie zaznaczono
                break  # przerwij

        # Poszukiwanie minimalnego pokrycia wierzchołkowego.
        cross_col = select_col  # tablica kolumn do skreślenia jest równa tablicy zaznaczonych kolumn
        cross_col.sort()  # posortuj tablice kolumn
        cross_row = []  # tablica kolumn do skreślenia
        for i in range(len(self.matrix)):  # dla każdego wiersza macierzy
            if i not in select_row:  # jeśli wiersz nie jest zaznaczony
                cross_row.append(i)  # dodaj wiersz do skreślenia
        cross_row.sort()  # posortuj tablice wierszy
        self.cross_row = cross_row
        self.cross_col = cross_col

    def get_more_independent_zeros(self):  # Metoda przeprowadzająca dalszą redukcję macierzy
        min_matrix_val = inf
        # Wyszukanie najmniejszej wartości w całej macierzy
        for i, _ in enumerate(self.matrix):
            for j, _ in enumerate(self.matrix[i]):
                if i not in self.cross_row and j not in self.cross_col and self.matrix[i][j] < min_matrix_val:
                    min_matrix_val = self.matrix[i][j]
        # Odjęcie najmniejszej wartości od wszystkich nieskreślonych elementów
        for i, _ in enumerate(self.matrix):
            for j, _ in enumerate(self.matrix[i]):
                if i in self.cross_row and j not in self.cross_col:
                    continue
                if i in self.cross_row and j in self.cross_col:
                    # Dodanie najmniejszej wartości do podwójnie przekreślonych elementów
                    self.matrix[i][j] += min_matrix_val
                if j in self.cross_col:
                    continue
                self.matrix[i][j] -= min_matrix_val
        self.theta += min_matrix_val  # Powiększenie thety o najmniejszą wartość

    def algorithm(self):
        print("Macierz wejściowa:")
        for row in self.matrix:
            print(row)
        print()

        self.reduce_matrix()  # zredukowanie macierzy
        print("Macierz po początkowej redukcji")
        for row in self.matrix:
            print(row)
        print("Wielkość redukcji macierzy: {}\n".format(self.theta))

        while True:
            self.assign()  # wyznaczenie zer niezaleznych i zależnych
            print("Wyznaczone zera:")
            print("Współrzędne zer niezależnych: {}".format(self.ind_zeros))
            print("Współrzędne zer zależnych: {}\n".format(self.dep_zeros)) if self.dep_zeros else print()
            # if len(self.ind_zeros) == len(self.matrix):
            #     break

            self.zero_crossing()  # wyznaczenie wierszy i kolumn do zakreślenia
            if len(self.cross_col) + len(self.cross_row) == len(self.matrix):
                break
            print("Wiersze do wykreślenia: {}".format(self.cross_row))
            print("Kolumny do wykreślenia: {}\n".format(self.cross_col))

            self.get_more_independent_zeros()  # wyznaczenie wiecej zer niezależnych
            print("Macierz po powiększeniu zbioru zer niezależnych")
            for row in self.matrix:
                print(row)
            print("Wielkość redukcji macierzy: {}\n".format(self.theta))

        # stworzenie tablicy rozwiązania optymalnego
        result = [[0 for i in range(len(self.matrix))] for j in range(len(self.matrix))]  # stworzenie macierzy zer
        for row in range(len(self.matrix)):  # dla każdego wiersza
            for col in range(len(self.matrix)):  # dla każdej  kolumny
                if (row, col) in self.ind_zeros:  # jesli współrzędne to współrzędne zera niezależnego
                    result[row][col] = 1  # zmień zero na 1

        print("Rozwiązanie optymalne")
        for row in result:
            print(row)
        print("Optymalny koszt przydziału: {}\n".format(self.theta))

matrix = [
    [3, 2, 4, 5, 2, 1],
    [7, 3, 4, 5, 1, 1],
    [2, 2, 3, 3, 5, 6],
    [1, 3, 4, 5, 6, 2],
    [2, 1, 3, 3, 4, 5],
    [1, 0, 2, 4, 2, 3]
]

matrix_1 = [
    [5, 4, 3, 2, 1],
    [4, 4, 3, 2, 1],
    [3, 3, 3, 2, 1],
    [2, 2, 2, 2, 1],
    [1, 1, 1, 1, 1]
]

matrix_2 = [
    [5, 4, 3, 2, 1],
    [5, 4, 3, 2, 1],
    [5, 4, 3, 2, 1],
    [5, 4, 3, 2, 1],
    [5, 4, 3, 2, 1]
]

matrix_3 = [
    [1, 2, 2, 2, 2],
    [2, 1, 2, 2, 2],
    [2, 2, 1, 2, 2],
    [2, 2, 2, 1, 2],
    [2, 2, 2, 2, 1]
]

m = Hungarian(matrix)
m.algorithm()


import turtle
import pandas

# Set up the screen for the game
screen = turtle.Screen()
screen.title("US States Game")
screen.setup(width=725, height=491)
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)

# Initialize turtle for displaying state names
state_turtle = turtle.Turtle()
state_turtle.hideturtle()
state_turtle.penup()

# Load state data from CSV file
data = pandas.read_csv("50_states.csv")

# Create a DataFrame from the loaded data
df = pandas.DataFrame(data)

# List to store guessed states
guessed_states = []

# Flag to control the game loop
game_is_on = True

# Main game loop
while game_is_on:
    answer_state = (
        screen.textinput(
            title=f"{len(guessed_states)}/50 States Guessed",
            prompt="What's another name of a state in the US?",
        )
    ).title()

    # Check if state already guessed
    if answer_state in guessed_states:
        print(f"You already guessed {answer_state}!")
        continue

    # Validate and process the guessed state
    if answer_state in df["state"].values:
        guessed_states.append(answer_state)
        print(f"{answer_state} is a valid US state!")
        state_row = df[df["state"] == answer_state].iloc[0]
        state_turtle.goto(int(state_row["x"]), int(state_row["y"]))
        state_turtle.write(answer_state, align="center", font=("Arial", 8, "normal"))

        # Check if all states have been guessed
        if len(guessed_states) == 50:
            print("Congratulations! You've guessed all 50 states!")
            game_is_on = False

    else:
        print(f"{answer_state} is not a valid US state!")

# Close the screen on click
screen.exitonclick()


from Birds.models import Finch
from django.views.generic import TemplateView
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.template import loader

from django.views import generic
from django.views.generic.edit import CreateView, UpdateView
from .models import Finch

#domain/
def index(request):
	return render(request, 'Birds/index.html')

#domain/all_unclaimed_males/
class Unc_MaleView(generic.ListView):
	template_name = 'Birds/all_unclaimed_males.html'
	model = Finch
	context_object_name= 'all_birds'
	def get_queryset(self):
		return Finch.objects.all()

def detail(request, pk, **kwargs):
	def get_context_data(self, **kwargs):
		return {"bird": self.get_object()}
	return HttpResponseRedirect(reverse('Birds:birdinfo', kwargs={'pk': birds.pk}))

# #domain/all_unclaimed_males/<BirdID>
# class DetailsView(generic.DetailView):
# 	model = Finch
# 	template_name = 'Birds/details.html'
# 	def get_context_data(self, **kwargs):
# 		return {"bird": self.get_object(),}

class FinchCreate(CreateView):
	model = Finch
	fields = ['BirdID','Location','Procedure','Experimenter','Notes']

class FinchUpdate(UpdateView):
	model = Finch
	fields = ['BirdID','Location','Procedure','Experimenter','Notes']

# def birddetails(request, **kwargs):
# 	if request.method == 'GET':
# 		return render(request, 'Birds/details.html')
# 	if request.method == 'POST':
# 		form = Finch(request.POST)
# 		if form.is_valid():
# 			obj = Finch()
# 			obj.Location = form.cleaned_data['Location']
# 			obj.save()
# 			return HttpResponseRedirect('/')

def search(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        birds = Finch.objects.filter(BirdID__icontains=q)
        return render(request, 'Birds/search_result.html',
                      {'birds': birds, 'query': q})
    else:
        return HttpResponse('Please submit a query!')


from selenium import webdriver # http://pythonclub.com.br/selenium-parte-1.html
from selenium.webdriver.common.keys import Keys # https://stackoverflow.com/questions/1629053/typing-enter-return-key-in-selenium
from selenium.webdriver.common.by import By # https://selenium-python.readthedocs.io/waits.html#explicit-waits
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time # https://www.tutorialspoint.com/python/time_sleep

def scrape(author_name):

    # Iniciando o Selenium e indo até a página
    wd = webdriver.Firefox(executable_path = "./geckodriver.exe") # https://stackoverflow.com/questions/40208051/selenium-using-python-geckodriver-executable-needs-to-be-in-path
    wd.get("https://scholar.google.com.br/")

    # Pesquisando pelo nome do autor
    WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#gs_hdr_tsi")))
    search_box = wd.find_element_by_css_selector("#gs_hdr_tsi")
    search_box.send_keys(author_name)
    search_box.send_keys(Keys.ENTER)

    # Clicando no primeiro perfil
    WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".gs_r")))

    try:
        profile = wd.find_element_by_css_selector(".gs_rt2 b")
        profile.click()
    except:
        wd.quit()
        print("Autor não encontrado.")
        return None

    # Clicando no mostrar mais até que não dê mais
    page, new_page = "", wd.page_source
    while page != new_page:
        time.sleep(0.5)
        page = new_page
        mostrar_mais = wd.find_element_by_css_selector("#gsc_bpf_more .gs_wr")
        mostrar_mais.click()
        new_page = wd.page_source

    # Coletando os títulos e autores
    title = []
    authors = []
    we = wd.find_elements_by_css_selector(".gsc_a_at")
    for i in we:
        title.append(i.text)
    we = wd.find_elements_by_css_selector(".gsc_a_at+ .gs_gray")
    for i in we:
        authors.append(list(filter(lambda x: x != "...", i.text.split(", ")))) # https://www.geeksforgeeks.org/python-ways-to-remove-particular-list-element/

    # Finalizando o Selenium e arrumando o output
    wd.quit()
    output = []
    for i in range(len(title)):
        output.append({"title": title[i], "authors": authors[i]})

    return output


import os
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
from PIL import Image
import requests
import copy
import traceback
# import paddle
# paddle.enable_static
import jieba
# jieba.enable_paddle()

from nonebot import on_command, CommandSession, scheduler, get_bot, MessageSegment

from utils import deco, fileio

resource_path = 'resources/wordcloud'

enabled_group_list = [1014696092, 723979982, 709216479, 1087846478, 1056873681, 659667024]

@scheduler.scheduled_job(
    'cron',
    day_of_week='*',
    hour='23',
    minute='0',
    second='0'
)
# @scheduler.scheduled_job(
#     'interval',
#     minutes=5
# )
async def _():
    bot = get_bot()

    # ensure filepath
    os.system(f'mkdir -p {os.path.join(resource_path, "chat_history")}')
    os.system(f'mkdir -p {os.path.join(resource_path, "group_wordcloud")}')

    # 分词
    stopwords = set()
    t = requests.get('https://raw.githubusercontent.com/hoochanlon/cn_stopwords/main/baidu_stopwords.txt').text.split()
    # t = open(os.path.join(resource_path, 'stopwords.txt'), 'r').readlines()
    content = [line.strip() for line in t]
    stopwords.update(content)

    for group_id in enabled_group_list:
        file_path = os.path.join(resource_path, f'chat_history/{group_id}.txt')
        group_word_cloud = '\n草，这不是啥也没聊吗'
        if os.path.exists(file_path):
            text = await fileio.read_txt(file_path)
            if text.strip():
                try:
                    jbc = list(jieba.cut(text))
                    # jbc = list(jieba.cut(text, use_paddle=True))
                    stopwords_group = copy.deepcopy(stopwords)
                    stopwords_group.update(jbc)

                    wc = WordCloud(background_color="white",# 设置背景颜色
                        max_words=2000, # 词云显示的最大词数
                        height=400, # 图片高度
                        width=800, # 图片宽度
                        max_font_size=50, #最大字体
                        stopwords=stopwords_group, # 设置停用词
                        font_path=os.path.join(resource_path, 'msyh.ttc'), # 兼容中文字体，不然中文会显示乱码
                        )
                    # 生成词云
                    wc.generate(text)
                    # 生成的词云图像保存到本地
                    img_path = os.path.join(resource_path, f'group_wordcloud/{group_id}.png')
                    wc.to_file(img_path)
                    # 发送图片
                    img_path_send = f'file://{os.getcwd()}/{img_path}'
                    group_word_cloud = MessageSegment.image(img_path_send)
                except Exception as e:
                    msg = f'catch exception: generate wordcloud\ne: {e}\ntraceback:\n{traceback.print_exc()}'
                    await bot.send_group_msg(group_id=1014696092, message=msg)
            await fileio.clear_file(file_path)
        send_content = '[测试版]你群今日群聊词云已生成，请查收\n{}'.format(group_word_cloud)
        await bot.send_group_msg(group_id=group_id, message=send_content)

@on_command('gather_group_msg', patterns='.*', only_to_me=False)
@deco.only_these_group(enabled_group_list)
async def gather_group_msg(session: CommandSession):
    msg_text = session.current_arg_text + '\n'
    await fileio.addline(os.path.join(resource_path, f'chat_history/{session.ctx.get("group_id")}.txt'), msg_text)

if __name__ == '__main__':
    with open('test.txt', 'r') as f:
        text = f.read()

    # 分词
    stopwords = set()
    # t = requests.get('https://raw.githubusercontent.com/hoochanlon/cn_stopwords/main/baidu_stopwords.txt').text.split()
    t = open(os.path.join(resource_path, 'stopwords.txt'), 'r').readlines()
    print(t)
    content = [line.strip() for line in t]
    stopwords.update(content)
    jbc = list(jieba.cut(text, use_paddle=True))
    print(jbc)
    stopwords.update(jbc)

    wc = WordCloud(background_color="white",# 设置背景颜色
        max_words=2000, # 词云显示的最大词数
        height=400, # 图片高度
        width=800, # 图片宽度
        max_font_size=50, #最大字体
        stopwords=stopwords, # 设置停用词
        font_path=os.path.join(resource_path, 'msyh.ttc'), # 兼容中文字体，不然中文会显示乱码
        )

    # 生成词云
    wc.generate(text)

    # 生成的词云图像保存到本地
    wc.to_file("test.png")

    # 显示图像
    plt.imshow(wc, interpolation='bilinear')
    # interpolation='bilinear' 表示插值方法为双线性插值
    plt.axis("off")# 关掉图像的坐标
    plt.show()


import requests
from bs4 import BeautifulSoup
import pandas as pd
import re
import click
from datetime import date, datetime
import os

HEADERS={
    'Referrer-Policy':'origin-when-cross-origin',
    'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36"
}

@click.command()
def main():
    click.echo("This is the Grab Scraper 🐳🐳🐳")
    click.echo('Enter the URL below. It should be similar to https://food.grab.com/my/en/restaurant/burger-king-plaza-low-yat-delivery/1-CYUVMB3DUEABUE')
    url = click.prompt('URL',type=str)
    click.echo('Running the Scraper')
    scrape(url)

def dt_now():
    return datetime.now().strftime('%d-%m-%y-%H-%M')

def scrape(url):

    req = requests.get(url,headers = HEADERS)
    if req.status_code != 200:
        raise ConnectionError('Unable to access URL')
    soup = BeautifulSoup(req.text, 'html.parser')
    click.secho("Webpage Accessed",fg='cyan')

    menu_div = soup.find('div',class_=re.compile('menuContentWrapper*'))# 4 is the index of the container
    categories = menu_div.find_all('div',class_=re.compile('category*'))

    click.secho("Categories Identified",fg='cyan')

    df = []
    for cat in categories:
        category_name = cat.find('h2',class_=re.compile('categoryName'))
        if category_name: # Some weird interaction which creates duplicatess
            category_name =category_name.text
        else:
            continue
        menu_items = cat.find_all('div',class_=re.compile("menuItemWrapper*"))
        for item in menu_items:

            item_name = item.find('h3').text
            item_desc = item.find('h6',class_=re.compile('itemDescription*'))
            item_desc = item_desc.text if item_desc else ""

            item_price = float(item.find('h6',class_=re.compile('discountedPrice*')).text)

            dis_div = item.find('div',class_=re.compile('ant-row itemDiscount*'))
            if dis_div:
                print(f'Discounted Price found for {item_name}')

            info = {
                'name':item_name,
                'category': category_name,
                'price': item_price,
                'description': item_desc,
            }

            df.append(info)

    df = pd.DataFrame.from_dict(df)
    restaurant_name = url.split('/')[-2]
    df = df.drop_duplicates()
    if not os.path.isdir('output'):
        os.mkdir('output')
    df.to_csv(f'output/{restaurant_name}_{dt_now()}.csv',index=False)
    click.secho("Data Saved",fg='cyan')

if __name__ == "__main__":
    main()


import os
import PySimpleGUI as sg

sg.theme('DarkAmber')

close_window_action = "Ja!"
print("Vilka snälla kollegor jag har")
file_selector_column = [
    [
        sg.Text("File Browser"),
        sg.In(size=(25,1), enable_events=True, key="-FOLDER-"),
        sg.FolderBrowse(),
    ],
    [
        sg.Listbox(
            values=[],enable_events=True, size=(40,20), key = "-FILE LIST-"
        )
    ]
]

layout = [
    [file_selector_column],
    [sg.Text("Hej! Ska vi bygga ett grafiskt gränssnitt på SUP:en?")],
    [sg.Button(close_window_action)]
]

# Create the window
window = sg.Window("Demo", layout, margins=(200, 50))

# Event loop
while True:
    event, values = window.read()
#     if event == "-FOLDER-":
#         folder = values["-FOLDER-"]
#         try:
#             file_list = os.listdir(folder)
#         except:
#             file_list = []
#         filenames = [
#             f
#             for f in file_list
#             if os.path.isfile(os.path.join(folder, f))
#             and f.lower().endswith((".pdf"))
#         ]

#     elif event == "-FILE LIST-":
#         try:
#             filename = os.path.join(
#                 values["-FOLDER-"], values["-FILE LIST-"][0]
#             )
#             window["-TOUT-"].update(filename)
#             window["-IMAGE-"].update(filename=filename)

#         except:
#             pass

    if event in (close_window_action, sg.WIN_CLOSED):
        break

window.close()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Audio solving module. """

import os
import random
import shutil
import tempfile

from asyncio import TimeoutError, CancelledError
from aiohttp.client_exceptions import ClientError

from nonocaptcha import util
from nonocaptcha.speech import Amazon, Azure, Sphinx, DeepSpeech, AzureSpeech
from nonocaptcha.base import Base
from nonocaptcha.exceptions import DownloadError, ReloadError, TryAgain

class SolveAudio(Base):
    def __init__(self, page, loop, proxy, proxy_auth, proc_id):
        self.page = page
        self.loop = loop
        self.proxy = proxy
        self.proxy_auth = proxy_auth
        self.proc_id = proc_id

    async def solve_by_audio(self):
        """Go through procedures to solve audio"""
        await self.get_frames()
        for _ in range(10):
            try:
                answer = await self.loop.create_task(self.get_audio_response())
            except DownloadError:
                raise
            except ReloadError:
                raise
            else:
                if not answer:
                    continue
            await self.type_audio_response(answer)
            await self.click_verify()
            try:
                result = await self.check_detection(self.animation_timeout)
            except TryAgain:
                continue
            else:
                return result
        else:
            return {"status": "retries_exceeded"}

    async def get_audio_response(self):
        """Download audio data then send to speech-to-text API for answer"""
        try:
            audio_url = await self.image_frame.evaluate(
                'jQuery("#audio-source").attr("src")')
            if not isinstance(audio_url, str):
                raise DownloadError(f"Audio url is not valid, expected `str`"
                                    "instead received {type(audio_url)}")
        except CancelledError:
            raise DownloadError("Audio url not found, aborting")

        self.log("Downloading audio file")
        try:
            audio_data = await self.loop.create_task(
                util.get_page(
                    audio_url,
                    proxy=self.proxy,
                    proxy_auth=self.proxy_auth,
                    binary=True,
                    timeout=self.page_load_timeout))
        except ClientError as e:
            self.log(f"Error `{e}` occured during audio download, retrying")
        else:
            answer = None
            service = self.speech_service.lower()
            if service in [
                "azure",
                "pocketsphinx",
                "deepspeech",
                "azurespeech"
            ]:
                if service == "azurespeech":
                    speech = AzureSpeech()
                elif service == "azure":
                    speech = Azure()
                elif service == "pocketsphinx":
                    speech = Sphinx()
                else:
                    speech = DeepSpeech()
                tmpd = tempfile.mkdtemp()
                tmpf = os.path.join(tmpd, "audio.mp3")
                await util.save_file(tmpf, data=audio_data, binary=True)
                answer = await self.loop.create_task(speech.get_text(tmpf))
                shutil.rmtree(tmpd)
            else:
                speech = Amazon()
                answer = await self.loop.create_task(
                    speech.get_text(audio_data))
            if answer:
                self.log(f'Received answer "{answer}"')
                return answer

            self.log("No answer, reloading")
            await self.click_reload_button()
            func = (
                f'"{audio_url}" !== '
                f'jQuery(".rc-audiochallenge-tdownload-link").attr("href")')
            try:
                await self.image_frame.waitForFunction(
                    func, timeout=self.animation_timeout)
            except TimeoutError:
                raise ReloadError("Download link never updated")

    async def type_audio_response(self, answer):
        self.log("Typing audio response")
        response_input = await self.image_frame.J("#audio-response")
        length = random.uniform(70, 130)
        await self.loop.create_task(
            response_input.type(text=answer, delay=length))

    async def click_verify(self):
        self.log("Clicking verify")
        verify_button = await self.image_frame.J("#recaptcha-verify-button"
                                                 )
        await self.click_button(verify_button)


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 20 21:14:04 2018

@author: Paris
"""

import numpy as np
import matplotlib.pyplot as plt
from pyDOE import lhs
from scipy.interpolate import griddata

from models_tf import DarcyNet2D

np.random.seed(1234)

if __name__ == "__main__":

    dataset = np.load('./test.npz')
    X = dataset['coo']
    K = dataset['k']
    U = dataset['u']

    idx = 11
    X_star = X
    k_star = K[idx:idx+1,:].T
    u_star = U[idx:idx+1,:].T

    N_u = 100
    N_k = 250
    N = u_star.shape[0]

    # Specify input domain bounds
    lb, ub = X.min(0), X.max(0)

    # Training data
    idx_k = np.random.choice(N, N_k)
    X_k = X[idx_k,:]
    Y_k = k_star[idx_k,:]

    idx_u = np.random.choice(N, N_u)
    X_u = X[idx_u,:]
    Y_u = u_star[idx_u,:]

    X_f = X_star
    Y_f = np.zeros((N, 1))

    # Create model
    layers_u = [2,50,50,50,1]
    layers_k = [2,50,50,50,1]
    model = DarcyNet2D(X_k, Y_k, X_u, Y_u, X_f, Y_f,
                      layers_k, layers_u, lb, ub)

    # Train
    model.train()

    # Predict at test points
    k_pred = model.predict_k(X_star)
    u_pred = model.predict_u(X_star)

    # Relative L2 error
    error_k = np.linalg.norm(k_star - k_pred, 2)/np.linalg.norm(k_star, 2)
    error_u = np.linalg.norm(u_star - u_pred, 2)/np.linalg.norm(u_star, 2)

    # Plot
    nn = 200
    x = np.linspace(lb[0], ub[0], nn)
    y = np.linspace(lb[1], ub[1], nn)
    XX, YY = np.meshgrid(x,y)

    K_plot = griddata(X_star, k_pred.flatten(), (XX, YY), method='cubic')
    U_plot = griddata(X_star, u_pred.flatten(), (XX, YY), method='cubic')

    K_error = griddata(X_star, np.abs(k_star-k_pred).flatten(), (XX, YY), method='cubic')
    U_error = griddata(X_star, np.abs(u_star-u_pred).flatten(), (XX, YY), method='cubic')

    fig = plt.figure(1)
    plt.subplot(2,2,1)
    plt.pcolor(XX, YY, K_plot, cmap='viridis')
    plt.plot(X_k[:,0], X_k[:,1], 'ro', markersize = 1)
    plt.colorbar()
    plt.xlabel('$x_1$')
    plt.ylabel('$x_2$')
    plt.title('$k(x_1,x_2)$')

    plt.subplot(2,2,2)
    plt.pcolor(XX, YY, U_plot, cmap='viridis')
    plt.plot(X_u[:,0], X_u[:,1], 'ro', markersize = 1)
    plt.colorbar()
    plt.xlabel('$x_1$')
    plt.ylabel('$x_2$')
    plt.title('$u(x_1,x_2)$')

    plt.subplot(2,2,3)
    plt.pcolor(XX, YY, K_error, cmap='viridis')
    plt.colorbar()
    plt.xlabel('$x_1$')
    plt.ylabel('$x_2$')
    plt.title('Absolute error')

    plt.subplot(2,2,4)
    plt.pcolor(XX, YY, U_error, cmap='viridis')
    plt.colorbar()
    plt.xlabel('$x_1$')
    plt.ylabel('$x_2$')
    plt.title('Absolute error')


from setuptools import setup

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(
    name='django-bazaar-of-wonders',
    author='https://github.com/Bazaar-Trader',
    version='0.1.40',

    description='Bazaar of Wonders is a Django-based web application that aggregates card details and pricing statistics for trading card games, namely, Magic: The Gathering.',
    long_description=long_description,
    long_description_content_type="text/markdown",

    url="https://github.com/Bazaar-Trader/Bazaar_Of_Wonders",
    packages=['bazaar_of_wonders','main','bazaar_of_wonders_server_scripts','bazaar_of_wonders_db'],
    include_package_data=True,
    install_requires=['django','django-tinymce4-lite','django-materializecss-form','PyYAML','bs4','django-environ','apscheduler'],
    python_requires='>=3.8',
    classifiers=[
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent",
    ],

    entry_points =
    { 'console_scripts':
        [
            'bazaar_start = bazaar_of_wonders_server_scripts.run:main',
        ]
    },

)


import sys
import index
import query

ARQ_INDICE = "result/indice.txt"
ARQ_RESPOSTA = "result/resposta.txt"

# chama a função passando o nome do arquivo base como parâmetro
ind = index.Index(sys.argv[1], ARQ_INDICE)
ind.createIndex()

# chama a função passando o nome do arquivo de consulta como parâmetro
qObj = query.Query(sys.argv[2], ARQ_INDICE, ind.loadBase())
q = qObj.executeQuery()
print(q)
arqResp = open(ARQ_RESPOSTA, 'w')
arqResp.write(str(len(q)) + "\n")
for arq in q:
    arqResp.write(arq + "\n")


import logging
import os
import subprocess
from datetime import date
from flask import Flask,render_template,request
from logging.handlers import RotatingFileHandler

app=Flask(__name__)

@app.route('/')
def main_page():
    # will display main game page
    year = date.today().year
    return render_template('index.html', year=year)

@app.route('/api')
def api_docs():
    # serves api documentation page
    return render_template('api_doc.html')

@app.route('/get_winner', methods = ['GET', 'POST'])
def winner_request():
    # getting the winner api endpoint
    if request.method == 'GET' and 'board' in request.args:
        return exec_ai(request.args["board"], 'o', '-w')
    elif request.method == 'POST' and "board" in request.form:
        return exec_ai(request.form["board"], 'o', '-w')
    return render_template("data_error.html")

@app.route('/get_move', methods = ['GET', 'POST'])
def move_request():
    # getting next move api endpoint
    if (request.method == 'GET' and 'board' in request.args
            and 'player' in request.args):
        return exec_ai(request.args["board"], request.args["player"], "-m")
    elif (request.method == 'POST' and "board" in request.form
            and "player" in request.form):
        return exec_ai(request.form["board"], request.form["player"], "-m")
    return render_template("data_error.html")

def exec_ai(board_data, player, flag):
    abspath_cwd = os.path.dirname(os.path.abspath(__file__))
    script_path = os.path.join(abspath_cwd, 'backend_ai/./TTAI')
    return subprocess.check_output([script_path, board_data, player, flag])

if __name__ == "__main__":
    abspath_cwd = os.path.dirname(os.path.abspath(__file__))
    file_handler = RotatingFileHandler(os.path.join(abspath_cwd, '../tictac_error.log'),
        maxBytes=1024 * 1024 * 100, backupCount=20)
    file_handler.setLevel(logging.INFO)
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    file_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)
    app.run(debug=True)


from typing import Optional

from db.models.user import User
from sqlalchemy import (
    select,
)
from app.crud.base import CRUDBase
from app.schemas.user import (
    UserFiltersSchema,
    UserOrderingSchema,
    UserOrderingAsc,
    UserOrderingDesc,
    UserOrderingRoleAsc,
    UserOrderingRoleDesc,
)
from sqlalchemy import (
    String,
    cast,
    or_,
    select,
)
from db.models.user import Role

class UserCRUD(CRUDBase):

    def get_user_by_login(
        self,
        login: str,
    ) -> Optional[User]:
        query = self.db.execute(select(User).filter(User.login == login))
        self.db.commit()
        user = query.scalars().first()
        return user

    def get_user_by_id(
        self,
        user_id: int,
    ) -> Optional[User]:
        query = self.db.execute(select(User).filter(User.id == user_id))
        self.db.commit()
        user = query.scalars().first()
        return user

    def get_users(
        self,
        search: Optional[str] = None,
        filters: Optional[UserFiltersSchema] = None,
        ordering: Optional[UserOrderingSchema] = None,
    ):
        query = select(self.model)
        # Только активные пользователи
        query = query.filter(self.model.is_active == True)
        if search:
            query = query.filter(
                or_(
                    cast(self.model.id, String).ilike(f'%{search}%'),
                    self.model.full_name.ilike(f'%{search}%'),
                    self.model.email.ilike(f'%{search}%'),
                    self.model.phone_number.ilike(f'%{search}%'),
                    self.model.city.ilike(f'%{search}%'),
                    self.model.address.ilike(f'%{search}%'),
                    self.model.zip_code.ilike(f'%{search}%'),
                    self.model.role.has(Role.title.ilike(f'%{search}%')),
                )
            )
        if filters:
            for key, value in filters:
                if key not in filters.__fields_set__:
                    continue
                else:
                    if key == 'role_title':
                        query = query.filter(self.model.role.has(Role.title.ilike(f'%{value}%')))
                    elif type(value) == str:
                        query = query.filter(getattr(self.model, key).ilike(f'%{value}%'))
                    elif type(value) == list:
                        query = query.filter(getattr(self.model, key).in_(value))

        if ordering:
            ordering_param = ordering.ordering
            if ordering_param in UserOrderingAsc:
                query = query.order_by(getattr(self.model, ordering_param.name).asc())
            elif ordering_param in UserOrderingDesc:
                query = query.order_by(getattr(self.model, ordering_param.name).desc())
            elif ordering_param in UserOrderingRoleAsc:
                query = (
                    query.join(self.model.role)
                    .order_by(getattr(Role, ordering_param.name).asc())
                )
            elif ordering_param in UserOrderingRoleDesc:
                query = (
                    query.join(self.model.role)
                    .order_by(getattr(Role, ordering_param.name).desc())
                )
        else:
            query = query.order_by(self.model.created_at.desc())

        users = self.db.execute(query).scalars().all()

        return users


#To count the number of strings where the string length is 2 or more and the first and last characters are the same from a given list of strings. Sample List : ['abc', 'xyz', 'aba', '1221'] Expected Result : 2

def match_words(words):
  ctr = 0

  for word in words:
    if len(word) > 2 and word[0] == word[-1]:
      ctr += 1
  return ctr
n=int(input())
words = input().split()
print(match_words(words))


from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from models import *
from pyramid.session import SignedCookieSessionFactory
from pyramid.security import Allow, Deny, Authenticated, Everyone

my_session_factory = SignedCookieSessionFactory('itsasecrert')

class RootFactory(object):
    def __init__(self, request):
        self.__acl__ = [
            (Allow, Everyone, 'view'),
            (Allow, Authenticated, 'add')
        ]

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all()

    authn_policy = AuthTktAuthenticationPolicy('sosecret', hashalg='sha512')
    authz_policy = ACLAuthorizationPolicy()

    config = Configurator(settings=settings, session_factory=my_session_factory, root_factory=RootFactory)
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)
    config.include('pyramid_chameleon')
    config.include('pyramid_jinja2')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home','/')
    config.add_route('view_blog', '/index')
    config.add_route('register', '/register')
    config.add_route('view_my', '/my')
    config.add_route('blog_article', '/post/{id}')
    config.add_route('blog_create','/post')
    config.add_route('login','/login')
    config.add_route('logout','/logout')
    config.add_route('about','/about')
    config.scan()
    return config.make_wsgi_app()


import pygame
from PPlay import window
from PPlay import keyboard
from PPlay import gameobject
from PPlay import sprite
from PPlay import collision

width, height = 640, 480
janela = window.Window(width, height)
janela.set_title("PONG")

bola = sprite.Sprite("assets/ball.png")
ball_speed = 200
ballX = ballY = ball_speed

pad1 = sprite.Sprite("assets/pad1.png")
pad1.set_position(0, height/2)
pad2 = sprite.Sprite("assets/pad2.png")
pad2.set_position(janela.width - pad2.width, height/2)
pad_vel = 300
pad1.pontos = 0
pad2.pontos = 0
drawpos1X = janela.width/4

drawpos2X = 3 * janela.width/4

drawposY = janela.height/15

dificuldade = 1

teclado = keyboard.Keyboard()

def rst_pos(GameObject):
    GameObject.set_position(width / 2, height / 2)

while True:
    janela.set_background_color((50, 150, 80))
    bola.draw()
    pad1.draw()
    pad2.draw()
    #bola.update()
    bola.move_x(ballX*janela.delta_time())
    bola.move_y(ballY*janela.delta_time())
    if 0 > bola.x:
        #gol da dir
        rst_pos(bola)
        ballX *= -1
        ballX = ballY = ball_speed
        pad2.pontos+=1
    if bola.x> janela.width:
        # gol da esq
        rst_pos(bola)
        #ballX+=20
        ballX = ballY = ball_speed
        ballX *= -1
        pad1.pontos-=1
    if bola.y >= janela.height - bola.height:
        bola.y = janela.height - bola.height - 1
        ballY += 50
        ballY *= -1
    if bola.y <=3:
        bola.y = 4
        ballY += 50
        ballY *= -1
    if bola.y <= pad2.y + pad2.height / 2 and pad2.y > 0 and bola.x > janela.width/2 - 30:
        pad2.move_y(-pad_vel * janela.delta_time() * dificuldade)
    elif bola.y >= pad2.y + pad2.height / 2 and pad2.y < height - pad2.height and bola.x > janela.width/2 - 30:
        pad2.move_y(pad_vel * janela.delta_time() * dificuldade)

    if teclado.key_pressed("UP") and pad2.y >0 :
        pad2.move_y(-pad_vel*janela.delta_time())
    elif teclado.key_pressed("DOWN") and pad2.y < height-pad2.height:
        pad2.move_y(pad_vel*janela.delta_time())

    if teclado.key_pressed("W") and pad1.y >0 :
        pad1.move_y(-pad_vel*janela.delta_time())
    elif teclado.key_pressed("S") and pad1.y < height-pad1.height:
        pad1.move_y(pad_vel*janela.delta_time())

    if (bola.x + bola.width >= pad2.x and pad2.y+ pad2.height >bola.y+bola.height/2 > pad2.y):
        bola.x = pad2.x - bola.width -1
        ballX*=-1
    if (bola.x <= pad1.x + pad1.width and pad1.y + pad1.height > bola.y + bola.height / 2 > pad1.y):
        bola.x = pad1.x + pad1.width + 1
        ballX *= -1
    janela.draw_text(str(pad1.pontos), drawpos1X, drawposY)
    janela.draw_text(str(pad2.pontos), drawpos2X, drawposY)

    janela.update()


import pytest
from decorator import name, greeting_decorator, nickname, farewell_decorator

def test_name_decorator():
    actual = name('bob')
    expected = 'Hello there, bob'
    assert actual == expected

def test_nicknname_farewell():
    actual = nickname('Tim')
    expected = 'Well, Tim, It\'s been real. Take care!'
    assert actual == expected


'''
ComboBox
=======

Based on Spinner
'''

__all__ = ('ComboBox', 'ComboBoxOption')

from kivy.properties import ListProperty, ObjectProperty, BooleanProperty
from kivy.uix.button import Button
from kivy.uix.dropdown import DropDown
from kivy.lang import Builder

Builder.load_string('''
<ComboBoxOption>:
    size_hint_y: None
    height: 44

<ComboBox>:
    background_normal: 'atlas://data/images/defaulttheme/spinner'
    background_down: 'atlas://data/images/defaulttheme/spinner_pressed'
    on_key:
        if self.items: x, y = zip(*self.items); self.text = y[x.index(args[1])]
''')

class ComboBoxOption(Button):
    pass

class ComboBox(Button):
    items = ListProperty()
    key = ObjectProperty()

    option_cls = ObjectProperty(ComboBoxOption)

    dropdown_cls = ObjectProperty(DropDown)

    is_open = BooleanProperty(False)

    def __init__(self, **kwargs):
        self._dropdown = None
        super(ComboBox, self).__init__(**kwargs)
        self.items_dict = dict(self.items)
        self.bind(
            on_release=self._toggle_dropdown,
            dropdown_cls=self._build_dropdown,
            option_cls=self._build_dropdown,
            items=self._update_dropdown,
            key=self._update_text)
        self._build_dropdown()
        self._update_text()

    def _update_text(self, *largs):
        try:
            self.text = self.items_dict[self.key]
        except KeyError:
            pass

    def _build_dropdown(self, *largs):
        if self._dropdown:
            self._dropdown.unbind(on_select=self._on_dropdown_select)
            self._dropdown.dismiss()
            self._dropdown = None
        self._dropdown = self.dropdown_cls()
        self._dropdown.bind(on_select=self._on_dropdown_select)
        self._update_dropdown()

    def _update_dropdown(self, *largs):
        dp = self._dropdown
        cls = self.option_cls
        dp.clear_widgets()
        for key, value in self.items:
            item = cls(text=value)
            # extra attribute
            item.key = key
            item.bind(on_release=lambda option: dp.select(option.key))
            dp.add_widget(item)

    def _toggle_dropdown(self, *largs):
        self.is_open = not self.is_open

    def _on_dropdown_select(self, instance, data, *largs):
        self.key = data
        self.is_open = False

    def on_is_open(self, instance, value):
        if value:
            self._dropdown.open(self)
        else:
            self._dropdown.dismiss()


import logging

from django.conf import settings
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

from avanan.slack.models import SQSQueue

logger = logging.getLogger(__name__)

def get_slack_webclient():
    return WebClient(token=settings.SLACK_USER_TOKEN)

def produce_sqs(message):
    queue_instance, created = SQSQueue.get_default_queue()
    queue = queue_instance.get_aws_queue()
    response = queue.send_message(MessageBody=message)
    return response

def delete_message(timestamp, channel):
    try:
        client = get_slack_webclient()
        response = client.chat_delete(
            channel=channel,
            ts=timestamp)
        logger.info(response)
    except SlackApiError as e:
        assert e.response["ok"] is False
        assert e.response["error"]
        return e.response['error']