import csv
import datetime

menuu = "Please Choose a Pizza Base:  " \
        "\n1: Classic" \
        "\n2: Margherita" \
        "\n3: TurkPizza(lahmacun)" \
        "\n4: Pepperoni" \
        "\n5: Four Seasons Pizza" \
        "\n And sauce of your choice:  " \
        "\n1: Olives" \
        "\n2: Mushrooms" \
        "\n3: GoatCheese" \
        "\n4: Meat" \
        "\n5: Onions" \
        "\n6: Corn"
with open("menu.txt", 'w') as menu:
    menu.write(menuu)

class Pizza:
    def get_description(self):
        return self.description

    def get_cost(self):
        return self.cost

class Classic(Pizza):
    def get_description(self):
        return "Classic Pizza"

    def get_cost(self, size):
        return 7.25 + (size * 2)

class Margherita(Pizza):
    def get_description(self):
        return "Margherita Pizza"

    def get_cost(self, size):
        return 8.90 + (size * 2)

class Lahmacun(Pizza):
    def get_description(self):
        return "Turk Pizza (Lahmacun)"

    def get_cost(self, amount):
        return 3 * amount

class Pepperoni(Pizza):
    def get_description(self):
        return "Pepperoni Pizza"

    def get_cost(self, size):
        return 10 + (size * 2)

class FourSeasons(Pizza):
    def get_description(self):
        return "Four Seasons Pizza"

    def get_cost(self, size):
        return 10 + (size * 2)

class Decorator(Pizza):
    def __init__(self, component):
        self.component = component

    def get_cost(self):
        return self.component.get_cost() + Pizza.get_cost(self)

    def get_description(self):
        return self.component.get_description() + ' ' + Pizza.get_description(self)

class Olives(Decorator):
    def __init__(self, component):
        Decorator.__init__(self, component)
        self.description = "Olives"
        self.cost = 0.99

    def get_cost(self):
        return self.cost

    def get_description(self):
        return self.component.get_description() + ", " + self.description

class Mushrooms(Decorator):
    def __init__(self, component):
        Decorator.__init__(self, component)
        self.description = "Mushrooms"
        self.cost = 1.25

    def get_cost(self):
        return self.cost

    def get_description(self):
        return self.component.get_description() + ", " + self.description

class GoatCheese(Decorator):
    def __init__(self, component):
        Decorator.__init__(self, component)
        self.description = "Goat Cheese"
        self.cost = 1.25

    def get_cost(self):
        return self.cost

    def get_description(self):
        return self.component.get_description() + ", " + self.description

class Meat(Decorator):
    def __init__(self, component):
        Decorator.__init__(self, component)
        self.description = "Meat"
        self.cost = 1.99

    def get_cost(self):
        return self.cost

    def get_description(self):
        return self.component.get_description() + ", " + self.description

class Onions(Decorator):
    def __init__(self, component):
        Decorator.__init__(self, component)
        self.description = "Onions"
        self.cost = 0.99

    def get_cost(self):
        return self.cost

    def get_description(self):
        return self.component.get_description() + ", " + self.description

class Corn(Decorator):
    def __init__(self, component):
        Decorator.__init__(self, component)
        self.description = "Corn"
        self.cost = 0.99

    def get_cost(self):
        return self.cost

    def get_description(self):
        return self.component.get_description() + ", " + self.description

def get_pizza_choice():
    while True:
        print("Choose a pizza. İf you want to exit enter 'q' :")
        choice = input()
        if choice == "1":
            return Classic()
        elif choice == "2":
            return Margherita()
        elif choice == "3":
            return Lahmacun()
        elif choice == "4":
            return Pepperoni()
        elif choice == "5":
            return FourSeasons()
        elif choice == "q":
            return None
        else:
            print("Invalid choice!")

def get_size():
    choice = -1
    while choice == -1:
        print("Please choose size:\n"
              "0-Small\n"
              "1-Medium\n"
              "2-Large")
        try:
            choice = int(input())
        except:
            choice = -1
        if choice == 1 or choice == 2 or choice == 0:
            return choice
        else:
            print("İnvalid choice!")

def get_sauce_choice(pizza):
    choice = 0
    while True:
        print("1: Olives\n"
              "2: Mushrooms\n"
              "3: GoatCheese\n"
              "4: Meat\n"
              "5: Onions\n"
              "6: Corn")
        try:
            choice = int(input())
        except:
            pass
        if choice == 1:
            return Olives(pizza)
        elif choice == 2:
            return Mushrooms(pizza)
        elif choice == 3:
            return GoatCheese(pizza)
        elif choice == 4:
            return Meat(pizza)
        elif choice == 5:
            return Onions(pizza)
        elif choice == 6:
            return Corn(pizza)
        else:
            print("İnvalid selection")

def id_checker(id_number):
    if len(id_number) != 11 or not id_number.isdigit():
        print(id_number)
        print("Invalid ID number")
        return False
    else:
        return True

def get_last_credit_card(id_number):
    last_credit_card = ""
    try:
        with open("Orders_Database.csv", "r") as file:
            reader = csv.reader(file)
            for row in reader:
                if row[1] == id_number:
                    last_credit_card = row[2]
    except FileNotFoundError:
        pass
    return last_credit_card

def add_order_to_database(name, id_number, credit_card_number, pizza_description):
    with open("Orders_Database.csv", "a", newline="") as file:
        writer = csv.writer(file)
        now = datetime.datetime.now()
        order_time = now.strftime("%d-%m-%Y %H:%M:%S")
        writer.writerow([name, id_number, credit_card_number, pizza_description, order_time])

def credit_card_checker(credit_card):
    if len(credit_card) != 16 or not credit_card.isdigit():
        return False
    else:
        return True

if __name__ == '__main__':
    print(menuu)
    cost = 0.0
    pizza_choice = get_pizza_choice()
    if pizza_choice is not None:
        print(pizza_choice.get_description())
        c1 = input("Any sauce ?\nİf you want please enter '1'\n")
        if c1 == "1":
            souce = get_sauce_choice(pizza_choice)
            if pizza_choice.get_description() == "Turk Pizza (Lahmacun)":
                size = 0
                while size <= 0:
                    size = int(input("How many Turk Pizza do you want?\n"))
                    if size <= 0:
                        print("Invalid selection")
                cost = pizza_choice.get_cost(size) + souce.get_cost()
            else:
                size = get_size()
                cost = pizza_choice.get_cost(size) + souce.get_cost()
            if size == 0:
                size_text ="Small"
            elif size == 1:
                size_text ="Medium"
            else :
                size_text = "Large"

            description = souce.get_description() + ", " + size_text
            print(description)
            print("Cost : " + str(cost)+"$")

        else:
            size = get_size()
            if size == 0:
                size_text ="Small"
            elif size == 1:
                size_text ="Medium"
            else :
                size_text = "Large"
            cost = str(pizza_choice.get_cost(size))
            description = pizza_choice.get_description() + " ," + size_text
            print(description + " " + cost+"$")
        name = input("Name Surname :")
        id_number = input("Enter your ID number:\n")
        is_İd = id_checker(id_number)
        while True:
            if is_İd == False:
                id_number = input("Please check your ID number:\n")
                is_İd = id_checker(id_number)
            else:
                break

        last_credit_card = get_last_credit_card(id_number)

        if last_credit_card:
            use_last_credit_card = input("Do you want to use last credit card information? (Y/N): ")
            if use_last_credit_card.lower() == "y":
                credit_card_number = last_credit_card
            else:
                credit_card_number = input("Enter your credit card number: ")
                isCreditcard = credit_card_checker(credit_card_number)
                while True:
                    if not isCreditcard:
                        credit_card_number = input("Please check your Credit Card İnformation:\n")
                        isCreditcard = credit_card_checker(credit_card_number)
                    else:
                        break
        else:
            credit_card_number = input("Enter your credit card number: ")
            isCreditcard = credit_card_checker(credit_card_number)
            while True:
                if not isCreditcard:
                    credit_card_number = input("Please check your Credit Card İnformation:\n")
                    isCreditcard = credit_card_checker(credit_card_number)
                else:
                    break

        add_order_to_database(name, id_number, credit_card_number, description)

        print("Your order is taked, enjoy it :)")
    else:
        print("See you again ! ")


# import pygame library
import tracemalloc
from tracemalloc import start
import pygame
import time

# initialise the pygame font
pygame.font.init()

# Total window
screen = pygame.display.set_mode((700, 700))

# Title and Icon
pygame.display.set_caption("SUDOKU SOLVER USING BACKTRACKING")
img = pygame.image.load('android.svg')
pygame.display.set_icon(img)

x = 0
y = 0
dif = 500 / 9
val = 0
# Default Sudoku Board.
grid =[
		[7, 8, 0, 4, 0, 0, 1, 2, 0],
		[6, 0, 0, 0, 7, 5, 0, 0, 9],
		[0, 0, 0, 6, 0, 1, 0, 7, 8],
		[0, 0, 7, 0, 4, 0, 2, 6, 0],
		[0, 0, 1, 0, 5, 0, 9, 3, 0],
		[9, 0, 4, 0, 6, 0, 0, 0, 5],
		[0, 7, 0, 3, 0, 0, 0, 1, 2],
		[1, 2, 0, 0, 0, 7, 4, 0, 0],
		[0, 4, 9, 2, 0, 6, 0, 0, 7]
	]

# Load test fonts for future use
font1 = pygame.font.SysFont("comicsans", 30)
font2 = pygame.font.SysFont("comicsans", 10)
def get_cord(pos):
	global x
	x = pos[0]//dif
	global y
	y = pos[1]//dif

# Highlight the cell selected
def draw_box():
	for i in range(2):
		pygame.draw.line(screen, (255, 0, 0), (x * dif-3, (y + i)*dif), (x * dif + dif + 3, (y + i)*dif), 7)
		pygame.draw.line(screen, (255, 0, 0), ( (x + i)* dif, y * dif ), ((x + i) * dif, y * dif + dif), 7)

# Function to draw required lines for making Sudoku grid
def draw():
	# Draw the lines

	for i in range (9):
		for j in range (9):
			if grid[i][j]!= 0:

				# Fill blue color in already numbered grid
				pygame.draw.rect(screen, (0, 153, 153), (i * dif, j * dif, dif + 1, dif + 1))

				# Fill grid with default numbers specified
				text1 = font1.render(str(grid[i][j]), 1, (0, 0, 0))
				screen.blit(text1, (i * dif+17, j * dif+5))
	# Draw lines horizontally and verticallyto form grid
	for i in range(10):
		if i % 3 == 0 :
			thick = 7
		else:
			thick = 1
		pygame.draw.line(screen, (0, 0, 0), (0, i * dif), (500, i * dif), thick)
		pygame.draw.line(screen, (0, 0, 0), (i * dif, 0), (i * dif, 500), thick)

# Fill value entered in cell
def draw_val(val):
	text1 = font1.render(str(val), 1, (0, 0, 0))
	screen.blit(text1, (x * dif + 15, y * dif + 15))

# Raise error when wrong value entered
def raise_error1():
	text1 = font1.render("WRONG !!!", 1, (0, 0, 0))
	screen.blit(text1, (20, 570))
def raise_error2():
	text1 = font1.render("Wrong !!! Not a valid Key", 1, (0, 0, 0))
	screen.blit(text1, (20, 570))

# Check if the value entered in board is valid
def valid(m, i, j, val):
	for it in range(9):
		if m[i][it]== val:#check column
			return False
		if m[it][j]== val:#check row
			return False
	#check square
	it = i//3
	jt = j//3
	for i in range(it * 3, it * 3 + 3):
		for j in range (jt * 3, jt * 3 + 3):
			if m[i][j]== val:
				return False
	return True

