import os

from query_func import \
    id_request, \
    get_records, \
    get_deal_by_salesman, \
    max_sum_deal, \
    min_sum_deal, \
    max_sum_deal_by_specific_salesman, \
    min_sum_deal_by_specific_salesman, \
    max_sum_deal_by_specific_customer, \
    min_sum_deal_by_specific_customer, \
    max_sum_deal_by_all_salesman, \
    min_sum_deal_by_all_salesman, \
    max_sum_deal_by_all_customer, \
    avg_sum_sale_by_customer, \
    avg_sum_sale_by_seller

from sqlalchemy import func

from models.salesmen import Salesman
from models.sales import Sale
from models.customers import Customer

from models.database import DATABASE_NAME, Session
import create_database as db_creator

from save_to_file_decorator import save_to_file

session = Session()

def user_menu():
    while True:
        choice_action = input('Выберите действие (1 - выборка, 2 - вставка, 3 - обновление, 4 - удаление): ')
        if choice_action == '1':
            command = input('Введите команду: ')

            if command == '1':
                # Все сделки
                all_deal = [print(f'{i}. {deal}') for i, deal in enumerate(get_records(Sale), 1)]

            elif command == '2':
                # Сделки конкретного продавца
                all_seller = [print(f'{i}. {seller}') for i, seller in enumerate(get_records(Salesman), 1)]
                print()

                user_query = get_deal_by_salesman(int(input('Введите ID: ')))

                if user_query:
                    for row in user_query:
                        print(row)
                else:
                    print('Продавец не найден')

                print('===' * 20)

            elif command == '3':
                # Макс. сумма сделки
                print(max_sum_deal())

            elif command == '4':
                # Мин. сумма сделки
                print(min_sum_deal())

            elif command == '5':
                # Макс. сумма сделки для конкретного продавца
                all_seller = [print(f'{i}. {seller}') for i, seller in enumerate(get_records(Salesman), 1)]

                user_query = max_sum_deal_by_specific_salesman(int(input('Введите ID продавца: ')))

                if user_query:
                    for row in user_query:
                        print(row)
                else:
                    print('Продавец не найден')

            elif command == '6':
                # Мин. сумма сделки для конкретного продавца
                all_seller = [print(f'{i}. {seller}') for i, seller in enumerate(get_records(Salesman), 1)]

                user_query = min_sum_deal_by_specific_salesman(int(input('Введите ID продавца: ')))

                if user_query:
                    for row in user_query:
                        print(row)
                else:
                    print('Продавец не найден')

            elif command == '7':
                # Макс. сумма сделки для конкретного покупателя
                all_customers = [print(f'{i}. {cust}') for i, cust in enumerate(get_records(Customer), 1)]

                user_query = max_sum_deal_by_specific_customer(int(input('Введите ID покупателя: ')))

                if user_query:
                    for row in user_query:
                        print(row)
                else:
                    print('Покупатель не найден')

            elif command == '8':
                # Мин. сумма сделки для конкретного покупателя
                all_customers = [print(f'{i}. {cust}') for i, cust in enumerate(get_records(Customer), 1)]

                user_query = min_sum_deal_by_specific_customer(int(input('Введите ID покупателя: ')))

                if user_query:
                    for row in user_query:
                        print(row)
                else:
                    print('Покупатель не найден')

            elif command == '9':
                # Продавец, у которого макс. сумма продаж по всем сделкам
                user_query = [print(f'{i}. {seller}') for i, seller in enumerate(max_sum_deal_by_all_salesman(), 1)]

            elif command == '10':
                # Продавец, у которого мин. сумма продаж по всем сделкам
                user_query = [print(f'{i}. {seller}') for i, seller in enumerate(min_sum_deal_by_all_salesman(), 1)]

            elif command == '11':
                # Покупателя, у которого макс. сумма покупок по всем сделкам
                user_query = [print(f'{i}. {cust}') for i, cust in enumerate(max_sum_deal_by_all_customer(), 1)]

            elif command == '12':
                # Ср. сумма покупок для каждого покупателя.
                user_query = [print(f'{i}. {cust}') for i, cust in enumerate(avg_sum_sale_by_customer(int(input(
                                                                                'Введите ID покупателя: '))), 1)]

            elif command == '13':
                # Ср. сумма покупок для каждого продавца.
                user_query = [print(f'{i}. {seller}') for i, seller in enumerate(avg_sum_sale_by_seller(int(input(
                    'Введите ID покупателя: '))), 1)]

        elif choice_action == '2':
            print('Меню вставки данных \n')

            choice_table = input('Выберите таблицу (1 - customers, 2 - sales, 3 - salesmen): ')
            if choice_table == '1':
                new_cust_id = int(input('Введите id покупателя: '))
                new_cust_name = input('Введите имя покупателя: ')
                new_cust_city = input('Введите город покупателя: ')
                new_salesman_id = int(input('Введите id продавца: '))

                customer = Customer(new_cust_id, new_cust_name, new_cust_city, new_salesman_id)
                session.add(customer)

                session.commit()

            elif choice_table == '2':
                new_sales_id = int(input('Введите id товара: '))
                new_salesman_id = int(input('Введите id продавца: '))
                new_customer_id = int(input('Введите id покупателя: '))
                new_amt = int(input('Введите сумму товара: '))
                new_sales_date = input('Введите дату сделки: ')

                sale = Sale(new_sales_id, new_salesman_id, new_customer_id, new_amt, new_sales_date)
                session.add(sale)

                session.commit()

            elif choice_table == '3':
                new_salesman_id = int(input('Введите id продавца: '))
                new_sls_name = input('Введите имя продавца: ')
                new_sls_city = input('Введите город продавца: ')

                salesman = Salesman(new_salesman_id, new_sls_name, new_sls_city)
                session.add(salesman)

                session.commit()

        elif choice_action == '3':
            print('Меню обновления данных \n')

            choice_table = input('Выберите таблицу (1 - customers, 2 - sales, 3 - salesmen): ')

            if choice_table == '1':
                user_request = [print(f'{i}. {cust}') for i, cust in enumerate(session.query(Customer), 1)]

                cust_id = int(input("Введите ID покупателя, которого хотите обновить: "))
                key_request = id_request(Customer, cust_id)

                if key_request:
                    new_cust_id = int(input('Введите новый id покупателя: '))
                    new_cust_name = input('Введите новое имя покупателя: ')
                    new_cust_city = input('Введите новый город покупателя: ')
                    new_salesman_id = int(input('Введите новый id продавца: '))
                    query = session.get(Customer, cust_id)
                    update_query = session.query(Customer).filter_by(customer_id=cust_id)
                    data_update = dict(customer_id=new_cust_id,
                                       cust_name=new_cust_name,
                                       cust_city=new_cust_city,
                                       salesman_id=new_salesman_id)
                    update_query.update(data_update)
                    session.commit()
                else:
                    print("Запись с указанным ID не найдена.")

            if choice_table == '2':
                user_request = [print(f'{i}. {sale}') for i, sale in enumerate(session.query(Sale), 1)]

                sale_id = int(input("Введите ID товара, которого хотите обновить: "))
                key_request = id_request(Sale, sale_id)

                if key_request:
                    new_sales_id = int(input('Введите новый id товара: '))
                    new_slsman_id = int(input('Введите новый id продавца: '))
                    new_cust_id = int(input('Введите новый id покупателя: '))
                    new_amt = float(input('Введите новую цену товара: '))
                    query = session.get(Sale, sale_id)
                    update_query = session.query(Sale).filter_by(sales_id=sale_id)
                    data_update = dict(sales_id=new_sales_id,
                                       salesman_id=new_slsman_id,
                                       customer_id=new_cust_id,
                                       amt=new_amt)
                    update_query.update(data_update)
                    session.commit()
                else:
                    print("Запись с указанным ID не найдена.")

            if choice_table == '3':
                user_request = [print(f'{i}. {seller}') for i, seller in enumerate(session.query(Salesman), 1)]

                seller_id = int(input("Введите ID продавца, которого хотите обновить: "))
                key_request = id_request(Salesman, seller_id)

                if key_request:
                    new_salesman_id = int(input('Введите новый id продавца: '))
                    new_sls_name = input('Введите новое имя продавца: ')
                    new_sls_city = input('Введите новый город продавца: ')
                    query = session.get(Salesman, seller_id)
                    update_query = session.query(Salesman).filter_by(salesman_id=seller_id)
                    data_update = dict(salesman_id=new_salesman_id,
                                       sls_name=new_sls_name,
                                       sls_city=new_sls_city)
                    update_query.update(data_update)
                    session.commit()
                else:
                    print("Запись с указанным ID не найдена.")

        elif choice_action == '4':
            print('Меню удаления данных \n')

            choice_table = input('Выберите таблицу (1 - customers, 2 - sales, 3 - salesmen): ')
            if choice_table == '1':
                user_request = [print(f'{i}. {cust}') for i, cust in enumerate(session.query(Customer), 1)]

                cust_id = int(input("Введите ID покупателя, который хотите удалить: "))
                record = session.query(Customer).filter(Customer.customer_id == cust_id).first()

                if record:
                    session.delete(record)
                    session.commit()
                    print('Запись удалена')
                else:
                    print("Запись с указанным ID не найдена.")

            if choice_table == '2':
                user_request = [print(f'{i}. {sale}') for i, sale in enumerate(session.query(Sale), 1)]

                sales_id = int(input("Введите ID товара, который хотите удалить: "))

                record = session.query(Sale).filter(Sale.sales_id == sales_id).first()

                if record:
                    session.delete(record)
                    session.commit()
                    print('Запись удалена')
                else:
                    print("Запись с указанным ID не найдена.")

            if choice_table == '3':
                user_request = [print(f'{i}. {seller}') for i, seller in enumerate(session.query(Salesman), 1)]

                seller_id = int(input("Введите ID продавца, который хотите удалить: "))
                record = session.query(Salesman).filter(Salesman.salesman_id == seller_id).first()

                if record:
                    session.delete(record)
                    session.commit()
                    print('Запись удалена')
                else:
                    print("Запись с указанным ID не найдена.")

if __name__ == '__main__':
    db_is_created = os.path.exists(DATABASE_NAME)
    if not db_is_created:
        db_creator.create_database()

    user_menu()


# -*- coding: utf-8 -*-
"""Represent the PATCH method for HTTP 1.1.

The HTTP PATCH method as implemented in this module is defined in the
following document:

`IETF RFC 5789 <http://tools.ietf.org/html/rfc5789>`_

"""

# Support Python 2 & 3.
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from pyneric.future import *

from . import Method

PATCH = Method(
    'PATCH',
    "Modify the target resource with the request payload.",
    safe=False,
    idempotent=False,
    cacheable=False,
)
"""Representation of the HTTP 1.1 PATCH request method."""

CACHEABLE_PATCH = Method(
    PATCH.token,
    PATCH.description,
    safe=PATCH.safe,
    idempotent=PATCH.idempotent,
    cacheable=True,
)
"""Representation of the HTTP 1.1 cacheable PATCH request method.

Use this responsibly (pun intended, but also serious).  From the RFC:

    A response to this method is only cacheable if it contains explicit
    freshness information (such as an Expires header or
    "Cache-Control: max-age" directive) as well as the Content-Location
    header matching the Request-URI, indicating that the PATCH response
    body is a resource representation.  A cached PATCH response can
    only be used to respond to subsequent GET and HEAD requests; it
    MUST NOT be used to respond to other methods (in particular,
    PATCH).

"""


def rearrange_digits(input_list):
    """
    Rearrange Array Elements so as to form two number such that their sum is maximum.

    Args:
       input_list(list): Input List
    Returns:
       (int),(int): Two maximum sums
    """
    first_num = second_num = 0
    quick_sort(input_list, 0, len(input_list) - 1)
    for index, value in enumerate(input_list):
        if index % 2 == 0:
            first_num = first_num * 10 + value
        else:
            second_num = second_num * 10 + value
    return [first_num, second_num]

