import importlib.util
import json
import logging
import os
import sys
from pathlib import Path

from starlette.applications import Starlette
from starlette.responses import JSONResponse, PlainTextResponse
from starlette.routing import Route

import traceback
import typer
import uvicorn

from .serializer_deserializer import decode

logging.basicConfig(format="%(levelname)s:     %(message)s", datefmt="", level=logging.INFO)
logger = logging.getLogger("uvicorn.access")

async def some_startup_task():
    global inference_handler

    _handler_path = Path(os.environ.get("HANDLER_PATH", "handler.py"))
    module_name = f"{_handler_path.stem}.EndpointHandler"

    spec = importlib.util.spec_from_file_location(module_name, _handler_path)
    # add the whole directory to path for submodlues
    sys.path.insert(0, str(_handler_path.parents[0]))
    # import custom handler
    handler = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = handler
    spec.loader.exec_module(handler)
    # init custom handler with model_dir
    inference_handler = handler.EndpointHandler(str(_handler_path.parents[0]))
    # logger.info(f"Loaded EndpointHandler from {str(_handler_path)} file")

async def predict(request):
    try:
        content_type = request.headers.get("content-Type", None)
        deserialized_body = decode(await request.body(), content_type)
        # checks if input schema is correct
        if "inputs" not in deserialized_body:
            raise ValueError(f"Body needs to provide a inputs key, recieved: {json.dumps(deserialized_body)}")

        # run handler call
        pred = inference_handler(deserialized_body)
        return JSONResponse(pred)
    except Exception as e:
        print(traceback.format_exc())
        return JSONResponse({"error": str(e)}, status_code=400)

async def health(request):
    return PlainTextResponse("Ok")

app = app = Starlette(
    debug=True,
    routes=[
        Route("/", health, methods=["GET"]),
        Route("/health", health, methods=["GET"]),
        Route("/", predict, methods=["POST"]),
        Route("/predict", predict, methods=["POST"]),
    ],
    on_startup=[some_startup_task],
)

def emulate(handler: str = "handler.py", port: int = 5000):
    os.environ["HANDLER_PATH"] = handler
    logger.info(f"Loading handler from {handler} file")
    uvicorn.run(app, port=port, host="0.0.0.0", log_level="info")

if __name__ == "__main__":
    typer.run(emulate)


N = int(input())
is_s = [1] * 4000001
is_s[1] = 0
is_s[0] = 0

for i in range(2, 4000001):
    if is_s[i]:
        temp = 2
        while True:
            if temp * i > 4000000:
                break
            is_s[i * temp] = 0
            temp += 1
arr = []
for i in range(2, 4000001):
    if is_s[i]:
        arr.append(i)

count = 0
final = len(arr)
S = 0
s = -1
e = -1
while True:
    # if ((e == final) and (s == final)):
    #     break
    if e == final:
        s += 1
        if s < final:
            S -= arr[s]
        else:
            break
    elif S < N:
        e += 1
        if e < final:
            S += arr[e]
    elif S >= N:
        s += 1
        if s < final:
            S -= arr[s]
    if S == N:
        count += 1
print(count)

Solved/알고리즘/투포인터알고리즘/소수의연속합.py


# Задание 1

geo_logs = [
	{'visit1': ['Москва', 'Россия']},
	{'visit2': ['Дели', 'Индия']},
	{'visit3': ['Владимир', 'Россия']},
	{'visit4': ['Лиссабон', 'Португалия']},
	{'visit5': ['Париж', 'Франция']},
	{'visit6': ['Лиссабон', 'Португалия']},
	{'visit7': ['Тула', 'Россия']},
	{'visit8': ['Тула', 'Россия']},
	{'visit9': ['Курск', 'Россия']},
	{'visit10': ['Архангельск', 'Россия']}
]

new_geo_logs = []

for visits in geo_logs:
	for visit, country in visits.items():
		if 'Россия' in country:
			new_geo_logs.append(visits)

print(new_geo_logs)

# Задание 2

ids = {'user1': [213, 213, 213, 15, 213],
       'user2': [54, 54, 119, 119, 119],
       'user3': [213, 98, 98, 35]}

unique_id = []
newlist = []

for user, id in ids.items():
	id = set(id)
	unique_id.append(id)

for i in unique_id:
	for j in i:
		newlist.append(j)

newlist = set(newlist)
newlist = list(newlist)
print(newlist)

# Задание 3

queries = [
	'смотреть сериалы онлайн',
	'новости спорта',
	'афиша кино',
	'курс доллара',
	'сериалы этим летом',
	'курс по питону',
	'сериалы про спорт',
	'погода',
	'игра престолов',
	'афиша кино',
	'курс по питону',
	'',
	'курс по питону',
	'курс по питону',
	'qwertyuiop asdfghjkl zxcvbnm test',
	''
]

numbers = {}

for requests in queries:
	words = requests.split()
	if len(words) in numbers.keys():
		numbers[len(words)] += 1
	else:
		numbers.update({len(words): 1})

for key, value in numbers.items():
	percent = round((value / len(queries)) * 100, 2)
	print(f'Поисковых запросов из {key}: {percent}% (запросов - {value})')

# Задание 4

stats = {'facebook': 55, 'yandex': 120, 'vk': 115, 'google': 99, 'email': 42, 'ok': 98, }

x = []
for v in stats.values():
	x.append(v)
y = (max(x))

new_dict = {}
for k, v in stats.items():
	new_dict[v] = k

print(f'{new_dict[y]}')


import lcm
import matplotlib.pyplot as plt
import numpy as np
import csv

from graph_data import vertex_data
from graph_data import map_data
from graph_data import sensors_data

# This file is used to visualize the gaussian process occupancy grid map (Work with test_gpc_sensor.cpp)
fontsize_dis = 8

num_row = 30
num_col = 30

class Vertex(object):
    def __init__(self, index, pos_x, pos_y, p, ig, occu):
        self.idx_ = index
        self.pos_ = [pos_x, pos_y]
        self.p_ = p
        self.ig_ = ig
        self.occupancy_ = occu

class map_vis(object):
    def __init__(self):
        self.num_row_ = num_row
        self.num_col_ = num_row
        self.num_fig = 0
        self.training_data_ = []

        self.graph_init()

    def graph_reset(self):
        self.vertex_ = {}

    def graph_init(self):
        self.graph_reset()

        for idx in range(self.num_col_ * self.num_row_):
            row = self.num_row_ - idx/ self.num_row_ - 1
            col = idx % self.num_col_
            p = 0.5
            ig = 0
            occupancy = "UNKNOWN"
            new_vertex = Vertex(idx, row, col, p, ig, occupancy)
            self.vertex_[idx] = new_vertex

    def map_data_handler(self, channel, data):
        self.graph_init()
        msg = map_data.decode(data)
        for cell in msg.vertex_:
            idx = cell.idx_
            self.vertex_[idx].ig_ = cell.ig_
            self.vertex_[idx].p_ = cell.p_
            if self.vertex_[idx].p_ == 0.0:
                self.vertex_[idx].occupancy_ = "FREE"
            elif self.vertex_[idx].p_ == 1.0:
                self.vertex_[idx].occupancy_ = "OCCUPIED"

    def training_data_handler(self,channel,data):
        msg = sensors_data.decode(data)
        for pos in msg.sensor_pos_:
            self.training_data_.append(pos)

        self.GP_map_vis()

    def vis(self):
        # Draw grid map
        x_min = 0
        x_max = self.num_col_
        y_min = 0
        y_max = self.num_row_
        plt.grid(color='black', linestyle='-', linewidth=1)
        plt.xlim(x_min,x_max)
        plt.ylim(y_min,y_max)
        plt.xticks(np.arange(x_min, x_max+1, 1))
        plt.yticks(np.arange(y_min, y_max+1, 1))

        # Draw each cell
        for cell in self.vertex_.values():
            plt.text(cell.pos_[1] + 0.25, cell.pos_[0] + 0.25,"{}".format(round(cell.p_,3)), color='black', fontsize=20)

        ZZ = np.empty([self.num_col_, self.num_row_])
        for cell in self.vertex_.values():
            ZZ[cell.pos_[1],cell.pos_[0]] = cell.p_

        # The number here is the num of col and row + 1
        XX, YY = np.mgrid[0:self.num_col_:11j, 0:self.num_row_:11j]

        CMAP = plt.get_cmap('jet')
        plt.pcolormesh(XX,YY,ZZ,cmap=CMAP)
        cb = plt.colorbar(shrink = 1.0)
        cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=30)

    def GP_map_vis(self):
        x_min = 0
        x_max = self.num_col_
        y_min = 0
        y_max = self.num_row_
        plt.grid(color='black', linestyle='-', linewidth=1.5)
        plt.xlim(x_min,x_max)
        plt.ylim(y_min,y_max)
        plt.xticks(np.arange(x_min, x_max+1, 10))
        plt.yticks(np.arange(y_min, y_max+1, 10))

         # Draw each cell
        for cell in self.vertex_.values():
            plt.text(cell.pos_[1] + 0.25, cell.pos_[0] + 0.25,"{}".format(round(cell.p_,2)), color='black', fontsize=fontsize_dis)
            if (cell.p_ >= 0.45 and cell.p_ <= 0.55):
                x_region = np.arange(cell.pos_[1], cell.pos_[1] + 2, 1)
                y_region = cell.pos_[0]
                plt.fill_between(x_region, y_region, y_region +1, facecolor='gray', interpolate=True)

            if (cell.p_ > 0.55):
                x_region = np.arange(cell.pos_[1], cell.pos_[1] + 2, 1)
                y_region = cell.pos_[0]
                plt.fill_between(x_region, y_region, y_region +1, facecolor='black', interpolate=True)

        for dt in self.training_data_:
            cv = self.vertex_[dt]
            row = cv.pos_[1] + 0.5
            col = cv.pos_[0] + 0.5
            plt.plot(row,col,"*r",markersize=20)

        plt.show()

def main():
    lc = lcm.LCM()
    map = map_vis()

    for i in range(100000):
        Graph_data = str(i) + "GraphDataGP"
        Training_data = str(i) + "TrainingData"
        subscription = lc.subscribe(Graph_data, map.map_data_handler)
        subscription = lc.subscribe(Training_data, map.training_data_handler)

    try:
        while True:
            lc.handle()
    except KeyboardInterrupt:
        pass

    lc.unsubscribe(subscription)

if __name__ == '__main__':
    main()


#%%
def charToPriority(char):
    if 'a' <= char <= 'z':
        return ord(char) - ord('a') + 1
    elif 'A' <= char <= 'Z':
        return ord(char) - ord('A') + 27
    else:
        return 0
#%%
with open("input", "r") as f:
    rows = [x.strip() for x in f.readlines()]