# Solves the sudoku board using depth first search
def solve(grid, i, j):
	#print(grid)
	#สร้างตัวแปร save ขึ้นมาเพื่อเก็บค่าที่เป็นไปได้แต่ละช่อง
	save = [
				[[], [], [], [], [], [], [], [], []],
				[[], [], [], [], [], [], [], [], []],
				[[], [], [], [], [], [], [], [], []],
				[[], [], [], [], [], [], [], [], []],
				[[], [], [], [], [], [], [], [], []],
				[[], [], [], [], [], [], [], [], []],
				[[], [], [], [], [], [], [], [], []],
				[[], [], [], [], [], [], [], [], []],
				[[], [], [], [], [], [], [], [], []]
				]
	# สร้างตัวแปรในการทำ loop ตรวจสอบแต่ละ squre
	i_ref = 0
	j_ref = 0
	count = 0
	while i <= 8 and j <= 8 :
		if grid[i][j] == 0 :
			# print("Empty")
			for it in range(1,10) :   #หาค่าที่เป็นไปได้ในช่องนั้นๆ แล้วเก็บเข้า save
				if valid(grid,i,j,it) == True :
					#print(i,j,"= ",it)
					save[i][j].append(it)
			if len(save[i][j]) == 1 :   #ถ้าค่าที่เป็นไปได้มีแค่ค่าเดียวให้ใส่ลงช่อง แล้วเอาค่านั้นออกจากต save
				grid[i][j] = save[i][j][0]
				save[i][j].pop()
			pygame.event.pump()
			screen.fill((255, 255, 255))
			draw()
			draw_box()
			pygame.display.update()
			pygame.time.delay(80)
		# else :
		# 	print(grid[i][j])
		if i - i_ref < 2 :
			i+=1
		else :
			if j - j_ref < 2 :
				i = i_ref
				j += 1
			else :
				#print(save)
				i_ref += 3
				i = i_ref
				j = j_ref
				count += 1
				if (count)%3 == 0 and count != 0:
					# print("New squre")
					j_ref += 3
					j = j_ref
					i_ref = 0
					i = i_ref
	#print(save)
	for i_check in range(8) :    #เช็ค save ว่ายังมีค่าที่เป็นไปได้เหลือป่าว ถ้าเหลือก็ recursive ถ้าไม่เหลือก็เสร็จ
		for j_check in range(8) :
			if save[i_check][j_check] != [] :
				#print(save[i_check][j_check])
				solve(grid,0,0)
				break
	#save.sort()

	# print(save[0][2])
	#print(grid)
# Display instruction for the game
def instruction():
	text1 = font2.render("PRESS D TO RESET TO DEFAULT / R TO EMPTY", 1, (0, 0, 0))
	text2 = font2.render("ENTER VALUES AND PRESS ENTER TO VISUALIZE", 1, (0, 0, 0))
	screen.blit(text1, (20, 520))
	screen.blit(text2, (20, 540))

# Display options when solved
def result():
	text1 = font1.render("FINISHED PRESS R or D", 1, (0, 0, 0))
	screen.blit(text1, (20, 570))
run = True
flag1 = 0
flag2 = 0
rs = 0
error = 0

# The loop thats keep the window running
while run:

	# White color background
	screen.fill((255, 255, 255))

	# Loop through the events stored in event.get()
	for event in pygame.event.get():
		# Quit the game window
		if event.type == pygame.QUIT:
			run = False
		# Get the mouse position to insert number
		if event.type == pygame.MOUSEBUTTONDOWN:
			flag1 = 1
			pos = pygame.mouse.get_pos()
			get_cord(pos)
		# Get the number to be inserted if key pressed
		if event.type == pygame.KEYDOWN:
			if event.key == pygame.K_LEFT:
				x-= 1
				flag1 = 1
			if event.key == pygame.K_RIGHT:
				x+= 1
				flag1 = 1
			if event.key == pygame.K_UP:
				y-= 1
				flag1 = 1
			if event.key == pygame.K_DOWN:
				y+= 1
				flag1 = 1
			if event.key == pygame.K_1:
				val = 1
			if event.key == pygame.K_2:
				val = 2
			if event.key == pygame.K_3:
				val = 3
			if event.key == pygame.K_4:
				val = 4
			if event.key == pygame.K_5:
				val = 5
			if event.key == pygame.K_6:
				val = 6
			if event.key == pygame.K_7:
				val = 7
			if event.key == pygame.K_8:
				val = 8
			if event.key == pygame.K_9:
				val = 9
			if event.key == pygame.K_RETURN:
				flag2 = 1

			# If R pressed clear the sudoku board
			if event.key == pygame.K_r:
				rs = 0
				error = 0
				flag2 = 0
				grid =[
				[0, 0, 0, 0, 0, 0, 0, 0, 0],
				[0, 0, 0, 0, 0, 0, 0, 0, 0],
				[0, 0, 0, 0, 0, 0, 0, 0, 0],
				[0, 0, 0, 0, 0, 0, 0, 0, 0],
				[0, 0, 0, 0, 0, 0, 0, 0, 0],
				[0, 0, 0, 0, 0, 0, 0, 0, 0],
				[0, 0, 0, 0, 0, 0, 0, 0, 0],
				[0, 0, 0, 0, 0, 0, 0, 0, 0],
				[0, 0, 0, 0, 0, 0, 0, 0, 0]
				]
			# If D is pressed reset the board to default
			if event.key == pygame.K_d:
				rs = 0
				error = 0
				flag2 = 0
				grid =[
					[7, 8, 0, 4, 0, 0, 1, 2, 0],
					[6, 0, 0, 0, 7, 5, 0, 0, 9],
					[0, 0, 0, 6, 0, 1, 0, 7, 8],
					[0, 0, 7, 0, 4, 0, 2, 6, 0],
					[0, 0, 1, 0, 5, 0, 9, 3, 0],
					[9, 0, 4, 0, 6, 0, 0, 0, 5],
					[0, 7, 0, 3, 0, 0, 0, 1, 2],
					[1, 2, 0, 0, 0, 7, 4, 0, 0],
					[0, 4, 9, 2, 0, 6, 0, 0, 7]
				]

	if flag2 == 1:
		tracemalloc.start()
		start_time = time.time()
		if solve(grid, 0, 0)== False:
			error = 1
		else:
			rs = 1
		elasped_time = time.time()-start_time
		print("time=",end='')
		print(elasped_time)
		flag2 = 0
		print(tracemalloc.get_traced_memory())
		tracemalloc.stop()
	if val != 0:
		draw_val(val)
		# print(x)
		# print(y)
		if valid(grid, int(x), int(y), val)== True:
			grid[int(x)][int(y)]= val
			flag1 = 0
		else:
			grid[int(x)][int(y)]= 0
			raise_error2()
		val = 0

	if error == 1:
		raise_error1()
	if rs == 1:
		result()
	draw()
	if flag1 == 1:
		draw_box()
	instruction()

	# Update window
	pygame.display.update()

# Quit pygame window
pygame.quit()


def SelectionSort(ar):
    length = len(ar)
    for i in range(length-1):
        '''
        length - 1 considers till last but one index.
        This is because when we reach the last element, the array is already sorted.
        '''
        min = i
        for j in range(i+1, length):
            '''
            "j" starts from "i+1" as unsorted elements begin from "i".
            '''
            if ar[min] > ar[j]:
                min = j
        ar[i], ar[min] = ar[min], ar[i]

ar = [3, 2, 1, 4, 5, 9, 8, 7, 6]
SelectionSort(ar)
print(ar)


#!/usr/bin/env python

import logging
import gc
from mem import memory_usage, all_info

logging.basicConfig(
    format='%(asctime)-15s  %(levelname)s  %(filename)s:%(lineno)d  %(message)s',
    level=logging.DEBUG,
)

def make_big_list():
    x = [1.0]
    for i in range(6):
        y = []
        for _ in xrange(10):
            y.extend(x)
        x = y
    return x

# http://stackoverflow.com/questions/23369937

"""
Long running Python jobs that consume a lot of memory while
running may not return that memory to the operating system
until the process actually terminates, even if everything
is garbage collected properly.

The solution I need for my problem is that FOR EACH PIECE,
I'll need to spawn a new process AND TERMINATE THAT PROCESS
when its work is done. I think that's the only way out of this
morass.
"""

def main():
    for _ in xrange(5):
        logging.debug(memory_usage())
        logging.debug(all_info(gc.get_objects()))
        x = make_big_list()
        logging.debug(memory_usage())
        logging.debug(all_info(gc.get_objects()))
        del x
        logging.debug(memory_usage())
        logging.debug(all_info(gc.get_objects()))

if __name__ == "__main__":
    main()


import numpy as np

def minmax(x):
    if not isinstance(x, np.ndarray) or not np.issubdtype(x.dtype, np.number) or \
        not (x.ndim == 1 or (x.ndim == 2 and (x.shape[0] == 1 or x.shape[1] == 1))):
        return None
    if x.shape[0] == 0 or (x.ndim == 2 and x.shape[1] == 0):
        return None
    normalize_minmax = lambda i: (i - np.amin(x)) / (np.amax(x) - np.amin(x))
    normalize_vect = np.vectorize(normalize_minmax)
    return normalize_vect(x).reshape(1, -1)[0]


from django.urls import path
from .views import ItemCreateView,ItemCategoryListView,ItemCategoryEditView,CategoryRemoveView,ProductCreateView,ProductListView,ProductEditView,ProductRemoveView,ViewCustomerOrders,LogInView,LogoutView,StatusUpdateView

urlpatterns = [
    path('additem',ItemCreateView.as_view(),name="additem"),
    path('items',ItemCategoryListView.as_view(),name="listitems"),
    path('items/<int:pk>',ItemCategoryEditView.as_view(),name="updatecategory"),
    path("itemremove/<int:pk>",CategoryRemoveView.as_view(),name="removecategory"),
    path("addproduct",ProductCreateView.as_view(),name="addproduct"),
    path("products",ProductListView.as_view(),name="products"),
    path("product/<int:pk>",ProductEditView.as_view(),name="updateproduct"),
    path("productremove/<int:pk>",ProductRemoveView.as_view(),name="removeproduct"),
    path("orders",ViewCustomerOrders.as_view(),name="orders"),
    path("login",LogInView.as_view(),name="login"),
    path("logout",LogoutView.as_view(),name="logout"),
    path("status/<int:pk>",StatusUpdateView.as_view(),name="status")
    ]


# Prompt form___exe.3 Push </>
print("Prompt form Exe.4 Push </>")
# An invocation that counts the number of times the letter a occurs in “banana”.
# Default 'banana'
words_nd = input("Enter text:\n").lower()
# Default 'a'
prompt = input("Enter letter to find its number of times:\n").lower()
word_count = words_nd.count(prompt)
print(word_count)
# Done with Exercise 4 Code Strings Chapter 4


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/2/14 16:57
# @Author  : Baimohan/PH
# @Site    : https://github.com/BaiMoHan
# @File    : function_return_test.py
# @Software: PyCharm
def get_math_func(types):   # python支持在函数内定义函数为局部函数，局部函数对外隐藏
    # 定义一个计算平方的局部函数
    def square(n):
        return n ** 2
    # 定义一个计算立方的局部函数
    def cub(n):
        return n ** 3
    # 定义一个计算阶乘的局部函数
    def factorial(n):
        result = 1
        for index in range(2, n + 1):
            result *= index
        return result
    # 调用局部函数
    if types == 'square':
        return square
    elif types == 'cub':
        return cub
    else:
        return factorial

if __name__ == '__main__':
    math_func = get_math_func('cub')    # 程序返回一个嵌套函数
    # print(math_func)    <function get_math_func.<locals>.cub at 0x0000013E3F41C318>
    print(math_func(5))
    math_func = get_math_func('square')
    print(math_func(5))
    math_func = get_math_func('')
    print(math_func(5))


from django.core.management.base import BaseCommand
from django.utils import timezone
from profile_app.models import Roiincome,Package,LevelIncome
from account.models import Account