def quick_sort(input_list, begin_index, end_index):
    """
    Sorted input_list via quick sort.
    """
    if end_index <= begin_index:
        return
    pivot_idx = sort_partition(input_list, begin_index, end_index)
    quick_sort(input_list, begin_index, pivot_idx - 1)
    quick_sort(input_list, pivot_idx + 1, end_index)

def sort_partition(input_list, begin_index, end_index):
    pivot_idx = end_index
    pivot_value = input_list[pivot_idx]
    left_index = begin_index
    while pivot_idx != left_index:
        item = input_list[left_index]
        if item > pivot_value:
            left_index += 1
            continue
        input_list[left_index] = input_list[pivot_idx - 1]
        input_list[pivot_idx - 1] = pivot_value
        input_list[pivot_idx] = item
        pivot_idx -= 1
    return pivot_idx

def test_function(test_case):
    output = rearrange_digits(test_case[0])
    solution = test_case[1]
    if sum(output) == sum(solution):
        print("Pass")
    else:
        print("Fail", output, test_case[0])

test_function([[1, 2, 3, 4, 5], [542, 31]])
test_case = [[4, 6, 2, 5, 9, 8], [964, 852]]
test_function(test_case)
test_case = [[], []]                        #test empty input
test_function(test_case)
test_case = [[1], [1]]                      #test one element list
test_function(test_case)


from multiprocessing import Pool
from sys import argv

import pandas as pd
from numpy import average
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler

fileName = argv[1]

dataSet = pd.read_csv(fileName, index_col=0)

y = dataSet['class']
spectro = dataSet['spectrometric_redshift'].values

for column in ('Unnamed: 0', 'Unnamed: 0.1', 'Unnamed: 0.1.1', 'Unnamed: 0.1.1.1', 'galex_objid', 'sdss_objid', 'class', 'spectrometric_redshift', 'pred'):
	try: dataSet.drop(columns=column, inplace=True)
	except: pass

X = StandardScaler().fit_transform(dataSet)

def score(indices):
	train_index, test_index = indices

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

	knn = KNeighborsClassifier(5)
	knn.fit(X_train, y_train)
	y_pred = knn.predict(X_test)

	spectro_pred = [0 if z <= 0.0033 else (1 if z >= 0.004 else 2) for z in spectro_test]

	return accuracy_score(y_test, y_pred), accuracy_score(spectro_pred, y_pred)

scores = Pool(10).map(score, KFold(n_splits=10, random_state=29, shuffle=True).split(X))

print(round(average([i[0] * 100 for i in scores]), 2),
      round(average([i[1] * 100 for i in scores]), 2))


"""import random
class Coin:
    def __init__ (self):
        self.sideup = 'Heads'

    def toss (self):
        if random.radint(0,1) == 0:
            self.sideup = 'Heads'
        else:
            self.sideup = 'Tails'

    def get_sideup (self):
        return self.get_sideup()

coin = Coin()

print(coin.get_sideup())

for i in range(10):
    coin.toss()
    print("Tossing the coin in round " + str(i+1) + coin.getsideup())
"""

"""
for y in range(2000):
        x = (float(9.8 * y))
        z = (float(10 * (y - 5)))
        if x == z and y > 0:
            print(y)
        """
for y in range(500):
    difference = 1
    x = float((0 * y) + (4.9 * (pow(y,2))))
    z = float((10 * y) + (5 * (pow(y - difference,2))))
    if int(x) < int(z) and y > 5:
        print(x)
        print(z)
        print(y)
        break


inp=input('Enter Input : ').split('/')
lft,rht=list(map(int,inp[0].split())),list(map(int,inp[1].split()))
lft=sorted(lft)

for i in rht:
    c=False
    for j in lft:
        if c==False:
            if lft[-1]<i:
                print("No First Greater Value")
                c=True
            elif j>i:
                print(j)
                c=True


import argparse
import sys
import yaml
import ast

def parse_args():
    parser = argparse.ArgumentParser(prog=sys.argv[0],
                                     formatter_class=argparse.RawDescriptionHelpFormatter,
                                     description="""
customize_s3_conf.py is a tool to generating customized config file for S3 server.
Script uses some predefined file as a base for changing some parameters.
Using this base file script generates new one that contains updated values
specified by user.

Example of usage:
$ ./customize_s3_conf.py -s /opt/seagate/cortx/s3/conf/s3config.yaml
                         -d /opt/seagate/cortx/s3/conf/s3config.yaml
                         --s3-srv-param "S3_DI_DISABLE_DATA_CORRUPTION_IEM=False"
                         --s3-auth-param "S3_AUTH_IP_ADDR='ipv4:127.0.0.1'"
                         --s3-motr-param "S3_MOTR_LOCAL_ADDR='<ipaddress>@tcp:12345:33:100'"
                         --s3-thirdparty-param "S3_LIBEVENT_POOL_BUFFER_SIZE=16384"
""")

    parser.add_argument("-s", "--src-conf-file", type=str, required=True,
                        help="path to config file used as base")

    parser.add_argument("-d", "--dst-conf-file", type=str, required=True,
                        help="path to store result")

    parser.add_argument("--s3-srv-param", action='append', required=False,
                        help="""parameter of S3_SERVER_CONFIG section
                        to be overrided in a form 'PARAM_NAME=PARAM_VALUE'""")

    parser.add_argument("--s3-auth-param", action='append', required=False,
                        help="""parameter of S3_AUTH_CONFIG section
                        to be overrided in a form 'PARAM_NAME=PARAM_VALUE'""")

    parser.add_argument("--s3-motr-param", action='append', required=False,
                        help="""parameter of S3_MOTR_CONFIG section
                        to be overrided in a form 'PARAM_NAME=PARAM_VALUE'""")

    parser.add_argument("--s3-thirdparty-param", action='append', required=False,
                        help="""parameter of S3_THIRDPARTY_CONFIG section
                        to be overrided in a form 'PARAM_NAME=PARAM_VALUE'""")

    return parser.parse_args()

def read_src_config(src_config_path):
    with open(src_config_path) as f:
        return yaml.safe_load(f.read())

def write_dst_config(cdf_data, dst_config_path):
    with open(dst_config_path, 'wt') as f:
        f.write(yaml.dump(cdf_data))

def override_param(conf_data, section_name, param_name, param_val_str):
    param_val = ast.literal_eval(param_val_str)
    print(f'overriding {section_name}:{param_name} to {param_val_str}')
    conf_data[section_name][param_name] = param_val

def main():
    args = parse_args()
    conf_data = read_src_config(args.src_conf_file)

    if args.s3_srv_param is not None:
        for key_val in args.s3_srv_param:
            key, val = key_val.split('=')
            override_param(conf_data, 'S3_SERVER_CONFIG', key, val)

    if args.s3_auth_param is not None:
        for key_val in args.s3_auth_param:
            key, val = key_val.split('=')
            override_param(conf_data, 'S3_AUTH_CONFIG', key, val)

    if args.s3_motr_param is not None:
        for key_val in args.s3_motr_param:
            key, val = key_val.split('=')
            override_param(conf_data, 'S3_MOTR_CONFIG', key, val)

    if args.s3_thirdparty_param is not None:
        for key_val in args.s3_thirdparty_param:
            key, val = key_val.split('=')
            override_param(conf_data, 'S3_THIRDPARTY_CONFIG', key, val)

    write_dst_config(conf_data, args.dst_conf_file)

if __name__ == '__main__':
    main()


import pygame
import sys
import random
from pygame.math import Vector2 as Vector

class Apple:
    def __init__(self):
        self.randomize()

    def draw_apple(self):
        xPos = int(self.pos.x * cellSize)
        yPos = int(self.pos.y * cellSize)
        appleRect = pygame.Rect(xPos, yPos, cellSize, cellSize)
        screen.blit(apple, appleRect)

    def randomize(self):
        self.x = random.randint(0, cellNumber - 1)
        self.y = random.randint(0, cellNumber - 1)
        self.pos = Vector(self.x, self.y)

class Snake:
    def __init__(self):
        self.body = [Vector(7, 10), Vector(6, 10), Vector(5, 10)]
        self.direction = Vector(1, 0)
        self.newBlock = False

        self.headUp = pygame.image.load('Images/head_up.png').convert_alpha()
        self.headDown = pygame.image.load('Images/head_down.png').convert_alpha()
        self.headRight = pygame.image.load('Images/head_right.png').convert_alpha()
        self.headLeft = pygame.image.load('Images/head_left.png').convert_alpha()

        self.tailUp = pygame.image.load('Images/tail_up.png').convert_alpha()
        self.tailDown = pygame.image.load('Images/tail_down.png').convert_alpha()
        self.tailRight = pygame.image.load('Images/tail_right.png').convert_alpha()
        self.tailLeft = pygame.image.load('Images/tail_left.png').convert_alpha()

        self.bodyVertical = pygame.image.load('Images/body_vertical.png').convert_alpha()
        self.bodyHorizontal = pygame.image.load('Images/body_horizontal.png').convert_alpha()

        self.bodyTR = pygame.image.load('Images/body_tr.png').convert_alpha()
        self.bodyTL = pygame.image.load('Images/body_tl.png').convert_alpha()
        self.bodyBR = pygame.image.load('Images/body_br.png').convert_alpha()
        self.bodyBL = pygame.image.load('Images/body_bl.png').convert_alpha()

        self.crunchSound = pygame.mixer.Sound('Sound/crunch.wav')
        self.moveSound = pygame.mixer.Sound('Sound/move.wav')
        self.endSound = pygame.mixer.Sound('Sound/ending.wav')

        self.crunchSound.set_volume(0.1)
        self.moveSound.set_volume(0.1)
        self.endSound.set_volume(0.05)

    def draw_snake(self):
        self.update_head_graphics()
        self.update_tail_graphics()

        for i, block in enumerate(self.body):
            xPos = int(block.x * cellSize)
            yPos = int(block.y * cellSize)
            snakeRect = pygame.Rect(xPos, yPos, cellSize, cellSize)

            if i == 0:
                screen.blit(self.head, snakeRect)
            elif i == len(self.body) - 1:
                screen.blit(self.tail, snakeRect)
            else:
                previousBlock = self.body[i + 1] - block
                nextBlock = self.body[i - 1] - block
                if previousBlock.x == nextBlock.x:
                    screen.blit(self.bodyVertical, snakeRect)
                elif previousBlock.y == nextBlock.y:
                    screen.blit(self.bodyHorizontal, snakeRect)
                else:
                    if previousBlock.x == -1 and nextBlock.y == -1 or previousBlock.y == -1 and nextBlock.x == -1:
                        screen.blit(self.bodyTL, snakeRect)
                    elif previousBlock.x == -1 and nextBlock.y == 1 or previousBlock.y == 1 and nextBlock.x == -1:
                        screen.blit(self.bodyBL, snakeRect)
                    if previousBlock.x == 1 and nextBlock.y == -1 or previousBlock.y == -1 and nextBlock.x == 1:
                        screen.blit(self.bodyTR, snakeRect)
                    if previousBlock.x == 1 and nextBlock.y == 1 or previousBlock.y == 1 and nextBlock.x == 1:
                        screen.blit(self.bodyBR, snakeRect)

    def move_snake(self):
        if self.newBlock:
            body_copy = self.body[:]
            body_copy.insert(0, body_copy[0] + self.direction)
            self.body = body_copy[:]
            self.newBlock = False
        else:
            body_copy = self.body[:-1]
            body_copy.insert(0, body_copy[0] + self.direction)
            self.body = body_copy[:]

    def add_block(self):
        self.newBlock = True

    def update_head_graphics(self):
        head_rotation = self.body[1] - self.body[0]
        if head_rotation == Vector(1, 0):
            self.head = self.headLeft
        elif head_rotation == Vector(-1, 0):
            self.head = self.headRight
        elif head_rotation == Vector(0, 1):
            self.head = self.headUp
        elif head_rotation == Vector(0, -1):
            self.head = self.headDown

    def update_tail_graphics(self):
        tail_rotation = self.body[-2] - self.body[-1]
        if tail_rotation == Vector(1, 0):
            self.tail = self.tailLeft
        elif tail_rotation == Vector(-1, 0):
            self.tail = self.tailRight
        elif tail_rotation == Vector(0, 1):
            self.tail = self.tailUp
        elif tail_rotation == Vector(0, -1):
            self.tail = self.tailDown

    def play_crunch_sound(self):
        self.crunchSound.play()

    def play_move_sound(self):
        self.moveSound.play()

    def play_ending_sound(self):
        self.endSound.play()

    def reset(self):
        self.body = [Vector(7, 10), Vector(6, 10), Vector(5, 10)]

    def getDirection(self):
        return self.direction