#%%
total = 0
for r in rows:
    total += charToPriority((set(r[:len(r)//2]) & set(r[len(r)//2:])).pop())
print(total)
# %%
from itertools import zip_longest
from functools import reduce
#%%
total = 0
N = 3
for rs in zip_longest(*( [iter(rows)]*N)):
    intersection = reduce(lambda x,y: set(x) & set(y), rs)
    total += charToPriority(intersection.pop())
print(total)
# %%


# https://leetcode.com/problems/linked-list-cycle/submissions/

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        seen_items = set()
        while head:
            if head in seen_items:
                return True
            seen_items.add(head)
            head = head.next
        return False


import sys
import collections

finput = sys.stdin.readline

dq = collections.deque()
dq.append((0, 0))

N = int(finput())
K = int(finput())

board = [[0]*N for _ in range(N)]
board[0][0] = 1

for i in range(K):
    y, x = map(int, finput().split())
    board[y-1][x-1] = 2

L = int(finput())
info = [finput().split() for _ in range(L)]

dy, dx = (-1,0,1,0), (0,1,0,-1)

board[0][0] = 1

def move(cy,cx, d):
    global board

    ny, nx = cy + dy[d], cx + dx[d]

    if ny >= N or nx >= N or nx < 0 or ny < 0 or board[ny][nx] == 1:
        return True
    elif board[ny][nx] == 0:
        dq.append((ny,nx))
        board[ny][nx] = 1
        py, px = dq.popleft()
        board[py][px] = 0
    else:
        dq.append((ny, nx))
        board[ny][nx] = 1

    return False

def solve():
    result = 0
    curD = 1

    for i in info:
        sec = int(i[0])

        for _ in range(result, sec, 1):
            result += 1
            cy, cx = dq[len(dq)-1]

            if move(cy, cx, curD):
                return result
        if i[1] == 'D':
            curD = (curD + 1) % 4
        else:
            curD = (curD + 3) % 4

    cy, cx = dq[len(dq) - 1]
    result += 1
    while not move(cy,cx,curD):
        result += 1
        cy, cx = dq[len(dq) - 1]

    return result

print(solve())


from useful_packages3 import enumerated_list

from useful_packages3 import list_index_number
from useful_packages3 import name_insert
from useful_packages3 import delete_function
from useful_packages3 import file_closer
from useful_packages3 import file_opener
from useful_packages3 import ady_getter
import os
from useful_packages3 import phone_number_insert
from useful_packages3 import list_index_number2

products_list = []

couries_list = []
# ```txt
# LOAD products list from products.txt
file_opener("products.txt", products_list)
# LOAD couriers list from couriers.txt
file_opener("couries.txt", couries_list)

# CREATE orders list of dictionaries
orders_list = [{
   "customer_name": "John",
   "customer_address": "Unit 1, 11 Main Street, LONDON, WH1 1ER",
   "customer_phone": "0789887331",
   "Courie": 7,
   "status": "preparing"
},
{
   "customer_name": "Erica",
   "customer_address": "Unit 2, 12 Main Street, LONDON, WH2 2ER",
   "customer_phone": "0789887332",
   "Courie": 6,
   "status": "starting"
},
{
   "customer_name": "Corrin",
   "customer_address": "Unit 3, 13 Main Street, LONDON, WH3 3ER",
   "customer_phone": "0789887333",
   "Courie": 5,
   "status": "preparing"
},
{
   "customer_name": "Ahmed",
   "customer_address": "Unit 4, 14 Main Street, LONDON, WH4 4ER",
   "customer_phone": "0789887334",
   "Courie": 4,
   "status": "completed"
},
{
   "customer_name": "Eugene",
   "customer_address": "Unit 5, 15 Main Street, LONDON, WH5 5ER",
   "customer_phone": "0789887335",
   "Courie": 7,
   "status": "preparing"}]

# CREATE order status list
menu_options = [' Save & Exit app', 'Products Menu', 'Couriers Menu','Orders Menu']
order_status_list = ['starting','preparing','completed']

# GET user input for main menu option
user_input = ''
cafe_open = True
while  cafe_open == True and user_input not in ['0','1','2','3']:
    os.system('clear')
    enumerated_list(menu_options)

    user_input = input('please insert a number from 0,1,2,3: ')
    print('')

    if user_input == '0':
         #SAVE products list to products.txt
         #SAVE couriers list to couriers.txt
         #EXIT app
        file_closer("products.txt", products_list)
        file_closer("couries.txt", couries_list)
        cafe_open = False

    # ELSE IF user input is 1:
    elif user_input == '1':

        print('welcome to the products menu')
        open_menu = True
        #PRINT product menu options
        menu_options1 = ['Return to main menu','Print product list','Create a new product','Update existing product','Delete existing product']

        user_input1 = ''

        #GET user input for product menu option
        while  open_menu == True and user_input1 not in ['0','1','2','3','4']:
            enumerated_list(menu_options1)
            user_input1 = input('please insert a choice from 0,1,2,3,4:  ')

            #IF user inputs 0:

            if user_input1 == '0':
               #RETURN to main menu
                print('Going back to Main menu')
                open_menu = False
                user_input = ''
            #     ELSE IF user input is 1:

            elif user_input1 == '1':

                 # PRINT products list
                enumerated_list(products_list)

                user_input1 = ''

            elif user_input1 == '2':
                os.system('clear')

                new_product = '0'

                #GET user input for product name

                new_product = name_insert(new_product)

                #APPEND product name to products list

                products_list.append(new_product)
                enumerated_list(products_list)

                user_input1 = ''

            elif user_input1 == '3':
                #STRETCH GOAL - UPDATE existing produc

                os.system('clear')

                #PRINT product names with its index value
                enumerated_list(products_list)
                #GET user input for product index value
                product_index  = ''
                #GET user input for new product name
                switch_product = '0'

                product_index = list_index_number(product_index,products_list)

                switch_product = name_insert(switch_product)

                #UPDATE product name at index in products list
                products_list[product_index] = switch_product
                enumerated_list(products_list)
                user_input = ''

                user_input1 = ''

            elif user_input1 == '4':
                os.system('clear')
                delete_product = ''
                #STRETCH GOAL - DELETE product

                #PRINT products list
                enumerated_list(products_list)

               #GET user input for product index value
                delete_product = list_index_number(delete_product,products_list)

                #DELETE product at index in products list
                delete_function(delete_product,products_list)

                enumerated_list(products_list)
                print(' ')
                print(' ')

                user_input1 = ''

    elif user_input == '2':

        print('welcome to couries menu')

        #   open_couries_menu = True
        open_couries_menu = True

        #PRINT couries menu options
        menu_options2 = ['Return to main menu','Print courie list','Create a new courie','Update existing courie','Delete existing courie']

        user_input2 = ''

        #GET user input for product menu option
        while  open_couries_menu == True and user_input2 not in ['0','1','2','3','4']:
            enumerated_list(menu_options2)
            user_input2 = input('please insert a choice from 0,1,2,3,4:  ')

            if user_input2 == '0' :

               #RETURN to main menu
               print('returning to main menu')

               user_input = ''

               open_couries_menu = False

            elif user_input2 == '1':
                #PRINT couriers list
                enumerated_list(couries_list)

                print(' ')
                print(' ')

                user_input2 = ''

            elif user_input2 == '2':
                 os.system('clear')
                 new_courie = '0'

                #GET user input for courie name

                 new_courie = name_insert(new_courie)

                #APPEND courie name to couries list

                 couries_list.append(new_courie)
                 enumerated_list(couries_list)

                 print(' ')
                 print(' ')

                 user_input2 = ''

            elif user_input2 == '3':
                os.system('clear')
                switch_courie_number = ''
                switch_courie = '0'

                #STRETCH GOAL - UPDATE existing couries

                #PRINT couries names with its index value
                enumerated_list(couries_list)
               #GET user input for couries index value
                switch_courie_number = list_index_number(switch_courie_number,couries_list)

               #GET user input for new courie name
                switch_courie = name_insert(switch_courie)
               #UPDATE couries name at index in couries list
                couries_list[switch_courie_number] = switch_courie

                enumerated_list(couries_list)

                print(' ')
                print(' ')
                user_input2 = ''

            elif user_input2 == '4':
                os.system('clear')
                delete_courie_number = ''
                #STRETCH GOAL - DELETE courie

                #PRINT products courie
                enumerated_list(couries_list)

               #GET user input for product index value
                delete_courie_number = list_index_number(delete_courie_number,couries_list)

                #DELETE product at index in products list
                delete_function(delete_courie_number,couries_list)

                enumerated_list(couries_list)

                print(' ')
                print(' ')

                user_input2 = ''

    # ELSE IF user input is 3:
    elif user_input == '3':

        print('welcome to orders menue')

        open_orders_menu = True
        menu_options3 = ['Main Menu',' View Orders Dictionary','New order Input',' Update existing order status','update existing order details',' delete product']

        user_input3 = ''

        while  open_orders_menu == True and user_input3 not in ['0','1','2','3','4','5']:
            enumerated_list(menu_options3)
            user_input3 = input('please insert a choice from 0,1,2,3,4,5:  ')

            # IF user input is 0:
            if user_input3 == '0' :

               #RETURN to main menu
               print('returning to main menu')

               user_input = ''

               open_couries_menu = False

             # ELSE IF user input is 1:
            elif user_input3 == '1':
                 #  PRINT orders dictionary
                enumerated_list(orders_list)

                print(' ')
                print(' ')

                user_input3 = ''

            # ELSE IF user input is 2:
            elif user_input3 == '2':
               os.system('clear')
               my_dict = {"customer_name": "0","customer_address": "0","customer_phone": "0","Courie": '' ,"status": "0"}

            # Customer_name
               while my_dict["customer_name"] == '0':
                 my_dict["customer_name"] = name_insert(my_dict["customer_name"])
                 if my_dict["customer_name"].replace(' ','').isalpha() == False:
                      my_dict["customer_name"] = '0'
                 else:
                     break

             # Customer address

               while my_dict["customer_address"] == '0':
                    my_dict["customer_address"] = ady_getter(my_dict["customer_address"])
                    if my_dict["customer_address"] == '£':
                        print("Please insert a valid input for the address.")
                        my_dict["customer_address"] = '0'
                    else:
                        print('thank you address inserted correctly')
                        break

            #Customer Phone Number
               while my_dict["customer_phone"] == '0':
                my_dict["customer_phone"] = phone_number_insert(my_dict["customer_phone"])
                if my_dict["customer_phone"].replace(' ','').isdigit() == False:
                    my_dict["customer_phone"] = '0'
                else:
                    break

             #GET user input for courier index to select courier
               print('now please choose a couries from the list below by typing in a index number')
               #PRINT couriers list with index value for each courier
               enumerated_list(couries_list)
                #GET user input for courier index to select courier
               cory_num = ''
               cory_num = list_index_number(cory_num,couries_list)
               my_dict['Courie'] = couries_list[cory_num]

               #SET order status to be 'PREPARING'
               my_dict["status"] = "preparing"
                #APPEND order to orders list
               orders_list.append(my_dict)
               enumerated_list(orders_list)
               user_input3 = ''

            # ELSE IF user input is 3:
            elif user_input3 == '3':
                os.system('clear')

                 #     PRINT orders list with its index values

                enumerated_list(orders_list)
                switch_number = ''
                #     GET user input for order index value
                switch_number = list_index_number(switch_number,orders_list)

                #PRINT order status list with index values
                enumerated_list(order_status_list)
                change_status_number = ''
                print('please select an approprite number that macthes the status you wish to change your order to')
                # GET user input for order status index value
                change_status_number = list_index_number(change_status_number,order_status_list)
                 #UPDATE status for order
                orders_list[switch_number]['status'] = order_status_list[change_status_number]
                enumerated_list(orders_list)

                user_input3 = ''

            elif user_input3 == '4':
                os.system('clear')

                enumerated_list(orders_list)

                change_number = ''

                print('please insert the number of the order u wish to change')

                change_number = list_index_number(change_number,orders_list)

                my_dict2 = {"customer_name": "0","customer_address": "0","customer_phone": "0","courie": ""}

                print(" ")

                #customer name
                while my_dict2["customer_name"] == '0':
                    my_dict2["customer_name"] = name_insert(my_dict2["customer_name"])
                if my_dict2["customer_name"].strip() == '' :
                    print('no name was inserted, name wont be changed')
                elif my_dict2["customer_name"].replace(' ','').isalpha() == True:
                    orders_list[change_number]["customer_name"] = my_dict2["customer_name"]
                else:
                    print('insert a valid input or leaveit empty ')

                # customer address
                while my_dict2["customer_address"] == "0":
                    my_dict2["customer_address"] = ady_getter(my_dict2["customer_address"])

                if my_dict2["customer_address"] == "£":
                    print('address wont be changed')
                else:
                    print('address was changed')
                    orders_list[change_number]["customer_address"] = my_dict2["customer_address"]

                # customer phone
                while my_dict2["customer_phone"] == '0':
                    my_dict2["customer_phone"] = phone_number_insert(my_dict2["customer_phone"])
                    if my_dict2["customer_phone"].replace(' ','') != '' and my_dict2["customer_phone"].replace(' ','').isdigit() == False:
                        print("please leave the field empty or insert 11 digits phone number")
                        my_dict2["customer_phone"] = '0'

                    elif my_dict2["customer_phone"].replace(' ','').isdigit() == True:
                        orders_list[change_number]["customer_phone"] = my_dict2["customer_phone"]
                    else:
                        print("phone number won't be changed")
                        break

                #courie
                enumerated_list(couries_list)
                cory_switch = "£"

                while cory_switch == "£":
                    cory_switch = list_index_number2(cory_switch,couries_list)
                    if type(cory_switch) != int:
                        print('courie wont be changed')
                        break
                    else:
                        orders_list[change_number]["Courie"] = cory_switch

                enumerated_list(orders_list)
                print("")
                user_input3 = ''

            elif user_input3 == '5':
                os.system('clear')
                #PRINT orders list
                enumerated_list(orders_list)
                #GET user input for order index value
                del_choice = ''

                del_choice = list_index_number(del_choice, orders_list)

                 #DELETE order at index in order list
                orders_list.pop(del_choice)

                enumerated_list(orders_list)

                print('')

                user_input3 = ''


grade2gpa: Dict[str, float] = { 'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F': 0.0 }
students: int = int(input())
# STATE: students * [6:(⊤, [-inf, inf], ⊤), 7:(≠0, [-inf, inf], ⊤), 7.1 * 10:(⊤, [-inf, inf], ⊤)]
for _ in range(students):
    name: str = input()
    grades: int = int(input())
    gpa: float = 0.0
    for _ in range(grades):
        grade: str = input()
        gpa += grade2gpa[grade]
    result: float = gpa / grades
    print(result)


# -*- coding: utf-8 -*-
"""
This module contains the abstract base class `Piece` and other topological structures that play the roles of containers
or layouts in LegoNet. These classes are useful for building complicated non-sequential models, and will enable users to
build these non-sequential models in the same way as how they build sequential ones(simply calling `add` for times).

An alternative to using these topological structures when building non-sequential models is to directly use layers
in functional style(e.g. ``FullyConnected(128)(input_tensor)``). This method is even more powerful and enables users
to build more complicated models, but requires more careful design and coding.

"""

import abc

import tensorflow as tf

class Piece(object):
    """Abstract base class for all elements in graph.

    Attributes:
        name: The name of this `Piece`, might be used for visualization. Use default if `None` is passed.
        reuse: Indicates whether or not this `Piece` is in reuse mode.

    """

    # TODO: add operators: +, &

    __metaclass__ = abc.ABCMeta

    def __init__(self, name=None):
        """Initializes a new `Piece` instance.

        Since `Piece` is a abstract class, this method should only be called by
        its derived classes.

        Args:
            name: Name of this `Piece`. Use default name if `None` is passed.

        """

        self.name = name
        self.reuse = False

    @abc.abstractmethod
    def __call__(self, flow):
        """Constructs this `Piece` in a `TensorFlow` graph.

        Args:
            flow: The input `Tensor` to this `Piece`.

        Returns:
            The output `Tensor` of this `Piece`.

        """

        pass

class Plate(Piece):
    """Abstract base class for all kinds of layouts.

    Plate is a special kind of `Piece`, which itself contains other `Piece`s (including other `Plate` s). Different
    `Plate` s might use different strategies for how its inner `Piece` s are connected, but looking from the outside,
    `Plate` acts totally the same as other `Piece` s. They are very useful for constructing complicated non-sequential
    neural network models.

    Attributes:
        child_pieces: a list of `Piece` s that are contained within a `Plate` instance.

    """

    def __init__(self, name=None):
        """Initializes a new `Plate` instance.

        Args:
            name: Name of this `Plate`. Use default name if `None` is passed.
        """

        super(Plate, self).__init__(name)
        self.child_pieces = []

    def add(self, piece):
        """Adds a `Piece` to this `Plate`.

        Args:
            piece: A `Piece` object.

        Returns:
            None

        """

        self.child_pieces.append(piece)

class Sequential(Plate):
    """A `Plate` whose inner `Piece` s are in a sequential layout."""

    def __init__(self, name=None):
        """Initializes a new `Sequential` instance.

        Args:
            name: Name of this `Piece`. Use default name if `None` is passed.

        """

        super(Sequential, self).__init__(name)

        self.child_pieces = []

    def __call__(self, flow=None):
        """Constructs the Sequential and its inner `Piece` s.

        Args:
            flow: Input `Tensor` object. (Default value = None)

        Returns:
            Output of this `Sequential`.

        """

        with tf.variable_op_scope([flow], self.name, 'Sequential', reuse=self.reuse):
            if not self.reuse:
                self.reuse = True
            for piece in self.child_pieces:
                flow = piece(flow)

        return flow

class Parallel(Plate):
    """A `Plate` whose inner pieces are in a parallel layout."""

    def __init__(self, name=None, mode='concat', along_dim=None):
        """Initializes a new instance of Parallel.

        Args:
            name: Name of this `Piece`. Use default name if `None` is passed.
            mode: The way to merge paralleled `Piece` s. Now supports "concat", "sum", "mean".
            along_dim: The dimension along which the merging operation will be done. Only take effect in "concat"
        mode.

        """

        if mode == 'concat' and along_dim is None:
            raise ValueError('Must specify along_dim for concat mode.')
        super(Parallel, self).__init__(name)

        self.child_pieces = []
        if mode not in ['concat', 'sum', 'mean']:
            raise ValueError('Unknown mode: {0}'.format(mode))
        self.mode = mode
        self.along_dim = along_dim

    def __call__(self, flow=None):
        """Constructs the Sequential and its inner pieces.

        Args:
            flow: Input `Tensor` object. (Default value = None)

        Returns:
            Output of this `Parallel`.

        """

        # build inner pieces.
        with tf.variable_op_scope([], self.name, 'Parallel', reuse=self.reuse):
            if not self.reuse:
                self.reuse = True

            outputs = []
            for i, piece in enumerate(self.child_pieces):
                outputs.append(piece(flow))

            if self.mode == 'concat':
                return tf.concat(self.along_dim, outputs)
            elif self.mode == 'mean':
                return tf.add_n(outputs) / len(self.child_pieces)
            elif self.mode == 'sum':
                return tf.add_n(outputs)


#############################################################################################
# Virtual Environment (Sanal ortam) ve Package Managemen (Paket Yönetimi)
#############################################################################################

# Sanal ortamların listelenmesi:
# conda env list

# Sanal ortam oluşturma:
# conda create -n myevn

# Sanal ortamı aktif etme:
# conda activate myevn

# Yüklü paketlerin listelenmesi:
# conda list

# Paket yükleme:
# conda install numpy

# Paket silme:
# conda remove package_name

# Belirli bir versiyona göre paket yükleme:
# conda install numpy=1.20.1

# Paket yükseltme:
# conda upgrade numpy

# tüm paketlerin yükseltilmesi:
# conda upgrade -all

# pip : (pypi) Paket Yönetim Aracı

# Paket yükleme
# pip install package_name

# Paket yükleme versiyona göre
# pip install package_name== 1.20.1

# var olan bir environment ' ı oluşturma
# conda env export > environment.yaml

students = ["John", "Mark", "Venessa", "Mariam"]

students_no = ["John", "Venessa"]

[student.lower() if student in students_no else student.upper() for student in students]

dictionary = {'a': 1,
              'b': 2,
              'c': 3,
              'd': 4}

dictionary.keys()
dictionary.values()
dictionary.items()

{i**2 for i in dictionary.values()}


import osqp
import numpy as np
import scipy
from scipy import sparse

# NOTE: this code does not work due to improper modeling of torques in contact with the robot arm

# To get this code working without contact torques, we need to extend the CBF formalism to accomodate
# systems where the control input is two derivatives away from the state variable. We use
# exponential barrier functions from this CBF review paper: https://arxiv.org/abs/1903.11199

# This code uses OSQP to solve a quadratic program to compute the safe torque and was based off
# of an example script in the docs: https://osqp.org/docs/examples/least-squares.html
# For ease of debugging, I converted all the sparse linear algebra operations into normal explicit
# numpy operations. We are solving a problem of dimensionality-14, which, for these solvers, is pretty
# small, but in case you need a speed up, you can use the original script as a guide of where
# to re-substitute the scipy.linalg.sparse operations.

# Generate problem data
# sp.random.seed(1)
# m = 30
# n = 20
# Ad = sparse.random(m, n, density=0.7, format='csc')
# b = np.random.randn(m)

# problem setup
# OSQP data

class JointLimitCBFSolver():

    def __init__(self, lower_limits, upper_limits, gamma=1.0):
        self.ll = lower_limits
        self.ul = upper_limits # (both of shape (7,)
        self.gamma = gamma  # for proportional class K function (see Ames above)
        self.prob = osqp.OSQP()
        self.init_problem = False

    def compute_safe_osc_output(self, q, qd, qdd, g, u_pi):
        f = np.concatenate([qd, qdd])

        # this is a slight variant, since joint space are 'generalized' coordinates for the system
        #
        g = np.vstack([np.zeros((7, 6)), g])

        # compute CBF h(x) and \partial h / \partial x
        h = -(q - self.ll) * (q - self.ul)
        dh_dx = np.diag(-(2 * q - (self.ul + self.ll)))
        # compute lie derivatives (but since this is R^n, they are directional derivs)
        Lf_h = np.dot(dh_dx, f)  # since the velocity of the system is f (dynamics)
        Lg_h = np.dot(dh_dx, g)  # affine control transformation

        # in addition to these, we need to compute the following terms
        # Lf^2_h (lie derivative of h twice in the direction of f)
        # LgLf (lie derivative of h first in direction of f then in direction of g)
        # Here are the expressions written out in basic calculus:

        # Lf^2_h
        # \sum_j f_j (\sum_i \frac{del f_i}{del x_j} x \frac{del h}{\del x_i} + f_i \frac{del h}{x_j x_i}
        # we have {del h}{del x_i} in dh_dx. we need{del f_i}{del x_j} (derivative of ith coord of f with respect to joint variable j}{
        # LgLf_h
        # \sum_j g_j (same summation mess indexed by i for Lf^2_h)

        P = scipy.linalg.block_diag(np.zeros((6, 6)), np.eye(6))
        c = np.zeros(6 + 6)
        A = np.vstack([
            np.hstack([np.eye(6), -np.eye(6)]),
            np.hstack([Lg_h, np.zeros((14, 6))])])
        l = np.hstack([u_pi, -self.gamma * h - Lf_h])
        u = np.hstack([u_pi, np.inf * np.ones(7)])
        # then, modify this constraint here to respect the exponential ZBF:
        # currently, we respect the constraint Lf_h + Lg_h u + \gamma h(x) \geq 0
        # now we need to replace that with Lf^2_h + LfLg_h u + (gamma, gamma) \dot (h(x), Lfh) \geq 0.

        # Create an OSQP object
        prob = osqp.OSQP()

        # Setup workspace
        prob.setup(P, c, A, l, u)

        # Solve problem
        return prob.solve()


import sys
import pandas as pd

# read content and return vocabulary of top
# words and corresponding counts
def load_vocabulary(content, size):

    # create word counts
    countMap = {}
    for sub in content:
        for w in content[sub]:
            if w in countMap:
                countMap[w] = countMap[w] + 1
            else:
                countMap[w] = 1

    # create corresponding count and word lists
    counts = []
    vocab = []
    for word in countMap:
        counts.append(countMap[word])
        vocab.append(word)

    # create a DataFrame
    count_data = {'count': counts, 'word': vocab}
    count_table = pd.DataFrame(count_data,columns=['count','word'])

    # sort DataFrame to preserve list correspondence
    count_table = count_table.sort_values('count',ascending=False)

    counts_sort = list(count_table['count'])
    vocab_sort = list(count_table['word'])

    # limit counts and vocab to size
    counts_sized = counts_sort[0:size]
    vocab_sized = vocab_sort[0:size]

    # create final data
    final_counts = pd.Series(counts_sized,vocab_sized)

    return {'counts': counts_sized, 'words': vocab_sized}

def vocab_intersect(words, vocab):
    count = [0] * len(vocab)
    for w in words:
        try:
            select = vocab.index(w)
            count[select] = count[select] + 1
        except ValueError:
            True

    return count

# count words in vocab accross subreddits and create
# count data
def load_count_set(content, vocab):
    data = {}
    labels = []
    for sub in content:
        count = vocab_intersect(content[sub],vocab)
        data[sub] = count
        labels.append(sub)
    count_set = pd.DataFrame(data,columns=labels)
    return count_set

def normalize(counts):
    means = counts.mean(axis=1)
    ranges = counts.max(axis=1) - counts.min(axis=1)
    features = counts.sub(means,axis=0).div(ranges,axis=0)
    return features

print ('generating dataset from content...')

import pickle

# load downloaded words
file = open('data/word.txt','rb')
all_words = pickle.load(file)

vocab_data = load_vocabulary(all_words, int(sys.argv[1]))

vocab = pd.DataFrame(vocab_data,columns=['words','counts'])
vocab.to_csv('data/vocab.csv',index=False)

count_set = load_count_set(all_words,vocab_data['words'])
count_set.to_csv('data/counts.csv',index=False)

feature_set = normalize(count_set)
feature_set.to_csv('data/data.csv',index=False)

print ('done')


import glob
from shutil import copyfile
from tqdm import tqdm

img_path = "/dataset.local/all/hangd/src_code_3/Pytorch-UNet/dataset/imgs/*"
dest_img_path = "/dataset.local/all/hangd/dynamic_data/one32rd/imgs"
dest_mask_path = "/dataset.local/all/hangd/dynamic_data/one32rd/masks"

count = 0
num_first_trial_files = len(glob.glob(img_path))//32

for img in tqdm(glob.glob(img_path)):
    # print(img)
    count += 1
    copyfile(img, dest_img_path+img[img.rfind("/"):])
    mask_path = img.replace("/imgs/", "/masks/")
    copyfile(mask_path, dest_mask_path+mask_path[mask_path.rfind("/"):])
    if count == num_first_trial_files:
        break


'''
resize 256*256

'''
import cv2
import os

train_path = './data'

list1=[]
for file in os.listdir(train_path):
    class_image_path = os.listdir(train_path + "/" + file)
    # print(file)
    image_out_path = train_path + '/' + file
    for files in class_image_path:
        # print(image_input_dir + '/' + file + '/' + files)
        image_path = train_path + '/' + file + '/' + files
        img = cv2.imread(image_path)
        dst_size = (256, 256)
        img_resize = cv2.resize(img, dst_size, interpolation = cv2.INTER_AREA)
        cv2.imwrite(image_path, img_resize)
        print(img_resize.shape)

# for files in os.listdir(train_path):
#     train_path2 = os.listdir(train_path + "/" + files)
#     for file in train_path2:
#         train_path = train_path + '/' + file + '/' + files
#         print(train_path+ '/n')
#         img = cv2.imread(train_path)
#         dst_size = (256, 256)
#         img_resize = cv2.resize(img, dst_size, interpolation = cv2.INTER_AREA)
#         cv2.imwrite(train_path, img_resize)
#         print(img_resize.shape)


"""Add challenge resource

Revision ID: 5c1825290fc4
Revises: c63d06374f79
Create Date: 2020-12-15 17:31:28.562671

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = '5c1825290fc4'
down_revision = 'c63d06374f79'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('challenge',
    sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
    sa.Column('title', sa.String(length=255), nullable=False),
    sa.Column('description', sa.String(), nullable=True),
    sa.Column('end_date', sa.DateTime(), nullable=False),
    sa.Column('active', sa.Boolean(), nullable=False),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('title')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('challenge')
    # ### end Alembic commands ###


from app_data import EventHandler, PluginLoader, app_logger, Config

class App:
    """Main App class, this coordinates the other features of the app."""
    event_handler: EventHandler
    plugin_loader: PluginLoader
    default_plugin_path: str = "plugins"
    default_config_path: str = "application.ini"

    def __init__(self, plugin_path: str = None, config_path: str = None):
        self.event_handler = EventHandler()
        self.plugin_loader = PluginLoader(plugin_path or self.default_plugin_path)
        self.config = Config(config_path or self.default_config_path)
        self.running = False

    def update(self):
        self.event_handler.update()
        self.plugin_loader.update()

    def teardown(self):
        app_logger.logger.info("App teardown")
        self.plugin_loader.teardown()
        self.event_handler.teardown()
        quit()

    def run(self):
        app_logger.logger.info("App run")
        self.plugin_loader.load()
        self.running = True
        while self.running:
            self.update()
        self.teardown()

if __name__ == "__main__":
    app = App()
    app.run()


#!/usr/bin/env python3

"""
This script contains a proof-of-concept of how streams (and their consumers) could be added and removed dynamically.
It has three main components:

- The code outside of the classes represents the tool, like the :mod:`tools.consume` tool.
  It has two purposes: it instantiates everything, and it assigns tasks to the :class:`TaskManager`.
  In reality, the code will be slightly more complex since, like the :mod:`tools.consume` tool, the outer code will be split into two processes: `stream_process` and a `consume_process`.

- The :class:`TaskManager` represents a `SplitConsumer`.
  While running, it continuously monitors its assigned tasks.
  If it has a task it has not seen before, it sets it running.
  If any ongoing task is no longer assigned to it, the class instructs the task to stop and stores its output.
  Once it has no more tasks to perform, the :class:`TaskManager` returns each task's output.

- The :class:`Task` represents a `Consumer`.
  The :class:`Task` performs its job until the :class:`TaskManager` instructs it to stop, at which point it returns an output.

The following communication takes place:

- Between the outer code and the :class:`TaskManager`.
  The two share a list of tasks for the input (from the outer code to the :class:`TaskManager`) and a dictionary for the input (from the :class:`TaskManager` to the outer code).
  The latter already exists in the :mod:`consume` tool, while the former would have to be added separately.
  The final version would also have to add a queue of tweets to the communication.
- Between the :class:`TaskManager` and the :class:`Task`.
  The :class:`TaskManager` instructs the :class:`Task` to stop, and when it does, the :class:`TaskManager` gathers its output.

Of course, the outer code does not have to assign the tasks to the :class:`TaskManager`.
The :class:`TaskManager` could load them itself (such as by loading the streams from a database).
The outer code assigns the tasks only to be more interactive.

The main difference, then, lies in the :class:`TaskManager`'s :func:`TaskManager.run_tasks` function.
Instead of running (using `asyncio.gather`) all tasks at once, it sets them running using `asyncio.ensure_future` and 'tracks' them (in the `ongoing` variable).
The :class:`TaskManager` only gathers the tasks' outputs (using `asyncio.gather`) when it stops them.
Here too, the logic to stop tasks can be different; the :class:`TaskManager` could check with the database whether they are still relevant and stop them otherwise.
"""

import asyncio
from multiprocessing import Process, Manager
from multiprocessing.managers import BaseManager
import signal
import time

loop = asyncio.get_event_loop()

class TaskManager():

    def __init__(self):
        """
        Initialize the tasks application.
        """

        self.running = False

    def run(self, tasks, outputs):
        """
        Run the tasks from the given shared list.

        :param tasks: A list of tasks shared by all processes.
        :type tasks: :class:`multiprocessing.managers.ListProxy`
        :param outputs: A list of outputs shared by all processes.
        :type outputs: :class:`multiprocessing.managers.DictProxy`
        """

        async def run_tasks():
            ongoing = { } # the ongoing tasks, storing the tuples of the asyncio tasks and the :class:`Task` class.
            while tasks:
                # start the new tasks
                for task in tasks:
                    if task.ID not in ongoing and task.ID not in outputs:
                        _task = asyncio.ensure_future(task.run())
                        ongoing[task.ID] = (_task, task)

                # gather the results from the stopped tasks
                for task_id, (asyncio_task, task) in ongoing.items():
                    if task_id not in outputs and not any( task_id == _task.ID for _task in tasks ):
                        task.stop()
                        outputs[task_id] = (await asyncio.gather(asyncio_task))[0]
                        print(f"Task { task_id } has stopped with counter { outputs[task_id] }")

                await asyncio.sleep(0.1)

            # gather the results from any remaining tasks
            for task_id, (asyncio_task, task) in ongoing.items():
                if task_id not in outputs and not any( task_id == _task.ID for _task in tasks ):
                    task.stop()
                    outputs[task_id] = (await asyncio.gather(asyncio_task))[0]
                    print(f"Task { task_id } has stopped with counter { outputs[task_id] }")

        def sigint_handler(signal, frame):
            """
            Stop all remaining tasks when the user presses CTRL+C.
            Clearing the remaining tasks also means that the `run_tasks` function will stop processing any tasks.
            For a demo, try pressing CTRL+C before the third task starts.
            """
            while len(tasks):
                tasks.pop()

        signal.signal(signal.SIGINT, sigint_handler)

        self.running = True
        loop.run_until_complete(run_tasks())

    def stop(self):
        """
        Instruct the task manager to stop running.
        """

        self.running = False

class Task():

    def __init__(self, ID):
        """
        Create a task.

        :param ID: The task ID.
                   Tasks need a unique ID because when they are loaded from the shared list into memory, their ID changes.
        :type ID: int
        """

        self.ID = ID
        self.running = False

    async def run(self):
        """
        Set the task running.

        :return: The ID of times the function printed something.
        :rtype: int
        """

        print(f"Task { self.ID } starting")
        self.running = True
        counter = 0 # how many full seconds have elapsed
        progress = 0 # how long the task has run for (seconds)

        while self.running:
            progress += 0.1
            if int(round(progress, 2)) > counter:
                print(f"Task { self.ID } running", flush=True)
                counter = int(round(progress, 2))
            await asyncio.sleep(0.1)

        print(f"Task { self.ID } stopping after { round(progress, 2) }s")
        return counter

    def stop(self):
        """
        Instruct the task to stop running.
        """

        self.running = False

# do nothing (here) when the user presses CTRL+C as the task manager will stop on its own
def sigint_handler(signal, frame):
    return
signal.signal(signal.SIGINT, sigint_handler)

# set up the shared inputs and outputs
resource_manager = Manager()
tasks, outputs = resource_manager.list(), resource_manager.dict()

# start the task manager
manager = TaskManager()
task_manager = Process(target=manager.run, args=(tasks, outputs))
task_manager.start()

# start the first task
tasks.append(Task(1))

# start a second task
time.sleep(2)
tasks.append(Task(2))

# stop the first task and start a third
time.sleep(3)
if len(tasks):
    tasks.pop(0)
tasks.append(Task(3))

task_manager.join()
print(outputs)


from typing import Dict, List

def part1(lines: List[int]):
    current = 0

    one = 0
    three = 1

    while len(lines) > 0:
        allowed = [x for x in lines if current + 3 >= x and current < x]
        use = min(allowed)
        if use - current == 1:
            one += 1
        elif use - current == 3:
            three += 1

        current = use
        lines = [x for x in lines if x != current]

    print(one, three, one * three)

total_arrangements: Dict[int, int] = {}

def count_arrangements(lines: List[int], c: int) -> int:
    if c in total_arrangements.keys():
        return total_arrangements[c]

    valid_next = [x for x in lines if c + 3 >= x and c < x]

    total = 0
    for x in valid_next:
        x_total = count_arrangements(lines, x)
        total_arrangements[x] = x_total
        total += x_total

    return total

def part2(lines: List[int]):
    target = max(lines)
    total_arrangements[target] = 1

    arrangements = count_arrangements(lines, 0)
    print(arrangements)

def main():
    f = open('inputs/day10.txt')
    lines = [int(x.strip()) for x in f.readlines()]

    part1(lines)
    part2(lines)

if __name__ == "__main__":
    main()


from typing import List
from project.baked_food.baked_food import BakedFood
from project.baked_food.bread import Bread
from project.baked_food.cake import Cake
from project.drink.drink import Drink
from project.drink.tea import Tea
from project.drink.water import Water
from project.table.inside_table import InsideTable
from project.table.outside_table import OutsideTable
from project.table.table import Table

class Bakery:
	def __init__(self, name: str):
		self.name = name
		self.food_menu: List[BakedFood] = []
		self.drinks_menu: List[Drink] = []
		self.tables_repository: List[Table] = []
		self.__total_income = 0
		self.total_income = 0

	@property
	def valid_food_types(self):
		return {"Bread": Bread, "Cake": Cake}

	@property
	def valid_drink_types(self):
		return {"Tea": Tea, "Water": Water}

	@property
	def valid_table_types(self):
		return {"InsideTable": InsideTable, "OutsideTable": OutsideTable}

	@property
	def name(self):
		return self.__name

	@name.setter
	def name(self, value):
		if value.strip() == '':
			raise ValueError("Name cannot be empty string or white space!")
		self.__name = value

	@staticmethod
	def __get_entity_from_name(entities, entity_name):
		for entity in entities:
			if entity.name == entity_name:
				return entity

	def __get_table_from_number(self, table_number):
		for table in self.tables_repository:
			if table.table_number == table_number:
				return table

	def __process_order(self, table, type_of_order, *order):

		items_that_are_not_available = []
		result = [f"Table {table.table_number} ordered:"]

		for item_name in order:

			if type_of_order == 'food':
				item = self.__get_entity_from_name(self.food_menu, item_name)
			else:
				item = self.__get_entity_from_name(self.drinks_menu, item_name)

			if not item:
				items_that_are_not_available.append(item_name)

			else:

				if type_of_order == 'food':
					table.order_food(item)
				else:
					table.order_drink(item)

				result.append(str(item))

		result.append(f"{self.name} does not have in the menu:")
		for item in items_that_are_not_available:
			result.append(item)

		return '\n'.join(result)

	# This is where Judge required methods start
	#
	def add_food(self, food_type: str, name: str, price: float):
		if self.__get_entity_from_name(self.food_menu, name):
			raise Exception(f"{food_type} {name} is already in the menu!")

		if food_type not in self.valid_food_types:
			return

		food = self.valid_food_types[food_type](name, price)
		self.food_menu.append(food)

		return f"Added {name} ({food_type}) to the food menu"

	def add_drink(self, drink_type: str, name: str, portion: float, brand: str):
		if self.__get_entity_from_name(self.drinks_menu, name):
			raise Exception(f"{drink_type} {name} is already in the menu!")

		if drink_type not in self.valid_drink_types:
			return

		drink = self.valid_drink_types[drink_type](name, portion, brand)
		self.drinks_menu.append(drink)

		return f"Added {name} ({brand}) to the drink menu"

	def add_table(self, table_type: str, table_number: int, capacity: int):
		if self.__get_table_from_number(table_number):
			raise Exception(f"Table {table_number} is already in the bakery!")

		if table_type not in self.valid_table_types:
			return

		table = self.valid_table_types[table_type](table_number, capacity)
		self.tables_repository.append(table)

		return f"Added table number {table_number} in the bakery"

	def reserve_table(self, number_of_people: int):
		for table in self.tables_repository:

			if table.capacity >= number_of_people and not table.is_reserved:
				table.reserve(number_of_people)

				return f"Table {table.table_number} has been reserved for {number_of_people} people"

		return f"No available table for {number_of_people} people"

	def order_food(self, table_number: int, *food_order):
		table = self.__get_table_from_number(table_number)

		if not table:
			return f"Could not find table {table_number}"

		return self.__process_order(table, 'food', *food_order)

	def order_drink(self, table_number: int, *drinks_order):
		table = self.__get_table_from_number(table_number)

		if not table:
			return f"Could not find table {table_number}"

		return self.__process_order(table, 'drink', *drinks_order)

	def leave_table(self, table_number: int):
		table = self.__get_table_from_number(table_number)
		if table:
			table_bill = table.get_bill()
			self.__total_income += table_bill
			table.clear()

			return f"Table: {table_number}\nBill: {table_bill:.2f}"

	def get_free_tables_info(self):
		result = []
		for table in self.tables_repository:
			free = table.free_table_info()
			if free:
				result.append(free)
		return '\n'.join(result)
		# return '\n'.join(t.free_table_info() for t in self.tables_repository)

	def get_total_income(self):
		return f"Total income: {self.__total_income:.2f}lv"


def find_garbage_match(entry, i):
    while i < len(entry):
        item = entry[i]
        if item == '!':
            i += 1
        elif item == '>':
            return i
        i += 1

def get_score(entry):
    i = 0
    total = 0
    cur_g = 0
    while i < len(entry):
        item = entry[i]
        if item == '<':
            i = find_garbage_match(entry, i)
        elif item == '!':
            i += 1
        elif item == '{':
            cur_g += 1
        elif item == '}':
            total += cur_g
            cur_g -= 1
        i += 1
    return total

def main():
    entry = input()
    resp = get_score(entry)
    print(resp)

if __name__ == '__main__':
    main()


from sys import stdin
input = stdin.readline

def get_total_Wh_from_bill(A):
    # 사용량에 따른 기준 요금
    pay_list = [100 * 2, 100 * 2 + 9900 * 3, 100 * 2 + 9900 * 3 + 990000 * 5]
    if A <= pay_list[0]:
        total_Wh = A // 2
    elif A <= pay_list[1]:
        total_Wh = 100 + (A - pay_list[0]) // 3
    elif A <= pay_list[2]:
        total_Wh = 10000 + (A - pay_list[1]) // 5
    else:
        total_Wh = 1000000 + (A - pay_list[2]) // 7

    return total_Wh

def get_bill_from_Wh(Wh):
    # 사용 기준량
    limit_list = [100, 10000, 1000000]
    if Wh <= limit_list[0]:
        bill = Wh * 2
    elif Wh <= limit_list[1]:
        bill = 100 * 2 + (Wh - limit_list[0]) * 3
    elif Wh <= limit_list[2]:
        bill = 100 * 2 + 9900 * 3 + (Wh - limit_list[1]) * 5
    else:
        bill = 100 * 2 + 9900 * 3 + 990000 * 5 + (Wh -limit_list[2]) * 7

    return bill

def solution(A, B):
    total_Wh = get_total_Wh_from_bill(A)

    start = 1
    end = total_Wh
    while True:
        # x 상근이
        x = (start + end) // 2
        # y 이웃
        y = total_Wh - x

        # 이웃 - 상근이 요금
        diff_xy = get_bill_from_Wh(y) - get_bill_from_Wh(x)

        # 차이가 B와 같으면 그 때의 상근이의 요금 출력
        if diff_xy == B:
            return get_bill_from_Wh(x)

        # 차이가 B 보다 큰 것은 x의 사용량이 늘어나야함
        if diff_xy > B:
            start = x + 1
        # 차이가 B 보다 작으면 x의 사용량이 줄어들어야함
        else:
            end = x - 1

if __name__ == '__main__':
    while True:
        A, B = map(int, input().split())
        if A == 0 and B == 0:
            break
        print(solution(A, B))


from selenium import webdriver # https://www.selenium.dev/documentation
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import unittest # https://docs.python.org/3/library/unittest.html

class NavigationExample(unittest.TestCase):

    URL = "https://google.com"

    '''
        Overrides the setUp method provided by unittest.TesCase
    '''
    def setUp(self):
        self.browser = webdriver.Chrome()
        self.browser.set_page_load_timeout(30) # seconds for page to load
        self.browser.implicitly_wait(10) # seconds for elements
        self.browser.get(self.URL)
        self.browser.maximize_window()

    def tearDown(self):
        self.browser.quit()

    def accept_cookies(self):
        accept_cookies_btn = self.browser.find_element(By.XPATH, "//button[div[text()='Accept all']]")
        # Accept cookies
        accept_cookies_btn.click()

    '''
        Uses JavaScript executor for opening a tab (compatible with Selenium < 4)
    '''
    def test_new_tab_example(self):
        wait = WebDriverWait(self.browser, 10)
        self.accept_cookies()

        # get identifier for current tab
        original_tab = self.browser.current_window_handle # unique window handle ID

        # open a new tab by executing JS and wait for it to open
        self.browser.execute_script("window.open('https://bing.com')")
        wait.until(EC.number_of_windows_to_be(2))

        # switch to new tab
        self.browser.switch_to.window(self.browser.window_handles[1])

        # close current tab
        self.browser.close()

        # return to original tab
        self.browser.switch_to.window(original_tab)

        self.assertEqual("Google", self.browser.title)

    '''
        Selenium 4 compatible way of opening a new tab
    '''
    def test_new_tab_example2(self):
        wait = WebDriverWait(self.browser, 10)
        self.accept_cookies()

        # get identifier for current tab
        original_tab = self.browser.current_window_handle # unique window handle ID

        # open a new tab and switch to it
        self.browser.switch_to.new_window("tab")
        wait.until(EC.number_of_windows_to_be(2))

        # close current tab
        self.browser.close()

        # return to original tab
        self.browser.switch_to.window(original_tab)

        self.assertEqual("Google", self.browser.title)

    '''
        Selenium 4 compatible way of opening a new browser window
    '''
    def test_new_window_example(self):
        self.accept_cookies()

        # get identifier for current tab
        original_tab = self.browser.current_window_handle # unique window handle ID

        # open a new window and switch to it
        self.browser.switch_to.new_window("window")

        # close current window
        self.browser.close()

        # return to original window
        self.browser.switch_to.window(original_tab)

        self.assertEqual("Google", self.browser.title)

    def test_resize_window_example(self):
        self.accept_cookies()

        # window sizes
        mobile_window_size = (520, 850)
        tablet_window_size = (780, 1024)
        desktop_window_size = (1024, 720)

        # get original size
        original_window_size = self.browser.get_window_size()
        original_width = original_window_size.get("width")
        original_height = original_window_size.get("height")

        # change to mobile size
        self.browser.set_window_size(mobile_window_size[0], mobile_window_size[1])
        new_size = self.browser.get_window_size()
        self.assertEqual(new_size.get("width"), mobile_window_size[0])
        self.assertEqual(new_size.get("height"), mobile_window_size[1])

        # change to tablet size
        self.browser.set_window_size(tablet_window_size[0], tablet_window_size[1])
        new_size = self.browser.get_window_size()
        self.assertEqual(new_size.get("width"), tablet_window_size[0])
        self.assertEqual(new_size.get("height"), tablet_window_size[1])

        # change to desktop size
        self.browser.set_window_size(desktop_window_size[0], desktop_window_size[1])
        new_size = self.browser.get_window_size()
        self.assertEqual(new_size.get("width"), desktop_window_size[0])
        self.assertEqual(new_size.get("height"), desktop_window_size[1])

    def test_screenshot_example(self):
        self.accept_cookies()
        search_bar = self.browser.find_element(By.NAME, "q")
        search_bar.send_keys("kittens")
        # take a screenshot of the search bar with text in it
        search_bar.screenshot("./search_bar.png")

        # take a screenshot of the page
        search_bar.send_keys(Keys.ENTER)
        self.browser.save_screenshot("./search_result.png")

        self.assertEqual("kittens - Google Search", self.browser.title)

# Run tests
if __name__ == '__main__':
    unittest.main(verbosity=2)


from functools import reduce
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

# noinspection PyTypeChecker
def k_means(data, kernel, step=0):
    """
    :param data: samples
    :param kernel: numeric or list
    :param step: int
    """
    # c: set groups, u: kernel vector
    if isinstance(kernel, list):
        c = [[sample] for sample in kernel]
        u = [data[sample] for sample in kernel]
    else:
        index = np.arange(len(data))
        np.random.shuffle(index)
        index = index[:kernel]
        c = [[sample] for sample in index]
        u = [data[sample] for sample in index]

    for i in range(step):
        # append all the vectors into different set groups.
        for sample_index in range(len(data)):
            dist_list = [np.linalg.norm(data[sample_index] - u[set_index]) for set_index in range(len(u))]
            set_index = np.argmin(np.array(dist_list))
            if sample_index not in c[set_index]:
                c[set_index].append(sample_index)

        # reset the kernel vector.
        for set_index in range(len(u)):
            sum_vector = reduce(lambda x, y: x + y, [data[sample_index] for sample_index in c[set_index]])
            u[set_index] = sum_vector / len(c[set_index])

    # matrix of samples after k-means.
    v = []
    for set_index in range(len(u)):
        v.append(data[c[set_index]])
    return c, u, v

# noinspection PyTypeChecker
def k_means_graph(data, kernel, step=0):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    c, u, v = k_means(data=data, kernel=kernel, step=step)
    for index in range(len(c)):
        point, = ax.plot(v[index][:, 0], v[index][:, 1], 'o', markersize=10)
        ax.plot(u[index][0], u[index][1], '+', c=point.get_color(), markersize=10)

if __name__ == '__main__':
    watermelon = pd.read_csv('./watermelon.csv', sep='\t', header=0)

    k_means_graph(data=watermelon.values, kernel=3, step=5)

    pd.scatter_matrix(watermelon, diagonal='kde', alpha=.8, marker='o')
    plt.show()


#!/usr/bin/python3
# -*- coding: utf-8

import sys
import argparse
from collections import Counter
import json
from progressbar import Bar
from vkgroups import VkUser

def write_json_file(uid: "int user id",
                    groups: "list of dict with groups info"):
    filename = "{}_groups.json".format(uid)
    with open(filename, 'w', encoding="utf8") as jf:
        jf.write(json.dumps(groups, ensure_ascii=False, indent=3))
    print("group analysis results has been stored in {}".format(filename))

def main(vk: "VkUser object provides access to VK API",
         limit: "int number friends per group"):
    user_friends = vk.get_friends_list()
    user_groups = vk.get_groups_list(vk.get_user_id())
    friends_number = len(user_friends)
    print("{}({}) has {} friends and participate in {} groups\n".format(vk.get_user_name(), vk.get_user_id(),
                                                                        friends_number, len(user_groups)))
    friends_groups = list()
    bar = Bar(friends_number, 'loading friends groups')
    for i, friend in enumerate(user_friends):
        groups = vk.get_groups_list(friend)
        if groups:
            friends_groups.extend(groups)
        bar.show_progress(i)
    else:
        bar.show_progress_100("loaded groups data for {} friends".format(friends_number))
    group_counts = Counter(friends_groups)  # count number of friends using each group, place results in the dict
    result = list(set(user_groups) - set(group_counts.keys()))  # unique user groups
    if limit > 0:  # add groups where friends participate
        for group, count in group_counts.items():
            if group in user_groups and count <= limit:
                result.append(group)
    write_json_file(vk.get_user_id(), [vk.get_group_info(group) for group in result])

def check_limit(value: "int") -> int:
    ival = int(value)
    if ival < 0 or ival > 99:
        raise argparse.ArgumentTypeError("{} is an invalid limit value".format(value))
    return ival

if __name__ == '__main__':
    ap = argparse.ArgumentParser(description='This program looks for secret groups of the VK user')
    ap.add_argument("uid", help="  user id or short 'screen name'")
    ap.add_argument("--token", dest="token", action="store", help="  VK API access token")
    ap.add_argument("--limit", dest="limit", action="store", type=check_limit, default=0,
                    help="  max number of friends in one group (0 <= limit <= 99, default=0)")
    args = ap.parse_args(sys.argv[1:])
    if args.token:
        vkapi = VkUser(userid=args.uid, token=args.token)
    else:
        vkapi = VkUser(userid=args.uid)
    main(vkapi, args.limit)


import pygame
from pygame.sprite import Sprite

class Bullet(Sprite):
    """A class to manage all the bullets fired fromthe ship."""

    def __init__(self, ai_settings, screen, ship):
        """Create a bullet object at the current ship's position."""
        super(Bullet, self).__init__()
        self.screen = screen

        # Let's crete a bullet at top left corner initially since we dont have a image ref.
        # i.e., (0, 0) and then set it to the correct position.
        self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height)
        self.rect.centerx = ship.rect.centerx
        self.rect.top = ship.rect.top

        # Now let's store the bullet's y-co-ordinate as a decimal value
        self.y = float(self.rect.y)

        self.color = ai_settings.bullet_color
        self.speed_factor = ai_settings.bullet_speed_factor

    def update(self):
        """Move the bullet up the screen."""
        # Update the decimal position of the bullet on the screen.
        self.y -= self.speed_factor
        # Now we must also update the rectangle position on the screen.
        self.rect.y = self.y

    def draw_bullets(self):
        """Draw the bullets on the screen."""
        pygame.draw.rect(self.screen, self.color, self.rect)


from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import sql

pages=set()

def getlink(newpage, recursionLevel):
    global pages
    if recursionLevel > 4:
        return;
    frompage_id = sql.insertPageIfNotExists(newpage)
    url = urlopen("https://en.wikipedia.org"+newpage)
    html = BeautifulSoup(url,"lxml")
    print(html.title.get_text())
    links = html.findAll("a",href=re.compile("^/wiki/((?!:).)*$"))
    for link in links:
        href = link.attrs['href']
        if href not in pages:
            topage_id=sql.insertPageIfNotExists(href)
            sql.insertLink(frompage_id, topage_id)
            pages.add(href)
            print(href)
            getlink(href,recursionLevel+1)

getlink("/wiki/Main_Page",0)


#!/usr/bin/env python3

from __future__ import print_function
import rospy
from arm20_srv.srv import arm_seq_send,arm_seq_sendResponse
from arm20_msg.msg import cmd_robot_msg
import time

pi=3.1415926535897931
coe=614.4/pi

pub = rospy.Publisher('cmd_arm_msg', cmd_robot_msg, queue_size=1)

def send_commands_to_arm(req):
    global UDP_PORT,UDP_IP,id_robot
    response = arm_seq_sendResponse()
    cmd=cmd_robot_msg()
    for x in range(1,7):
        aux = 512 + req.joint_data.position[x-1]*coe
        aux=int(aux)
        cmd.ip=UDP_IP
        cmd.port=UDP_PORT
        cmd.id=id_robot
        cmd.instruction=17
        cmd.op1=x-1
        cmd.op2 = (aux >> 8) & 0xff
        cmd.op3 = aux & 0xff
        cmd.op4=0
        cmd.op5=0
        time.sleep(0.2)
        pub.publish(cmd)		# publish the position of each joint
        #rospy.loginfo(message)
    cmd.instruction=18
    pub.publish(cmd)			# publish the command to move to new position
    response.status="sended"
    return response

def set_arm_commands_server():
    rospy.init_node('set_arm_server')
    s = rospy.Service('cmd_service_arm_seq', arm_seq_send, send_commands_to_arm)
    rospy.spin()

if __name__ == "__main__":
    UDP_IP = "192.168.0.154"   #esp8266 ip and port
    UDP_PORT = 8888
    id_robot=238
    set_arm_commands_server()


#!/usr/bin/python3
""" finds the peak integer """

def find_peak(list_of_integers):
    """ finds peak integer of list """
    arr = list_of_integers
    if arr:
        if len(arr) == 1:
            return arr[0]
        if arr[0] > arr[1]:
            return arr[0]
        if arr[len(arr) - 1] > arr[len(arr) - 2]:
            return arr[len(arr) - 1]
        mid = len(arr) // 2
        if arr[mid - 1] >= arr[mid]:
            return find_peak(arr[0:mid])
        if arr[mid + 1] >= arr[mid]:
            return find_peak(arr[mid + 1:])
        return arr[mid]


#!/usr/bin/env python3

def yes_no( str ):

    while (1):
        answer = input(str)
        answer = answer.lower()
        if (answer == "y" or answer == "yes" or answer == "yep"):
            return True
        elif (answer == "n" or answer == "no" or answer == "nah"):
            return False
        else:
            print("Not a valid response. Try again.")

if (yes_no("Does this work? ")):
    print("YES!!")
else:
    print("NO!!")


from datetime import datetime, timedelta
import multiprocessing
import faster_whisper

STYLES = {
    # Great format to run with screenshots
    1: [
        "Fontsize={font_size},",
        "PrimaryColour={primary_color},",
        "OutlineColour=&H40000000,",
        "Bold={bold},",
        "Alignment=6,",
        "MarginL=0,",
        "MarginR=0,",
        "MarginV=200",
    ],
    # Centerd Bold Text
    2: [
        "Fontsize={font_size},",
        "PrimaryColour=&HFFFFFF&,",
        "OutlineColour=&H40000000,",
        "Bold={bold},",
        "Alignment=10,",
        "MarginL=0,",
        "MarginR=0,",
        "MarginV=0",
    ],
}

def get_subtitles_style(
    primary_color: str = "&HFFFFFF&",
    font_size: float = 18,
    bold: bool = True,
    desired_style: int = 1,
):
    """
    Get subtitles style.
    :param primary_color: Primary color.
    :param font_size: Font size.
    :param bold: Bold text.
    :param desired_style: Desired style.
    :return: Subtitles style.
    """
    return "".join(STYLES[desired_style]).format(
        primary_color=primary_color, font_size=font_size, bold=bold
    )

def generate_srt(subtitles: list) -> str:
    """
    Generate an SRT file from a list of timestamps of words
    :param subtitles: Subtitles list.
    :return: .srt file contents
    """
    timestamp_format = datetime.strptime(
        "00:00:00,000", "%H:%M:%S,%f"
    )  # Null element of addition to keep the timestamp format
    srt = []
    for i, subtitle in enumerate(subtitles):
        start_time = (subtitle["start_time"] + timestamp_format).strftime(
            "%H:%M:%S,%f"
        )[:-3]
        end_time = (subtitle["end_time"] + timestamp_format).strftime("%H:%M:%S,%f")[
            :-3
        ]
        words = subtitle["words"]

        srt.append(f"{i+1}")
        srt.append(f"{start_time} --> {end_time}")
        srt.append(" ".join(words) + "\n")

    return "\n".join(srt)

def append_segment_to_subtitles(subtitles: list, segment: tuple) -> list:
    """
    Append segment to subtitles.
    :param subtitles: Subtitles list.
    :param segment: Segment to append.
    :return: Subtitles list.
    """
    # Calculate end_time for each word
    start_time = timedelta(seconds=segment.start)
    end_time = timedelta(seconds=segment.end)
    # Create subtitle for each word
    subtitle = {
        "start_time": start_time,
        "end_time": end_time,
        "words": [segment.word],
    }
    subtitles.append(subtitle)
    return subtitles

def transcribe_audio(audio_path: str, srt_path: str, word_by_word: bool = True) -> None:
    """
    Transcribe audio file to SRT file.
    :param audio_path: Path to the audio file.
    :param srt_path: Path to the SRT file.
    :param word_by_word: If True, the subtitles will be generated by each word.
    """
    model = faster_whisper.WhisperModel(
        "base", cpu_threads=multiprocessing.cpu_count()
    )  # You can choose: [tinu, base, small, medium] to more accurate subtitles
    transcribe = model.transcribe(audio=audio_path, word_timestamps=True)
    segments = transcribe[0]
    subtitles = []
    for segment in segments:
        # Segment Information
        words = segment.words
        if word_by_word:
            for word in words:
                subtitles = append_segment_to_subtitles(subtitles, word)
        else:
            subtitles = append_segment_to_subtitles(subtitles, segment)

    # Gererate the SRT File
    srt_content = generate_srt(subtitles)

    # Write the SRT File
    with open(srt_path, "w", encoding="utf-8") as file:
        file.write(srt_content)


from selenium import webdriver
import time
import unittest

class NewVisitorTest(unittest.TestCase):

    def setUp(self):
        self.browser = webdriver.Firefox()

    def tearDown(self):
        self.browser.quit()

    def test_opens_blog_home_page_and_browses(self):
        #user opens blog home page
        self.opens_blog_page()

        #they expect the correct header and title to be shown
        self.assertIn("Davinder's Blog", self.browser.title)
        header_text = self.browser.find_element_by_tag_name('h1').text
        self.assertIn("Davinder's Blog", header_text)

        time.sleep(1)

        #they then move on to the CV page
        self.opens_CV_page()

        #this also needs the correct header and title
        self.assertIn("Davinder's CV", self.browser.title)
        header_text = self.browser.find_element_by_tag_name('h1').text
        self.assertIn("Davinder's CV", header_text)

        time.sleep(1)

        #they also see an option to return to the Blog site
        header_text = self.browser.find_element_by_tag_name('h3').text
        self.assertIn("Davinder's Blog", header_text)

        #they test this link
        self.opens_blog_page()

        time.sleep(1)

        #they then move back to the CV page
        self.opens_CV_page()

        time.sleep(1)

        #they click on a section of the CV expect to see the details
        self.opens_CV_section_detail(1)

        time.sleep(1)

        #they click edit and expect to see the option to edit the section
        self.opens_CV_section_edit(1)

        time.sleep(1)

        #they then move back to the CV page
        self.opens_CV_page()

        time.sleep(1)

        #they click on another section of the CV expect to see the details
        self.opens_CV_section_detail(2)
        time.sleep(1)

        #they click edit and expect to see the option to edit the section
        self.opens_CV_section_edit(2)

        time.sleep(1)

    def opens_CV_page(self):
        self.browser.get('http://dsb874.pythonanywhere.com/CV')

    def opens_blog_page(self):
        self.browser.get('http://dsb874.pythonanywhere.com/')

    def opens_CV_section_detail(self, pageNum):
        self.browser.get('http://dsb874.pythonanywhere.com/section/'+str(pageNum)+'/')

    def opens_CV_section_edit(self, pageNum):
        self.browser.get('http://dsb874.pythonanywhere.com/section/'+str(pageNum)+'/edit/')

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


import typing

from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.utils.callback_data import CallbackData

ikb_booking_callback = CallbackData("booking", "id")

def cancel_booking_btn(
        booking: dict
):
    markup = InlineKeyboardMarkup(1)
    btns = [
        InlineKeyboardButton(
            text=f"Отменить: {booking.get('width').strftime('%Y-%m-%d %H:%M')} ({booking.get('master_name')})",
            callback_data=ikb_booking_callback.new(id=booking.get("id"))
        )
    ]
    markup.add(*btns)

    return markup


"""
Paraphrase NL datasets of question datasets w/ two axes
"""

import os
import pandas as pd

from datetime import datetime
from dotenv import load_dotenv

from framework.utils import get_nl, AXES
from itertools import combinations
from langchain.chat_models import ChatOpenAI

load_dotenv(".env")

D_LOC = os.path.join("exp", "d3_question", "result", "task3.csv")
MODELS = ["gpt-3.5-turbo-0613", "gpt-4-0613", "gpt-4-32k-0613"]

df_data = {
    "sentences": [],
    "axes": [],
    "axes2": [],
    "ptypes": [],
    "scores": [],
    "scores2": [],
    "dnames": [],
}

def gen_prompt(sent, axes):
    prompt = f"""
{axes[0][2]}
{axes[1][2]}
Score-A of 1 indicates a higher tendency to use {axes[0][0]} language and a Score-A of 5 indicates a higher tendency to use {axes[0][1]} language.
Score-B of 1 indicates a higher tendency to use {axes[1][0]} language and a Score-B of 5 indicates a higher tendency to use {axes[1][1]} language.
Rewrite the following sentence as if it were spoken by a person with a given score for language usage.

Sentence: {sent}

##
Score-A 1, Score-B 1:
Score-A 1, Score-B 2:
Score-A 1, Score-B 3:
Score-A 1, Score-B 4:
Score-A 1, Score-B 5:

Score-A 2, Score-B 1:
Score-A 2, Score-B 2:
Score-A 2, Score-B 3:
Score-A 2, Score-B 4:
Score-A 2, Score-B 5:

Score-A 3, Score-B 1:
Score-A 3, Score-B 2:
Score-A 3, Score-B 3:
Score-A 3, Score-B 4:
Score-A 3, Score-B 5:

Score-A 4, Score-B 1:
Score-A 4, Score-B 2:
Score-A 4, Score-B 3:
Score-A 4, Score-B 4:
Score-A 4, Score-B 5:

Score-A 5, Score-B 1:
Score-A 5, Score-B 2:
Score-A 5, Score-B 3:
Score-A 5, Score-B 4:
Score-A 5, Score-B 5:
"""
    return prompt

def run_agent(sent, axes_list, model, temp=0.0):
    llm = ChatOpenAI(temperature=temp, model=model)
    return tuple(llm.predict(gen_prompt(sent, axes)) for axes in axes_list)

if __name__ == "__main__":
    df = pd.read_csv(D_LOC)

    for i, row in df.iterrows():
        if i < 46:
            continue
        num_ptypes = 5
        num_axes = 6  # 4C2
        num_score = 25
        count = num_axes * num_score  # axes 6, score 25

        q1 = row["lookup-nonvisual"]
        q2 = row["lookup-visual"]
        q3 = row["compositional-nonvisual"]
        q4 = row["compositional-visual"]
        q5 = row["open-ended"]

        df_data["ptypes"].extend(
            ["lookup-nonvisual"] * count
            + ["lookup-visual"] * count
            + ["compositional-nonvisual"] * count
            + ["compositional-visual"] * count
            + ["open-ended"] * count
        )
        df_data["dnames"].extend([row["dnames"]] * count * num_ptypes)
        df_data["scores"].extend([1, 2, 3, 4, 5] * 5 * num_ptypes * num_axes)
        df_data["scores2"].extend(
            [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5]
            * num_ptypes
            * num_axes
        )

        axes_list = list(combinations(AXES, 2))

        axes_data = []
        axes_data2 = []
        for _ in range(num_ptypes):
            for axes_l in axes_list:
                axes_data.extend([f"{axes_l[0][0]}-{axes_l[0][1]}"] * num_score)
                axes_data2.extend([f"{axes_l[1][0]}-{axes_l[1][1]}"] * num_score)
        df_data["axes"].extend(axes_data)
        df_data["axes2"].extend(axes_data2)

        for sent in [q1, q2, q3, q4, q5]:
            print(f"{i}: q1-q5: {sent}")
            out = run_agent(sent, axes_list, model=MODELS[1])
            for k, o in enumerate(out):
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 1, Score-B 1:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 1, Score-B 2:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 1, Score-B 3:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 1, Score-B 4:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 1, Score-B 5:(.+?)(?:\n|$)")
                )

                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 2, Score-B 1:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 2, Score-B 2:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 2, Score-B 3:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 2, Score-B 4:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 2, Score-B 5:(.+?)(?:\n|$)")
                )

                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 3, Score-B 1:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 3, Score-B 2:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 3, Score-B 3:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 3, Score-B 4:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 3, Score-B 5:(.+?)(?:\n|$)")
                )

                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 4, Score-B 1:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 4, Score-B 2:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 4, Score-B 3:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 4, Score-B 4:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 4, Score-B 5:(.+?)(?:\n|$)")
                )

                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 5, Score-B 1:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 5, Score-B 2:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 5, Score-B 3:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 5, Score-B 4:(.+?)(?:\n|$)")
                )
                df_data["sentences"].append(
                    get_nl(o, pattern=r"Score-A 5, Score-B 5:(.+?)(?:\n|$)")
                )
                # print(f"len(df_data['sentences']): {len(df_data['sentences'])}")

        df = pd.DataFrame(df_data)
        df.to_csv(
            os.path.join(
                "exp", "d3_question", "result", f"task4_two_tmp_{datetime.now()}.csv"
            ),
            index=False,
        )

    df = pd.DataFrame(df_data)
    df.to_csv(
        os.path.join("exp", "d3_question", "result", "task4_two.csv"),
        index=False,
    )