class Command(BaseCommand):
    help = 'Roi Income'

    def sendLevelIncome(self,userId,income):

        try:
            user = Account.objects.get(id=userId)

            # send 1 level Income...
            firstleveluser = user.sponsor
            if firstleveluser.is_active1 and firstleveluser.is_able_for_income:
                levelincome = LevelIncome(user=firstleveluser, from_user=user,
                level="1", income=(income*15)/100)
                levelincome.save()
                firstleveluser.total_level_income += (income*15)/100
                firstleveluser.total_income += (income*15)/100
                firstleveluser.available_amount += (income*15)/100
                firstleveluser.save()

            # send 2 level Income...
            secondleveluser = firstleveluser.sponsor
            if secondleveluser.is_active1 and secondleveluser.is_able_for_income:
                levelincome = LevelIncome(user=secondleveluser, from_user=user,
                level="2", income=(income*12)/100)
                levelincome.save()
                secondleveluser.total_level_income += (income*12)/100
                secondleveluser.total_income += (income*12)/100
                secondleveluser.available_amount += (income*12)/100
                secondleveluser.save()

            # send 3 level Income...
            thirdleveluser = secondleveluser.sponsor
            if thirdleveluser.is_active1 and thirdleveluser.is_able_for_income:
                levelincome = LevelIncome(user=thirdleveluser, from_user=user,
                level="3", income=(income*9)/100)
                levelincome.save()
                thirdleveluser.total_level_income += (income*9)/100
                thirdleveluser.total_income += (income*9)/100
                thirdleveluser.available_amount += (income*9)/100
                thirdleveluser.save()

            # send 4 level Income...
            fourthleveluser = thirdleveluser.sponsor
            if fourthleveluser.is_active1 and fourthleveluser.is_able_for_income:
                levelincome = LevelIncome(user=fourthleveluser, from_user=user,
                level="4", income=(income*9)/100)
                levelincome.save()
                fourthleveluser.total_level_income += (income*9)/100
                fourthleveluser.total_income += (income*9)/100
                fourthleveluser.available_amount += (income*9)/100
                fourthleveluser.save()

            # send 5 level Income...
            fifthleveluser = fourthleveluser.sponsor
            if fifthleveluser.is_active1 and fifthleveluser.is_able_for_income:
                levelincome = LevelIncome(user=fifthleveluser, from_user=user,
                level="5", income=(income*9)/100)
                levelincome.save()
                fifthleveluser.total_level_income += (income*9)/100
                fifthleveluser.total_income += (income*9)/100
                fifthleveluser.available_amount += (income*9)/100
                fifthleveluser.save()

            # send 6 level Income...
            sixthleveluser = fifthleveluser.sponsor
            if sixthleveluser.is_active1 and sixthleveluser.is_able_for_income:
                levelincome = LevelIncome(user=sixthleveluser, from_user=user,
                level="6", income=(income*6)/100)
                levelincome.save()
                sixthleveluser.total_level_income += (income*6)/100
                sixthleveluser.total_income += (income*6)/100
                sixthleveluser.available_amount += (income*6)/100
                sixthleveluser.save()

            # send 7 level Income...
            sevenleveluser = sixthleveluser.sponsor
            if sevenleveluser.is_active1 and sevenleveluser.is_able_for_income:
                levelincome = LevelIncome(user=sevenleveluser, from_user=user,
                level="7", income=(income*6)/100)
                levelincome.save()
                sevenleveluser.total_level_income += (income*6)/100
                sevenleveluser.total_income += (income*6)/100
                sevenleveluser.available_amount += (income*6)/100
                sevenleveluser.save()

            # send 8 level Income...
            eightleveluser = sevenleveluser.sponsor
            if eightleveluser.is_active1 and eightleveluser.is_able_for_income:
                levelincome = LevelIncome(user=eightleveluser, from_user=user,
                level="8", income=(income*6)/100)
                levelincome.save()
                eightleveluser.total_level_income += (income*6)/100
                eightleveluser.total_income += (income*6)/100
                eightleveluser.available_amount += (income*6)/100
                eightleveluser.save()

            # send 9 level Income...
            nineleveluser = eightleveluser.sponsor
            if nineleveluser.is_active1 and nineleveluser.is_able_for_income:
                levelincome = LevelIncome(user=nineleveluser, from_user=user,
                level="9", income=(income*6)/100)
                levelincome.save()
                nineleveluser.total_level_income += (income*6)/100
                nineleveluser.total_income += (income*6)/100
                nineleveluser.available_amount += (income*6)/100
                nineleveluser.save()

            # send 10 level Income...
            tenleveluser = nineleveluser.sponsor
            if tenleveluser.is_active1 and tenleveluser.is_able_for_income:
                levelincome = LevelIncome(user=tenleveluser, from_user=user,
                level="10", income=(income*6)/100)
                levelincome.save()
                tenleveluser.total_level_income += (income*6)/100
                tenleveluser.total_income += (income*6)/100
                tenleveluser.available_amount += (income*6)/100
                tenleveluser.save()

            # send 11 level Income...
            elevenleveluser = tenleveluser.sponsor
            if elevenleveluser.is_active1 and elevenleveluser.is_able_for_income:
                levelincome = LevelIncome(user=elevenleveluser, from_user=user,
                level="11", income=(income*4)/100)
                levelincome.save()
                elevenleveluser.total_level_income += (income*4)/100
                elevenleveluser.total_income += (income*4)/100
                elevenleveluser.available_amount += (income*4)/100
                elevenleveluser.save()

            # send 12 level Income...
            twelveleveluser = elevenleveluser.sponsor
            if twelveleveluser.is_active1 and twelveleveluser.is_able_for_income:
                levelincome = LevelIncome(user=twelveleveluser, from_user=user,
                level="12", income=(income*4)/100)
                levelincome.save()
                twelveleveluser.total_level_income += (income*4)/100
                twelveleveluser.total_income += (income*4)/100
                twelveleveluser.available_amount += (income*4)/100
                twelveleveluser.save()

            # send 13 level Income...
            thirteenleveluser = twelveleveluser.sponsor
            if thirteenleveluser.is_active1 and thirteenleveluser.is_able_for_income:
                levelincome = LevelIncome(user=thirteenleveluser, from_user=user,
                level="13", income=(income*4)/100)
                levelincome.save()
                thirteenleveluser.total_level_income += (income*4)/100
                thirteenleveluser.total_income += (income*4)/100
                thirteenleveluser.available_amount += (income*4)/100
                thirteenleveluser.save()

            # send 14 level Income...
            fourtheenleveluser = thirteenleveluser.sponsor
            if fourtheenleveluser.is_active1 and fourtheenleveluser.is_able_for_income:
                levelincome = LevelIncome(user=fourtheenleveluser, from_user=user,
                level="14", income=(income*4)/100)
                levelincome.save()
                fourtheenleveluser.total_level_income += (income*4)/100
                fourtheenleveluser.total_income += (income*4)/100
                fourtheenleveluser.available_amount += (income*4)/100
                fourtheenleveluser.save()

            # send 15 level Income...
            fiftheenleveluser = fourtheenleveluser.sponsor
            if fiftheenleveluser.is_active1 and fiftheenleveluser.is_able_for_income:
                levelincome = LevelIncome(user=fiftheenleveluser, from_user=user,
                level="15", income=(income*4)/100)
                levelincome.save()
                fiftheenleveluser.total_level_income += (income*4)/100
                fiftheenleveluser.total_income += (income*4)/100
                fiftheenleveluser.available_amount += (income*4)/100
                fiftheenleveluser.save()

# --------------------------------------------------------------------#
#                      |  # Super Level Income |                      #
# --------------------------------------------------------------------#

            # send 16 level Income...
            sixteenleveluser = fiftheenleveluser.sponsor
            pack50  = Package.objects.get(amount=50)
            if sixteenleveluser.is_active1 and sixteenleveluser.is_able_for_income and pack50 in  sixteenleveluser.supper_packages.all():
                levelincome = LevelIncome(user=sixteenleveluser, from_user=user,
                level="16", income=(income*3)/100)
                levelincome.save()
                sixteenleveluser.total_level_income += (income*3)/100
                sixteenleveluser.total_income += (income*3)/100
                sixteenleveluser.available_amount += (income*3)/100
                sixteenleveluser.save()

            # send 17 level Income...
            seventeenleveluser = sixteenleveluser.sponsor
            if seventeenleveluser.is_active1 and seventeenleveluser.is_able_for_income and pack50 in  seventeenleveluser.supper_packages.all():
                levelincome = LevelIncome(user=sixteenleveluser, from_user=user,
                level="17", income=(income*3)/100)
                levelincome.save()
                seventeenleveluser.total_level_income += (income*3)/100
                seventeenleveluser.total_income += (income*3)/100
                seventeenleveluser.available_amount += (income*3)/100
                seventeenleveluser.save()

            # send 18 level Income...
            eightteenleveluser = seventeenleveluser.sponsor
            if eightteenleveluser.is_active1 and eightteenleveluser.is_able_for_income and pack50 in  eightteenleveluser.supper_packages.all():
                levelincome = LevelIncome(user=eightteenleveluser, from_user=user,
                level="18", income=(income*3)/100)
                levelincome.save()
                eightteenleveluser.total_level_income += (income*3)/100
                eightteenleveluser.total_income += (income*3)/100
                eightteenleveluser.available_amount += (income*3)/100
                eightteenleveluser.save()

            # send 19 level Income...
            nineteenleveluser = eightteenleveluser.sponsor
            pack100  = Package.objects.get(amount=100)
            if nineteenleveluser.is_active1 and nineteenleveluser.is_able_for_income and pack100 in  nineteenleveluser.supper_packages.all():
                levelincome = LevelIncome(user=nineteenleveluser, from_user=user,
                level="19", income=(income*2)/100)
                levelincome.save()
                nineteenleveluser.total_level_income += (income*2)/100
                nineteenleveluser.total_income += (income*2)/100
                nineteenleveluser.available_amount += (income*2)/100
                nineteenleveluser.save()

            # send 20 level Income...
            twenteelevel = nineteenleveluser.sponsor
            if twenteelevel.is_active1 and twenteelevel.is_able_for_income and pack100 in  twenteelevel.supper_packages.all():
                levelincome = LevelIncome(user=twenteelevel, from_user=user,
                level="20", income=(income*2)/100)
                levelincome.save()
                twenteelevel.total_level_income += (income*2)/100
                twenteelevel.total_income += (income*2)/100
                twenteelevel.available_amount += (income*2)/100
                twenteelevel.save()

            # send 21 level Income...
            twenteeonelevel = twenteelevel.sponsor
            pack250  = Package.objects.get(amount=250)
            if twenteeonelevel.is_active1 and twenteeonelevel.is_able_for_income and pack250 in  twenteeonelevel.supper_packages.all():
                levelincome = LevelIncome(user=twenteeonelevel, from_user=user,
                level="21", income=(income*1)/100)
                levelincome.save()
                twenteeonelevel.total_level_income += (income*1)/100
                twenteeonelevel.total_income += (income*1)/100
                twenteeonelevel.available_amount += (income*1)/100
                twenteeonelevel.save()

            # send 22 level Income...
            twenteetwolevel = twenteeonelevel.sponsor
            if twenteetwolevel.is_active1 and twenteetwolevel.is_able_for_income and pack250 in  twenteetwolevel.supper_packages.all():
                levelincome = LevelIncome(user=twenteetwolevel, from_user=user,
                level="22", income=(income*1)/100)
                levelincome.save()
                twenteetwolevel.total_level_income += (income*1)/100
                twenteetwolevel.total_income += (income*1)/100
                twenteetwolevel.available_amount += (income*1)/100
                twenteetwolevel.save()

            # send 23 level Income...
            twenteethreelevel = twenteetwolevel.sponsor
            pack500  = Package.objects.get(amount=500)
            if twenteethreelevel.is_active1 and twenteethreelevel.is_able_for_income and pack250 in  twenteethreelevel.supper_packages.all():
                levelincome = LevelIncome(user=twenteethreelevel, from_user=user,
                level="23", income=(income*1)/100)
                levelincome.save()
                twenteethreelevel.total_level_income += (income*1)/100
                twenteethreelevel.total_income += (income*1)/100
                twenteethreelevel.available_amount += (income*1)/100
                twenteethreelevel.save()

            # send 24 level Income...
            twenteefourlevel = twenteethreelevel.sponsor
            if twenteefourlevel.is_active1 and twenteefourlevel.is_able_for_income and pack250 in  twenteefourlevel.supper_packages.all():
                levelincome = LevelIncome(user=twenteefourlevel, from_user=user,
                level="24", income=(income*1)/100)
                levelincome.save()
                twenteefourlevel.total_level_income += (income*1)/100
                twenteefourlevel.total_income += (income*1)/100
                twenteefourlevel.available_amount += (income*1)/100
                twenteefourlevel.save()

            # send 25 level Income...
            twenteefivelevel = twenteefourlevel.sponsor
            if twenteefivelevel.is_active1 and twenteefivelevel.is_able_for_income and pack250 in  twenteefivelevel.supper_packages.all():
                levelincome = LevelIncome(user=twenteefivelevel, from_user=user,
                level="24", income=(income*1)/100)
                levelincome.save()
                twenteefivelevel.total_level_income += (income*1)/100
                twenteefivelevel.total_income += (income*1)/100
                twenteefivelevel.available_amount += (income*1)/100
                twenteefivelevel.save()

        except Exception as e:
            print(e)

    def handle(self, *args, **kwargs):
        try:
            allActiveUsers = Account.objects.filter(is_active1=True)
            for user in allActiveUsers:
                if user.is_able_for_income:
                    for package in user.packages.all():
                        if Roiincome.objects.filter(user=user, package=package).count() <= 300:
                            income = (package.amount*1)/100
                            roi_obj = Roiincome(user=user, package=package, income=income)
                            roi_obj.save()

                            #update roiincome....
                            user.total_roi_income += income

                            #update available income.....
                            user.available_amount += income

                            # update total income.....
                            user.total_income += income

                            user.save()

                            self.sendLevelIncome(user.id,income)

        except Exception as e:
            print(e)