class Game:
    def __init__(self):
        self.apple = Apple()
        self.snake = Snake()
        self.grassColor = (167, 209, 61)

    def update(self):
        self.snake.move_snake()
        self.check_eat()
        self.check_collision()

    def draw_elements(self):
        self.draw_grass()
        self.apple.draw_apple()
        self.snake.draw_snake()
        self.draw_score()

    def move_up(self):
        if self.snake.direction.y != 1 and self.snake.direction.y != -1:
            self.snake.direction = Vector(0, -1)
            self.snake.play_move_sound()

    def move_down(self):
        if self.snake.direction.y != -1 and self.snake.direction.y != 1:
            self.snake.direction = Vector(0, 1)
            self.snake.play_move_sound()

    def move_right(self):
        if self.snake.direction.x != -1 and self.snake.direction.x != 1:
            self.snake.direction = Vector(1, 0)
            self.snake.play_move_sound()

    def move_left(self):
        if self.snake.direction.x != 1 and self.snake.direction.x != -1:
            self.snake.direction = Vector(-1, 0)
            self.snake.play_move_sound()

    def check_eat(self):
        if self.apple.pos == self.snake.body[0]:
            self.apple.randomize()
            self.snake.add_block()
            self.snake.play_crunch_sound()

        for block in self.snake.body[1:]:
            if block == self.apple.pos:
                self.apple.randomize()

    def check_collision(self):
        if not 0 <= self.snake.body[0].x < cellNumber or not 0 <= self.snake.body[0].y < cellNumber:
            self.snake.play_ending_sound()
            self.end_game()
        for block in self.snake.body[1:]:
            if block == self.snake.body[0]:
                self.end_game()

    def draw_grass(self):
        for row in range(cellNumber):
            if row % 2 == 0:
                for col in range(cellNumber):
                    if col % 2 == 0:
                        grassRect = pygame.Rect(col * cellSize, row * cellSize, cellSize, cellSize)
                        pygame.draw.rect(screen, self.grassColor, grassRect)
            else:
                for col in range(cellNumber):
                    if col % 2 != 0:
                        grassRect = pygame.Rect(col * cellSize, row * cellSize, cellSize, cellSize)
                        pygame.draw.rect(screen, self.grassColor, grassRect)

    def draw_score(self):
        scoreText = str(len(self.snake.body) - 3)
        scoreSurface = gameFont.render(scoreText, True, (56, 74, 12))
        x_pos = int(cellSize * cellNumber - 60)
        y_pos = int(cellSize * cellNumber - 40)
        scoreRect = scoreSurface.get_rect(center=(x_pos, y_pos))
        appleRect = apple.get_rect(midright=(scoreRect.left, scoreRect.centery))
        backgroundRect = pygame.Rect(appleRect.left, appleRect.top, appleRect.width + scoreRect.width + 6,
                                     appleRect.height)

        pygame.draw.rect(screen, (167, 209, 61), backgroundRect)
        screen.blit(scoreSurface, scoreRect)
        screen.blit(apple, appleRect)
        pygame.draw.rect(screen, (56, 74, 12), backgroundRect, 2)

    def end_game(self):
        self.snake.play_ending_sound()
        pygame.time.delay(1010)
        pygame.quit()
        sys.exit()
        # self.snake.reset()
        # self.direction = Vector(1, 0)

def start_game():
    global cellSize, cellNumber, screen, apple, game, gameFont

    pygame.mixer.pre_init(44100, -16, 2, 512)
    pygame.init()
    cellSize = 40
    cellNumber = 20
    screen = pygame.display.set_mode((cellNumber * cellSize, cellNumber * cellSize))
    clock = pygame.time.Clock()
    apple = pygame.image.load('Images/apple.png').convert_alpha()
    game = Game()
    SCREEN_UPDATE = pygame.USEREVENT
    gameFont = pygame.font.Font(None, 25)

    pygame.time.set_timer(SCREEN_UPDATE, 150)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == SCREEN_UPDATE:
                game.update()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    game.move_up()
                if event.key == pygame.K_DOWN:
                    game.move_down()
                if event.key == pygame.K_LEFT:
                    game.move_left()
                if event.key == pygame.K_RIGHT:
                    game.move_right()
        screen.fill((175, 215, 70))
        game.draw_elements()
        pygame.display.update()
        clock.tick(144)

if __name__ == '__main__':
    start_game()


# 2. Напишите программу, которая найдёт произведение пар чисел списка. Парой считаем первый и последний элемент, второй и предпоследний и т.д.
# *Пример:*
# - [2, 3, 4, 5, 6] => [12, 15, 16];
# - [2, 3, 5, 6] => [12, 15]

import random

spisok = []
a = int(input("Введите количество элементов: "))
for i in range(a):
    spisok.append(random.randint(1, 100))
print(f"Cписок:\n {spisok}")
sumNum = 0
len_list = 0
if len(spisok) % 2 == 0:
    len_list = len(spisok) // 2
    for i in range(len_list):
        print(spisok[i] * spisok[len(spisok) - 1 - i], end=" ")