from itertools import count
from math import gcd

def get_lcm(values):
    lcm = values[0]
    for value in values[1:]:
      lcm = lcm * value // gcd(lcm, value)
    return lcm

def good(number, busses, test_index):
    bus, offset = busses[test_index]
    if offset == 0:
        if (number % bus) == offset:
            return True
    else:
        if bus - (number % bus) == offset % bus:
            return True
    return False

def main():

    with open("day13.txt", "r") as fin:
        fin.readline()
        bus_line = fin.readline().strip()

    busses = sorted(
        [(int(x), offset)
         for offset, x in enumerate(bus_line.split(","))
         if x != "x"],
        reverse=True,
    )
    values = [bus[0] for bus in busses]

    step_value = busses[0][0]
    timestamp = -busses[0][1]
    test_index = 1
    while True:
        timestamp += step_value
        if good(timestamp, busses, test_index):
            test_index += 1
            step_value = get_lcm(values[:test_index])

            if test_index == len(busses):
                break

    # Do a last check
    for i in range(len(busses)):
        assert good(timestamp, busses, i)

    print(f"Earliest good time stamp: {timestamp}")

if __name__ == '__main__':
    main()


#!/usr/bin/env python3
import json
import base64
from emzmachine import run_program

WELCOME_MESSAGE = """EmzMachine 8000
---------------

Input EmzMachine 8000 OpCodes (as hex string):
"""