#!/usr/local/bin/python3
"""
Bradley Dilger, cbdilger@gmail.com
parse captions copied from YouTube,
reduce the number of timestamps printed out,
put them in brackets,
and concatenate the strings involved.

Usage:
process-yt-captions.py < raw-caption-file.txt > processed-captions.txt

00:00	all right we see red lights that's what
00:02	we want to see all right so I printed
00:06	out the questions okay so what we're
00:08	gonna do is first we have some questions

becomes

[00:00]
all right we see red lights that's what we want to see all right so I printed out the questions okay so what we're gonna do is first we have some questions
"""

# make an empty hash
Transcript = {}

# start our counter
increment = 0

# higher numbers will print fewer timestamps
timestamp = 8

# read in file from standard input
# https://stackoverflow.com/questions/1450393/how-do-you-read-from-stdin

# needed for standard input
import sys

# read transcript file and build a directory with time:content as key:value pairs
for line in sys.stdin:
    time,content = (line.rstrip()).split('\t')
    Transcript[time] = content

# print transcript file
for time in Transcript.keys():
	increment = increment + 1

	if (increment % timestamp == 0):
		print("\n\n", '[', time, ']', sep='')
		print(Transcript[time], end=' ')
	else:
		print(Transcript[time], end=' ')

print()


# Usando Python, faça o que se pede (código e printscreen):
#
#     Crie uma lista vazia;
#     Adicione os elementos: 1, 2, 3, 4 e 5,  usando append();
#     Imprima a lista;
#     Agora, remova os elementos 3 e 6 (não esqueça de checar se eles estão na lista);
#     Imprima a lista modificada;
#     Imprima também o tamanho da lista usando a função len();
#     Altere o valor do último elemento para 6 e imprima a lista modificada.

# Vars
lista = list()

# funcs
def add_list(elementos):

    for elemento in elementos:
        lista.append(elemento)

    print(lista)

def check_and_remove_from_list(elementos, remover):

    for elemento in elementos:
        for num in remover:
            if elemento == num:
                lista.remove(elemento)

    print(lista)

def change_last(elementos, mod):

    lista[len(lista) - 1] = mod

    print(lista)

# MAIN
remover = [3, 6]
elementos = [1, 2, 3, 4, 5]
add_list(elementos)
check_and_remove_from_list(elementos, remover)
print(len(lista))
change_last(elementos, 6)


import logging

from openupgradelib import openupgrade

import odoo

_logger = logging.getLogger(__name__)

def load_modules(registry, force_demo=False, status=None, update_module=False):
    with registry.cursor() as cr:
        # create a technical table
        # to track number of rows per table before and after the migration
        if not openupgrade.table_exists(cr, "openupgrade_track_row_count"):
            cr.execute(
                """
                CREATE TABLE IF NOT EXISTS openupgrade_track_row_count (
                    id serial NOT NULL,
                    table_name character varying(128) NOT NULL,
                    old_row_count integer DEFAULT 0,
                    new_row_count integer
                );
                """,
            )
            # update old rows count of all table before running the migration
            cr.execute(
                """
                WITH tbl AS (
                  SELECT table_name
                  FROM information_schema.tables
                  WHERE table_name not like 'pg_%'
                      AND table_name not like 'ir_%'
                      AND table_name not like 'test_%'
                      AND table_name not like '%_test'
                      AND table_name != 'openupgrade_track_row_count'
                      AND table_schema = 'public'
                )
                INSERT INTO openupgrade_track_row_count (table_name, old_row_count)
                SELECT
                  table_name,
                  (xpath('/row/c/text()',
                    query_to_xml(format('select count(*) AS c from %I', table_name),
                    false,
                    true,
                    '')))[1]::text::int AS old_row_count
                FROM tbl;
                """,
            )

    load_modules._original_method(
        registry,
        force_demo=force_demo,
        status=status,
        update_module=update_module,
    )

    with registry.cursor() as cr:
        # update new number of rows of all table after running the migration
        cr.execute(
            """
            WITH tbl AS (
              SELECT id, table_name
              FROM openupgrade_track_row_count
            )
            UPDATE openupgrade_track_row_count otrc
            SET new_row_count =
              (xpath('/row/c/text()',
                query_to_xml(format('select count(*) AS c from %I', otrc.table_name),
                false,
                true,
                '')))[1]::text::int
            FROM tbl
            WHERE (
                SELECT 1
                FROM information_schema.tables
                WHERE table_name=otrc.table_name
                ) > 0
                AND otrc.id = tbl.id;
            """,
        )
    with registry.cursor() as cr:
        cr.execute(
            """
            SELECT table_name, old_row_count, new_row_count
            FROM openupgrade_track_row_count
            WHERE old_row_count != new_row_count
            """,
        )
        result = cr.dictfetchall()
        if bool(result):

            def msg(col1, col2, col3):
                return "%s%s| %s%s| %s%s\n" % (
                    col1,
                    " " * (50 - len(col1)),
                    col2,
                    " " * (15 - len(str(col2))),
                    col3,
                    " " * (15 - len(str(col3))),
                )

            msg_all = msg("Table name", "Old row count", "New row count")
            for r in result:
                msg_all += msg(r["table_name"], r["old_row_count"], r["new_row_count"])
            _logger.warning(
                "The following tables have different number of rows:\n" "%s\n" % msg_all
            )

load_modules._original_method = odoo.modules.load_modules
odoo.modules.load_modules = load_modules


import pandas as pd
import os
import numpy as np

class DataLoader:
    """
    Class for loading and retrieving raw data from the CSVs into various formats.
    """

    def __init__(self):
        pass

    def load_all_three_dfs(
        self, raw_data_path, train_size=None, val_size=None, test_size=None
    ):

        train_df = self.load_data_df(raw_data_path + "train/")
        test_df = self.load_data_df(raw_data_path + "test/")
        val_df = self.load_data_df(raw_data_path + "dev/")

        if train_size:
            train_df = train_df.sample(train_size, random_state=1)
        if test_size:
            test_df = test_df.sample(test_size, random_state=1)
        if val_size:
            val_df = val_df.sample(val_size, random_state=1)

        return train_df, val_df, test_df

    def load_data_df(self, path):

        full_path = [path + "/" + file for file in os.listdir(path=path)]

        list_of_dfs = []
        for file in full_path:
            list_of_dfs.append(self.read_file_df(file))

        return pd.concat(list_of_dfs)

    def read_file_df(self, file):

        return pd.read_csv(file, index_col=None)

    def numpy_input_sequence(self, df):
        return np.array(df["sequence"].values)

if __name__ == "__main__":
    Loader = DataLoader()

    df = Loader.load_data_df("random_split/train")

    print(df.shape)


# Solution to Project Euler problem 145.

# The following solution works, but it's glacially slow.
# It got the correct result after ~1250s on my machine.

def all_digits_odd(n):
    """Returns True if n contains only odd digits, False otherwise."""
    # Because we have to turn n into a string to loop over it,
    # this test for oddness is much faster than converting each
    # digit-string back into an integer and taking it modulo 2.
    for digit in str(n):
        if digit in {"0", "2", "4", "6", "8"}:
            return False
    else:
        return True

def run():
    count_reversible = 0
    for i in range(1_000_000_000):  # numbers below one billion
        # Skip numbers which end in a zero - their reverse
        # would have a leading zero, which isn't allowed.
        if i % 10 == 0:
            continue
        # Otherwise, reverse i, add i and reverse_i together,
        # and test whether all digits in this sum are odd.
        reverse_i = int(str(i)[::-1])
        if all_digits_odd(i + reverse_i):
            count_reversible += 1

    return count_reversible

if __name__ == "__main__":
    print(run())


import sys
import gym
import time
from gym import wrappers
from gym_foo.agent.agent import Agent
from gym_foo.agent.random_agent import RandomAgent
from gym_foo.agent.q_learning_agent_v2 import QLearnAgent_V2
from gym_foo.agent.attack_agent import TowerRushAgent, AttackTowerAgent, AttackMainTowerAgent
from gym_foo.model.battlefield_detail import BattleField
from gym_foo.Utils import *
import random
import os

object_path = os.path.dirname(__file__)
alpha = 0.5
gamma = 0.9
agent_model_path = os.path.join(object_path, 'agent_model_v2/train_0/agent0.pkl')

if __name__ == "__main__":
    win = 0
    total = 0
    agent_0 = QLearnAgent_V2(team=0, agent_model_path=agent_model_path)
    for iter in range(500):
        grid = gym.make('ava-v1')
        # grid = wrappers.Monitor(grid, './videos', force=True)  # 记录回放动画
        grid.reset()
        # grid.render()
        is_start = True
        agent_1 = random.choice([TowerRushAgent(team=1), AttackTowerAgent(team=1), AttackMainTowerAgent(team=1)])
        while True:
            if is_start:
                state, score, is_terminate, detail = grid.initial_state()
                is_start = False

            detail_for_agent0 = BattleField(
                battle_field_total=detail,
                team=0
            )

            detail_for_agent1 = BattleField(
                battle_field_total=detail,
                team=1
            )

            agent0_s0_list = []
            for hive in detail_for_agent0.get_self_hives():
                agent0_s0_list.append(get_status_rewards_from_detail_v2(detail_for_agent0, hive)[1])
            agent1_r11, agent1_s0 = get_status_rewards_from_detail(detail_for_agent1)
            agent0_a0_list, agent0_action_list = agent_0.generate_action(state, score, detail_for_agent0)
            action_list = [agent0_action_list, agent_1.generate_action(state, score, detail_for_agent1)]
            state, score, is_terminate, detail = grid.step(action_list)
            s1_detail_for_agent0 = BattleField(
                battle_field_total=detail,
                team=0
            )
            s1_detail_for_agent1 = BattleField(
                battle_field_total=detail,
                team=1
            )
            agent0_s1_list = []
            agent0_r0 = None
            for hive in detail_for_agent0.get_self_hives():
                agent0_r0, agent0_s1 = get_status_rewards_from_detail_v2(s1_detail_for_agent0, hive)
                agent0_s1_list.append(agent0_s1)
            agent1_r0, agent1_s1 = get_status_rewards_from_detail(s1_detail_for_agent1)
            # train agent0
            # s1处的最大动作
            a1_list = [agent_0.greedy(agent0_s1) for agent0_s1 in agent0_s1_list]
            key1 = ["%s_%s" % (agent0_s1, a1) for agent0_s1, a1 in zip(agent0_s1_list, a1_list)]
            key = ["%s_%s" % (agent0_s0, agent0_a0) for agent0_s0, agent0_a0 in zip(agent0_s0_list, agent0_a0_list)]
            # 利用qlearning方法更新值函数

            for k, k1 in zip(key, key1):
                agent_0.qfunc[k] = agent_0.qfunc.get(k, 0.0) + alpha * (agent0_r0 + gamma * agent_0.qfunc.get(k1, 0.0) - agent_0.qfunc.get(k, 0.0))

            if is_terminate:
                agent_0.save_agent_model(agent_model_path)
                # print('Over, score:', score, detail)
                s0, s1 = detail.get_score()
                if s0 >= s1:
                    win += 1
                total += 1
                print('iter: %d, score: %s, win: %d, total: %d, win_rate: %f, beat: %s, state_num: %d' % (iter, str(detail.get_score()), win, total, win / total, type(agent_1), len(agent_0.qfunc)))
                # print(detail.get_battle_reports())
                # print(detail_for_agent0.get_scout_reports())
                # print(detail_for_agent1.get_scout_reports())
                break

            else:
                # print('Round, score:', score, detail)
                pass


#!/usr/bin/python3

import os, sys
bindir = os.path.abspath(os.path.dirname(sys.argv[0]))
libdir = bindir + "/../lib"
sys.path.append(libdir)

import logging

import lacuna
import lacuna.exceptions as err
import lacuna.binutils.libspies_report as lib

sr  = lib.SpiesReport()
l   = sr.client.user_logger

### sr.planets will be a list, containing either just the planet name passed
### in by the user, or all of the user's planet names if 'all' was passed in.
for pname in sr.planets:

    ### Set the current planet name as our 'working' planet
    try:
        sr.set_planet( pname )
    except err.NoSuchBuildingError as e:
        l.info( "{} does not have a working Intelligence Ministry.  Skipping.".format(sr.planet.name) )
        continue

    ### Get data on spies at this planet
    l.info( "Gathering spy data on {}.".format(sr.planet.name) )
    sr.gather_spy_data()