else:
    len_list = len(spisok) // 2
    for i in range(len_list):
        print(spisok[i] * spisok[len(spisok) - 1 - i], end=" ")

    print((spisok[len(spisok) // 2]))


from math import atan2, sqrt, tan
from math import degrees as deg
from math import radians as rad

def py(c1,c2, c3=0): #Pythagorean Theorem
    return sqrt(c1**2 + c2**2 + c3**2)

def convertV(Vx,Vy,Vz,p,f):
    """
    POV: Px (p[0]), Py (p[1]), Pz (p[2])\n
    Frame: f[0] (Distance from P to the Frame), f[1]: Angle of frame in X, f[2]: Angle of the frame in y\n
    Vector: Vx, Vy, Vz
    """

    Dx, Dy, Dz= p[0]-Vx, p[1]-Vy, p[2]-Vz

    Ax= deg(atan2(Dz, Dx)) - f[1]
    #print('Ax:', Ax)
    x= tan(rad(Ax)) * f[0]

    Hy= py(Dx, Dz, Dy)
    #print('Hy:', Hy)

    Ay= deg(atan2(Dy, Hy))*-1 - f[2]
    #print('Ay:', Ay)
    y= tan(rad(Ay))*f[2]

    return((int(x),int(y)))


#   Exercício Python 024 - Verificando as primeiras letras de um texto
#   Faça um programa que leia o nome de uma cidade
#   e diga se ela começa ou não com o nome "Santos"

cidade = str(input("Digitei o nome da cidade: "))

if cidade.split()[0].find('Santos'):
    print("Não começa com Santos")

else:
    print("Começa com Santos")


import unittest
from HTMLTestRunner import HTMLTestRunner
from TestSuites.Glitzi_Cliente.Servicios.Spa import *
from TestSuites.Glitzi_Cliente.Servicios.Unias import *
from TestSuites.Glitzi_Cliente.Servicios.Maquillaje import *
from TestSuites.Glitzi_Cliente.Servicios.Peinado import *
from TestSuites.Glitzi_Cliente.Servicios.Workshops import *
from TestSuites.Glitzi_Cliente.Servicios.Paquetes_de_Spa_y_Belleza import *
from TestSuites.Glitzi_Cliente.Pruebas_de_Sistema.Agendar_y_pagar_una_cita import *

import os

from TestSuites.config.QaseAPI import *

# Servicios
lista_test_cases_spa=[10,11,12,13,14,15,16,18,78]
lista_test_cases_unias=[17,20,32,38,55,59,63,64,79]
lista_test_cases_cabello=[26,66,40,33,57,69,19,61,81]
lista_test_cases_maquillaje=[34,39,27,65,56,68,21,60,80]
lista_test_cases_peinado=[82,62,22,70,58,35,50,41,28,67]
lista_test_cases_workshops=[84,52,24,54,51,37,43,53,30]
lista_test_cases_paquetes_de_spa_y_belleza=[83,47,23,49,46,45,36,44,42,29,48]

#Pruebas de sistema
lista_test_cases_agendar_y_pagar=[119,120,132,126,130,131,122]
lista_test_cases_cerrar_sesion=[111]
lista_test_cases_iniciar_sesion=[75]

lista_test_cases=[*lista_test_cases_spa,*lista_test_cases_unias,*lista_test_cases_cabello,*lista_test_cases_iniciar_sesion,
                  *lista_test_cases_agendar_y_pagar,*lista_test_cases_cerrar_sesion,*lista_test_cases_maquillaje,*lista_test_cases_peinado,*lista_test_cases_workshops,
                  *lista_test_cases_paquetes_de_spa_y_belleza]

try:
    active_id = get_id_of_active_run("GLITZI")
    delete_test_run("GLITZI", active_id)
    try:
        active_id = get_id_of_active_run("GLITZI")
        delete_test_run("GLITZI", active_id)
    except:
        pass
except:
    pass

create_test_run("Automatic Test Run","Prueba Test Suite API","GLITZI",lista_test_cases,2)
active_id=get_id_of_active_run("GLITZI")

# get the directory path to output report file
dir = os.getcwd()

# #
# particular = unittest.TestLoader().loadTestsFromTestCase(test_CTA_Ver_Detalles_del_servicio51.ver_detalles_workshops)
# particular2= unittest.TestLoader().loadTestsFromTestCase(test_CTA_Ver_Detalles_del_Servicio56.ver_detalles_maquillaje)
# testsuite= unittest.TestSuite([particular,particular2])

testsuite = unittest.TestLoader().discover('.')
# open the report file
outfile = open(dir + "\SeleniumPythonTestSummary.html", "w")

# configure HTMLTestRunner options
runner = HTMLTestRunner(log=True, verbosity=2, output='report', title='Test report', report_name='report',
                            open_in_browser=True, description="HTMLTestReport")
runner.run(testsuite)

complete_run("GLITZI",active_id)
# delete_test_run("GLITZI", active_id)


"""Airflow graph for model training and dataset creation.

A combined graph of dataset creation and model training. The beginning of the graph is exactly the graph defined in
get_dataset.py. Trains neural TPC model with supplied parameters using generated dataset inside TPC-FastSim Docker
container.
Key features:
* Supports training resuming after fail.
* Supports training on both GPU and CPU.
* Saves training logs to S3 in real time.
If the training is successful triggers convert-and-upload-model graph defined in convert_and_upload_model.py

Parameters:
    ignore_saves: if True starts training from the beginning even if intermediate save for the model and dataset
        parameters is present.
    dataset_parameters: a dictionary with arbitrary dataset parameters.
    model_config: a dictionary with neural TPC model hyperparameters.
    model_name: desired model name in MLflow Model Registry. If the model is present in registry, the version will be
        incremented.
"""

import datetime
import os
from airflow import DAG
from airflow.operators.python import PythonOperator, BranchPythonOperator
from airflow.operators.trigger_dagrun import TriggerDagRunOperator
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.models import Param
from docker.types import DeviceRequest
from pathlib import Path
from get_dataset import create_get_dataset_operators
from util import (
    DockerOperatorExtended,
    DockerOperatorRemoteMapping,
    Constants,
    Templates,
    USER_DEFINED_MACROS,
    DagRunParam,
    DagRunParamsDict,
)

DEFAULT_ARGS = {
    "start_date": datetime.datetime.min,
}

def create_config(model_config, model_dir, airflow_bucket):
    """Converts model_config DAG parameter to yaml and saves it with the model.

    Args:
        model_config: dictionary with model hyperparameters.
        model_dir: trained model intermediate representations directory.
        airflow_bucket: S3 bucket name for temp files.
    """

    import yaml
    import tempfile
    from util import local_folder_to_s3

    with tempfile.TemporaryDirectory() as file_dir:
        file_dir = Path(file_dir)
        (file_dir / "models" / "configs").mkdir(exist_ok=True, parents=True)
        with open(file_dir / "models" / "configs" / "model.yaml", "w") as f:
            yaml.dump(model_config, f, default_flow_style=False)

        local_folder_to_s3(
            "S3",
            airflow_bucket,
            s3_path=f"/tmp/{model_dir}",
            local_path=file_dir / "models",
        )

def copy_model_to_done_folder(model_dir, saved_models_bucket, dataset_parameters):
    """Copies model with "intermediate" S3 prefix using "done" prefix.

    Args:
        model_dir: saved model S3 prefix.
        saved_models_bucket: S3 bucket name.
        dataset_parameters: parameters of the dataset used during training.
    """

    import yaml
    import tempfile
    from util import local_folder_to_s3

    s3_hook = S3Hook(aws_conn_id="S3")
    for key in s3_hook.list_keys(
        bucket_name=saved_models_bucket, prefix=f"intermediate/{model_dir}"
    ):
        s3_hook.copy_object(
            source_bucket_name=saved_models_bucket,
            dest_bucket_name=saved_models_bucket,
            source_bucket_key=key,
            dest_bucket_key=key.replace("intermediate", "done"),
        )

    with tempfile.TemporaryDirectory() as file_dir:
        file_dir = Path(file_dir)
        with open(file_dir / "dataset.yaml", "w") as f:
            yaml.dump(dataset_parameters, f, default_flow_style=False)

        local_folder_to_s3(
            "S3",
            saved_models_bucket,
            s3_path=f"/done/{model_dir}",
            local_path=file_dir / "dataset.yaml",
        )

def decide_if_continue(ignore_saves, model_dir, saved_models_bucket):
    """Checks if training should be resumed. Returns "prepare-config" if training should be started from the beginnning,
     otherwise returns "train-model-continue"

    Args:
        ignore_saves: if True always starts training from the beginning.
        model_dir: model saves directory.
        saved_models_bucket: S3 bucket name for intermediate model representations.
    """

    s3_hook = S3Hook(aws_conn_id="S3")

    if ignore_saves or not s3_hook.check_for_prefix(
        bucket_name=saved_models_bucket,
        prefix=f"intermediate/{model_dir}",
        delimiter="/",
    ):
        return "prepare-config"
    return "train-model-continue"

def create_train_model_dag(dag_id="train-model"):

    params = DagRunParamsDict(
        DagRunParam(
            name="ignore_saves", dag_param=Param(default=False, type="boolean")
        ),
        DagRunParam(
            name="dataset_parameters", dag_param=Param(default=dict(), type="object")
        ),
        DagRunParam(
            name="model_config", dag_param=Param(default=dict(), type="object")
        ),
        DagRunParam(name="model_name", dag_param=Param(default="", type="string")),
    )

    dag = DAG(
        dag_id,
        schedule_interval=None,
        catchup=False,
        default_args=DEFAULT_ARGS,
        user_defined_macros=USER_DEFINED_MACROS,
        params=params.dag_params_view(),
        render_template_as_native_obj=True,
    )

    with dag:

        dataset_dir_template = Templates.dataset_dir(params["dataset_parameters"])
        model_dir_template = Templates.model_dir(
            params["dataset_parameters"], params["model_config"]
        )

        get_dataset_operator = create_get_dataset_operators(dag, params)

        prepare_config_operator = PythonOperator(
            task_id="prepare-config",
            dag=dag,
            python_callable=create_config,
            op_kwargs={
                "model_config": params["model_config"],
                "model_dir": model_dir_template,
                "airflow_bucket": Constants.airflow_bucket,
            },
        )

        decide_if_continue_operator = BranchPythonOperator(
            task_id="decide-if-continue",
            dag=dag,
            python_callable=decide_if_continue,
            op_kwargs={
                "ignore_saves": params["ignore_saves"],
                "model_dir": model_dir_template,
                "saved_models_bucket": Constants.saved_models_bucket,
            },
        )

        common_train_args = {
            "dag": dag,
            "image": "alexdrydew/tpc-trainer",
            "docker_url": "unix://var/run/docker.sock",
            # GPU passthrough configuration
            "device_requests": [DeviceRequest(capabilities=[["gpu"]], count=1)]
            if os.getenv("TRAIN_ON_GPU") == "true"
            else [],
            # save to continue training later in case of fail
            "map_output_on_fail": True,
            "network_mode": Constants.network_name,
            # S3 credentials for training logs
            "environment": {
                "AWS_ACCESS_KEY_ID": Constants.s3_access_key,
                "AWS_SECRET_ACCESS_KEY": Constants.s3_secret_access_key,
                "S3_ENDPOINT": f"{Constants.s3_hostname}:{Constants.s3_port}",
                "S3_USE_HTTPS": 0,
                "S3_VERIFY_SSL": 0,
            },
        }

        train_model_operator_from_start = DockerOperatorExtended(
            task_id="train-model-from-start",
            **common_train_args,
            remote_mappings=[
                DockerOperatorRemoteMapping(
                    bucket=Constants.airflow_bucket,
                    remote_path=f"/tmp/{model_dir_template}/models/configs",
                    mount_path="/TPC-FastSim/models/configs",
                    sync_on_start=True,
                ),
                DockerOperatorRemoteMapping(
                    bucket=Constants.datasets_bucket,
                    remote_path=f"/{dataset_dir_template}",
                    mount_path="/TPC-FastSim/data/data_v4",
                    sync_on_start=True,
                ),
                DockerOperatorRemoteMapping(
                    bucket=Constants.saved_models_bucket,
                    remote_path=f"/intermediate/{model_dir_template}",
                    mount_path="/TPC-FastSim/saved_models",
                    sync_on_finish=True,
                ),
            ],
            command=[
                "sh",
                "-c",
                f'python run_model_v4.py --checkpoint_name {params["model_name"]}_{model_dir_template} '
                f"--config models/configs/model.yaml --logging_dir s3://{Constants.tensorboard_bucket}/logs "
                f"--gpu_num " + ("0" if os.getenv("TRAIN_ON_GPU") == "true" else "''"),
            ],
        )
        train_model_operator_continue = DockerOperatorExtended(
            task_id="train-model-continue",
            **common_train_args,
            remote_mappings=[
                DockerOperatorRemoteMapping(
                    bucket=Constants.airflow_bucket,
                    remote_path=f"/tmp/{model_dir_template}/models/configs",
                    mount_path="/TPC-FastSim/models/configs",
                    sync_on_start=True,
                ),
                DockerOperatorRemoteMapping(
                    bucket=Constants.datasets_bucket,
                    remote_path=f"/{dataset_dir_template}",
                    mount_path="/TPC-FastSim/data/data_v4",
                    sync_on_start=True,
                ),
                DockerOperatorRemoteMapping(
                    bucket=Constants.saved_models_bucket,
                    remote_path=f"/intermediate/{model_dir_template}",
                    mount_path="/TPC-FastSim/saved_models",
                    sync_on_start=True,
                    sync_on_finish=True,
                ),
            ],
            command=[
                "sh",
                "-c",
                f'python run_model_v4.py --checkpoint_name {params["model_name"]}_{model_dir_template} '
                f"--logging_dir s3://{Constants.tensorboard_bucket}/logs "
                f"--gpu_num " + ("0" if os.getenv("TRAIN_ON_GPU") == "true" else "''"),
            ],
        )

        copy_trained_model_operator = PythonOperator(
            task_id="copy-to-done",
            dag=dag,
            python_callable=copy_model_to_done_folder,
            op_kwargs={
                "model_dir": model_dir_template,
                "saved_models_bucket": Constants.saved_models_bucket,
                "dataset_parameters": params["dataset_parameters"],
            },
            trigger_rule="one_success",
        )

        trigger_convert_model_dag = TriggerDagRunOperator(
            task_id="trigger-convert-model",
            dag=dag,
            trigger_dag_id="convert-and-upload-model",
            trigger_run_id="{{ dag_run.run_id  }}",
            conf={
                "saved_model_dir": model_dir_template,
                "model_name": params["model_name"],
            },
        )

        get_dataset_operator >> decide_if_continue_operator

        (
            decide_if_continue_operator
            >> prepare_config_operator
            >> train_model_operator_from_start
            >> copy_trained_model_operator
        )
        (
            decide_if_continue_operator
            >> train_model_operator_continue
            >> copy_trained_model_operator
        )
        copy_trained_model_operator >> trigger_convert_model_dag

    return dag

dag = create_train_model_dag()


"""
Description
Given a linked list and two values v1 and v2. Swap the two nodes in the linked list with values v1 and v2. It's guaranteed there is no duplicate values in the linked list. If v1 or v2 does not exist in the given linked list, do nothing.
"""

"""
Definition of ListNode
"""
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

class Solution:
    """
    @param head: a ListNode
    @param v1: An integer
    @param v2: An integer
    @return: a new head of singly-linked list
    """
    def swapNodes(self, head, v1, v2):
        #find preV1 and preV2
        #swap (preV1.next, preV2.next) then swap (preV1.next.next, preV2.next.next)
        dummy = ListNode(0, head)
        preV1 = dummy
        preV2 = dummy
        while preV1.next and preV1.next.val != v1:
            preV1 = preV1.next
        if not preV1.next:
            return dummy.next
        while preV2.next and preV2.next.val != v2:
            preV2 = preV2.next
        if not preV2.next:
            return dummy.next
        preV1.next, preV2.next = preV2.next, preV1.next
        preV1.next.next, preV2.next.next = preV2.next.next, preV1.next.next
        return dummy.next

LinkedList/511 · Swap Two Nodes in Linked List.py


__author__ = 'calthorpe_associates'

class BuiltFormKeys(object):
    """
    Keys for used by Built Forms
    """

    BUILDING_USE_RESIDENTIAL = 'Residential'
    BUILDING_USE_OFFICE = 'Office'
    BUILDING_USE_RETAIL = 'Retail'
    BUILDING_USE_INDUSTRIAL = 'Industrial'

    INFRASTRUCTURE_STREET = PLACETYPE_COMPONENT_STREET = 'Street'
    INFRASTRUCTURE_UTILITIES = PLACETYPE_COMPONENT_UTILITY = 'Utility'
    INFRASTRUCTURE_PARK = PLACETYPE_COMPONENT_PARK = 'Park'
    INFRASTRUCTURE_TYPES = [INFRASTRUCTURE_STREET, INFRASTRUCTURE_UTILITIES, INFRASTRUCTURE_PARK]

    BUILDINGTYPE_CIVIC = 'Civic'
    BUILDINGTYPE_RESIDENTIAL = 'Residential'
    BUILDINGTYPE_DETACHED_RESIDENTIAL = 'Detached Residential'
    BUILDINGTYPE_ATTACHED_AND_MULTIFAMILY = 'Attached and Multifamily Residential'
    BUILDINGTYPE_OFFICE_INDUSTRIAL = 'Office/Industrial'
    BUILDINGTYPE_COMMERCIAL_RETAIL = 'Commercial/Retail'
    BUILDINGTYPE_MIXED_USE = 'Mixed Use'
    BUILDINGTYPE_INSTITUTIONAL = 'Institutional'
    BUILDINGTYPE_BLANK = 'Blank'
    BUILDINGTYPE_AGRICULTURAL = 'Agriculture'

    RESIDENTIAL_BUILDINGTYPE_CATEGORIES = [
        BUILDINGTYPE_RESIDENTIAL, BUILDINGTYPE_DETACHED_RESIDENTIAL,
        BUILDINGTYPE_ATTACHED_AND_MULTIFAMILY
    ]

    EMPLOYMENT_BUILDINGTYPE_CATEGORIES = [
        BUILDINGTYPE_AGRICULTURAL,
        BUILDINGTYPE_OFFICE_INDUSTRIAL, BUILDINGTYPE_COMMERCIAL_RETAIL, BUILDINGTYPE_INSTITUTIONAL
    ]

    NET_COMPONENTS = [BUILDINGTYPE_RESIDENTIAL,
                      BUILDINGTYPE_DETACHED_RESIDENTIAL,
                      BUILDINGTYPE_ATTACHED_AND_MULTIFAMILY,
                      BUILDINGTYPE_OFFICE_INDUSTRIAL,
                      BUILDINGTYPE_COMMERCIAL_RETAIL,
                      BUILDINGTYPE_MIXED_USE,
                      BUILDINGTYPE_INSTITUTIONAL,
                      BUILDINGTYPE_BLANK,
                      BUILDINGTYPE_AGRICULTURAL]

    GROSS_COMPONENTS = INFRASTRUCTURE_TYPES + [BUILDINGTYPE_CIVIC]

    COMPONENT_CATEGORIES = NET_COMPONENTS + GROSS_COMPONENTS

    ATTACHED_RESIDENTIAL = 'Attached Single Family'
    MULTIFAMILY_2_TO_4 = 'Multifamily 2 To 4'
    MULTIFAMILY_5P = 'Multifamily 5 Plus'
    LARGE_LOT_SINGLE_FAMILY = 'Single Family Large Lot'
    SMALL_LOT_SINGLE_FAMILY = 'Single Family Small Lot'
    SINGLE_FAMILY = 'Single Family'

    MULTIFAMILY_AND_ATTACHED = [ATTACHED_RESIDENTIAL, MULTIFAMILY_2_TO_4, MULTIFAMILY_5P]
    DETACHED_RESIDENTIAL = [LARGE_LOT_SINGLE_FAMILY, SMALL_LOT_SINGLE_FAMILY]

    RESIDENTIAL_CATEGORY = 'Residential'
    RETAIL_CATEGORY = 'Retail'
    OFFICE_CATEGORY = 'Office'
    PUBLIC_CATEGORY = 'Public'
    INDUSTRIAL_CATEGORY = 'Industrial'
    AGRICULTURE_CATEGORY = 'Agriculture'
    MILITARY_CATEGORY = 'Military'

    RESIDENTIAL_SUBCATEGORIES = MULTIFAMILY_AND_ATTACHED + DETACHED_RESIDENTIAL
    ALL_RESIDENTIAL_USES = MULTIFAMILY_AND_ATTACHED + DETACHED_RESIDENTIAL + [RESIDENTIAL_CATEGORY]

    TOP_LEVEL_EMPLOYMENT_CATEGORIES = [RETAIL_CATEGORY,
                                       OFFICE_CATEGORY,
                                       INDUSTRIAL_CATEGORY]

    RETAIL_SUBCATEGORIES = [
        'Retail Services',
        'Restaurant',
        'Accommodation',
        'Arts Entertainment',
        'Other Services'
    ]

    OFFICE_SUBCATEGORIES = [
        'Office Services',
        'Public Admin',
        'Education Services',
        'Medical Services'
    ]

    INDUSTRIAL_SUBCATEGORIES = [
        'Manufacturing',
        'Wholesale',
        'Transport Warehouse',
        'Construction Utilities',
        'Agriculture',
        'Extraction',
        'Armed Forces'
    ]

    COMMERCIAL_SUBCATEGORIES = RETAIL_SUBCATEGORIES + OFFICE_SUBCATEGORIES + INDUSTRIAL_SUBCATEGORIES
    BUILDING_USE_DEFINITION_METACATEGORIES = [
        RESIDENTIAL_CATEGORY,
        OFFICE_CATEGORY,
        RETAIL_CATEGORY,
        INDUSTRIAL_CATEGORY
    ]

    BUILDING_USE_DEFINITION_CATEGORIES = {
        'Retail Services': RETAIL_CATEGORY,
        'Restaurant': RETAIL_CATEGORY,
        'Accommodation': RETAIL_CATEGORY,
        'Arts Entertainment': RETAIL_CATEGORY,
        'Other Services': RETAIL_CATEGORY,

        'Office Services': OFFICE_CATEGORY,
        'Public Admin': OFFICE_CATEGORY,
        'Education Services': OFFICE_CATEGORY,
        'Medical Services': OFFICE_CATEGORY,

        'Manufacturing': INDUSTRIAL_CATEGORY,
        'Wholesale': INDUSTRIAL_CATEGORY,
        'Transport Warehouse': INDUSTRIAL_CATEGORY,
        'Construction Utilities': INDUSTRIAL_CATEGORY,

        'Agriculture': INDUSTRIAL_CATEGORY,
        'Extraction': INDUSTRIAL_CATEGORY,

        'Armed Forces': INDUSTRIAL_CATEGORY,

        LARGE_LOT_SINGLE_FAMILY: RESIDENTIAL_CATEGORY,
        SMALL_LOT_SINGLE_FAMILY: RESIDENTIAL_CATEGORY,
        ATTACHED_RESIDENTIAL: RESIDENTIAL_CATEGORY,
        MULTIFAMILY_2_TO_4: RESIDENTIAL_CATEGORY,
        MULTIFAMILY_5P: RESIDENTIAL_CATEGORY,
    }

    BUILDINGTYPE_SOURCE_ID_LOOKUP = {
        'by_name': {
            'Airport': {'fp_id': None, 'source_id': 62},
            'Campus/College High': {'fp_id': 395, 'source_id': 43},
            'Campus/College Low': {'fp_id': 346, 'source_id': 44},
            'Church': {'fp_id': 394, 'source_id': 59},
            'Connected Tourism': {'fp_id': None, 'source_id': 64},
            'Estate Lot': {'fp_id': 352, 'source_id': 21},
            'Garden Apartment': {'fp_id': 373, 'source_id': 16},
            'Health Office': {'fp_id': None, 'source_id': 66},
            'High-Rise Mixed Use': {'fp_id': 344, 'source_id': 2},
            'High-Rise Office': {'fp_id': 351, 'source_id': 25},
            'High-Rise Residential': {'fp_id': 380, 'source_id': 9},
            'Hospital/Civic/Other Institutional': {'fp_id': 400, 'source_id': 45},
            'Hotel High': {'fp_id': 358, 'source_id': 37},
            'Hotel Low': {'fp_id': 378, 'source_id': 38},
            'Industrial High': {'fp_id': 385, 'source_id': 33},
            'Industrial Low': {'fp_id': 347, 'source_id': 34},
            'Large Lot 7500': {'fp_id': 399, 'source_id': 20},
            'Low Density Commercial': {'fp_id': None, 'source_id': 61},
            'Low Intensity Strip Commercial (weighted avg)': {'fp_id': 342, 'source_id': 41},
            'Low-Rise Mixed Use': {'fp_id': 360, 'source_id': 4},
            'Low-Rise Office': {'fp_id': 361, 'source_id': 27},
            'Main Street Commercial (Retail + Office/Medical)': {'fp_id': 396, 'source_id': 28},
            'Main Street Commercial/MU High (3-5 Floors)': {'fp_id': 392, 'source_id': 6},
            'Main Street Commercial/MU Low (1-2 Floors)': {'fp_id': 343, 'source_id': 7},
            'Medium Intensity Strip Commercial (weighted avg)': {'fp_id': 365, 'source_id': 40},
            'Medium Lot 5500': {'fp_id': 353, 'source_id': 19},
            'Mid-Rise Mixed Use': {'fp_id': 357, 'source_id': 3},
            'Mid-Rise Office': {'fp_id': 363, 'source_id': 26},
            'Military General Catch-All': {'fp_id': None, 'source_id': 60},
            'Non-Urban Elementary School': {'fp_id': 387, 'source_id': 47},
            'Non-Urban High School': {'fp_id': 348, 'source_id': 51},
            'Non-Urban Middle School': {'fp_id': 345, 'source_id': 49},
            'Office Park High': {'fp_id': 390, 'source_id': 31},
            'Office Park Low': {'fp_id': 377, 'source_id': 32},
            'Open Space': {'fp_id': None, 'source_id': 65},
            'Park/Recreation': {'fp_id': None, 'source_id': 63},
            'Parking Structure': {'fp_id': 370, 'source_id': 30},
            'Parking Structure+Ground-Floor Retail': {'fp_id': 397, 'source_id': 29},
            'Parking Structure/Mixed Use': {'fp_id': 359, 'source_id': 5},
            'Public Infrastructure': {'fp_id': None, 'source_id': 68},
            'Regional Mall': {'fp_id': 391, 'source_id': 39},
            'Rural Employment': {'fp_id': 389, 'source_id': 42},
            'Rural Ranchette': {'fp_id': 369, 'source_id': 23},
            'Rural Residential': {'fp_id': 382, 'source_id': 22},
            'Skyscraper Mixed Use': {'fp_id': 384, 'source_id': 1},
            'Skyscraper Office': {'fp_id': 362, 'source_id': 24},
            'Skyscraper Residential': {'fp_id': 355, 'source_id': 8},
            'Small Lot 4000': {'fp_id': 354, 'source_id': 18},
            'Standard Podium Multi-Family': {'fp_id': 366, 'source_id': 12},
            'Standard Townhome': {'fp_id': 388, 'source_id': 15},
            'Suburban Civic Complex': {'fp_id': 368, 'source_id': 57},
            'Suburban Multifamily Apt/Condo': {'fp_id': 381, 'source_id': 13},
            'Town Civic Complex': {'fp_id': 372, 'source_id': 56},
            'Town/Branch Library': {'fp_id': 367, 'source_id': 58},
            'Transit/Rail Station': {'fp_id': None, 'source_id': 67},
            'Urban City Hall': {'fp_id': 386, 'source_id': 52},
            'Urban Convention Center': {'fp_id': 374, 'source_id': 55},
            'Urban Courthouse': {'fp_id': 393, 'source_id': 54},
            'Urban Elementary School': {'fp_id': 383, 'source_id': 46},
            'Urban High School': {'fp_id': 356, 'source_id': 50},
            'Urban Mid-Rise Residential': {'fp_id': 349, 'source_id': 10},
            'Urban Middle School': {'fp_id': 350, 'source_id': 48},
            'Urban Podium Multi-Family': {'fp_id': 371, 'source_id': 11},
            'Urban Public Library': {'fp_id': 375, 'source_id': 53},
            'Urban Townhome/Live-Work': {'fp_id': 379, 'source_id': 14},
            'Very Small Lot 3000': {'fp_id': 376, 'source_id': 17},
            'Warehouse High': {'fp_id': 364, 'source_id': 35},
            'Warehouse Low': {'fp_id': 398, 'source_id': 36}
        },

        'by_source_id': {
            1: 'Skyscraper Mixed Use',
            2: 'High-Rise Mixed Use',
            3: 'Mid-Rise Mixed Use',
            4: 'Low-Rise Mixed Use',
            5: 'Parking Structure/Mixed Use',
            6: 'Main Street Commercial/MU High (3-5 Floors)',
            7: 'Main Street Commercial/MU Low (1-2 Floors)',
            8: 'Skyscraper Residential',
            9: 'High-Rise Residential',
            10: 'Urban Mid-Rise Residential',
            11: 'Urban Podium Multi-Family',
            12: 'Standard Podium Multi-Family',
            13: 'Suburban Multifamily Apt/Condo',
            14: 'Urban Townhome/Live-Work',
            15: 'Standard Townhome',
            16: 'Garden Apartment',
            17: 'Very Small Lot 3000',
            18: 'Small Lot 4000',
            19: 'Medium Lot 5500',
            20: 'Large Lot 7500',
            21: 'Estate Lot',
            22: 'Rural Residential',
            23: 'Rural Ranchette',
            24: 'Skyscraper Office',
            25: 'High-Rise Office',
            26: 'Mid-Rise Office',
            27: 'Low-Rise Office',
            28: 'Main Street Commercial (Retail + Office/Medical)',
            29: 'Parking Structure+Ground-Floor Retail',
            30: 'Parking Structure',
            31: 'Office Park High',
            32: 'Office Park Low',
            33: 'Industrial High',
            34: 'Industrial Low',
            35: 'Warehouse High',
            36: 'Warehouse Low',
            37: 'Hotel High',
            38: 'Hotel Low',
            39: 'Regional Mall',
            40: 'Medium Intensity Strip Commercial (weighted avg)',
            41: 'Low Intensity Strip Commercial (weighted avg)',
            42: 'Rural Employment',
            43: 'Campus/College High',
            44: 'Campus/College Low',
            45: 'Hospital/Civic/Other Institutional',
            46: 'Urban Elementary School',
            47: 'Non-Urban Elementary School',
            48: 'Urban Middle School',
            49: 'Non-Urban Middle School',
            50: 'Urban High School',
            51: 'Non-Urban High School',
            52: 'Urban City Hall',
            53: 'Urban Public Library',
            54: 'Urban Courthouse',
            55: 'Urban Convention Center',
            56: 'Town Civic Complex',
            57: 'Suburban Civic Complex',
            58: 'Town/Branch Library',
            59: 'Church',
            60: 'Military General Catch-All',
            61: 'Low Density Commercial',
            62: 'Airport',
            63: 'Park/Recreation',
            64: 'Connected Tourism',
            65: 'Open Space',
            66: 'Health Office',
            67: 'Transit/Rail Station',
            68: 'Public Infrastructure'
        }
    }


from django import forms
from energize_andover.models import *
class SchoolForm(forms.ModelForm):
    class Meta:
        model = School
        fields = ['Name']

class ClosetForm(forms.ModelForm):
    class Meta:
        model = Closet
        fields = ['Name', 'Old_Name']

class PanelForm(forms.ModelForm):
    class Meta:
        model = Panel
        fields = ['Name', 'Voltage']

class RoomForm(forms.ModelForm):
    class Meta:
        model = Room
        fields = ['Name', 'OldName', 'Type']

class CircuitForm(forms.ModelForm):
    class Meta:
        model = Circuit
        fields = ['Name', 'Number', 'Panel']
        #widgets = {'Rooms': forms.CheckboxSelectMultiple, 'Devices': forms.CheckboxSelectMultiple}

class DeviceForm(forms.ModelForm):
    class Meta:
        model = Device
        fields = ['Name']

class AdderTypeForm(forms.Form):
    type = forms.ChoiceField(
        label='Select object type to add',
        choices=[('', ''),
                 ('Closet', 'Closet'),
                 #('School', 'School'),
                 ('Panel', 'Panel'),
                 ('Room', 'Room'),
                 ('Device', 'Device')
                 ],
        required=True
    )

def get_all_users():
    users = []
    usrs = User.objects.all()
    for i in usrs:
        users.append((i.username, i.username))
    return users

class PopulationForm(forms.Form):

    New_School = forms.CharField(
        label='New School: ',
        required=True
    )

    Room_File = forms.FileField(
        label='Select a file for Room Mapping'
    )

    Panel_File = forms.FileField(
        label='Select a file for Panel and Circuit Mapping'
    )

    Device_File = forms.FileField(
        label='Select a file for Device Mapping'
    )

    Device_Association_File = forms.FileField(
        label='Select a file for Additional Device Info',
        required = False
    )

    all_users = forms.MultipleChoiceField(choices=get_all_users(),
                                          widget=forms.CheckboxSelectMultiple(),
                                          label="Which Users Can Access: ")


#!/usr/bin/python3
""" Python program that solves the N queens problem."""

import sys

def is_valid_solution(resolve):
    """ Solution validator """
    for i in range(len(resolve)):
        for j in range(i + 1, len(resolve)):
            if resolve[i] == resolve[j]:
                return False
            if abs(resolve[i] - resolve[j]) == abs(i - j):
                return False
    return True

def solve_n_queens(n, solutions, resolve=[]):
    """ Solve nqueen's problem recursively"""
    if len(resolve) == n:
        if is_valid_solution(resolve):
            solutions.append([[i, resolve[i]] for i in range(n)])
        return
    for i in range(n):
        if i not in resolve:
            new_solution = resolve + [i]
            if is_valid_solution(new_solution):
                solve_n_queens(n, solutions, new_solution)

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: nqueens N")
        sys.exit(1)
    try:
        n = int(sys.argv[1])
    except ValueError:
        print("N must be a number")
        sys.exit(1)
    if n < 4:
        print("N must be at least 4")
        sys.exit(1)
    solutions = []
    solve_n_queens(n, solutions)
    for solution in solutions:
        print(solution)


# !/usr/bin/env python
# -*- coding: utf-8 -*-
# from logconfig import LogConfig
# logger = LogConfig.get_logger()
import os
import logging
logger = logging.getLogger('mylogger')

# import MySQLdb
class Bloom(object):

    # filter ids that have been crawled
    @classmethod
    def getIds(self):
        # f = open(r'../files/w_id_high.csv','r')
        # f = open(r'bloom/id_high_un.csv','r')
        # f = open(r'bloom/id_low_un.csv','r')
        f = open(r'bloom/id_root_30_un.csv','r')
        bloom = []
        # index = 0 # 每个爬虫各负责一端Ip
        # end = 50000
        index = 0 # 10万以内好了吗？
        end = 5000
        num = 0
        # for line in f.readlines():
        #     if(line!="\n"):
        #         num += 1
        #         if num>index and num<=end:
        #             lines = line.split(",")
        #             bloom.append(lines[0])
        for line in f.readlines():
            num += 1
            if num>index and num<=end:
                id = line.strip()
                bloom.append(id)
        ids = bloom
        return ids

    # 获取已经爬过的Ids
    # def get_already_ids(self):
    def getdb(self):
        # db = MySQLdb.connect('166.111.134.51','root','fit4-305','weibo',charset = 'utf8')
        db = MySQLdb.connect("localhost","Tiger","123456","weibo",charset='utf8')
        return db

    def getIdsDataBase(self):
        #从数据库获取id
        ids = {}
        db = self.getdb()
        cursor = db.cursor()
        sql = "select id from weibo.user_profile"
        cursor.execute(sql)
        data = cursor.fetchall()
        for each in data:
            # print(each)
            # ids.append(each[0])
            ids[each[0]] = ""
        return ids

from pybloom import ScalableBloomFilter
class FileBloom(object):
    def __init__(self):
        self.file_path = "bloom/bloom_weibo.txt";
        self.bloom_filter = ScalableBloomFilter(initial_capacity=10000,error_rate=0.001)

    def read_bloom(self):
        if os.path.exists(self.file_path):
            f = open(self.file_path,"r")
            ids = f.readlines()
            for id in ids:
                id_s = id.strip()
                self.bloom_filter.add(id_s)
            f.close()
        else:
            f = open(self.file_path,"w")
            f.close()

    def to_file(self):
        pass

    def update_bloom_file(self,m_id):
        f =open(self.file_path,"a")
        f.write(str(m_id)+"\n")
        f.close()

    def update_bloom(self,m_id):
        self.bloom_filter.add(m_id)

    def has_id(self,m_id):
        if m_id in self.bloom_filter:
            return True
        else:
            return False

if __name__ == "__main__":
    fb = FileBloom()
    fb.read_bloom()
    fb.update_bloom_file("23920323")
    fb.update_bloom("23920323")
# if __name__ == "__main__":
#     bl = Bloom()
#     ids = bl.getIdsDataBase()
#     f = open(r'id_root_30.csv','r')
#     uids = []
#     for line in f.readlines():
#         id = line.strip()
#         uids.append(id)
#     f.close()
#     print(len(uids))
#     uids = list(set(uids))
#     print(len(uids))
#     f = open(r'id_root_30_un.csv','w')
#     for uid in uids:
#         if uid not in ids:
#             print(uid)
#             f.write(uid+"\n")
#     f.close()

# ids = Bloom.getIds()
# ids = Bloom.getIdsDataBase()
# logger.info(ids)
# print(len(ids))


#!/usr/bin/env python3

from testUtils import Utils
from Cluster import Cluster
from Node import Node
from TestHelper import TestHelper
import os
import subprocess
import signal

###############################################################
#   Producer ha paused API
# Creates a cluster with
# - is_active_raft_cluster = True or False
# and switch it to simulate region switch
###############################################################

Print = Utils.Print
args = TestHelper.parse_args({"--dump-error-details", "--keep-logs", "-v", "--leave-running", "--clean-run"})
Utils.Debug = args.v
producers = 3
totalNodes = producers
cluster = Cluster(walletd=True)
dumpErrorDetails = args.dump_error_details
keepLogs = args.keep_logs
dontKill = args.leave_running
killAll = args.clean_run
testSuccessful = False
killEosInstances = not dontKill
specificExtraNodeosArgs = {}

try:
    TestHelper.printSystemInfo("BEGIN")
    cluster.killall(allInstances=killAll)
    cluster.cleanup()
    for i in range(producers):
        Node.create_ha_config(i)
    path_to_config_ha = os.getcwd()
    extraNodeosArgs = " --resource-monitor-not-shutdown-on-threshold-exceeded"
    for i in range(producers):
        specificExtraNodeosArgs[i] = \
            " --plugin eosio::producer_ha_plugin --producer-ha-config {}/config_ha_{}.json".format(
                path_to_config_ha, i)
    if cluster.launch(pnodes=producers, totalNodes=totalNodes, totalProducers=producers, useBiosBootFile=False,
                      dontBootstrap=True, specificExtraNodeosArgs=specificExtraNodeosArgs, prod_ha=True,
                      extraNodeosArgs=extraNodeosArgs) is False:
        Utils.errorExit("Failed to stand up eos cluster.")

    if not cluster.waitOnClusterSync(timeout=30, blockAdvancing=5):
        Utils.errorExit("Cluster failed to produce blocks.")
    else:
        Utils.Print("Cluster in Sync")

    nodes = cluster.getNodes()
    Leader, nonLeaders = cluster.find_leader_and_nonleaders()

    # get_info
    result = nonLeaders[0][1].get_producer_ha_info()
    if result["leader_id"] != Leader[0][0]:
        Utils.errorExit("v1/producer_ha/get_info API leader_id from standby BP is not the leader")
    else:
        Utils.Print("v1/producer_ha/get_info API leader_id from standby BP is the leader")

    # now turn the Raft cluster to standby mode
    for node in nodes:
        node.kill()

    for i in range(producers):
        Node.create_ha_config(i, None, None, is_active=False)

    for node in nodes:
        res = node.relaunch(cachePopen=True)
        if not res:
            Utils.errorExit("Relaunching node failed")
    cluster.setNodes(nodes)

    # wait for 10 blocks in case the producer_ha still have some blocks to apply to the producer_plugin
    if cluster.waitOnClusterSync(timeout=45, blockAdvancing=10):
        Utils.errorExit("Cluster still produce blocks.")
    else:
        Utils.Print("Cluster not producing")

    result = nodes[0].get_producer_ha_info()
    if result["leader_id"] == -1:
        Utils.errorExit("v1/producer_ha/get_info API leader_id is -1. Not expected")
    else:
        Utils.Print("v1/producer_ha/get_info API leader_id is not -1. Expected.")

    if result["is_active_raft_cluster"]:
        Utils.errorExit("v1/producer_ha/get_info API is_active_raft_cluster is True. Not expected")
    else:
        Utils.Print("v1/producer_ha/get_info API is_active_raft_cluster is False. Expected")

    # now turn the Raft cluster back to active mode
    for node in nodes:
        node.kill()

    for i in range(producers):
        Node.create_ha_config(i, None, None, is_active=True)

    for node in nodes:
        res = node.relaunch(cachePopen=True)
        if not res:
            Utils.errorExit("Relaunching node failed")
    cluster.setNodes(nodes)

    if not cluster.waitOnClusterSync(timeout=60, blockAdvancing=5):
        Utils.errorExit("Cluster failed to produce blocks.")
    else:
        Utils.Print("Cluster is producing again")

    Leader, nonLeaders = cluster.find_leader_and_nonleaders()

    # get_info
    result = nonLeaders[0][1].get_producer_ha_info()
    if result["leader_id"] != Leader[0][0]:
        Utils.errorExit("v1/producer_ha/get_info API leader_id from standby BP is not the leader")
    else:
        Utils.Print("v1/producer_ha/get_info API leader_id from standby BP is the leader")

    testSuccessful = True

finally:
    TestHelper.shutdown(cluster, None, testSuccessful, killEosInstances, False, keepLogs, killAll, dumpErrorDetails)

exitCode = 0 if testSuccessful else 1
exit(exitCode)


import os

from sqlalchemy import (
    create_engine,
    Integer,
    Column,
    String,
    ForeignKey)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker

BASE_DIR = os.path.dirname(os.path.realpath(__file__))
conn = 'sqlite:///' + os.path.join(BASE_DIR, 'blog.db')

e = create_engine(conn, echo=True)

Base = declarative_base()

"""
class User(Base):
        id: int
        username: str
        email: str

class Post:
        id: int
        title: str
        content: str
        user_id: int foreignkey
"""

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    username = Column(String(40), nullable=False)
    email = Column(String(40), nullable=False)
    posts = relationship('Posts', backref='author')

    def __repr__(self):
        return f'<User {self.username}>'

class Post(Base):
    __tablename__ = 'posts'
    id = Column(Integer(), primary_key=True)
    title = Column(String(45), nullable=False)
    content = Column(String(255), nullable=False)
    user_id = Column(Integer, ForeignKey('users.id'))

    def __repr__(self):
        return f'<User{self.title}>'

Base.metadata.create_all(e)
session = sessionmaker()(bind=e)


"""Main Application Handler."""
import json
import webbrowser
from typing import Any

import click

from .config.config import Config
from .controllers.student_controller import StudentController
from .openapi_docs.decorators import openapi
from .openapi_docs.decorators import response_schema
from .openapi_docs.open_api import OpenApi
from .utils.banner import Banner
from .utils.decorators import singleton

# Include all controllers
student_controller = StudentController()
(
    PersonSchema,
    StudentSchema,
    StudentIdSchema,
    StudentParamsSchema,
) = student_controller.schemas

@singleton
class _Application:
    """Main application class runner."""

    _openapi: Any

    def __init__(self) -> None:
        """Application Runner."""
        # Set application config environment
        Config().environment = "development"

        # Print project banner
        Banner.paste()

        # Register APIs with OpenAPI spec
        self._openapi = OpenApi()
        self._openapi.register("/api/v1/students", self.get_students)
        self._openapi.register("/api/v1/student/{id}", self.get_student_by_id)
        self._openapi.register("/api/v1/student", self.create_student)
        self._openapi.register("/api/v1/student/{id}", self.update_student)
        self._openapi.register("/api/v1/student/{id}", self.delete_student)

    @property
    def settings(self) -> str:
        """
        Getter method for application settings.

        Returns:
            Application settings
        """
        return self.settings

    def openapi_serve(self) -> None:
        """Serve OpenAPI docs."""
        # Generate Open API docs
        self._openapi.generate_doc()

        # Serve Open API docs
        webbrowser.open("http://127.0.0.1:3000", new=2)
        self._openapi.serve_doc()

    # Get all students API
    # path="/api/v1/students"
    # --------------------
    @openapi(
        tags=["Student"],
        method="GET",
        summary="Get all students",
        description="Get all student from database",
        responses={
            200: {
                "description": "Ok. Get students",
                "content": {
                    "application/json": {
                        "schema": {"type": "array", "items": StudentSchema}
                    }
                },
                "links": {
                    "GetStudentById": {
                        "operationRef": "/api/student/{id}",
                        "parameters": {"id": "$response.body#/id"},
                        "description": "The `id` value returned in the "
                        "response can be used as "
                        "the `id` parameter "
                        "in `GET /api/student/{id}`.",
                    }
                },
            },
            400: {"description": "Bad request"},
            401: {"description": "Unauthorized"},
            422: {"description": "Validation error"},
            500: {"description": "Server error"},
        },
    )  # type: ignore
    @response_schema(StudentSchema)  # type: ignore
    def get_students(self) -> None:
        """Endpoint handler for student API, return all students."""
        response = student_controller.get_all()
        print(json.dumps(response, indent=2))

    # Get student by id API
    # path="/api/v1/student/{id}"
    # ---------------------
    @openapi(
        tags=["Student"],
        method="GET",
        summary="Get student by id",
        description="Get student by id from database",
        parameters=[
            {
                "in": "path",
                "name": "id",
                "schema": StudentParamsSchema,
                "required": "true",
            }
        ],
        responses={
            200: {
                "description": "Ok. Get student",
                "content": {"application/json": {"schema": StudentSchema}},
            },
            400: {"description": "Bad request"},
            401: {"description": "Unauthorized"},
            422: {"description": "Validation error"},
            500: {"description": "Server error"},
        },
    )  # type: ignore
    @response_schema(StudentSchema)  # type: ignore
    def get_student_by_id(self, _id: str) -> None:
        """
        Endpoint handler for student API, return particular students.

        Parameters:
            _id (str): student id
        """
        response = student_controller.get()
        print(json.dumps(response, indent=2))

    # Create student API
    # path="/api/v1/student"
    # ------------------
    @openapi(
        tags=["Student"],
        method="POST",
        summary="Create student",
        description="Create new student in database",
        requestBody={
            "description": "Optional description in *Markdown*",
            "required": True,
            "content": {"application/json": {"schema": PersonSchema}},
        },
        responses={
            201: {
                "description": "Ok. Create student",
                "content": {"application/json": {"schema": StudentIdSchema}},
            },
            400: {"description": "Bad request"},
            401: {"description": "Unauthorized"},
            422: {"description": "Validation error"},
            500: {"description": "Server error"},
        },
    )  # type: ignore
    # For OpenAPI >=3 we don"t need request_schema
    # @request_schema(PersonSchema)  # type: ignore
    def create_student(self, request: Any) -> None:
        """
        Endpoint handler for student API, create student.

        Parameters:
            request (Any): student request object
        """
        response = student_controller.post(request)
        print(json.dumps(response, indent=2))

    # Put student by id API
    # path="/api/v1/student/{id}"
    # ---------------------
    @openapi(
        tags=["Student"],
        method="PATCH",
        summary="Update student by id",
        description="Update student by id in database",
        parameters=[
            {
                "in": "path",
                "name": "id",
                "schema": StudentParamsSchema,
                "required": "true",
            }
        ],
        responses={
            200: {
                "description": "Ok. Student updated",
                "content": {"application/json": {"schema": StudentSchema}},
            },
            400: {"description": "Bad request"},
            401: {"description": "Unauthorized"},
            422: {"description": "Validation error"},
            500: {"description": "Server error"},
        },
    )  # type: ignore
    @response_schema(StudentSchema)  # type: ignore
    def update_student(self, _id: str, request: Any) -> None:
        """
        Endpoint handler for student API, update particular students.

        Parameters:
            _id (str): student id
            request (Any): student object
        """
        response = student_controller.patch(_id, request)
        print(json.dumps(response, indent=2))

    # Delete student by id API
    # path="/api/v1/student/{id}"
    # ---------------------
    @openapi(
        tags=["Student"],
        method="DELETE",
        summary="Delete student by id",
        description="Delete student by id from database",
        parameters=[
            {
                "in": "path",
                "name": "id",
                "schema": StudentParamsSchema,
                "required": "true",
            }
        ],
        responses={
            204: {"description": "Ok. Student deleted"},
            400: {"description": "Bad request"},
            401: {"description": "Unauthorized"},
            422: {"description": "Validation error"},
            500: {"description": "Server error"},
        },
    )  # type: ignore
    def delete_student(self, _id: str) -> None:
        """
        Endpoint handler for student API, delete particular students.

        Parameters:
            _id (str): student id
        """
        response = student_controller.delete(_id)
        print(json.dumps(response, indent=2))

@click.command()
@click.version_option()
def main() -> None:
    """viper_boot."""
    _Application()

    # Initialise, register and serve OpenAPI docs.
    _Application().openapi_serve()

    # Invoking APIs manually
    # _Application().get_student_by_id(uuid.uuid4().hex)
    # _Application().get_students()
    # _Application().create_student(
    #     {
    #         "first_name": "James",
    #         "last_name": "Smith",
    #         "dob": datetime(1978, 10, 10),
    #         "gender": GenderEnum.MALE,
    #     }
    # )
    # _Application().update_student(
    #     uuid.uuid4().hex,
    #     {
    #         "first_name": "James",
    #         "last_name": "Smith",
    #         "dob": datetime(1978, 10, 10).date().isoformat(),
    #         "gender": GenderEnum.MALE.name,
    #     }
    # )
    # _Application().delete_student(uuid.uuid4().hex)

if __name__ == "__main__":
    main(prog_name="viper_boot")  # pragma: no cover


from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.conf import settings
from .models import *
from .forms import *
import stripe
import json
from django.http import HttpResponse
import json

# Create your views here.
stripe.api_key = settings.STRIPE_API_KEY

def index(request):

    context = {}

    return render(request, "front-office/index.html", context)

@login_required
def dashboard(request):
    context = {}

    return render(request, "backoffice/base.html", context)

@login_required
def fixes(request):
    context = {}

    return render(request, "backoffice/fixes.html", context)

@login_required
def customerProfile(request):
    form = CustomerProfileForm()
    context = {
        'form': form,
    }

    return render(request, "backoffice/profile.html", context)

@login_required
def addFixes(request):

    context = {}

    return render(request, "backoffice/fixes.html", context)

@login_required
def capsulesView(request):

    context = {}

    return render(request, "backoffice/capsules.html", context)

@login_required
def addFixAttachement(request):
    if request.method == "POST":
        fix_pk = request.POST.get("fix_id")
        fix = SmallFix.objects.get(pk=fix_pk)
        for file in request.FILES:
            attachment = FixAttachment(file=file)
            attachment.save()
            fix.files.add(attachment)
        fix.save()

        return JsonResponse({'succes':True})

    return HttpResponse('test')

@login_required
def getPublishableKey(request):

    key = settings.STRIPE_PUBLISHABLE_KEY

    return JsonResponse({'key': key})

@login_required
def chargePaymentToken(request):
    if request.method == "POST":
        transaction = StripeTransaction()
        transaction.save()
        data = request.body
        data = json.loads(request.body)
        token = data["token"]
        amount = data["amount"]
        if amount > 50:
            try:
                res = stripe.Charge.create(
                  amount=str(amount),
                  currency="eur",
                  description="BMDG Partners",
                  source=token,  # obtained with Stripe.js
                  idempotency_key=str(transaction.idempotency_key),
                )
                print(res)
                return JsonResponse({'success': True})
            except:
                return JsonResponse({'success': False})
        else:
            return JsonResponse({'success': False})


import gl
print(sys.version)
print(gl.version())
gl.resetdefaults()
# help(gl)

import sys
import os
from datetime import datetime
# Load main image and overlay
data_path = os.path.join('/', 'mnt', 'tosh', 'Projects', 'MEP', 'mep-scripts', 'Data')
reference_mouse_path = os.path.join(data_path, 'Mouse', 'Reference')
reference_human_path = os.path.join(data_path, 'Human', 'Reference')
analysis_path = os.path.join(data_path, 'Analysis')

# main_path = os.path.join(reference_path, 'average_template_50_reoriented.nii.gz')
# overlay1_path = os.path.join(analysis_path, 'annotation_50_reoriented_pVal_inv_sig_volIncrease.nii.gz')
# overlay2_path = os.path.join(analysis_path, 'annotation_50_reoriented_pVal_inv_sig_volDecrease.nii.gz')

# gl.loadimage(main_path)
# gl.overlayload(overlay1_path)
# gl.overlayload(overlay2_path)

# gl.opacity(1, 50)
# gl.opacity(2, 50)
# gl.minmax(1, 0, 3)
# gl.minmax(2, 0, 3)
# gl.colorname(1, '1red')
# gl.colorname(2, '3blue')

strtime = str(datetime.now())
output_dir_path = os.path.join(analysis_path,
							   'imageSequenceFolders', 'sequence_2D_' + strtime)
if not os.path.exists(output_dir_path):
	os.mkdir(output_dir_path)

y_min = -13.15 ###
y_max = 0 ###
y_step = 0.05 ###
# y_min = -102 ###
# y_max = 78 ###
# y_step = 0.85 ###

y = y_min
count = 0
while y <= y_max:
	print(y)
	count = count + 1
	print(count)

	gl.orthoviewmm(0, y, -4)
	gl.view(2)
	gl.linewidth(0)
	gl.colorbarposition(0)

	filepath = os.path.join(output_dir_path, 'image_' + str(round(count)).rjust(3, '0')) + '_' + str(y)
	print(f'filepath = {filepath}')
	gl.savebmp(filepath)

	y = y + y_step


from tortoise.contrib.fastapi import register_tortoise
from data.model import *
from fastapi import FastAPI, Depends

TORTOISE_ORM = {
    "connections": {"default": 'sqlite://notesdb.sqlite'},
    "apps": {
        "models": {
            "models": ["data.model.user", "data.model.note", "aerich.models"],
            "default_connection": "default",
        },
    },
}

def init_db(app: FastAPI):
    register_tortoise(
        app,
        db_url='sqlite://notesdb.sqlite',
        modules={"models": ["data.model.user", "data.model.note"]},
        generate_schemas=False,
        add_exception_handlers=False,
    )


import tensorflow as tf

__all__ = [
	"build_updates",
	"build_loss",
	"cost_function"
]

def build_updates(optimization):

	if 'optimizer' in optimization.keys():
		optimizer = optimization['optimizer']
	else:
		optimizer = 'adam'
		optimization['learning_rate'] = 0.001

	if optimizer == 'sgd':
		learning_rate = 0.005
		if 'learning_rate' in optimization.keys():
			leanring_rate = optimization['learning_rate']
		use_locking = False
		if 'use_locking' in optimization.keys():
			use_locking = optimization['use_locking']
		name = 'adadelta'
		if 'name' in optimization.keys():
			name = optimization['name']
		return tf.train.GradientDescentOptimizer(learning_rate=learning_rate,
												 use_locking=use_locking,
												 name=name)

	elif optimizer == 'momentum':
		learning_rate = 0.005
		if 'learning_rate' in optimization.keys():
			leanring_rate = optimization['learning_rate']
		momentum = 0.9
		if 'momentum' in optimization.keys():
			momentum = optimization['momentum']
		use_nesterov = True
		if 'use_nesterov' in optimization.keys():
			use_nesterov = optimization['use_nesterov']
		use_locking = False
		if 'use_locking' in optimization.keys():
			use_locking = optimization['use_locking']
		name = 'momenum'
		if 'name' in optimization.keys():
			name = optimization['name']
		return tf.train.MomentumOptimizer(learning_rate=learning_rate,
										  momentum=momentum,
										  use_nesterov=use_nesterov,
										  use_locking=use_locking,
										  name=name)

	elif optimizer == 'adam':
		learning_rate = 0.001
		if 'learning_rate' in optimization.keys():
			leanring_rate = optimization['learning_rate']
		beta1 = 0.95
		if 'beta1' in optimization.keys():
			beta1 = optimization['beta1']
		beta2 = 0.999
		if 'beta2' in optimization.keys():
			beta2 = optimization['beta2']
		epsilon = 1e-08
		if 'epsilon' in optimization.keys():
			epsilon = optimization['epsilon']
		use_locking = False
		if 'use_locking' in optimization.keys():
			use_locking = optimization['use_locking']
		name = 'adam'
		if 'name' in optimization.keys():
			name = optimization['name']
		return tf.train.AdamOptimizer(learning_rate=learning_rate,
									  beta1=beta1,
									  beta2=beta2,
									  epsilon=epsilon,
									  use_locking=use_locking,
									  name=name)

	elif optimizer == 'rmsprop':
		learning_rate = 0.001
		if 'learning_rate' in optimization.keys():
			leanring_rate = optimization['learning_rate']
		rho = 0.95
		if 'rho' in optimization.keys():
			rho = optimization['rho']
		epsilon = 1e-08
		if 'epsilon' in optimization.keys():
			epsilon = optimization['epsilon']
		use_locking = False
		if 'use_locking' in optimization.keys():
			use_locking = optimization['use_locking']
		name = 'rmsprop'
		if 'name' in optimization.keys():
			name = optimization['name']
		return tf.train.RMSPropOptimizer(learning_rate=learning_rate,
										 rho=rho,
										 epsilon=epsilon,
										 use_locking=use_locking,
										 name=name)

	elif optimizer == 'adadelta':
		learning_rate = 0.001
		if 'learning_rate' in optimization.keys():
			leanring_rate = optimization['learning_rate']
		rho = 0.95
		if 'rho' in optimization.keys():
			rho = optimization['rho']
		epsilon = 1e-08
		if 'epsilon' in optimization.keys():
			epsilon = optimization['epsilon']
		use_locking = False
		if 'use_locking' in optimization.keys():
			use_locking = optimization['use_locking']
		name = 'adadelta'
		if 'name' in optimization.keys():
			name = optimization['name']
		return tf.train.AdadeltaOptimizer(learning_rate=learning_rate,
										  rho=rho,
										  epsilon=epsilon,
										  use_locking=use_locking,
										  name=name)

	elif optimizer == 'adagrad':
		learning_rate = 0.001
		if 'learning_rate' in optimization.keys():
			leanring_rate = optimization['learning_rate']
		initial_accumulator_value = 0.95
		if 'initial_accumulator_value' in optimization.keys():
			initial_accumulator_value = optimization['initial_accumulator_value']
		use_locking = False
		if 'use_locking' in optimization.keys():
			use_locking = optimization['use_locking']
		name = 'adagrad'
		if 'name' in optimization.keys():
			name = optimization['name']
		return tf.train.AdagradOptimizer(learning_rate=learning_rate,
										 initial_accumulator_value=initial_accumulator_value,
										 use_locking=use_locking,
										 name=name)

def build_loss(network, predictions, targets, optimization):

	# cost function
	if (optimization['objective'] == 'binary') | (optimization['objective'] == 'categorical'):
		clip_value = True
	else:
		if 'clip_value' in optimization.keys():
			clip_value = optimization['clip_value']
		else:
			clip_value = False

	# build loss function
	loss = cost_function(predictions=predictions, targets=targets,
						 objective=optimization['objective'],
						 clip_value=clip_value)

	if 'l1' in optimization.keys():
		l1 = get_l1_parameters(network)
		loss += tf.reduce_sum(tf.abs(l1)) * optimization['l1']

	if 'l2' in optimization.keys():
		l2 = get_l1_parameters(network)
		loss += tf.reduce_sum(tf.square(l2)) * optimization['l2']

	return loss

def cost_function(predictions, targets, objective, **kwargs):

	if 'clip_value' in kwargs.keys():
		if kwargs['clip_value']:
			predictions = tf.clip_by_value(predictions,1e-7,1-1e-7)

	if objective == 'binary':
		predictions = tf.nn.sigmoid(predictions)
		loss = -tf.reduce_mean(targets*tf.log(predictions) + (1-targets)*tf.log(1-predictions))
		#loss = tf.nn.sigmoid_cross_entropy_with_logits(predictions, targets, name='binary_loss')

	elif objective == 'categorical':
		loss = -tf.reduce_mean(tf.reduce_sum(targets*tf.log(predictions), axis=1))
		#loss = tf.nn.softmax_cross_entropy_with_logits(predictions, targets, name='softmax_loss')

	elif objective == 'squared_error':
		loss = tf.reduce_mean(tf.square(predictions - targets))
		#loss = tf.nn.l2_loss(predictions-targets, name='squared_error')

	elif objective == 'vae':
		loss = []

	return loss

def get_l1_parameters(net):
	params = []
	for layer in net:
		if hasattr(net[layer], 'is_l1_regularize'):
			if net[layer].is_l1_regularize():
				variables = net[layer].get_variable()
				if isinstance(variables, list):
					for var in variables:
						params.append(var.get_variable())
				else:
					params.append(variables.get_variable())
	return merge_parameters(params)

def get_l2_parameters(net):
	params = []
	for layer in net:
		if hasattr(net[layer], 'is_l2_regularize'):
			if net[layer].is_l2_regularize():
				variables = net[layer].get_variable()
				if isinstance(variables, list):
					for var in variables:
						params.append(var.get_variable())
				else:
					params.append(variables.get_variable())
	return merge_parameters(params)

def merge_parameters(params):
	all_params = []
	for param in params:
		all_params = tf.concat([all_params, tf.reshape(param, [-1,])],0) #changed  the syntax for concat
	return all_params


def func():
    start = list(input())
    end = list(input())

    if len(start) != len(end):
        print("False")
        return

    while "X" in start:
        start.remove("X")

    while "X" in end:
        end.remove("X")

    if start == end:
        print("True")
    else:
        print("False")

func()


from django.contrib import admin
from tinymce.widgets import TinyMCE
from django.db import models
# Register your models here.
from .models import Cat, Category

class TutorialAdmin(admin.ModelAdmin):
    fieldsets = [
        ("Title/date", {'fields': ["title", "published"]}),
        ("URL", {'fields': ["slug"]}),
        ("Content", {"fields": ["content","cat_category","birth"]}),

        ("Icon",{"fields": ["icon"]})
    ]
    formfield_overrides = {
        models.TextField: {'widget': TinyMCE()},
    }

admin.site.register(Category)
admin.site.register(Cat, TutorialAdmin)


def test19():
    n=int(input())
    d=int(input())
    x=input().split(" ")
    num=0
    b=[]
    for i in x:
        b.append(int(i))
    for i in range(1,n):
        if b[i-1]>=b[1]:
            while True:
                if b[i-1]<b[i]:
                    break
                b[i]=b[i]+d
                num=num+1
    print(num)
test19()


import speech_recognition as sr
import os
from gensim import summarization as summary
import nltk.tokenize
from nltk.stem.snowball import SnowballStemmer
import json

import sys
from pathlib import Path

isFilePresent = True
POS_REWARD = 1.0
NEG_REWARD = 1.0
THRESHOLD = 0.3
DIR = 'Outputs\\Transcriptions'

def getKeywords(text):

    nltk.download('wordnet')
    tokenized = nltk.tokenize.word_tokenize(text)
    stemmer = SnowballStemmer("english", ignore_stopwords=False)
    rawkws = summary.keywords(text)
    keyws = rawkws.split()

    return keyws

def writeData(text, params):
    final_keywords = ""
    for word in params:
        if params.get(word) > THRESHOLD:
            final_keywords += (word+",")

    final_keywords = final_keywords[:-1]
    print(final_keywords)

if __name__ == "__main__":

    params = {}
    receivedKeywords = getKeywords(sys.argv[1])
    # updateConfidence(receivedKeywords, params)
    writeData(receivedKeywords, params)


# Always prefer setuptools over distutils
# To use a consistent encoding
from codecs import open
from os import path

from setuptools import setup

# The directory containing this file
HERE = path.abspath(path.dirname(__file__))

# Get the long description from the README file
with open(path.join(HERE, 'README.md')) as f:
    long_description = f.read()

# This call to setup() does all the work
setup(
    name="stocksent",
    version="0.4.5",
    description="A Python library for sentiment analysis of various tickers from the latest news by trusted sources, "
                "and tools to plot results.",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://stocksent.readthedocs.io/",
    author="Arya Manjaramkar",
    author_email="aryagm01@email.com",
    license="Mozilla Public License 2.0",
    classifiers=[
        "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
        "Natural Language :: English",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Operating System :: OS Independent"
    ],
    packages=["stocksent"],
    include_package_data=True,
    install_requires=["numpy", "matplotlib",
                      "pandas", "nltk", "wordcloud", "bs4"]
)


import math
import matplotlib.pyplot as plt
import matplotlib
plt.style.use('ggplot')
x = xrange(2,100)
birthday = [1-(math.factorial(365)/math.factorial(365 - k))/float(365**k) for k in x]

plt.plot(x, birthday, 'g-')
plt.ylim(0,1.05)
plt.xlabel('# of people')
plt.ylabel('Probability')
plt.show()