if __name__ == "__main__":
    try:
        USER_PROGRAM = bytearray.fromhex(input(WELCOME_MESSAGE))
    except:
        print("Error occured in reading program.\nPlease input program as hexadecimal string.")
        exit(1)

    print('Program:', bytes(USER_PROGRAM))

    hyp = run_program(USER_PROGRAM)

    for vm in hyp.vms:
        if vm[0] == 'USER':
            print("result:")
            for item in vm[3].stdout:
                print(item)

            print("machine state")
            machine_state = vm[3].machine_state
            machine_state['FB'] = base64.b64encode(machine_state['FB']).decode()
            machine_state['TEXT'] = machine_state['TEXT'].decode()
            print(json.dumps(machine_state))
    exit(0)


#!/usr/bin/env python3
from core import ACUX
import sys, time
import traceback

API_KEY = "api_key" # CHANGE_IT
SERVER = "ip:3443" # CHANGE_IT

if len(sys.argv) > 2:
	targ = open(sys.argv[1], 'r').read().splitlines()
	urls = list((targ))
	date = sys.argv[2]
else:
	print("urls.txt and first report's date (year-month-day) required\nFor example: " + sys.argv[0] + " urls.txt 2020-01-31")
	exit()

acunetix = ACUX(host=SERVER,api=API_KEY,timeout=30)
downloads = []
allreports = acunetix.reports()