sr.display_full_report()


import numpy as np
from qiskit.quantum_info import Statevector

class VQE:
	def __init__(self, ansatz, optimizer):
		self.ansatz = ansatz
		self.optimizer = optimizer

		self.hamiltonian = None
		self.x0 = None
		self.iter = None
		self.cost = None
		self.result = None

	def run(self, hamiltonian, x0=None):
		self.hamiltonian = hamiltonian
		if x0 is None:
			x0 = np.random.uniform(-2 * np.pi, 2 * np.pi, self.ansatz.num_parameters)
		self.x0 = x0

		self.iter = 0

		self.result = self.optimizer.minimize(self.cost_fun, self.x0)

		return VQEResult(self)

	def cost_fun(self, x):
		self.iter += 1
		qc = self.ansatz.assign_parameters(x)
		self.cost = Statevector(qc).expectation_value(self.hamiltonian).real
		self.callback()
		return self.cost

	def callback(self):
		if self.iter % 100 == 0:
			print(f'{self.iter}', f'{self.cost:.8f}')

class VQEResult:
	def __init__(self, vqe):
		self.eigenvalue = vqe.result.fun
		self.eigenstate = Statevector(vqe.ansatz.assign_parameters(vqe.result.x)).data
		self.optimal_parameters = vqe.result.x


import cv2
import numpy as np

# Read the image
img = cv2.imread('lena.jpg')

# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply Gaussian blur to the image
blur = cv2.GaussianBlur(gray, (5,5), 0)

# Perform unsharp masking
unsharp = cv2.addWeighted(gray, 1.5, blur, -0.5, 0)

# Perform Laplacian domain frequency filtering
laplacian = cv2.Laplacian(gray, cv2.CV_64F)
laplacian_filtered = np.uint8(np.abs(laplacian))

# Perform selective filtering
sel_filter = np.zeros_like(gray)
sel_filter[150:250, 150:250] = 1
sel_filtered = cv2.bitwise_and(gray, gray, mask=sel_filter)

# Display the results
cv2.imshow('Original Image', img)
cv2.imshow('Unsharp Masking', unsharp)
cv2.imshow('Laplacian Domain Frequency Filtering', laplacian_filtered)
cv2.imshow('Selective Filtering', sel_filtered)
cv2.waitKey(0)
cv2.destroyAllWindows()


import pandas as pd

from datetime import datetime

from general_utils import write_log

def load_data_to_postgresql(db_handlers, df_db_books, df_db_people, df_db_records):
    pg_cursor = db_handlers[2]
    pg_conn = db_handlers[3]
    write_log('Starting loading data into PostgreSQL database')
    write_log('Loading books in PostgreSQL')
    for book in df_db_books:
        try:
            temp1 = book['book_num_1']
            temp2 = book['book_num_2']
            if(pd.isnull(temp1)):
                temp1 = 0
            if(pd.isnull(temp2)):
                temp2 = 0
            temp1 = (int)(temp1)
            temp2 = (int)(temp2)
            # Добавить ON CONFLICT
            pg_cursor.execute("INSERT INTO books (id_book,title_book,author_book, type_book, year_book, library1_code, library2_code) " +\
                              "VALUES (%s, %s, %s, %s, %s, %s, %s) " +\
                              "ON CONFLICT(id_book) " +\
                              "DO UPDATE SET (library1_code, library2_code)=(EXCLUDED.library1_code, EXCLUDED.library2_code)",
                              (book['id'],book['title'],book['author'],book['type'],book['year'],temp1,temp2)
                              )
            pg_conn.commit()
        except Exception as e:
            print('Error ' + str(e))
            write_log('Error loading books in PostgreSQL: ' + str(e))
    write_log('Finished loading books')
    write_log('Starting loading people in PostgreSQL')
    for person in df_db_people:
        try:
            temp1 = person['library_card_1']
            temp2 = person['library_card_2']
            if(pd.isnull(temp1)):
                temp1 = 0
            if(pd.isnull(temp2)):
                temp2 = 0
            temp1 = (int)(temp1)
            temp2 = (int)(temp2)
            pg_cursor.execute("INSERT INTO people (id,surname_reader, name_reader, patronymic_reader, date_of_birth, library1_code, library2_code) " +\
                              "VALUES (%s, %s, %s, %s, %s, %s, %s) " +\
                              "ON CONFLICT (id) " +\
                              "DO UPDATE SET (library1_code, library2_code)=(EXCLUDED.library1_code, EXCLUDED.library2_code) ",
                              (person['id'],
                               person['surname'],
                               person['name'],
                               person['patronymic'],
                               person['date_of_birth'],
                               temp1, temp2)
                              )
            pg_conn.commit()
        except Exception as e:
            print('Error '+str(e))
            write_log('Error loading people in PostgreSQL ' + str(e))
    try:
        pg_cursor.executemany("INSERT INTO records (id_reader, id_book, date_of_issue, date_of_return, id_library) " +\
                              "VALUES (%s, %s, %s, %s, %s)", df_db_records)
        pg_conn.commit()
    except Exception as e:
        write_log('Error loading records in PostgreSQL ' + str(e))

def load_data_to_clickhouse(db_handlers,date_of_extraction):
    pg_cursor = db_handlers[2]
    ch_conn = db_handlers[4]
    temp_key = datetime.strptime(date_of_extraction, '%d/%m/%Y')
    key_for_postgres = temp_key.strftime('%Y-%m-%d')
    pg_cursor.execute("SELECT id_rec, id_reader,id_book, (SELECT type_book from books where id_book = records.id_book), date_of_issue, date_of_return, id_library " +\
                      "FROM records WHERE CAST(date_of_issue as DATE) = "
                      + str("'"+key_for_postgres+"'"))
    pg_data = pg_cursor.fetchall()
    ch_data = [(int(row[0]),int(row[1]),int(row[2]),row[3],row[4],row[5],int(row[6])) for row in pg_data]
    ch_conn.execute("INSERT INTO recdata2 " +\
                    "(id_rec, id_reader, id_book, type_book, date_of_issue, date_of_return, lib_id) VALUES", ch_data)


import tensorflow as tf
from tensorflow.contrib import rnn

def getDNN (x, LSTMCellSize, keep_prob):
    # We will add two dropout layers and LSTM cells with the number of units as LSTMCellSize.
	multi_cell = tf.contrib.rnn.MultiRNNCell([rnn.DropoutWrapper(rnn.BasicLSTMCell(LSTMCellSize), output_keep_prob=keep_prob) for _ in range(2)], state_is_tuple=True)

	# We use the cell to create RNN.
	# Note that outputs is not a tensor, it is a list with one element which is numpy array.
	outputs, states = rnn.static_rnn(multi_cell, [x], dtype=tf.float32)

	# hidden layer with sigmoid activation.
    # Size of the first fully connected layer is same with number of units in LSTM cell.
    # Common practice for this type of deep neural networks is that the size of the fully connected layers after LSTM cell
    # is reduced by half in each layer.
	W_fc1 = weight_variable([LSTMCellSize, 100])
	b_fc1 = bias_variable([100])
	h_fc1 = tf.nn.sigmoid(tf.matmul(outputs[0], W_fc1) + b_fc1)

    # hidden layer with sigmoid activation.
	W_fc2 = weight_variable([100, 50])
	b_fc2 = bias_variable([50])
	h_fc2 = tf.nn.sigmoid(tf.matmul(h_fc1, W_fc2) + b_fc2)

	# dropout layer
	drop2 = tf.nn.dropout(h_fc2, keep_prob)

	# hidden layer with sigmoid activation.
	W_fc3 = weight_variable([50, 25])
	b_fc3 = bias_variable([25])
	h_fc3 = tf.nn.sigmoid(tf.matmul(drop2, W_fc3) + b_fc3)

	# hidden layer with sigmoid activation
	W_fc4 = weight_variable([25, 7])
	b_fc4 = bias_variable([7])
	h_fc4 = tf.nn.sigmoid(tf.matmul(h_fc3, W_fc4) + b_fc4)

	# hidden layer with sigmoid activation
	W_fc5 = weight_variable([7, 7])
	b_fc5 = bias_variable([7])
	h_fc5 = tf.nn.sigmoid(tf.matmul(h_fc4, W_fc5) + b_fc5)

	finalLayerWeights = tf.Variable(tf.random_normal((7, 1)))
	finalLayerBiases = tf.Variable(tf.random_normal([1]))

	# Linear activation for the output layer
	# we are predicting a continuous variable
	pred = tf.matmul(h_fc5, finalLayerWeights) + finalLayerBiases

	return pred

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)


"""empty message

Revision ID: 92be4067e5bf
Revises: 6c9a4dfcd77b
Create Date: 2020-08-24 21:11:35.660453

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '92be4067e5bf'
down_revision = '6c9a4dfcd77b'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint('comments_user_id_fkey', 'comments', type_='foreignkey')
    op.drop_column('comments', 'user_id')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('comments', sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=False))
    op.create_foreign_key('comments_user_id_fkey', 'comments', 'users', ['user_id'], ['id'])
    # ### end Alembic commands ###

Flask API - Social Media Backend/migrations/versions/92be4067e5bf_.py


from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
# Create your models here.

class Movie(models.Model):
    title = models.CharField(max_length=20)
    audience = models.IntegerField()
    release_date = models.DateField()
    genre_menu = (('코미디','코미디'),('공포','공포'),('로맨스','로맨스'))
    genre = models.CharField(max_length=30,choices=genre_menu)
    score = models.IntegerField(validators=(MinValueValidator(0), MaxValueValidator(5),))
    poster_url = models.CharField(max_length=50)
    description = models.TextField()
    actor_image = models.ImageField(blank=True, null=True)


import csv
import os
import glob
import cv2
import numpy as np

face_ids=[]
all_Image_ID=[]
for infile in sorted(glob.glob(r'C:\Implementations\Ccollected Images\all_faces/*.png')):
    face_ids.append(infile)
    all_Image_ID.append(infile[47:-4])

Neutral = r'C:\Implementations\MultiTask CNN Results\0'
Neutral_Multi_CNN = [name for name in os.listdir(Neutral) if os.path.isdir(os.path.join(Neutral, name))]

Angry = r'C:\Implementations\MultiTask CNN Results\1'
Angry_Multi_CNN = [name for name in os.listdir(Angry) if os.path.isdir(os.path.join(Angry, name))]

Disgust=r'C:\Implementations\MultiTask CNN Results\2'
Disgust_Multi_CNN = [name for name in os.listdir(Disgust) if os.path.isdir(os.path.join(Disgust, name))]

Fear = r'C:\Implementations\MultiTask CNN Results\3'
Fear_Multi_CNN = [name for name in os.listdir(Fear) if os.path.isdir(os.path.join(Fear, name))]

Happy=r'C:\Implementations\MultiTask CNN Results\4'
Happy_Multi_CNN = [name for name in os.listdir(Happy) if os.path.isdir(os.path.join(Happy, name))]

Sad=r'C:\Implementations\MultiTask CNN Results\5'
Sad_Multi_CNN = [name for name in os.listdir(Sad) if os.path.isdir(os.path.join(Sad, name))]

Surprise=r'C:\Implementations\MultiTask CNN Results\6'
Surprise_Multi_CNN = [name for name in os.listdir(Surprise) if os.path.isdir(os.path.join(Surprise, name))]

face_id2=[]
for infile in sorted(glob.glob(r'C:\Implementations\SimpleCNN_Emotions+Gender\emotions\angry/*.png')):
    face_id2.append(infile)
angry_CNN_Simple=[]
for i in range(len(face_id2)):
    angry_CNN_Simple.append(face_id2[i][60:-4])

face_id1_=[]
for infile in sorted(glob.glob(r'C:\Implementations\SimpleCNN_Emotions+Gender\emotions\disgust/*.png')):
    face_id1_.append(infile)
Disgust_CNN_Simple=[]
for i in range(len(face_id1_)):
    Disgust_CNN_Simple.append(face_id1_[i][62:-4])

face_id3=[]
for infile in sorted(glob.glob(r'C:\Implementations\SimpleCNN_Emotions+Gender\emotions\fear/*.png')):
    face_id3.append(infile)
fear_CNN_Simple=[]
for i in range(len(face_id3)):
    fear_CNN_Simple.append(face_id3[i][59:-4])

face_id4=[]
for infile in sorted(glob.glob(r'C:\Implementations\SimpleCNN_Emotions+Gender\emotions\happy/*.png')):
    face_id4.append(infile)
happy_CNN_Simple=[]
for i in range(len(face_id4)):
    happy_CNN_Simple.append(face_id4[i][60:-4])

face_id1=[]
for infile in sorted(glob.glob(r'C:\Implementations\SimpleCNN_Emotions+Gender\emotions\neutral/*.png')):
    face_id1.append(infile)
Neutral_CNN_Simple=[]
for i in range(len(face_id1)):
    Neutral_CNN_Simple.append(face_id1[i][62:-4])

face_id5=[]
for infile in sorted(glob.glob(r'C:\Implementations\SimpleCNN_Emotions+Gender\emotions\sad/*.png')):
    face_id5.append(infile)
sad_CNN_Simple=[]
for i in range(len(face_id5)):
    sad_CNN_Simple.append(face_id5[i][58:-4])

face_id6=[]
for infile in sorted(glob.glob(r'C:\Implementations\SimpleCNN_Emotions+Gender\emotions\surprise/*.png')):
    face_id6.append(infile)
Surprise_CNN_Simple=[]
for i in range(len(face_id6)):
    Surprise_CNN_Simple.append(face_id6[i][58:-4])

face_id1=[]
for infile in sorted(glob.glob(r'C:\Implementations\XCeption_Emotions +Gender\emotion_BigXception\angry/*.png')):
    face_id1.append(infile)
Angry_Xception=[]
for i in range(len(face_id1)):
    Angry_Xception.append(face_id1[i][71:-4])

face_id2=[]
for infile in sorted(glob.glob(r'C:\Implementations\XCeption_Emotions +Gender\emotion_BigXception\disgust/*.png')):
    face_id2.append(infile)
Disgust_Xception=[]
for i in range(len(face_id2)):
    Disgust_Xception.append(face_id2[i][73:-4])

face_id3=[]
for infile in sorted(glob.glob(r'C:\Implementations\XCeption_Emotions +Gender\emotion_BigXception\fear/*.png')):
    face_id3.append(infile)
Fear_Xception=[]
for i in range(len(face_id3)):
   Fear_Xception.append(face_id3[i][70:-4])

face_id4=[]
for infile in sorted(glob.glob(r'C:\Implementations\XCeption_Emotions +Gender\emotion_BigXception\happy/*.png')):
    face_id4.append(infile)
Happy_Xception=[]
for i in range(len(face_id4)):
    Happy_Xception.append(face_id4[i][71:-4])

face_id5=[]
for infile in sorted(glob.glob(r'C:\Implementations\XCeption_Emotions +Gender\emotion_BigXception\neutral/*.png')):
    face_id5.append(infile)
Neutral_Xception=[]
for i in range(len(face_id5)):
    Neutral_Xception.append(face_id5[i][73:-4])

face_id6=[]
for infile in sorted(glob.glob(r'C:\Implementations\XCeption_Emotions +Gender\emotion_BigXception\sad/*.png')):
    face_id6.append(infile)
Sad_Xception=[]
for i in range(len(face_id6)):
    Sad_Xception.append(face_id6[i][69:-4])

face_id7=[]
for infile in sorted(glob.glob(r'C:\Implementations\XCeption_Emotions +Gender\emotion_BigXception\surprise/*.png')):
    face_id7.append(infile)
Surprise_Xception=[]
for i in range(len(face_id7)):
    Surprise_Xception.append(face_id7[i][74:-4])

### OpneFace ####

Angry = r'C:\Implementations\Emotions from AUs of OpenFace\0'
Angry_OpenFace = [name for name in os.listdir(Angry) if os.path.isdir(os.path.join(Angry, name))]

Disgust=r'C:\Implementations\Emotions from AUs of OpenFace\1'
Disgust_OpenFace = [name for name in os.listdir(Disgust) if os.path.isdir(os.path.join(Disgust, name))]

Fear=r'C:\Implementations\Emotions from AUs of OpenFace\2'
Fear_OpenFace = [name for name in os.listdir(Fear) if os.path.isdir(os.path.join(Fear, name))]

Happy=r'C:\Implementations\Emotions from AUs of OpenFace\3'
Happy_OpenFace = [name for name in os.listdir(Happy) if os.path.isdir(os.path.join(Happy, name))]

Sad=r'C:\Implementations\Emotions from AUs of OpenFace\4'
Sad_OpenFace = [name for name in os.listdir(Sad) if os.path.isdir(os.path.join(Sad, name))]

def search(list, platform):
    for i in range(len(list)):
        if list[i] == platform:
            return True
    return False
TH=1

for i in range(1855):

    Image_ID=all_Image_ID[i]

    G=np.zeros([7,1])

    ### 1-Simple_CNN #####
    _yes1 =search(angry_CNN_Simple,Image_ID)
    if _yes1==True:
        G[0]=TH

    _yes2 =search(Disgust_CNN_Simple,Image_ID)
    if _yes2==True:
        G[1]=TH

    _yes3 = search(fear_CNN_Simple,Image_ID)
    if _yes3==True:
        G[2]=TH

    _yes4 =search(happy_CNN_Simple,Image_ID)
    if _yes4==True:
        G[3]=TH
    _yes4_ =search(Neutral_CNN_Simple,Image_ID)
    if _yes4_==True:
        G[4]=TH

    _yes5 =search(sad_CNN_Simple,Image_ID)
    if _yes5==True:
        G[5]=TH

    _yes5 =search(Surprise_CNN_Simple,Image_ID)
    if _yes5==True:
        G[6]=TH

    ### 2-MultiTask_CNN ###
    _yes1 =search(Angry_Multi_CNN,Image_ID)
    if _yes1==True:
        G[0]=TH

    _yes2 =search(Disgust_Multi_CNN,Image_ID)
    if _yes2==True:
        G[1]=TH

    _yes3 = search(Fear_Multi_CNN,Image_ID)
    if _yes3==True:
        G[2]=TH

    _yes4 =search(Happy_Multi_CNN,Image_ID)
    if _yes4==True:
        G[3]=TH
    _yes5 =search(Neutral_Multi_CNN,Image_ID)
    if _yes5==True:
        G[4]=TH

    _yes4 =search(Sad_Multi_CNN,Image_ID)
    if _yes4==True:
        G[5]=TH
    _yes5 =search(Surprise_Multi_CNN,Image_ID)
    if _yes5==True:
        G[6]=TH

    ## 3-Xceptionnet
    _yes1 =search(Angry_Xception,Image_ID)
    if _yes1==True:
        G[0]=TH

    _yes2 =search(Disgust_Xception,Image_ID)
    if _yes2==True:
        G[1]=TH

    _yes3 = search(Fear_Xception,Image_ID)
    if _yes3==True:
        G[2]=TH

    _yes4 =search(Happy_Xception,Image_ID)
    if _yes4==True:
        G[3]=TH

    _yes5 =search(Neutral_Xception,Image_ID)
    if _yes5==True:
        G[4]=TH

    _yes6 =search(Sad_Xception,Image_ID)
    if _yes6==True:
        G[5]=TH

    _yes7 =search(Surprise_Xception,Image_ID)
    if _yes7==True:
        G[6]=TH

    ### 4-OpenFace ####

    _yes1 =search(Angry_OpenFace,Image_ID)
    if _yes1==True:
        G[0]=TH

    _yes2 =search(Disgust_OpenFace,Image_ID)
    if _yes2==True:
        G[1]=TH

    _yes3 = search(Fear_OpenFace,Image_ID)
    if _yes3==True:
        G[2]=TH

    _yes4 =search(Happy_OpenFace,Image_ID)
    if _yes4==True:
        G[3]=TH
    _yes5 =search(Sad_OpenFace,Image_ID)
    if _yes5==True:
        G[5]=TH

    ## genrating the text file
    path=r'C:\Implementations\Multi_Label/'+str(Image_ID)+'.txt'
    with open(path, 'w') as f:
        for item in G:
            #f.write(str(item) + "\n")
            y=' '.join(map(str, item))
            f.write(f"{y}\n")

import os
import glob
import numpy as np

text_path=r'C:\Implementations\Multi_Label/'
def READ_DAT():
    image_w=224
    image_h=224
    img_ = []
    text_=[]
    for i in range(1384):
        img=cv2.imread(face_ids[i])
        Image_ID=all_Image_ID[i]
        img = cv2.resize (img, (image_w,image_h), interpolation = cv2.INTER_AREA)
        img=img/255

        img_.append(img)

        u=text_path+Image_ID+'.txt'
        with open(u) as f:
            lines = f.readlines()
            A=[float(k) for k in lines]
            text_.append(A)

            #for line in f:
                #if line: #avoid blank lines
                    #text_.append(float(line.strip()))

    img_ = np.array(img_)
    text_ = np.array(text_)

    return img_,text_

images,text_files=READ_DAT()

Generate Multi-Class Labels/Generate Multi-Task Labels.py


from allauth.account import views as allauth_views
from django.urls import re_path
from user_sessions import views as user_sessions_views

from routechoices.dashboard import views

urlpatterns = [
    re_path(r"^$", views.home_view, name="home_view"),
    re_path(r"^account/?$", views.account_edit_view, name="account_edit_view"),
    re_path(r"^account/emails/?$", views.email, name="account_emails"),
    re_path(
        r"^account/change-password/?$",
        allauth_views.password_change,
        name="account_password_change",
    ),
    re_path(
        r"^account/delete/?$", views.account_delete_view, name="account_delete_view"
    ),
    re_path(
        r"^account/sessions/?$",
        view=user_sessions_views.SessionListView.as_view(),
        name="account_session_list",
    ),
    re_path(
        r"^account/sessions/delete-others/?$",
        view=views.CustomSessionDeleteOtherView.as_view(),
        name="account_session_delete_other",
    ),
    re_path(r"^club/?$", views.club_view, name="club_view"),
    re_path(
        r"^club/send-invite/?$", views.club_invite_add_view, name="club_invite_add_view"
    ),
    re_path(
        r"^club/custom-domain/?$",
        views.club_custom_domain_view,
        name="club_custom_domain_view",
    ),
    re_path(
        r"^club/delete/?$",
        views.club_delete_view,
        name="club_delete_view",
    ),
    re_path(
        r"^club/(?P<club_id>[A-Za-z0-9_-]+)/?$",
        views.club_set_view,
        name="club_set_view",
    ),
    re_path(r"^clubs/?$", views.club_select_view, name="club_select_view"),
    re_path(r"^clubs/new/?$", views.club_create_view, name="club_create_view"),
    re_path(r"^devices/?$", views.device_list_view, name="device_list_view"),
    re_path(r"^devices/new/?$", views.device_add_view, name="device_add_view"),
    re_path(r"^devices.csv$", views.device_list_download, name="device_list_download"),
    re_path(r"^maps/?$", views.map_list_view, name="map_list_view"),
    re_path(r"^maps/new/?$", views.map_create_view, name="map_create_view"),
    re_path(r"^maps/draw/?$", views.map_draw_view, name="map_draw_view"),
    re_path(
        r"^maps/upload-kmz/?$", views.map_kmz_upload_view, name="map_upload_kmz_view"
    ),
    re_path(
        r"^maps/upload-gpx/?$", views.map_gpx_upload_view, name="map_upload_gpx_view"
    ),
    re_path(
        r"^maps/(?P<map_id>[A-Za-z0-9_-]+)/?$",
        views.map_edit_view,
        name="map_edit_view",
    ),
    re_path(
        r"^maps/(?P<map_id>[A-Za-z0-9_-]+)/delete/?$",
        views.map_delete_view,
        name="map_delete_view",
    ),
    re_path(r"^events/?$", views.event_list_view, name="event_list_view"),
    re_path(r"^events/new/?$", views.event_create_view, name="event_create_view"),
    re_path(
        r"^events/(?P<event_id>[A-Za-z0-9_-]+)/?$",
        views.event_edit_view,
        name="event_edit_view",
    ),
    re_path(
        r"^events/(?P<event_id>[A-Za-z0-9_-]+)/competitors/?$",
        views.event_competitors_view,
        name="event_competitors_view",
    ),
    re_path(
        r"^events/(?P<event_id>[A-Za-z0-9_-]+)/competitors-printer-friendly/?$",
        views.event_competitors_printer_view,
        name="event_competitors_printer_view",
    ),
    re_path(
        r"^events/(?P<event_id>[A-Za-z0-9_-]+)/delete/?$",
        views.event_delete_view,
        name="event_delete_view",
    ),
    re_path(
        r"^events/(?P<event_id>[A-Za-z0-9_-]+)/route-upload/?$",
        views.event_route_upload_view,
        name="event_route_upload_view",
    ),
    re_path(r"^event-sets/?$", views.event_set_list_view, name="event_set_list_view"),
    re_path(
        r"^event-sets/new/?$", views.event_set_create_view, name="event_set_create_view"
    ),
    re_path(
        r"^event-sets/(?P<event_set_id>[A-Za-z0-9_-]+)/?$",
        views.event_set_edit_view,
        name="event_set_edit_view",
    ),
    re_path(
        r"^event-sets/(?P<event_set_id>[A-Za-z0-9_-]+)/delete/?$",
        views.event_set_delete_view,
        name="event_set_delete_view",
    ),
    re_path(
        r"^quick-event/?$",
        views.quick_event,
        name="quick_event_view",
    ),
    re_path(r"^upgrade/?$", views.upgrade, name="upgrade"),
]


# https://leetcode.com/problems/minimum-cost-to-cut-a-stick/
from typing import List
from functools import cache

class Solution:
    def minCost(self, n: int, cuts: List[int]) -> int:
        cuts.sort()

        @cache
        def cut(i: int, j: int, s: int, f: int) -> int:
            ans = float("inf")
            for m in range(i, j):
                if f > cuts[m] > s:
                    ans = min(ans, cut(i, m, s, cuts[m]) + cut(m + 1, j, cuts[m], f))
            return (f - s) + ans if ans < float("inf") else 0

        return cut(0, len(cuts), 0, n)

S = Solution()
X = S.minCost(n=9, cuts=[5, 6, 1, 4, 2])
print(X)


class CalculatorFunctions:
    def __init__(self, number1, number2, operation):
        self.number1 = number1
        self.number2 = number2
        self.operation = operation

    def addtion(self):
        """Returns an addtion of two number"""
        addition  = self.number1 + self.number2
        return print(addition)

    def subtraction(self):
        """Returns the subtraction of two number"""
        subtraction = self.number1 - self.number2
        return print("Subtraction", subtraction)

    def multiplication(self):
        """Returns the multiplication of two number"""
        multiplication = self.number1*self.number2
        return print("Multiplication", multiplication)

    def division(self):
        """Returns the division of two number"""
        division = self.number1/self.number2
        return print("Division", division)

    def choose_operation(self):
        """Allows the user to choose an operation"""
        if self.operation == '+' :
            self.addtion()
        elif self.operation == '-':
            self.subtraction()
        elif self.operation == '*':
            self.multiplication()
        elif self.operation == '/':
            self.division()
        else:
            print('Error. Please choose one of the listed operators')

while True:
    first_number = int(input('Choose a number: '))
    second_number = int(input('Choose a second number: '))
    operation = input('Enter the operand +, -, *, / ')
    calc_obj = CalculatorFunctions(first_number, second_number, operation)

    result = calc_obj.choose_operation()

    user_cont = input('Would you like to continue? (y/n) ')
    if user_cont == 'y':
        continue
    else:
        break


        # Первое задание
        # ------------------------------------------------------------------
# import copy
#
# first = tuple("hello", 21, 2.13, "square", 89,)
# second = copy.copy(first)
# third = first[:]
#
# print(first)
# print(second)
# print(third)

        # Второе задание
        # ------------------------------------------------------------------
# import random
#
# def kar(n) :
#     if n == 1:
#         kar = tuple(random.randint(0, 5) for i in range(10))
#         return kar
#     elif n == 2:
#         kar = tuple(random.randint(-5, 0) for i in range(10))
#         return kar
#
# kart1 = kar(1)
# kart2 = kar(2)
# kart3 = kart1 + kart2
#
# print("Первый кортеж: " + str(kart1))
# print("Второй кортеж: " + str(kart2))
#
# print("Третий кортеж: " + str(kart3))
# print("В нём столько нулей: " + str(kart3.count(0)))

        # Третье задание
        #------------------------------------------------------------------

# school = {"1А" : 25, "2Б" : 23, "11Г" : 17 , "8А" : 27 , "4Г" : 30 , "6Б" : 24 , "2А" : 25 , "3Д" : 23 , "9В" : 28 }
# print("Словарь до изменения" + str(school))
# sum = 0
# for value in school.values() :
#     sum = sum + int(value)
# print("Всего учеников: " + str(sum))
#
# school["6Б"]= 5
# school["1А"]= 19
# school.setdefault("6Д", 27)
# school.setdefault("9Г", 19)
# school.pop("11Г")
# school.pop("4Г")
# school.pop("3Д")
#
# print("Словарь после изменения" + str(school))
# sum = 0
# for value in school.values() :
#     sum = sum + int(value)
# print("Всего учеников: " + str(sum))

        # Четвертое задание
        #------------------------------------------------------------------
def obr(sl):
    for key, value in sl:
        sl2[value] =  key
    return sl2

sl1 = {1 : "hello", 2 : "world", 3 : "dog", 4 : "cat", 5 : "end"}
sl2 = {}

print("Исходный кортеж: " + str(sl1))
sl = sl1.items()
print("Переделанный кортеж: " + str(obr(sl)))


import requests

from prjstore.db.api import settings
from prjstore.db.schemas import seller as schemas
from prjstore.db.api.components.base import APIBase

class API_Seller(APIBase[schemas.CreateSeller, schemas.UpdateSeller, schemas.Seller]):
    prefix = 'seller'
    schema = schemas.Seller
    list_schema = schemas.ListSeller

    def __init__(self, headers):
        super().__init__(headers)

    def edit_name(self, seller_id: int, new_name: str) -> schemas.Seller:
        data = schemas.EditSellerName(seller_id=seller_id, new_name=new_name)
        r = requests.put(f"{settings.host}/{self.prefix}/edit_name",
                         data=data.json(), headers=self.headers)
        if r.status_code != 202:
            raise ConnectionError(r.text)
        else:
            return schemas.Seller(**r.json())

    def edit_active(self, seller_id: int, active: bool) -> schemas.Seller:
        data = schemas.EditSellerActive(seller_id=seller_id, active=active)
        r = requests.put(f"{settings.host}/{self.prefix}/edit_active",
                         data=data.json(), headers=self.headers)
        if r.status_code != 202:
            raise ConnectionError(r.text)
        else:
            return schemas.Seller(**r.json())


#!/usr/bin/python

import pickle

def parse_string(s):

    i = s.index('(')+1
    while True:
        res = []
        while True:
            if s[i] == ',':
                i += 1
            elif s[i] == ')':
                i += 1
                break
            elif s[i] == 'N':
                res.append(None)
                i += 4
            elif s[i] == "'":
                j= i = i + 1
                while True:
                    if s[j] == "'":
                        break
                    if s[j] == "\\":
                        j += 1
                    j += 1
                res.append(s[i:j])
                i = j + 1
            else:
                j = i+1
                while True:
                    if s[j] in [')', ',']:
                        x = s[i:j]
                        if x.count('.') != 0:
                            res.append(float(x))
                        else:
                            res.append(int(x))
                        break
                    j += 1
                i = j

        yield res

        if s[i] == ',':
            i += 2
        elif s[i] == ';':
            break

# CREATE TABLE `page` (
#   `page_id` int(8) unsigned NOT NULL AUTO_INCREMENT,
#   `page_namespace` int(11) NOT NULL DEFAULT '0',
#   `page_title` varbinary(255) NOT NULL DEFAULT '',
#   `page_restrictions` varbinary(255) NOT NULL DEFAULT '',
#   `page_counter` bigint(20) unsigned NOT NULL DEFAULT '0',
#   `page_is_redirect` tinyint(1) unsigned NOT NULL DEFAULT '0',
#   `page_is_new` tinyint(1) unsigned NOT NULL DEFAULT '0',
#   `page_random` double unsigned NOT NULL DEFAULT '0',
#   `page_touched` varbinary(14) NOT NULL DEFAULT '',
#   `page_links_updated` varbinary(14) DEFAULT NULL,
#   `page_latest` int(8) unsigned NOT NULL DEFAULT '0',
#   `page_len` int(8) unsigned NOT NULL DEFAULT '0',
#   `page_no_title_convert` tinyint(1) NOT NULL DEFAULT '0',
#   `page_content_model` varbinary(32) DEFAULT NULL,
#   PRIMARY KEY (`page_id`),
#   UNIQUE KEY `name_title` (`page_namespace`,`page_title`),
#   KEY `page_random` (`page_random`),
#   KEY `page_len` (`page_len`),
#   KEY `page_redirect_namespace_len` (`page_is_redirect`,`page_namespace`,`page_len`)
# ) ENGINE=InnoDB AUTO_INCREMENT=6180386 DEFAULT CHARSET=binary;
# /*!40101 SET character_set_client = @saved_cs_client */;

# CREATE TABLE `pagelinks` (
#   `pl_from` int(8) unsigned NOT NULL DEFAULT '0',
#   `pl_namespace` int(11) NOT NULL DEFAULT '0',
#   `pl_title` varbinary(255) NOT NULL DEFAULT '',
#   `pl_from_namespace` int(11) NOT NULL DEFAULT '0',
#   UNIQUE KEY `pl_from` (`pl_from`,`pl_namespace`,`pl_title`),
#   KEY `pl_namespace` (`pl_namespace`,`pl_title`,`pl_from`),
#   KEY `pl_backlinks_namespace` (`pl_from_namespace`,`pl_namespace`,`pl_title`,`pl_from`)
# ) ENGINE=InnoDB DEFAULT CHARSET=binary;

title_map = {}
ids_map = {}
titles = []
sizes = []
raw_links = {}
redirect = []

def parse():

    with open('page.sql') as f:
        i = 0
        while True:
            s = f.readline()
            i += 1
            print('PAGE:', i)
            if not s:
                break
            if not s.startswith('INSERT'):
                continue
            else:
                for (_id, namespace, title, _, _, is_redirect, _, _, _, _, _, size, _, _) in parse_string(s):
                    if namespace != 0:
                        continue
                    ids_map[_id] = len(titles)
                    title_map[title] = len(titles)
                    redirect.append(is_redirect == 1)
                    titles.append(title)
                    sizes.append(size)

    with open('pagelinks.sql') as f:
        i = 0
        while True:
            s = f.readline()
            i += 1
            print('RAW LINKS:', i)
            if not s:
                break
            if not s.startswith('INSERT'):
                continue
            else:
                for (_from, namespace, title, from_namespace) in parse_string(s):
                    if namespace == 0 and from_namespace == 0 and title in title_map and _from in ids_map:
                        _id = ids_map[_from]
                        if not _id in raw_links:
                            raw_links[_id] = []
                        raw_links[_id].append(title_map[title])

def dump():
    with open('wiki', 'wb') as f:
        pickle.dump(title_map, f)
        pickle.dump(ids_map, f)
        pickle.dump(titles, f)
        pickle.dump(sizes, f)
        pickle.dump(raw_links, f)
        pickle.dump(redirect, f)

def load():
    global title_map
    global ids_map
    global titles
    global sizes
    global raw_links
    global redirect

    with open('wiki', 'rb') as f:
        title_map = pickle.load(f)
        ids_map = pickle.load(f)
        titles = pickle.load(f)
        sizes = pickle.load(f)
        raw_links = pickle.load(f)
        redirect = pickle.load(f)

#parse()
load()
print('loaded')
dump()

removed = [False]*len(titles)
cnt = 0

flag = True
while flag:
    flag = False
    for i in range(len(titles)):
        if not removed[i] and redirect[i] and not raw_links.get(i, []):
            removed[i] = True
            flag = True
            cnt += 1

    for (k, v) in raw_links.items():
        if not removed[k]:
            raw_links[k] = [x for x in v if not removed[x]]

print('Removed: %d' % cnt)

n = 0
new_idx = [0]*len(titles)
for i in range(len(titles)):
    new_idx[i] = n
    if not removed[i]:
        n += 1

nlinks = 0
for x in raw_links.values():
    nlinks += len(x)

with open('wiki.txt', 'w') as f:
    f.write('%d %d\n' % (len(titles)-cnt, nlinks))
    for (_id, t) in enumerate(titles):
        if not removed[_id]:
            lnks =  raw_links.get(_id, [])
            f.write(t + '\n')
            f.write('%d %d %s\n' % (sizes[_id], redirect[_id], len(lnks)))
            for l in lnks:
                f.write(str(new_idx[l])+ '\n')


from PySide import QtCore
from PySide import QtGui
import marigold.ui.widgets.QTWidgets as QTWidgets

from marigold.components.BaseComponent import BaseComponent
import marigold.utility.NodeUtility as NodeUtility

class CharacterRootComponent( BaseComponent ):
    nodeType = 'CharacterRootComponent'
    def __init__( self, node=None, *args, **kwargs ):
        self.node = node
        super( CharacterRootComponent, self ).__init__( node=self.node )

    def requiredAttributes( self ):
        super( CharacterRootComponent, self ).requiredAttributes()
        NodeUtility.addPlug( self.newNode, 'characterName', 'dataType', 'string' )
        self.setAttribute( 'characterName', 'joe', self.newNode )

        NodeUtility.addPlug( self.newNode, 'skeletonGroupName', 'dataType', 'string' )
        self.setAttribute( 'skeletonGroupName', 'skeleton', self.newNode )

        NodeUtility.addPlug( self.newNode, 'rigGroupName', 'dataType', 'string' )
        self.setAttribute( 'rigGroupName', 'rig', self.newNode )

        NodeUtility.addPlug( self.newNode, 'modules', 'attributeType', 'message' )

    def componentGui( self, inNodeName, parent=None ):
            '''
            Creates the QT gui for this component.

            @return: QWidget.
            '''
            return componentWidget( inNodeName, parent=parent )

class componentWidget( QtGui.QWidget ):
    '''
    QT QWidget class for this component.
    '''
    def __init__( self, nodeName, parent=None ):
        super( componentWidget, self ).__init__( parent )
        self.parent = parent

        def on_context_menu( point, inNodeName ):
            popMenu = QtGui.QMenu()
            deleteAction = QtGui.QAction( 'Delete Component', popMenu, triggered=lambda a=inNodeName:self.deleteComponentFromObject( a ) )
            popMenu.addAction( deleteAction )

            popMenu.exec_( self.componentLabel.mapToGlobal( point ) )

        # Setup layout.
        verticalLayout = QtGui.QVBoxLayout()
        verticalLayout.setContentsMargins( 0,0,0,0 )
        verticalLayout.setSpacing( 0 )
        verticalLayout.setAlignment( QtCore.Qt.AlignTop )

        # Label for component
        componentLabel = QTWidgets.basicLabel( nodeName, 'bold', 10, 'black', '6E9094', inIndent=20 )
        componentLabel.setMinimumHeight( 18 )
        componentLabel.setContextMenuPolicy( QtCore.Qt.CustomContextMenu )
        componentLabel.customContextMenuRequested.connect( lambda point, nodeName=nodeName:on_context_menu( point, nodeName ) )

        # Properties
        propertyStack = QtGui.QVBoxLayout()

        propertyFrame = QTWidgets.basicFrame()
        propertyFrame.setMinimumHeight( 120 )
        propertyFrame.setMaximumHeight( 120 )

        # Add string edit property
        characterPlug = NodeUtility.getPlug( nodeName, 'characterName' )
        characterValue = NodeUtility.getPlugValue( characterPlug )
        characterTextLayout = QTWidgets.stringProperty( 'Character Name', characterValue )

        skelGroupPlug = NodeUtility.getPlug( nodeName, 'skeletonGroupName' )
        skelGroupValue = NodeUtility.getPlugValue( skelGroupPlug )
        skelGroupTextLayout = QTWidgets.stringProperty( 'Skeleton Group Name', skelGroupValue )

        rigGroupPlug = NodeUtility.getPlug( nodeName, 'rigGroupName' )
        rigGroupValue = NodeUtility.getPlugValue( rigGroupPlug )
        rigGroupTextLayout = QTWidgets.stringProperty( 'Rigging Group Name', rigGroupValue )

        '''
        ADD MODULES BUTTON. PROBABLY HAVE A POPUP LISTING UNCONNECTED MODULES IN THE SCENE??
        '''

        # Add everything to the vertical layout.
        propertyStack.addLayout( characterTextLayout )
        propertyStack.addLayout( skelGroupTextLayout )
        propertyStack.addLayout( rigGroupTextLayout )

        propertyFrame.setLayout( propertyStack )

        verticalLayout.addWidget( componentLabel )
        verticalLayout.addWidget( propertyFrame )

        # Connections
        charTextBox = propertyFrame.findChild( QtGui.QLineEdit, 'Character Name' )
        charTextBox.editingFinished.connect( lambda inPlugName='characterName', inQTType='QLineEdit', inPlugValue=charTextBox, inNodeName=nodeName
                                             :CharacterRootComponent( inNodeName ).setComponentAttributeFromQT( inPlugName, inQTType, inPlugValue, inNodeName ) )

        skelTextBox = propertyFrame.findChild( QtGui.QLineEdit, 'Skeleton Group Name' )
        skelTextBox.editingFinished.connect( lambda inPlugName='skeletonGroupName', inQTType='QLineEdit', inPlugValue=skelTextBox, inNodeName=nodeName
                                             :CharacterRootComponent( inNodeName ).setComponentAttributeFromQT( inPlugName, inQTType, inPlugValue, inNodeName ) )

        rigTextBox = propertyFrame.findChild( QtGui.QLineEdit, 'Rigging Group Name' )
        rigTextBox.editingFinished.connect( lambda inPlugName='rigGroupName', inQTType='QLineEdit', inPlugValue=rigTextBox, inNodeName=nodeName
                                            :CharacterRootComponent( inNodeName ).setComponentAttributeFromQT( inPlugName, inQTType, inPlugValue, inNodeName ) )

        #return mainWidget
        self.setLayout( verticalLayout )


from django.urls import path
from . import views

urlpatterns = [
    path('bank/', views.BankDetailsAPIView.as_view(), name='bank'),
    path('bank/<int:id>', views.BankDetailsDetailsAPIView.as_view(),
         name='bankDetails'),
    path('wallet/', views.WalletAPIView.as_view(), name='walletAddress'),
    path('wallet/<int:id>', views.WalletDetailsAPIView.as_view(),
         name='walletAddressDetails'),
    path('transaction/', views.WalletTransactionAPIView.as_view(), name='transaction'),
    path('transaction/<int:id>', views.WalletTransactionDetailsAPIView.as_view(),
         name='transactionDetails'),
    path('withdraw/', views.WalletWithdrawAPIView.as_view(), name='withdraw'),
    path('withdraw/<int:id>', views.WalletWithdrawDetailsAPIView.as_view(),
         name='withdrawDetails'),
    path('walletamount/', views.WalletGetAPI.as_view(), name='walletamount'),
    path('wallettransection/', views.WalletTransectionGetAPI.as_view(),
         name='wallettransection'),
    path('bankshow/', views.WalletBankGetAPI.as_view(), name='bankshow'),
    path('getwithdraw/', views.WalletWithdrawGetAPI.as_view(), name='getwithdraw'),
    path('vendorwithdraw/', views.vendorWithdrawRequest.as_view(),
         name='vendorwithdraw'),
    path('vendorpayment/', views.vendorPayment.as_view(), name='vendorpayment'),
    path('vendorPaymentCancel/', views.vendorPaymentCancel.as_view(),
         name='vendorPaymentCancel'),
    path('sendMail/', views.sendMail.as_view(), name='sendMail'),
    path('emailView/', views.emailView, name='emailView'),
    path('adminPointTransction/', views.adminPointTransction.as_view(), name='adminPointTransction'),

]


import tensorflow as tf

a = tf.ones([2,2])
an = tf.norm(a)  #二范数
print(an)

an_ = tf.norm(a,axis=1,ord=1)  #ord 表示范数类型，1范数，而范数
print(an_)

tf.reduce_mean
tf.reduce_max
tf.reduce_max
tf.reduce_all

# tf.argmax(a,axis=) #返回最大值的索引
tf.argmin()
tf.equal()
tf.unique() #去重


import sqlite3
import yaml

def main():
    conn = sqlite3.connect('../../pf2.db')

    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    stmt = """
    SELECT ancestries.short_name as name,
        flavor_text,
        hp,
        sizes.short_name AS size,
        speed,
        senses.short_name AS senses,
        ancestries.sources_pages
    FROM ancestries
        INNER JOIN
        sizes ON sizes.size_id = ancestries.size_id
        INNER JOIN
        senses ON senses.senses_id = ancestries.vision_id;
    """
    c.execute(stmt)
    res = [dict(row) for row in c.fetchall()]
    print(res)

    # for i in res:
    #     if i['hands'] == None or i['hands'] == '':
    #         i['hands'] = 0

    reslist = []
    for i in res:
        tmp = {
            "name": i['name'],
            "flavor_text": i['flavor_text'],
            "hp": i['hp'],
            "size": i['size'],
            'speed': i['speed'],
            'senses': i['senses'],
            "source": [
                {
                    'abbr': 'CRB',
                    'page_start': int(i['sources_pages']),
                    'page_stop': int(i['sources_pages'])
                },
            ],
            'boosts': None,
            'flaws': None,
            'traits': None
        }
        # add in boosts
        stmt = """
        SELECT abilityscores.short_name
            FROM abilityscores
            INNER JOIN
                ancestries_boosts ON abilityscores.abilityscores_id = ancestries_boosts.abilityscores_id
            INNER JOIN
                ancestries ON ancestries.ancestry_id = ancestries_boosts.ancestry_id
                WHERE ancestries.ancestry_id = (
                                            SELECT ancestries.ancestry_id
                                            WHERE ancestries.short_name = ?
                                        );
        """
        c.execute(stmt, (i['name'],))
        resboosts = [dict(row) for row in c.fetchall()]
        print(resboosts)
        if len(resboosts) == 0:
            tmp['boosts'] = None
        else:
            boostslist = []
            for j in resboosts:
                boostslist.append(j['short_name'])
            tmp['boosts'] = boostslist

        # add in flaws
        stmt = """
        SELECT abilityscores.short_name
            FROM abilityscores
            INNER JOIN
                ancestries_flaws ON abilityscores.abilityscores_id = ancestries_flaws.abilityscores_id
            INNER JOIN
                ancestries ON ancestries.ancestry_id = ancestries_flaws.ancestry_id
                WHERE ancestries.ancestry_id = (
                                            SELECT ancestries.ancestry_id
                                            WHERE ancestries.short_name = ?
                                        );
        """
        c.execute(stmt, (i['name'],))
        resflaws = [dict(row) for row in c.fetchall()]
        print(resflaws)
        if len(resflaws) == 0:
            tmp['flaws'] = None
        else:
            flawslist = []
            for j in resflaws:
                flawslist.append(j['short_name'])
            tmp['flaws'] = flawslist
        # add in traits
        stmt = """
        SELECT traits.short_name
            FROM traits
            INNER JOIN
                ancestries_traits ON traits.trait_id = ancestries_traits.trait_id
            INNER JOIN
                ancestries ON ancestries.ancestry_id = ancestries_traits.ancestry_id
                WHERE ancestries.ancestry_id = (
                                            SELECT ancestries.ancestry_id
                                            WHERE ancestries.short_name = ?
                                        );
        """
        c.execute(stmt, (i['name'],))
        restraits = [dict(row) for row in c.fetchall()]
        print(restraits)
        if len(restraits) == 0:
            tmp['traits'] = None
        else:
            traitslist = []
            for j in restraits:
                traitslist.append(j['short_name'])
            tmp['traits'] = traitslist

        reslist.append(tmp)

    # # print(reslist)

    tmpd = {'ancestries': reslist}

    # now dump to yaml
    final = yaml.safe_dump(tmpd, allow_unicode=True)
    with open('tmp-ancestries.yaml', 'w') as f:
        f.write(final)

if __name__ == "__main__":
    main()


#!/usr/bin/env python
import httplib, urllib
import urlparse
sceneLink = 'http://labelme.csail.mit.edu/tool.html?collection=LabelMe&folder=static_web_submitted_noa_ofen_jenny_chai_stims&image=Indoor85.jpg'

baseXML = 'http://labelme.csail.mit.edu/Annotations/'

parsed_path = urlparse.urlparse(sceneLink)
params = dict([p.split('=') for p in parsed_path[4].split('&')])

XMLLoc = baseXML + params['folder'] + '/' + params['image'].replace('jpg','xml')


print_line = ""
num = ""
elements = ""
line = input().upper()
for index in range(len(line) + 1):
    if index not in range(len(line)):
        print_line += (elements * int(num))
        break
    if line[index].isdigit():
        num += line[index]
    elif not num == "":
        print_line += (elements * int(num))
        num = ""
        elements = ""
        if not line[index].isdigit():
            elements += line[index]
    else:
        elements += line[index]

print(f"Unique symbols used: {len(set(print_line))}")
print(print_line)