for i in range(0,len(allreports['reports'])):
	for j in range(0,len(urls)):
		if allreports['reports'][i]['source']['description'].split(';')[0] == urls[j] and allreports['reports'][i]['generation_date'].split('T')[0] >= date:
			downloads.append(allreports['reports'][i]['download'][0]) # you can change 0 to 1 if you want to download pdf format
n = 1
for link in downloads:
	try:
		filename, filecontent = acunetix.downloader(endpoint=link)
		print(str(n) + ". Report created: " + filename)
		n += 1
		# print(filecontent)
		with open(filename, "wb") as file:
			file.write(filecontent)
		time.sleep(1)
	except:
		print("Downloading error")
		print(traceback.format_exc())
		exit()


from __future__ import print_function
import numpy as np
import h5py
#import cPickle as pickle
import pickle
import time
import utils

from keras.callbacks import Callback
from keras import backend as K

class LossHistory(Callback):
    def __init__(self, exp_path, save_interval):
        super(LossHistory, self).__init__()
        self.save_interval = save_interval
        self.exp_path = exp_path
        self.losses = []

    def on_train_begin(self, logs={}):
        self.losses = []

    def on_batch_end(self, batch, logs={}):
        self.losses.append(logs.get('loss'))

    def on_epoch_end(self, epoch, logs=None):
        if epoch % self.save_interval == 0:
            with open(self.exp_path + 'loss_history{:02d}.p'.format(epoch//self.save_interval), 'w') as f:
                pickle.dump(self.losses, f)

class RunlengthSaver(Callback):
    def __init__(self, exp_path, save_interval):
        super(RunlengthSaver, self).__init__()
        self.start = 0
        self.runlength = []
        self.exp_path = exp_path
        self.save_interval = save_interval

    def on_train_begin(self, logs=None):
        self.start = time.time()

    def on_epoch_end(self, epoch, logs=None):
        self.runlength.append(time.time() - self.start)
        if epoch % self.save_interval == 0:
            with open(self.exp_path + 'runlength{0:}.p'.format(epoch//self.save_interval), 'w') as f:
                pickle.dump(self.runlength, f)

class ModelSaver(Callback):
    def __init__(self, exp_path, save_interval):
        super(ModelSaver, self).__init__()
        self.save_interval = save_interval
        self.exp_path = exp_path

    def on_epoch_end(self, epoch, logs=None):
        if epoch % self.save_interval == 0:
            self.model.save_weights(self.exp_path + 'weights{:02d}.h5'.format(epoch))
            with open(self.exp_path + 'opt_state{:02d}.p'.format(epoch), 'w') as f:
                pickle.dump(self.model.optimizer.get_weights(), f)
            self.model.save(self.exp_path + 'model_state{:02d}.h5'.format(epoch))

class Trainer(object):
    def __init__(self, model, exp_path, training_source, validation_source, save_interval=10, bs=6,
                 steps_per_epoch=22*22, cubic=False, normalize=True):
        self.model = model
        self.bs = bs
        self.steps_per_epoch = steps_per_epoch
        self.cubic = cubic
        self.normalize = normalize
        if K.image_data_format() == 'channels_last':
            input_shape = self.model.model.input_shape[1:-1]
        else:
            input_shape = self.model.model.input_shape[2:]
        self.valid_generator = self.h5_data_generator(validation_source, input_shape,
                                                      num_outputs=len(self.model.model.output_names))
        self.train_generator = self.h5_data_generator(training_source, input_shape,
                                                      num_outputs=len(self.model.model.output_names))
        self.callbacks = [LossHistory(exp_path, save_interval=save_interval),
                          ModelSaver(exp_path, save_interval=save_interval),
                          RunlengthSaver(exp_path, save_interval=save_interval)]

    def run(self, epochs, start_epoch=0):
        epoch_history = self.model.model.fit_generator(self.train_generator,
                                                       epochs=epochs,
                                                       validation_data=self.valid_generator,
                                                       callbacks=self.callbacks + [self.model.scheduler],
                                                       steps_per_epoch=self.steps_per_epoch,
                                                       validation_steps=20,
                                                       max_queue_size=2*self.bs,
                                                       initial_epoch=start_epoch)#, workers=4, use_multiprocessing=True)

    def h5_data_generator(self, source, input_shape, num_outputs):
        train_ds = h5py.File(source, 'r')['raw']

        while True:
            if self.cubic:
                sample_downsampled = np.empty((self.bs,) + (input_shape[0]//self.model.scaling_factor,) + input_shape[
                                                                                1:])
            batch = np.empty((self.bs,)+input_shape)

            if self.cubic:
                batch_cubicup = np.empty((self.bs,) + input_shape)
            z_start = np.random.random_integers(0, train_ds.shape[0] - input_shape[0] - 1, self.bs)
            y_start = np.random.random_integers(0, train_ds.shape[1] - input_shape[1] - 1, self.bs)
            x_start = np.random.random_integers(0, train_ds.shape[2] - input_shape[2] - 1, self.bs)
            for k in range(self.bs):
                train_ds.read_direct(batch,
                                     np.s_[z_start[k]:z_start[k] + input_shape[0],
                                           y_start[k]:y_start[k] + input_shape[1],
                                           x_start[k]:x_start[k] + input_shape[2]],
                                     np.s_[k, :, :, :])
                if self.cubic:
                    sample_downsampled[k, :, :, :] = utils.downscale_manually(batch[k, :, :, :],
                                                                              factor=self.model.scaling_factor,
                                                                              axis=0)
                    batch_cubicup[k, :, :, :] = utils.cubic_up(sample_downsampled[k, :, :, :],
                                                               self.model.scaling_factor, axis=0)

            if K.image_data_format() == 'channels_last':
                ch_axis = -1
            else:
                ch_axis = 1

            if self.cubic:
                gt = np.expand_dims(batch_cubicup, ch_axis)
            batch = np.expand_dims(batch, ch_axis)
            if num_outputs == 1:
                if not self.cubic:
                    gt = batch
            else: #dummy
                gt = np.zeros((self.bs, 1, 1, 1, 1))
            if self.normalize:
                batch = (batch/255.).astype('float32')
                gt = (gt/255.).astype('float32')
            yield ([batch], [gt] * num_outputs)

    def evaluate(self, steps):
        print(self.model.model.metrics_names)
        print("Training set:")
        train_results = self.model.model.evaluate_generator(self.train_generator, steps=steps,
                                                            max_queue_size=2*self.bs)
        print(train_results)

        print("Validation set:")
        validation_results = self.model.model.evaluate_generator(self.valid_generator, steps=steps,
                                                                 max_queue_size=2*self.bs)
        print(validation_results)
        return train_results + validation_results


from vtool.maya_lib import rigs
from vtool.maya_lib import space
from vtool.maya_lib import rigs_util

control_size = process.get_option('Control Size', 'Setup.Controls')
sub_vis = process.get_option('Sub Controls Visible', 'Setup.Controls')

def main():

    rig = rigs.FkRig('head', 'C')
    rig.set_joints('joint_head')
    rig.set_control_shape('circle_corner')
    rig.set_create_sub_controls(True)
    rig.set_nice_sub_control_naming(True)
    rig.set_control_size(control_size)
    rig.set_sub_visibility(sub_vis)
    rig.create()

    control = rigs_util.Control('CNT_HEAD_1_C')
    control.rotate_shape(90,0,0)

    cmds.parent(rig.control_group, 'CNT_SUB_NECK_3_C')
    cmds.parent(rig.setup_group, 'setup')

    space.create_multi_follow(['CNT_SUB_GROUND_2_C', 'CNT_SUB_NECK_3_C'],
                                'xform_CNT_HEAD_1_C', 'CNT_HEAD_1_C',
                                constraint_type = 'orientConstraint')