from datetime import datetime
import graphene
from django.db import transaction

from gym_class.models import ClassMaster, ClassDetail, AttendanceMaster
from gym_class.types.classes.class_detail_input_type import ClassDetailInputType
from gym_class.types.classes.class_master_input_type import ClassMasterInputType

class CreateOrUpdateClass(graphene.Mutation):
    class Arguments:
        class_master = ClassMasterInputType()
        weekdays = graphene.List(graphene.Int, required=True)
        class_details = ClassDetailInputType()

    success = graphene.Boolean()
    student_exists = graphene.Boolean(default_value=False)
    is_duplicated = graphene.Boolean(default_value=False)

    @classmethod
    @transaction.atomic()
    def mutate(cls, _, info, **kwargs, ):
        print('버튼클릭됨')
        print(1)
        class_master = kwargs.get('class_master')
        class_details = kwargs.get('class_details')
        weekdays = kwargs.get('weekdays')
        user = info.context.user
        if class_master.id:
            new_class_master = ClassMaster.objects.get(pk=class_master.id)
            if ClassMaster.objects.filter(gym=user.gym, name=class_master.name) and new_class_master.name != class_master.name:
                return CreateOrUpdateClass(success=False, is_duplicated=True)
            if not new_class_master.is_deleted and class_master.is_deleted:
                if new_class_master.students.count() > 0:
                    return CreateOrUpdateClass(success=False, student_exists=True)
            new_class_master.name = class_master.name
            new_class_master.is_deleted = class_master.is_deleted
            new_class_master.save()
            for weekday in weekdays:
                new_class_detail = new_class_master.class_details.filter(day=weekday).first()
                if new_class_detail:
                    new_class_detail.hour_start = class_details.hour_start
                    new_class_detail.min_start = class_details.min_start
                    new_class_detail.hour_end = class_details.hour_end
                    new_class_detail.min_end = class_details.min_end
                    new_class_detail.is_deleted = False
                    new_class_detail.save()
                else:
                    ClassDetail.objects.create(class_master=new_class_master,
                                               day=weekday,
                                               **class_details)
            ## 체크 안된것들은 is_deleted = True
            new_class_master.class_details.exclude(day__in=weekdays).update(is_deleted=True)
        else:
            gym = user.gym
            if ClassMaster.objects.filter(gym=user.gym, name=class_master.name):
                return CreateOrUpdateClass(success=False, is_duplicated=True)
            new_class_master = ClassMaster.objects.create(gym=gym,
                                                          name=class_master.name,
                                                          )
            for weekday in weekdays:
                ClassDetail.objects.create(class_master=new_class_master,
                                           day=weekday,
                                           **class_details
                                           )
        today_date = datetime.today()
        now = datetime.now()
        today = now.weekday()
        today_detail = new_class_master.class_details.filter(day=today)
        if today_detail.exists():
            detail = today_detail.first()
            AttendanceMaster.objects.get_or_create(class_master=new_class_master,
                                                   class_detail=detail,
                                                   gym=user.gym,
                                                   date=today_date)
        return CreateOrUpdateClass(success=True)


with open("/Users/pia/Desktop/Advent of Code/3/input.txt", "r") as f:
    the_map = f.read()

the_map = the_map.split("\n")

def part_1(right, the_map):
    index = 0
    tree_counter = 0
    for line in the_map:
        if index > len(line)-1:
            index = index%len(line)
            if line[index] == '#':
                tree_counter += 1
        else:
            if line[index] == '#':
                tree_counter += 1
        index += right

    return tree_counter

def part_2(the_map):
    index = 0
    tree_counter = 0
    row = 0
    for line in the_map[:]:
        if (row%2) == 0:
            if index > len(line)-1:
                index = index%len(line)
                if line[index] == '#':
                    tree_counter += 1
            else:
                if line[index] == '#':
                    tree_counter += 1
            index += 1
        row += 1

    return tree_counter

nums = [1, 3, 5, 7]
answer = 1
for number in nums:
    anzahl_trees = part_1(number, the_map)
    print(anzahl_trees)
    answer = answer * anzahl_trees
    print(answer)

#answer = 87753728
anzahl_trees = part_2(the_map)
print(anzahl_trees)
answer = answer * anzahl_trees

print(answer)


import hashlib
import requests
import time
import binascii
cookie={'PHPSESSID':'9fvoqsjb6c9unl6ju54odgd2d5'}
task ="14"

url = "https://ringzer0team.com/challenges/"+task

def hash512(data):
	return hashlib.sha512(data).hexdigest()

def decode_binary_string(s):
	return ''.join(chr(int(s[i*8:i*8+8],2)) for i in range(len(s)//8))

def submit_flag(data):
	r = requests.get("https://ringzer0team.com/challenges/"+task+"/"+data,cookies=cookie)
	return r.content

def text(data):
	htmlContent = data
	begin = htmlContent.find("BEGIN")+33
	end = htmlContent.find("END")-20
	recv = htmlContent[begin:end]
	return recv

def main(data):
	recv = text(str(data))
	print("recv : ",recv,decode_binary_string(recv))
	rec = decode_binary_string(recv)
	getHash = hash512(rec.encode())
	msg = submit_flag(str(getHash))
	if "FLAG" in str(msg):
		msg = str(msg)
		print(msg[msg.find("FLAG"):msg.find("FLAG")+33])

if __name__ == '__main__':
	r1 = requests.get(url, cookies=cookie)
	print("[+] Connect ")
	main(r1.content)

	#print(main(a))


import bsddb3 as bsddb
import random
import time
import sys
import os

DA_FILE_B = "/tmp/my_db/btree_db"
DA_FILE_H = "/tmp/my_db/hashtable_db"
DA_FILE_IB = "/tmp/my_db/indexfile_btree_db"
DA_FILE_IRB = "/tmp/my_db/indexfile_rbtree_db"
DB_SIZE = 1000
SEED = 10000000

def main():

    if len(sys.argv) != 2:
        print("Invalid number of arguments, expected 1 but received " + str(len(sys.argv) - 1))
        return 0
    tmp = ["btree", "hash", "indexfile"]
    dbType = sys.argv[1]
    if dbType not in tmp:
        print("Invalid argument, should be 'btree', 'hash', or 'indexfile'")
        return 0

    cont = True
    while cont:

        go = True
        while go:
            ans, go = menu()

        # Create Database
        if ans == 1:
            data = getData()
            db = makeDB(dbType,data)
            print("----Syncing to disk----")

            if type(db) == tuple:
                db[0].sync()
                db[1].sync()
            else:
                db.sync()
            print("Sync complete.\n")

        # Perform Key Search
        elif ans == 2:
            db=openDB(dbType)

            if type(db) == tuple:
                keySearch(db[0])
            else:
                keySearch(db)

        # Perform DataSearch
        elif ans == 3:
            db=openDB(dbType)

            if type(db) == tuple:
                dataSearch(db, dbType)
            else:
                dataSearch(db)

        # Perform Range Search
        elif ans == 4:
            db=openDB(dbType)

            if type(db) == tuple:
                rangeSearch(db[0], "btree")
            else:
                rangeSearch(db, dbType)

        # Destroy Database
        elif ans == 5:
            destroyDB(dbType)

        # Quit program
        elif ans == 6:
            cont = False

    try:
        db.close()
    except:
        pass

def menu():
    print()
    print("[1] Create and populate a database.")
    print("[2] Retrieve records with a given key")
    print("[3] Retrieve records with a given data")
    print("[4] Retrieve records with a given range of key values")
    print("[5] Destroy the database")
    print("[6] Quit")
    ans = input("Enter an option: ")
    try:
        tmp = int(ans)
    except:
        print("Non-numerical input.")
        return null, True

    if tmp > 0 and tmp < 7:
        return tmp, False
    else:
        print("Enter an option within range.")
        return null, True

def makeDB(dbtype,data):
    if dbtype == "btree":
        db = makeBTree(data)
    elif dbtype == "hash":
        db = makeHashTable(data)
    elif dbtype == "indexfile":
        db = makeIndexFile(data)
    print()
    print("Database created and populated of type: "+ dbtype)
    print()
    return db

def destroyDB(dbtype):
    if dbtype == "btree":
        os.remove("/tmp/my_db/btree_db")
    elif dbtype == "hash":
        os.remove("/tmp/my_db/hashtable_db")
    elif dbtype == "indexfile":
        os.remove("/tmp/my_db/indexfile_hash_db")
        os.remove("/tmp/my_db/indexfile_btree_db")

def getData():

    random.seed(SEED)

    keyValuePairs = []

    for index in range(DB_SIZE):
        krng = 64 + get_random()
        key = ""
        for i in range(krng):
            key += str(get_random_char())
        vrng = 64 + get_random()
        value = ""
        for i in range(vrng):
            value += str(get_random_char())

        key = key.encode(encoding='UTF-8')
        value = value.encode(encoding='UTF-8')

        keyValuePairs.append( (key, value) )

    return keyValuePairs

def makeBTree(data):
    try:
        db = bsddb.btopen(DA_FILE_B, "w")
    except:
        print("DB doesn't exist, creating a new one")
        db = bsddb.btopen(DA_FILE_B, "c")

    for pair in data:
        db[pair[0]] = pair[1]

    return db

def makeHashTable(data):
    try:
        db = bsddb.hashopen(DA_FILE_H, "w")
    except:
        print("DB doesn't exist, creating a new one")
        db = bsddb.hashopen(DA_FILE_H, "c")

    for pair in data:
        db[pair[0]] = pair[1]

    return db

def makeIndexFile(data):
    try:
        dbBTree = bsddb.btopen(DA_FILE_IB, "w")
        dbRBTree = bsddb.btopen(DA_FILE_IRB, "w")
    except:
        print("DB doesn't exist, creating a new one")
        dbBTree = bsddb.btopen(DA_FILE_IB, "c")
        dbRBTree = bsddb.btopen(DA_FILE_IRB, "c")

    for pair in data:
        dbBTree[pair[0]] = pair[1]
        try:
            exists = dbRBTree.get(pair[1])
            exists = exists + " " + pair[0]
        except:
            dbRBTree[pair[1]] = pair[0]

    return (dbBTree, dbRBTree)

# answer should be the tuple of (key, value)
def writeAnswers(answer):
    file = open('answers', 'a')
    file.write(str(answer[0]) + '\n')
    file.write(str(answer[1]) + '\n')
    file.write('\n')

def get_random():
    return random.randint(0, 63)
def get_random_char():
    return chr(97 + random.randint(0, 25))

def openDB(string):
    if string == "btree":
        db = bsddb.btopen(DA_FILE_B, "r")
    elif string == "hash":
        db = bsddb.hashopen(DA_FILE_H, "r")
    elif string == "indexfile":
        db = (bsddb.btopen(DA_FILE_B, "r"), bsddb.hashopen(DA_FILE_H, "r"))
    return db

def keySearch(database):
    key= input("Please enter key: ")
    key = key.encode(encoding='UTF-8')
    before = time.time() * 1000
    answer = database.get(key)
    after = time.time() * 1000
    print()
    if answer == None:
        print("Entries retrieved: 0")
    else:
        print("Entries retrieved: 1")
        writeAnswers(answer)
    print("Total execution time in ms: " + str(after-before))

def dataSearch(database, dbType):
    value = input("Please enter a data value: ")
    value = value.encode(encoding='UTF-8')

    if dbType == "btree" or dbType == "hash":
        return dataSearchBH(database, value)
    elif dbType == "indexfile":
        return dataSearchIF(database[1], value)

def dataSearchBH(database, value):

    before = time.time() * 1000
    matches = []
    last = database.last()
    current = database.first()

    while current != last:
        if (current[1] == value):
            matches.append(current)
        current = database.next()
    after = time.time() * 1000

    print()
    print("Entries retrieved: " + str(len(matches)))
    print("Total execution time in ms: " + str(after-before))

    for each in matches:
        writeAnswers(each)

    return 1

def dataSearchIF(database, value):

    before = time.time() * 1000
    keyString = database.get(value)
    after = time.time() * 1000

    keyList = keyString.split()

    print()
    print("Entries retrieved: " + str(len(keyList)))
    print("Total execution time in ms: " + str(after-before))

    matches = []
    for key in keyList:
        matches.append((key,value))

    for each in matches:
        writeAnswers(each)

    return 1

def rangeSearch(database, dbType):

    lower = input("Please enter the start of the range: ")
    upper = input("Please enter the end of the range: ")

    lower = lower.encode(encoding='UTF-8')
    upper = upper.encode(encoding='UTF-8')

    if lower > upper:
        print("The start is lower than the end. Try again.")
        return

    if dbType == "btree":
        return rangeSearchBTree(database, lower, upper)
    elif dbType == "hash":
        return rangeSearchHash(database, lower, upper)

def rangeSearchBTree(database, lower, upper):
    before = time.time() * 1000

    values = []

    last = database.last()
    current = database.set_location(lower)

    while current[0] < upper and current != last:
        values.append(current)
        current = database.next()

    after = time.time() * 1000

    for each in values:
        writeAnswers(each)

    print("Values found within range: " + str(len(values)))
    print("Total execution time in ms: " + str(after - before))
    return 1

def rangeSearchHash(database, lower, upper):

    before = time.time() * 1000

    values = []

    last = database.last()
    current = database.first()

    while current != last:
        if current[0] > lower and current[0] < upper:
            values.append(current)

        current = database.next()

    after = time.time() * 1000

    for each in values:
        writeAnswers(each)

    print("Values found within range: " + str(len(values)))
    print("Total execution time in ms: " + str(after - before))
    return 1

if __name__ == "__main__":
    main()


from typing import Optional

from sqlalchemy import insert, select, update
from sqlalchemy.ext.asyncio import AsyncSession

from .models import Message, Role, User

async def get_user(db: AsyncSession, user_id: int) -> Optional[User]:
    query = select(User).filter_by(id=user_id)
    result = await db.execute(query)
    return result.scalar_one_or_none()

async def create_user(
    db: AsyncSession,
    user_id: int,
    first_name: str,
    last_name: Optional[str] = None,
    username: Optional[str] = None,
):
    exist = await get_user(db, user_id)
    if not exist:
        stmt = (
            insert(User)
            .values(
                id=user_id,
                first_name=first_name,
                last_name=last_name,
                username=username,
            )
            .returning(User.id)
        )
        await db.execute(stmt)

async def add_message(
    db: AsyncSession,
    user_id: int,
    role: Role,
    content: Optional[str] = None,
) -> int:
    stmt = (
        insert(Message)
        .values(
            user_id=user_id,
            role=role,
            content=content,
        )
        .returning(Message.id)
    )
    insert_result = await db.execute(stmt)
    return insert_result.scalar_one()

async def get_context(db: AsyncSession, user_id: int):
    stmt = select(Message).filter_by(user_id=user_id, is_in_context=True)
    insert_result = await db.execute(stmt)
    return insert_result.scalars().all()

async def clear_context(db: AsyncSession, user_id: int) -> None:
    stmt = (
        update(Message)
        .where(
            Message.user_id == user_id,
            Message.is_in_context.is_(True),
        )
        .values(is_in_context=False)
    )
    await db.execute(stmt)


from collections import deque
from heapq import heapify,heappop,heappush

import sys

readline = sys.stdin.readline
Q = int(readline())
S1 = deque()
S2 = []
heapify(S2)
for _ in range(Q):
    query = list(map(int, input().split()))
    q = query[0]
    if q == 1:
        x = query[1]
        S1.append(x)

    elif q == 2:
        if len(S2) == 0:
            print(S1.popleft())

        else:
            print(heappop(S2))
    else:  # q == 3
        while S1:
            heappush(S2,S1.popleft())


"""
The API scan command.
"""

from __future__ import with_statement
import os
import glob

import pytrack.song

audio_encodings = ['.mp3', '.ogg', '.wav']

def scan():
    analysis_file = 'analysis.pyta'
    songs = []

    # get all the songs in the directory
    for infile in os.listdir(os.getcwd()):
        if not os.path.splitext(infile)[1] in audio_encodings: continue
        songs.append(pytrack.song.Song(infile))

    # write scan data to file
    with open(os.path.join(os.getcwd(), analysis_file), 'w') as fd:
        for song in songs:
            fd.writelines(song.format_str())
            fd.write('\n\n')

    return songs


#!/usr/local/bin/python3

import os
import mimetypes
import hashlib
import re
import sys
import datetime

def format_data(table):
    file_list = ''
    max = 0
    for row in table:
        for word in row:
            if max < len(word):
                max = len(word)
    col = max + 3
    for row in table:
        file_list += "".join(word.ljust(col) for word in row) + '\n'
    print(file_list)
    return file_list

def list_files(curr_path):
    shared_files = []
    for file in os.listdir(curr_path):
        if os.path.isfile(os.path.join(curr_path, file)):
            shared_files.append(file)
    for f in os.listdir(curr_path):
        if os.path.isdir(os.path.join(curr_path, f)):
            rec_files = list_files(os.path.join(curr_path, f))
            shared_files += [os.path.join(f, fr) for fr in rec_files]
    return shared_files

def list_dir(flag, argv, curr_path):
    shared_files = []
    for file in os.listdir(curr_path):
        if os.path.isfile(os.path.join(curr_path, file)):
            shared_files.append(file)
    table = [['Title', 'Size', 'TimeStamp', 'Type']]
    for file in shared_files:
        # time = (datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(curr_path, file))).strftime('%Y-%m-%d %H:%M:%S'))
        time = int(os.path.getmtime(os.path.join(curr_path, file)))
        path = os.path.join(curr_path, file)
        if flag == 'shortlist':
            start_time = int(argv[0])
            end_time = int(argv[1])
            if time < start_time or time > end_time:
                continue
        elif flag == 'regex':
            if not re.fullmatch('.*' + argv[0], file):
                continue
        table.append([file, str(os.path.getsize(path)), str(time), mimetypes.guess_type(path)[0] or 'text/plain'])
    return table

def get_hash(path):
    with open(path, 'rb') as file_hash:
        hash_val = hashlib.md5()
        while True:
            data = file_hash.read(4096)
            if not data:
                break
            hash_val.update(data)
        return hash_val.hexdigest()

def list_hash(flag, argv, curr_path):
    shared_files = list_files(curr_path)
    # for file in os.listdir(curr_path):
    #     if os.path.isfile(os.path.join(curr_path, file)):
    #         shared_files.append(file)
    table = [['File', 'Hash Value', 'Time Modified']]
    if flag != 'verify' and flag != 'checkall':
        sending = 'incorrect flag given. Usage: flag: verify/ checkall'
        return sending
    else:
        if flag == 'verify':
            shared_files = [argv[0]]
        for file in shared_files:
            path = os.path.join(curr_path, file)
            if not os.path.isfile(path):
                # print('The file', argv[0], 'doesn\'t exist.')
                sending = 'The file ' + argv[0] + ' doesn\'t exist.'
                return sending
            else:
                time = int(os.path.getmtime(os.path.join(curr_path, file)))
                # time = (datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(curr_path, file))).strftime('%Y-%m-%d %H:%M:%S'))
                table.append([file, str(get_hash(path)), str(time)])
        return table


'''

 | |
-----
 | |       Mijn awesome grid.
-----
 | |

'''
import random

def drawBoard(board):

    print("          "+ board[0] + "|" + board[1] + "|" + board[2])
    print("          "+ "-----")
    print("          "+ board[3] + "|" + board[4] + "|" + board[5])
    print("          "+ "-----")
    print("          "+ board[6] + "|" + board[7] + "|" + board[8])

def getPlayerMove():

    move = 0
    while (move < 1 or move > 9 or isSpaceFree(board, move-1) == False):
        print("\n""Give a number between 1-9")
        move = int(input())

    move -= 1

    return move

def getComputerMove():

    cmove = random.randint(1,9)
    while (isSpaceFree(board, cmove-1) == False):
        print("Computer is playing..", cmove)
        cmove = random.randint(1,9)

    cmove -= 1

    return cmove

def isSpaceFree(board, spot):
    if board[spot] == " ":
        return True
    else:
        return False

def isWinner(board, icon):
    if (board[0] == icon and board[1] == icon and board[2] == icon
        or board[3] == icon and board[4] == icon and board[5] == icon
        or board[6] == icon and board[7] == icon and board[8] == icon
        or board[0] == icon and board[4] == icon and board[8] == icon
        or board[2] == icon and board[4] == icon and board[6] == icon
        or board[0] == icon and board[3] == icon and board[6] == icon
        or board[1] == icon and board[4] == icon and board[7] == icon
        or board[2] == icon and board[5] == icon and board[8] == icon):
        return True
    else:
        return False

board = [" "," "," "," "," "," "," "," "," ",]

isPlaying = True
playerIcon = "X"
computerIcon = "O"
turn = "computer"

def isBoardFull(board):
    for i in range(1, 9):
        if isSpaceFree(board, i):
            return False
    return True

while isPlaying:

    if turn == "player":
        drawBoard(board)
        move = getPlayerMove()
        board[move] = playerIcon

        if (isWinner(board, playerIcon) == True):
            drawBoard(board)
            print("You have won! You are amazing!")
            isPlaying = False
        else:
            if isBoardFull(board):
                drawBoard(board)
                print("You have ended in a tie! Mehh..")
                break
            else:
                turn = "computer"

    elif turn == "computer":
        move = getComputerMove()
        board[move] = computerIcon

        if (isWinner(board, computerIcon) == True):
            drawBoard(board)
            print("You have lost! Loser..")
            isPlaying = False
        else:
            if isBoardFull(board):
                drawBoard(board)
                print("You have ended in a tie! Mehh..")
                break
            else:
                turn = "player"


import os
import re

def getGitBranch():
    if not os.path.exists( ".git" ) or not os.path.isdir(".git"):
        return None

    version = open( ".git/HEAD" ,'r' ).read().strip()
    if not version.startswith( "ref: " ):
        return version
    version = version.split( "/" )
    version = version[len(version)-1]
    return version

def getGitBranchString( prefix="" , postfix="" ):
    t = re.compile( '[/\\\]' ).split( os.getcwd() )
    if len(t) > 2 and t[len(t)-1] == "mongo":
        par = t[len(t)-2]
        m = re.compile( ".*_([vV]\d+\.\d+)$" ).match( par )
        if m is not None:
            return prefix + m.group(1).lower() + postfix
        if par.find("Nightly") > 0:
            return ""

    b = getGitBranch()
    if b == None or b == "master":
        return ""
    return prefix + b + postfix

def getGitVersion():
    if not os.path.exists( ".git" ) or not os.path.isdir(".git"):
        return "nogitversion"

    version = open( ".git/HEAD" ,'r' ).read().strip()
    if not version.startswith( "ref: " ):
        return version
    version = version[5:]
    f = ".git/" + version
    if not os.path.exists( f ):
        return version
    return open( f , 'r' ).read().strip()


import sys
from collections import deque, defaultdict

g = defaultdict(list)
g2 = defaultdict(list)

for line in sys.stdin:
    line = line.strip()

    color, rest = line.split(' bags contain ')

    rest = rest.replace('bags', '').replace('bag', '').replace('.', '').split(', ')

    for color2 in rest:
        n, *t = color2.strip().split(' ')
        color2 = ' '.join(t)

        if color2 != 'other':
            n = int(n)
            g[color2].append(color)
            g2[color].append((n, color2))

# First star
q = deque()
q.append('shiny gold')
visited = defaultdict(bool)

count = 0

while q:
    color = q.popleft()

    for c in g[color]:
        if not visited[c]:
            visited[c] = True
            q.append(c)
            count += 1

print('First star: ', count)

# Second star
def dfs(color):
    s = 0
    for n, c in g2[color]:
        s += n * dfs(c) + n
    return s

print('First star: ', dfs('shiny gold'))


def findBraces():
    user = 'stacks06.txt'
    jOpen = open(user, "r")
    stack = []
    for i in jOpen:
        k = i.strip()
        for ch in k:
            # if current character is an open one just add to the stack
            if ch == '(' or ch == '[' or ch == '{':
                stack.append(ch)
            # if current character is any type of closing brace: ), }, ]
            if ch == ')' or ch == ']' or ch == '}':
                # If the stack is empty (nothing to compare)
                if len(stack) == 0:
                    # Quit now, it doesn't match
                    return "not balance"
                lastch = stack.pop()
                # if they match (meaning closing of the same type):
                # We're good
                # Pop the opening brace off the stack
                # If they don't match
                # Quit now, and tell them the braces don't match
                if lastch == '(' and (ch != ')'):
                    return "not balanced"
                if lastch == '[' and (ch != ']'):
                    return "not balanced"
                if lastch == '{' and (ch != '}'):
                    return "not balanced"
    # after reading the complete file
    # If there is anything on the stack, the braces didn't match
    if len(stack) != 0:
        return "not balanced"
    return "Balanced"

print(findBraces())


#Done by Carlos Amaral in 01/07/2020

"""
Start with a copy of user_profile.py from page 149. Build a
profile of yourself by calling build_profile() , using your first and last names
and three other key-value pairs that describe you.
"""

#User profile
def build_profile(*user_info):
    """Building a profile coutaining info about myself."""
    print(f"My profile:")
    for info in user_info:
        print(f"-{info}")

build_profile('Carlos', 'Amaral', '26','single', 'Portuguese')


from types import SimpleNamespace
import numpy as np
from copy import deepcopy
from python_example import Givens2Matrix_double as Givens2Matrix
from python_example import QRGivens_double as QRGivens
from utils import eigh_with_fixed_direction_range
from sklearn.mixture import GaussianMixture
from pso_v3.eigen_pso import EigenParticle

from pso_v3.base import GMMState

class GMMStateOld:
    def __init__(self, gmm) -> None:
        self.means = gmm.means_.astype('float64')
        self.weights = gmm.weights_.astype('float64')
        self.precisions = gmm.precisions_.astype('float64')
        self.n_comp = self.means.shape[0]

    def zeros_like(self):
        gmm_state_dict = {'means_': np.zeros_like(self.means),
                          'weights_': np.zeros_like(self.weights), 'precisions_': self.precisions}
        return GMMStateOld(SimpleNamespace(**gmm_state_dict))

    def __add__(self, gmm_2):
        self = deepcopy(self)
        self.means += gmm_2.means
        self.weights += gmm_2.weights
        self.precisions += gmm_2.precisions
        return self

class GMMStateSpectral:
    def __init__(self, means, weights, eigvals, rotations) -> None:
        self.means = means
        self.weights = weights
        self.eigvals = eigvals
        self.rotations = rotations
        self.n_comp, self.d = means.shape[0], means.shape[1]

    def scatter(self, std):
        delta_means = np.random.normal(0, std * np.mean(self.means), size=(self.n_comp, self.d))
        delta_givens =  np.random.uniform(-np.pi * std, std * np.pi, size=(self.n_comp, int(self.d * (self.d - 1) / 2)))

        eig_val_mean = [np.mean(self.eigvals[i]) for i in range(self.n_comp)]

        delta_eigvals = np.random.uniform(-std * np.mean(eig_val_mean), std * np.mean(eig_val_mean), size=(self.n_comp, self.d))

        self.means += delta_means
        self.rotations += delta_givens
        self.eigvals += delta_eigvals
        self.eigvals = (self.eigvals > 0) * self.eigvals + 1e-04
        # print(self.eigvals)

def to_linear(gmm_state: GMMStateOld):
    n_comp = gmm_state.precisions.shape[0]
    d = gmm_state.precisions.shape[1]

    eigvals = np.zeros([n_comp, d])
    rotations = np.zeros([n_comp, int(d * (d - 1) / 2)])

    for i in range(gmm_state.precisions.shape[0]):
        prec = gmm_state.precisions[i]

        eigenvalues, v = eigh_with_fixed_direction_range(prec)
        givens_rotations = QRGivens(v).squeeze()

        eigvals[i] = eigenvalues
        rotations[i] = givens_rotations
    gmm_spec = GMMStateSpectral(gmm_state.means, gmm_state.weights, eigvals, rotations)
    return gmm_spec

def to_manifold(gmm_spec_state: GMMStateSpectral) -> GMMStateOld:

    n_comp, d = gmm_spec_state.means.shape[0], gmm_spec_state.means.shape[1]

    prec_matrices = np.zeros([n_comp, d, d])
    for k in range(n_comp):
            eigvals = gmm_spec_state.eigvals[k]
            givens_rotations = gmm_spec_state.rotations[k]
            v = Givens2Matrix(np.expand_dims(givens_rotations, axis=1))
            spd_matr = v @ np.diag(eigvals) @ v.T
            prec_matrices[k] = spd_matr

    gmm_state_dict = {'means_': gmm_spec_state.means,
                        'weights_': gmm_spec_state.weights, 'precisions_': prec_matrices}

    return GMMStateOld(SimpleNamespace(**gmm_state_dict))

def gmm_scatter_around_best_init_states(data, n_comp, n_particles, std=0.01, gmm_states=None):
    if gmm_states is not None:
        states = [EigenParticle(data, n_comp, state, 0, 0, 0) for state in gmm_states]
        states = sorted(states, key=lambda x:-x.score())
        gmm = states[0].to_gmm()
    else:
        gmm = GaussianMixture(n_components=n_comp, covariance_type='full', n_init=n_particles, init_params='k-means++')
        gmm.fit(data)

    basic_score = gmm.score(data)
    print('Basic GMM score:', gmm.score(data))
    gmm_state = GMMStateOld(gmm)
    basic_state = deepcopy(gmm_state)
    ret_val = []
    for i in range(n_particles):
        gmm_state_copy = deepcopy(gmm_state)
        gmm_spectral_state = to_linear(gmm_state_copy)
        gmm_spectral_state.scatter(std)

        ret_val.append(to_manifold(gmm_spectral_state))

    return [GMMState(item.weights, item.means, item.precisions) for item in ret_val], basic_state.precisions

def get_best_gmm_state(states, data, n_comp):
    # data, n_comp, init_state, intertia, r_1, r_2
    particles = [EigenParticle(data, n_comp, state, 0, 0, 0) for state in states]
    particles = sorted(particles, key=lambda x:-x.score())
    return GMMState.from_gmm(particles[0].to_gmm()), particles[0].to_gmm().score(data)


from copy import deepcopy

import rastervision as rv
from rastervision.data.label_source import (
    LabelSourceConfig, LabelSourceConfigBuilder, ObjectDetectionLabelSource)
from rastervision.data.vector_source import VectorSourceConfig
from rastervision.protos.label_source_pb2 import LabelSourceConfig as LabelSourceConfigMsg

class ObjectDetectionLabelSourceConfig(LabelSourceConfig):
    def __init__(self, vector_source):
        super().__init__(source_type=rv.OBJECT_DETECTION)
        self.vector_source = vector_source

    def to_proto(self):
        msg = super().to_proto()
        opts = LabelSourceConfigMsg.ObjectDetectionLabelSource(
            vector_source=self.vector_source.to_proto())
        msg.object_detection_label_source.CopyFrom(opts)
        return msg

    def create_source(self, task_config, extent, crs_transformer, tmp_dir):
        vector_source = self.vector_source.create_source(
            crs_transformer=crs_transformer,
            extent=extent,
            class_map=task_config.class_map)
        return ObjectDetectionLabelSource(vector_source, crs_transformer,
                                          task_config.class_map, extent)

    def update_for_command(self, command_type, experiment_config,
                           context=None):
        self.vector_source.update_for_command(command_type, experiment_config,
                                              context)

    def report_io(self, command_type, io_def):
        self.vector_source.report_io(command_type, io_def)

class ObjectDetectionLabelSourceConfigBuilder(LabelSourceConfigBuilder):
    def __init__(self, prev=None):
        config = {}
        if prev:
            config = {'vector_source': prev.vector_source}

        super().__init__(ObjectDetectionLabelSourceConfig, config)

    def validate(self):
        super().validate()
        vector_source = self.config.get('vector_source')
        if vector_source is None:
            raise rv.ConfigError(
                'You must set the vector_source for ObjectDetectionLabelSourceConfig'
                ' Use "with_vector_source".')
        if not isinstance(vector_source, VectorSourceConfig):
            raise rv.ConfigError(
                'vector source must be a child of class VectorSourceConfig, got {}'.
                format(type(vector_source)))
        if vector_source.has_null_class_bufs():
            raise rv.ConfigError(
                'Setting buffer to None for a class in the vector_source is not allowed '
                'for ObjectDetectionLabelSourceConfig.')

    def from_proto(self, msg):
        b = ObjectDetectionLabelSourceConfigBuilder()

        # Added for backwards compatibility.
        if msg.HasField('object_detection_geojson_source'):
            vector_source = msg.object_detection_geojson_source.uri
        else:
            vector_source = rv.VectorSourceConfig.from_proto(
                msg.object_detection_label_source.vector_source)

        return b.with_vector_source(vector_source)

    def with_vector_source(self, vector_source):
        """Set the vector_source.

        Args:
            vector_source (str or VectorSource) if a string, assume it is
                a URI and use the default provider to construct a VectorSource.
        """
        if isinstance(vector_source, str):
            return self.with_uri(vector_source)

        b = deepcopy(self)
        if isinstance(vector_source, VectorSourceConfig):
            b.config['vector_source'] = vector_source
        else:
            raise rv.ConfigError(
                'vector_source must be of type str or VectorSource')

        return b

    def with_uri(self, uri):
        b = deepcopy(self)
        provider = rv._registry.get_vector_source_default_provider(uri)
        b.config['vector_source'] = provider.construct(uri)
        return b


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'''
#                               Polyak Algorithm with constant coefficients
'''

from numpy.linalg import norm

def Polyak(u0, v0, h, eps, E, gradE, N, gamma)  :
    n = 0
    itLst = [n]
    u = [u0]
    v = [v0]
    ok = 0
    while ok == 0 :
        n = n + 1
        itLst.append( n )
        if N == 2 :
            modifGrad_u = [i * h for i in gradE(u[-1])]
        else :
            modifGrad_u = h * gradE(u[-1])
        v.append( ( 1 - h * gamma ) * v[-1] - modifGrad_u )
        u.append( u[-1] + h * v[-1] )
        if norm(gradE(u[-1])) <= eps :
            ok = 1
    return itLst, u, v


import RecarrayTools as RT
from .. import Globals
from .TraceFieldDay import TraceFieldDay
import DateTimeTools as TT
from .GetPos import GetPos
import os
import numpy as np

def SaveFieldTraces(Model='T96',StartDate=20170101,EndDate=20191231,Verbose=True,Overwrite=False):
	'''
	Saves the Tsyganenko field trace footprints for RBSP within a range
	of dates.

	'''
	#populate the list of dates to trace first
	date = StartDate
	dates = []
	while date <= EndDate:
		dates.append(date)
		date = TT.PlusDay(date)
	n = np.size(dates)

	#now to load the position data
	pos = GetPos()

	#set the output path
	outpath = Globals.DataPath + 'Traces/{:s}/'.format(Model)
	if not os.path.isdir(outpath):
		os.system('mkdir -pv '+outpath)

	#loop throught the dates doing the traces
	for i in range(0,n):
		fname = outpath + '{:08d}.bin'.format(dates[i])
		if Overwrite or (not os.path.isfile(fname)):
			print('Tracing date {:8d} ({:d} of {:d})'.format(dates[i],i+1,n))
			T = TraceFieldDay(dates[i],Model,Verbose)
			RT.SaveRecarray(T,fname)
		else:
			print('File {:s} exists'.format(fname))


# -*- coding: utf-8 -*-
"""
Created on Sat Apr 15 17:39:25 2023

@author: mrsco
"""

# -*- coding: utf-8 -*-
"""
Created on Mon Aug  2 15:46:55 2021

@author: mrsco
"""
from protocols.protocol import protocol
from psychopy import core, visual, data, event, monitors
import serial, random, numpy, time
from psychopy.hardware import keyboard

class SnellenShapes(protocol):

    def __init__(self):
        super().__init__()
        self.protocolName = 'SnellenShapes'
        self.numberOfOptotypes = 10
        self.startingLevel = 5 #0 is the smallest optotype

        self.textColor = [-1.0, -1.0, -1.0]
        self.backgroundColor = [1.0, 1.0, 1.0]

        self.smallestOptotypeRadius_degrees = 0.2
        self.largestOptotypeRadius_degrees = 4

        self.preTime = 1.0 #s - unused for this stimulus
        self.stimTime = 1.0 #s - unused for this stimulus
        self.tailTime = 1.0 #s - unused for this stimulus

    def estimateTime(self):
        '''
        Estimate the total amount of time that this protocol will take to run
        given the current parameters

        Value is stored as total time in seconds in the property 'self.estimatedTime'
        which is initialized by the protocol superclass.

        returns: estimated time in seconds
        '''
        self._estimatedTime = 120 #return estimated time for the total stimulus in seconds

        return self._estimatedTime

    def calculateOptotypeRadii_pix(self):
        '''
        Calculates the radius of each optotype in pixels, given the minimmum and
        maximum radii and the number of optotype levels
        '''
        minRadius_pix = self.smallestOptotypeRadius_degrees*self.pixPerDegree
        maxRadius_pix = self.largestOptotypeRadius_degrees*self.pixPerDegree
        allRadii_pix = numpy.linspace(minRadius_pix, maxRadius_pix, num = self.numberOfOptotypes)
        return allRadii_pix

    def procedureAlgo(self, score, currentLevel, epochNum):
        if epochNum == 10:
            testComplete = 1
        else:
            testComplete = 0

        nextLevel = currentLevel + score

        if nextLevel > len(self.allRadii_pix)-1 or nextLevel < 0:
            testComplete = 1

        return testComplete, nextLevel

    def run(self, win, informationWin):
        '''
        Executes the SnellenShapes stimulus
        '''
        self._completed = 0 #started but not completed

        self._informationWin = informationWin #tuple, save here so you don't have to pass this as a function parameter every time you use it

        self.getFR(win)

        stimMonitor = win.monitor

        self.pixPerDegree = self.getPixPerDeg(stimMonitor)

        self.allRadii_pix = self.calculateOptotypeRadii_pix()

        #Pause for keystroke if the user wants to manually initiate
        if self.userInitiated:
            self.showInformationText(win, 'Stimulus Information: Snellen Shapes \nPress any key to begin')
            event.waitKeys() #wait for key press

        instructions = 'Snellen Shape Test for Visual Acuity: \nPress "C" for Circle and "S" for square \n\nPress any key to begin'
        self.showInformationText(win, instructions)
        event.waitKeys() #wait for key press

        kb = keyboard.Keyboard()

        win.color = self.backgroundColor
        win.flip()
        win.flip()

        #initialize the circle
        optotypeCircle = visual.Circle(
            win = win,
            units = 'pix',
            lineColor = self.textColor,
            lineWidth = 2,
            fillColor = self.backgroundColor
            )

        #initialize the square
        optotypeSquare = visual.Rect(
            win = win,
            units = 'pix',
            lineColor = self.textColor,
            lineWidth = 2,
            fillColor = self.backgroundColor
            )

        random.seed(self.randomSeed) #reinitialize the random seed

        epochNum = 0
        testComplete = False
        trialClock = core.Clock() #this will reset every trial
        nextOptotypeLevel = self.startingLevel

        while not testComplete:
            currentOptotypeLevel = nextOptotypeLevel
            currentRadius = self.allRadii_pix[currentOptotypeLevel]

            isCircle = random.random() > 0.5 #randomly choose the optotype

            if isCircle:
                optotypeCircle.radius = currentRadius
                optotypeCircle.draw()
            else:
                optotypeSquare.width = currentRadius
                optotypeSquare.height = currentRadius
                optotypeSquare.draw()

            win.flip()
            keypress = kb.waitKeys(keyList = ['c', 's', 'q'])
            thisKey = keypress[0].name

            if thisKey == 'q':
                break

            if (thisKey == 'c' and isCircle) or (thisKey =='s' and not isCircle):
                score = -1
            else:
                score = 1

            (testComplete, nextOptotypeLevel) = self.procedureAlgo(score, currentOptotypeLevel, epochNum)
            epochNum += 1

        print('Your optotype level is', currentOptotypeLevel, 'out of', self.numberOfOptotypes)
        self._completed = 1


def convolution(array1: list, array2: list):
    array2 = array2[::-1]
    start = 1
    end = len(array1)+len(array2)

    result = []

    for i in range(start, end):

        if i <= len(array1):
            arr1_comb, arr2_comb = array1[:i], array2[-i:]
        else:
            arr1_comb, arr2_comb = array1[i-len(array1):], array2[:len(array2)-i]

        element_sum = sum([el1*el2 for el1, el2 in zip(arr1_comb, arr2_comb)])
        result.append(element_sum)

    return result

x = [1, 2, 3, 4, 5]
y = [6, 7, 8, 9, 10]
print(convolution(x, y))


#-*- coding: utf-8 -*-
from mrjob.job import MRJob
from bs4 import BeautifulSoup
import re
import matplotlib.pyplot as plt
import IPython
"""
Implementing PageRank atop MapReduce
-- naveed

Port of hadoop implementation http://blog.xebia.com/2011/09/27/wiki-pagerank-with-hadoop/

Utility Classes:
    LineProtocol - Used to extract <page> tags from xml
    CustomMRJob - Inherited from MRJob, makes it easy to specify input/output file paths in job runner

MRJob Classes:
    PageLinkCalculate - Parse the page and output page with initial rank and outgoing results
    RankCalculate - Claculate PageRank of each wikipage
    RankingMapper - Order pages by ranks

Put input XML file in script directory
Intermediate results from RankCalculate are stored in out/0/, out/1/ ...
Final results are stored in 'out/result/' directory
"""

link_pat = re.compile("\\[.+?\\]")  # regular expression to extract links
link_page_pat = re.compile(r'\[{,2}(.+?)([\]|#])') # extract link text before ],|,#

DAMPING_FACTOR = 0.85

class LineProtocol(object):
    """ This custom protocol is used to feed entire <page></page> xml as a line to PageLinkCalculate mapper """
    def __init__(self):
        self.lines = ""
    def read(self, line):
        self.lines += line
        if '<page>' in line:
            self.lines = ""
        elif '</page>' in line:
            # one page is found,
            page = BeautifulSoup(self.lines)
            self.lines= ""
            return None, unicode(page)
        return None, None
    def write(self, key, value):
        return key, value

class CustomMRJob(MRJob):
    def make_runner(self, input_path, output_dir):
        ## Override make_runner to add input_path and output_dir
        self.input_paths = [input_path]
        self.output_dir = output_dir
        return super(CustomMRJob, self).make_runner()

    def job_runner_kwargs(self):
        kwargs = super(CustomMRJob, self).job_runner_kwargs()
        kwargs['input_paths'] = self.input_paths
        kwargs['output_dir'] = self.output_dir
        return kwargs

class PageLinkCalculate(CustomMRJob):
    """
    Parse title/text of each page
    Get the article’s name and its outgoing links.
    For each wikipage obtain the links to other pages.
    Store the page, initial rank (1.0) and outgoing links.
    """
    def mapper(self, key, value):
        if value:
            soup = BeautifulSoup(value)
            title = soup.find('title')
            text = soup.find('text')
            if title:
                title = title.string.replace(' ','_') # spaces are underscored
            if text and text.string:
                links = re.findall(link_pat, text.string)
                for link in links:
                    other_page = self._get_wiki_page_from_link(link)
                    if not other_page: continue
                    yield title, other_page

    def reducer(self, key, values):
        page_rank = "1.0"
        yield key, page_rank + "\t" + ','.join(values)
    def input_protocol(self):
        return LineProtocol()

    def _get_wiki_page_from_link(self, link):
        grp = re.search(link_page_pat, link)
        if grp:
            link_text = grp.group(1)
            link_text = re.sub(r'\s','_',link_text) # whitespaces with underscore
            link_text = link_text.replace(',','') # remove comma
            link_text = link_text.replace("&","&") # convert ampersands
            return link_text
        return None

class RankCalculate(CustomMRJob):
    """
    Calculate new PageRank
    Map each outgoing link to the page with its rank and total outgoing links.
    Store the page, new rank and outgoing links.
    This job is run multiple times to generate accurate results
    """
    def mapper(self, key, value):
        value = value.strip('"')    # remove extra quotes added by previous job
        values = value.split('\t')
        page = values[0].strip('"')
        links_and_ranks = values[1].split('\\t')
        rank = links_and_ranks[0].strip('"')
        page_rank = page + "\t" + rank
        yield page, "!"
        if len(links_and_ranks) < 2:
            return
        links = links_and_ranks[1]
        other_pages = links.split(',')

        for other_page in other_pages:
            yield other_page, page_rank + "\t" + str(len(other_pages))

        yield page, "|" + links

    def reducer(self, key, values):
        existing_wiki_page = False
        split = []
        sum_share_other_ranks = 0
        links = ""
        page_with_rank = ""
        for v in values:
            page_with_rank = v
            if page_with_rank[0] == '!':
                existing_wiki_page = True
                continue
            if page_with_rank[0] == '|':
                links = "\t" + page_with_rank[1:]
                continue
            split = page_with_rank.split('\t')
            page_rank = float(split[1])
            count_out_links = int(split[2])
            sum_share_other_ranks += (page_rank/count_out_links)
        if not existing_wiki_page:
            return
        new_rank = DAMPING_FACTOR * sum_share_other_ranks + (1-DAMPING_FACTOR)
        yield key, str(new_rank) + links

class RankingMapper(CustomMRJob):
    """
    Get the page and rank. And map the key: rank to value: page.
    """
    def mapper(self, key, value):
        rank, page = self._get_page_and_rank(key, value)
        yield float("{0:.2f}".format(float(rank))), page

    def _get_page_and_rank(self, key, value):
        tabbed_list = value.split('\t')
        page = tabbed_list[0].strip('"')
        rank_and_links = tabbed_list[1].strip('"')
        rank = rank_and_links.split('\\t')[0]
        return (rank, page)

def plot_graph(results):
    """ Plot Top 50 results on graph, assuming results are stored in descending order """
    fp = open(results)
    head=[fp.next() for x in xrange(50)]
    vals = [float(x.split('\t')[0]) for x in head]
    ticks = [x.split('\t')[1].strip('"') for x in head]
    plt.bar(range(50), vals, color='g')
    plt.title("PageRanks of NL Wiki (Top 50)")
    ax = plt.gca()
    ax.set_xticks(range(50))
    ax.set_xticklabels(ticks, rotation='vertical')
    plt.ylabel('Page Rank')
    plt.xlabel('Page')
    plt.tick_params(axis='both', which='major', labelsize=11)
    plt.show()

if __name__ == "__main__":
    pl_job = PageLinkCalculate()
    with pl_job.make_runner('*.xml', 'out/0/') as runner:
        runner.run()
    rc_job = RankCalculate()
    for i in range(4):
        with rc_job.make_runner('out/%d/' % i,'out/%d/' % (i+1)) as runner:
            runner.run()
    rm_job = RankingMapper()
    with rm_job.make_runner('out/4/', 'out/result') as runner:
        runner.run()

    plot_graph('out/result/final')


"""user reactions table created, modified likes, dislikes

Revision ID: 5cd91b62a771
Revises: 234824db25f0
Create Date: 2023-10-26 00:25:24.664417

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '5cd91b62a771'
down_revision = '234824db25f0'
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('users_reactions',
    sa.Column('rec_id', sa.Integer(), nullable=False),
    sa.Column('user_id', sa.UUID(), nullable=False),
    sa.ForeignKeyConstraint(['user_id'], ['users_table.user_uuid'], ),
    sa.PrimaryKeyConstraint('rec_id')
    )
    op.add_column('dislikes', sa.Column('placed_by', sa.String(length=50), nullable=False))
    op.create_unique_constraint(None, 'dislikes', ['placed_by'])
    op.add_column('likes', sa.Column('placed_by', sa.String(length=50), nullable=False))
    op.create_unique_constraint(None, 'likes', ['placed_by'])
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, 'likes', type_='unique')
    op.drop_column('likes', 'placed_by')
    op.drop_constraint(None, 'dislikes', type_='unique')
    op.drop_column('dislikes', 'placed_by')
    op.drop_table('users_reactions')
    # ### end Alembic commands ###


import sys

def read():
    return sys.stdin.readline

n = int(read())
l = []

for i in range(n):
    start, end = map(int, read().split())
    l.append((start, end))

l.sort(key=lambda x: (x[1], x[0]))

cnt = 0
end = 0

for i in l:
    if i[0] >= end:
        cnt += 1
        end = i[1]

print(cnt)


def Try(a_list, mid, n):
	curEnergy = mid
	for i in range(1, n + 1):
		diff = a_list[i] - a_list[i - 1]

		if curEnergy < diff:
			return False
		elif curEnergy == diff:
			curEnergy -= 1
	return True

T = int(input())

for tc in range(1, T + 1):
	print("Case {}: ".format(tc), end = "")

	n = int(input())
	a_list = [0] + list(map(int, input().split()))

	left = 1
	right = ans = a_list[n]

	while left <= right:
		mid = (left + right) // 2

		if Try(a_list, mid, n) == True:
			ans = mid
			right = mid - 1
		else:
			left = mid + 1

	print(ans)

11. Binary Search/Monkey and the Oiled Bamboo (Uva).py


from flask import Flask, request
from os import environ
from model import get_recommendations

app = Flask(__name__)

@app.route('/customerinput', methods=['POST'])
def customer_input():
    body_params = request.json
    customer_id = body_params["customer_id"]
    zone = body_params["zone"]
    print("Customer ID:", customer_id)
    print("Zone:", zone)

    top5 = get_recommendations(customer_id,zone)
    print(top5)
    json_top5 = top5.to_json(orient='records')

    return json_top5

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=environ.get("PORT", 3000))


from typing import List

class Solution:
    def checkvalid(self, lightOns, i, k):
        if i - k - 1 >= 0 and lightOns[i - k - 1]:
            ii = i - 1
            hasOn = False
            while ii >= i - k:
                if lightOns[ii]:
                    hasOn = True
                    break
                ii -= 1
            if not hasOn:
                return True
        if i + k + 1 < len(lightOns) and lightOns[i + k + 1]:
            ii = i + 1
            hasOn = False
            while ii <= i + k:
                if lightOns[ii]:
                    hasOn = True
                    break
                ii += 1
            if not hasOn:
                return True
        return False

    def kEmptySlots(self, bulbs: List[int], k: int) -> int:
        lightOns = len(bulbs) * [False]

        for i in range(len(bulbs)):
            lightOns[bulbs[i]-1] = True
            if self.checkvalid(lightOns,bulbs[i]-1,k):
                return i + 1

        return -1

s = Solution()
print(s.kEmptySlots([3,9,2,8,1,6,10,5,4,7], 1))
print(s.kEmptySlots([1,2,3] , 1))

print(s.kEmptySlots([1,3,2] , 1))


from flask import Flask, request
from app.models.amenity import Amenity

app = Flask(__name__)

'''GET: list of all amenities'''
@app.route('/amenities', methods = ['GET'])
def get_all_amenities():
    amenities = []
    for amenity in Amenity.select():
        amenities.append(amenity.to_hash())
    return jsonify({"amenities": amenities})

'''POST: create a new amenity from POST data parameters. '''
@app.route('/amenities', methods = ['POST'])
def create_asdfstate():
    content = request.get_json()
    if not all(param in content.keys() for param in ["name"]):
        #ERROR
        return "Failed: bad input"
    try:
        amenity = Amenity()
        amenity.name = content["name"]
        amenity.save()
    except Exception as e:
        return "Failed"
    return "Success"

'''GET: amenity with id = amenity_id'''
@app.route('/amenities/<amenity_id>', methods = ['GET'])
def get_statdasfde_by_id(amen_id):
    amens = Amenity.select().where(Amenity.id == int(amen_id))
    amen = None
    for u in amens:
        amen = u
    if amen == None:
        return "Failed"
    return jsonify(amen.to_hash())

'''DELETE: delete amenity with id = book_id'''
@app.route('/amenities/<amenity_id>', methods = ['DELETE'])
def get_staasedfazte_by_id(amen_id):
    amens = Amenity.select().where(Amenity.id == int(amen_id))
    amen = None
    for u in amens:
        amen = u
    if amen == None:
        return "Failed"
    amen.delete_instance()
    return "Success"

'''GET: list of all amenities for the selected place'''
@app.route('/places/<place_id>/amenities', methods = ['GET'])
def get_asdhfjahsdfja(place_id):
    pas = PlaceAmenities.select().where(PlaceAmenities.place.id == place_id)
    ams = []
    for pa in pas:
        ams.append(pa.amenity.to_hash())
    return jsonify(ams)


from .client import orm_api

class PromptExecution:
    """Prompt Execution Options - for prompts that have triggered HITL (human in the loop)
    Must be set with a prompt_execution_id
    Example:
    >>> prompt_execution = PromptExecution(prompt_execution_id="12345")

    Available Methods:
    get_list_hitl() : returns a list of prompts that have triggered HITL
    refresh() : refresh HITL prompts list
    hitl_accept() : accept the HITL prompt as is
    hitl_reject() : reject the HITL prompt and refresh
    hitl_modify_output(new_output) : modify the HITL prompt output and refresh
    hitl_modify_input(new_input) : modify the HITL prompt input and refresh

"""

    def __init__(self, prompt_execution_id, obj=''):
        self.prompt_execution_id = prompt_execution_id
        if obj:
            self.prompt_execution_id = obj['prompt_execution_id']
            self.prompt_id = obj['prompt_id']
            self.input = obj['input']
            self.output = obj['output']
            self.reason = obj['reason']
            self.status = obj['status']
            self.error = obj['error']
            if 'warning_message' in obj:
                self.warning_message = obj['warning_message']
            else:
                self.warning_message = ''
            if 'hitl_info' in obj:
                self.hitl_info = obj['hitl_info']
            else:
                self.hitl_info = '{}'

        if not hasattr(self, 'status'):
            self.refresh()

    @classmethod
    def get_list_hitl(cls):
        result = []
        get_path = f'hitl/'
        api_response = orm_api.endpoint(get_path).get()
        for object in api_response.payload:
            new = cls(prompt_execution_id=object['prompt_execution_id'], obj=object)
            result.append(new)
        return result

    def refresh(self):
        get_path = f'prompt/result/{self.prompt_execution_id}'
        api_response = orm_api.endpoint(get_path).get()
        self.__init__(prompt_execution_id=api_response.payload['prompt_execution_id'], obj=api_response.payload)

    def hitl_accept(self):
        post_path = f'hitl/{self.prompt_execution_id}/accept'
        orm_api.endpoint(post_path).post()
        self.refresh()

    def hitl_reject(self):
        post_path = f'hitl/{self.prompt_execution_id}/reject'
        orm_api.endpoint(post_path).post()
        self.refresh()

    def hitl_modify_output(self, new_output):
        post_path = f'hitl/{self.prompt_execution_id}/modify_output'
        orm_api.endpoint(post_path).post(json={'new_output': new_output})
        self.refresh()

    def hitl_modify_input(self, new_input):
        post_path = f'hitl/{self.prompt_execution_id}/modify_input'
        orm_api.endpoint(post_path).post(json={'new_input': new_input})
        self.refresh()

class InteletExecution:
    def __init__(self, intelet_execution_id, obj=''):
        self.intelet_execution_id = intelet_execution_id
        if obj:
            self.intelet_execution_id = obj['intelet_execution_id']
            self.intelet_id = obj['intelet_id']
            self.input = obj['input']
            self.output = obj['output']
            self.reason = obj['reason']
            self.status = obj['status']
            self.error = obj['error']
            self.executed_prompts = []
            self.pending_prompts = obj['pending_prompts']
            self.results = obj['results']

            for prompt in obj['executed_prompts']:
                p = PromptExecution('prompt_execution_id', obj=prompt)
                self.executed_prompts.append(p)

        if not hasattr(self, 'status'):
            self.refresh()

    def refresh(self):
        get_path = f'intelet/result/{self.intelet_execution_id}'
        api_response = orm_api.endpoint(get_path).get()
        self.__init__(intelet_execution_id=api_response.payload['intelet_execution_id'], obj=api_response.payload)


import csv
import os
import random
import string
from io import StringIO

import yaml

from hyperfoil import HyperfoilClient
from hyperfoil.resources import BenchmarkResource

class HyperfoilFactory:
    def __init__(self, client: 'HyperfoilClient'):
        self._client = client
        self._benchmark = {}
        self._files = {}

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    def close(self):
        for _, stream in self._files.values():
            stream.close()

    def create(self) -> 'BenchmarkResource':
        self._client.benchmark.create(files=self._files)
        return self._client.benchmark.read(self._benchmark['name'])

    def benchmark(self, benchmark: dict) -> 'HyperfoilFactory':
        self._benchmark = benchmark
        file = StringIO()
        yaml.dump(benchmark, file)
        file.seek(0)
        self.file('benchmark', file)
        return self

    def file(self, file_name: str, stream) -> 'HyperfoilFactory':
        if file_name in self._files:
            stream.close()
            raise Exception('File already loaded')
        self._files[file_name] = (file_name, stream)
        return self

    def generate_random_file(self, filename: str, size: int) -> 'HyperfoilFactory':
        file = StringIO()
        payload = ''.join([random.choice(string.ascii_letters) for _ in range(size)])
        file.write(payload)
        file.seek(0)
        self.file(filename, file)
        return self

    def csv_data(self, file_name: str, rows: [[str]], **kwargs) -> 'HyperfoilFactory':
        file = StringIO()
        csv_writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL, **kwargs)
        csv_writer.writerows(rows)
        file.seek(0)
        self.file(file_name, file)
        return self

    def save_files_locally(self, local_path: str):
        for filename, file in self._files.values():
            path = os.path.join(local_path, filename)
            with open(path, 'w') as write_file:
                write_file.write(file.read())
                file.seek(0)


import os

def gen_image(formula, filename, path = None):
    '''
    "List of options:"
    b <color>       Set the background color."
    B <color>       Set the border color."
    d <dpi>         Set the output resolution to the specified dpi."
    e <environment> Set the environment with [options] and {arguments}."
    f <formula>     The LaTeX formula."
    F <color>       Set the foreground color."
    h               Print this help message."
    H <file>        Insert the content of the specified file in the preamble."
    l <file>        Log file."
    m <margin>      Set the margin."
    o <file>        Specify the output file name."
    O               Optimize the image."
    p <packages>    A colon separated list of LaTeX package names."
    P <padding>     Set the padding."
    s <size>        Set the font size."
    S               Silent mode: don't print image file name."
    v               Show version."
    '''

    if path is None:
        path = os.getcwd()

    os.system(f'pnglatex -f "{formula}" -o {path}/data/{filename}.png -S')


import networkx as nx
from itertools import combinations
from functions.global_properties import V
from functions.local_properties import neighbors

def greedy_color(G):
    results = {}

    #init with none color
    for v in V(G):
        results[v]=None

    for v in V(G):

        neighbor_colors = []
        for n in neighbors(G,v):
            if results[n] != None:
                neighbor_colors.append(results[n])

        color = 0
        flag = False
        while not flag:
            if color not in neighbor_colors:
                flag = True
            else:
                color += 1

        results[v] = color

    return results


from .board import Board
from .player import Player
from .minimax import Minimax
import click

class Game:
    def __init__(self, player1 : Player, player2 : Player):
        self._board = Board()
        self._maxPlayer = player1 if player1.isMaxPlayer() else player2
        self._minPlayer = player2 if player1.isMaxPlayer() else player1
        if self._maxPlayer == self._minPlayer:
            raise ValueError("Both players cannot be maxPlayer")

        self._currentPlayer = self._maxPlayer
        self._maxPlayer_minimax = Minimax(self._maxPlayer.getSearchDepth())
        self._minPlayer_minimax = Minimax(self._minPlayer.getSearchDepth())
        self._currentPlayer_minimax = self._maxPlayer_minimax
        self._moves = []

    def runGame(self, returnMoves : bool = False):
        for _ in range(9):
            self._gameTurn()

            if self._board.checkWinCondition(self._currentPlayer.isMaxPlayer()):

                print(self._board)
                print(f"{self._currentPlayer.getName()} has won the game!")

                if returnMoves:
                    return self._moves
                else:
                    return 'X' if self._currentPlayer.isMaxPlayer() else 'O'

            self._switchPlayer()
        print(self._board)
        print("The game has ended in a draw!")

        return 'draw' if not returnMoves else self._moves

    def _switchPlayer(self):
        if self._currentPlayer == self._maxPlayer:
            self._currentPlayer = self._minPlayer
            self._currentPlayer_minimax = self._minPlayer_minimax
        else:
            self._currentPlayer = self._maxPlayer
            self._currentPlayer_minimax = self._maxPlayer_minimax

    def _gameTurn(self):
        if self._currentPlayer.getAi():
           self._aiTurn()
        else:
            self._humanTurn()

    def _aiTurn(self):
        print(self._board)
        y, x = self._currentPlayer_minimax.minimax(self._currentPlayer.getSearchDepth(), self._board, self._currentPlayer.isMaxPlayer())
        self._board.changeSquare(y, x, self._currentPlayer.getSign())
        self._moves.append((x,y))

    def _humanTurn(self):
        badInput = True
        while badInput:
            print(self._board)
            badInput = False
            try:
                x, y = input("Choose x and y coordinates for your move: ").split()
                try:
                    self._board.changeSquare(int(y), int(x), self._currentPlayer.getSign())
                except IndexError:
                    print("Wrong coords: try again")
                    badInput = True
            except ValueError:
                print("wrong input: try again")
                badInput = True


import json
import os
import time

from six.moves.urllib.request import Request, urlopen

path = os.path.dirname(os.path.realpath(__file__))
host = "localhost"

data = {
    "event": {
        "timestamp": int(time.time() * 1000),
        "message": "Synchronized transporter annular confinement beam to warp frequency 0.72e-17 hz",
        "notification_enabled": True,
        "tags": {"Region": "South"},
    }
}
req = Request("http://%s:5502/v1/events" % host)
req.add_header("Content-Type", "application/json")
response = urlopen(req, json.dumps(data).encode("utf-8"))
response_body = response.read()
response_json = json.loads(response_body)
print("Created event %s" % response_json)


# import the important modules and scripts
import os
os.chdir	(os.path.abspath(os.path.dirname(__file__)))
os.add_dll_directory(os.getcwd())
import wx
import globals as g
import shelve
import application
import sys
from language import init_translation
from settingsconfig import get, new, init_config, datapath
from scripts import editor, backup, finder
from scripts.translator import TranslateSelection, SwitchLangs
from docs_handler import GetDoc
from scripts.Speak import speak
from scripts.web_browser import Open
from gui import search_dialog, replace_dialog, text_viewer, extractor_dialog, translate_dialog, settings_dialog
from gui.updater import cfu
from html_handler import html_handler
from threading import Thread

init_translation("AdvancedNotepad") #initialize the translation with the domain
init_config() #initializing the configuration of the program

class notepad(wx.Frame): # the main class
	def __init__(self, file=None):
		g.appInfo = application.info()
		wx.Frame.__init__(self, parent=None, title=g.appInfo.name, size=(900, 700))
		g.UpdateTabs() # get the tabs from data and save it in to variable in the globals
		p=wx.Panel(self)
		self.Center()
		self.html = html_handler
		self.textField = editor.TextBox(p, -1, size=(870, 640))
		self.MenuBarSetup() #execute the function of Menu Bar creation
		self.Bind(wx.EVT_CLOSE, self.OnExit)
		for i in p.GetChildren():
			i.Bind(wx.EVT_KEY_DOWN, self.shortcuts)

		if file:
			self.textField.load_file(file)
		else:
			self.LoadLastTab()
		Thread(target=cfu, args=[True]).start() if get("cfu") else None
		self.Show()

	def MenuBarSetup(self):
		menubar = wx.MenuBar()
#define the menus
		file = wx.Menu()
		edit = wx.Menu()
		tools = wx.Menu()
		about = wx.Menu()
		htmlMenu = wx.Menu()
		contactMenu = wx.Menu()
		extractMenu = wx.Menu()
		translateMenu = wx.Menu()
		menubar.Append(file, _("file"))
		menubar.Append(edit, _("edit"))
		menubar.Append(tools, _("tools"))
		menubar.Append(htmlMenu, _("html"))
		menubar.Append(about, _("about"))
#the file menu options
		new = file.Append(-1, _("new: ctrl+n"))
		NewWindow = file.Append(-1, _("new window: ctrl+shift+n"))
		open = file.Append(-1, _("open file: ctrl+o"))
		save = file.Append(-1, _("save: ctrl+s"))
		saveAs = file.Append(-1, _("save as: ctrl+shift+s"))
		checkForUpdates = file.Append(-1, _("check for updates"))
		settings = file.Append(-1, _("settings: alt+s"))
		exit = file.Append(-1, _("exit"))
#edit menu options
		undo = edit.Append(-1, _("UnDo: ctrl+z"))
		cut = edit.Append(-1, _("cut: ctrl+x"))
		copy = edit.Append(-1, _("copy: ctrl+c"))
		paste = edit.Append(-1, _("paste: ctrl+v"))
		addCopy = edit.Append(-1, _("add copy: ctrl+d"))
		insertTime = edit.Append(-1, _("insert date and time: f5"))
		search = edit.Append(-1, _("Find: ctrl+f"))
		replace = edit.Append(-1, _("replace text: ctrl+h"))
		goTo = edit.Append(-1, _("go to: ctrl+g"))
#tools menu options
		translate = tools.AppendSubMenu(translateMenu, _("translate"))
		extract = tools.AppendSubMenu(extractMenu, _("extract"))
		urls = extractMenu.Append(-1, _("links: ctrl+u"))
		emails = extractMenu.Append(-1, _("emails: ctrl+e"))
		translateSelection = translateMenu.Append(-1, _("translate the selected text: ctrl+t"))
		translateAll = translateMenu.Append(-1, _("Translate the entire file: ctrl+shift+t"))
#the about menu options
		aboutTheProgram = about.Append(-1, _("about"))
		help = about.Append(-1, _("help file: f1"))
		telegramChannel = about.Append(-1, _("telegram channel"))
		contact = about.AppendSubMenu(contactMenu, _("contact us"))
		telegram = contactMenu.Append(-1, "telegram")
		facebook = contactMenu.Append(-1, "facebook")
		twitter = contactMenu.Append(-1, "twitter")
#html menu.
		heading = htmlMenu.Append(-1, _("create heading: alt+h"))
		url = htmlMenu.Append(-1, _("create URL: alt+u"))
		lst= htmlMenu.Append(-1, _("create list: alt+l"))
		paragraph = htmlMenu.Append(-1, _("create paragraph: alt+p"))
#binding the options
#the file menu
		self.Bind(wx.EVT_MENU, self.OnOpen, open)
		self.Bind(wx.EVT_MENU, self.save, save)
		self.Bind(wx.EVT_MENU, self.NewFile, new)
		self.Bind(wx.EVT_MENU, lambda e:os.startfile(sys.executable), NewWindow)
		self.Bind(wx.EVT_MENU, self.OnExit, exit)
		self.Bind(wx.EVT_MENU, lambda e:self.save(saveAs=True), saveAs)
		self.Bind(wx.EVT_MENU, lambda e:settings_dialog.SettingsDialog(self), settings)
		self.Bind(wx.EVT_MENU, lambda e:cfu(), checkForUpdates)
#the edit menu
		self.Bind(wx.EVT_MENU, lambda e:g.AddCopy(self.textField.StringSelection), addCopy)
		self.Bind(wx.EVT_MENU, lambda e:replace_dialog.ReplaceDialog(self), replace)
		self.Bind(wx.EVT_MENU, self.GoTo, goTo)
		self.Bind(wx.EVT_MENU, self.OnSearch, search)
		self.Bind(wx.EVT_MENU, self.textField.WriteTime, insertTime)
		self.Bind(wx.EVT_MENU, lambda e:self.textField.Undo(), undo)
		self.Bind(wx.EVT_MENU, lambda e:self.textField.Paste(), paste)
		self.Bind(wx.EVT_MENU, lambda e:self.textField.Copy(), copy)
		self.Bind(wx.EVT_MENU, lambda e:self.textField.Cut(), cut)
# the tools menu
		self.Bind(wx.EVT_MENU, lambda e: extractor_dialog.ExtractorDialog(self, finder.FindUrls(self.textField.Value)), urls)
		self.Bind(wx.EVT_MENU, lambda e:extractor_dialog.ExtractorDialog(self, finder.FindEmails(self.textField.Value), False), emails)
		self.Bind(wx.EVT_MENU, lambda e:translate_dialog.TranslateDialog(self), translateAll)
		self.Bind(wx.EVT_MENU, lambda e:TranslateSelection(self.textField.StringSelection), translateSelection)
#about items
		self.Bind(wx.EVT_MENU, lambda e:wx.MessageBox(g.appInfo.about, _("about the program")), aboutTheProgram)
		self.Bind(wx.EVT_MENU, lambda e:Open(g.appInfo.telegram), telegram)
		self.Bind(wx.EVT_MENU, lambda e:Open(g.appInfo.twitter), twitter)
		self.Bind(wx.EVT_MENU, lambda e:Open(g.appInfo.facebook), facebook)
		self.Bind(wx.EVT_MENU, lambda e:Open(g.appInfo.tchannel), telegramChannel)
		self.Bind(wx.EVT_MENU, lambda e:text_viewer.viewer(self, _("help"), _("help"), GetDoc()), help)
#html items
		self.Bind(wx.EVT_MENU, lambda e:self.html.HeadingsDialog(self), heading)
		self.Bind(wx.EVT_MENU, lambda e:self.html.UrlsDialog(self), url)
		self.Bind(wx.EVT_MENU, lambda e:self.html.ParagraphsDialog(self), paragraph)
		self.Bind(wx.EVT_MENU, lambda e:self.html.ListsDialog(self), lst)
		shortcuts = wx.AcceleratorTable([
			(wx.ACCEL_CTRL+wx.ACCEL_SHIFT, ord("N"), NewWindow.GetId()),
			(wx.ACCEL_CTRL, ord("N"), new.GetId()),
			(wx.ACCEL_CTRL, ord("O"), open.GetId()),
			(wx.ACCEL_CTRL, ord("S"), save.GetId()),
			(wx.ACCEL_CTRL, ord("G"), goTo.GetId()),
			(wx.ACCEL_CTRL, ord("F"), search.GetId()),
			(wx.ACCEL_CTRL, ord("H"), replace.GetId()),
			(wx.ACCEL_CTRL, ord("U"), urls.GetId()),
			(wx.ACCEL_CTRL, ord("E"), emails.GetId()),
			(wx.ACCEL_CTRL+wx.ACCEL_SHIFT, ord("T"), translateAll.GetId()),
			(wx.ACCEL_ALT, ord("S"), settings.GetId()),
			(wx.ACCEL_CTRL, ord("T"), translateSelection.GetId()),
			(wx.ACCEL_CTRL, ord("D"), addCopy.GetId()),
			(wx.ACCEL_ALT, ord("H"), heading.GetId()),
			(wx.ACCEL_ALT, ord("U"), url.GetId()),
			(wx.ACCEL_ALT, ord("P"), paragraph.GetId()),
			(wx.ACCEL_ALT, ord("L"), lst.GetId()),
			(0, wx.WXK_F1, help.GetId()),
		])
		self.SetAcceleratorTable(shortcuts)
		self.SetMenuBar(menubar)

	def NewFile(self, event=None):
		return self.textField.NewTab()

	def LoadLastTab(self):
		try:
			with shelve.open(os.path.join(datapath, "backup")) as f:
				file = f["last"]
				if not file in g.tabs: return
				self.textField.load_file(file)
		except: pass

	def GoTo(self, event=None):
		position = self.textField.PositionToXY(self.textField.InsertionPoint)
		lineNumber = wx.GetNumberFromUser(_("line number"), _("line number"), _("go to line"), position[-1], min=0, max=self.textField.NumberOfLines, parent=self)
		self.textField.InsertionPoint = self.textField.XYToPosition(1, lineNumber)

	def OnSearch(self, event=None):
		search = search_dialog.SearchDialog(self)
		search.ShowModal()

	def OnOpen(self, event):
		path = wx.FileSelector(_("open file"), wildcard=_("all files(*.*)|*.*|text documents(.txt)|*.txt|python scripts(.py)|*.py|html page(.html)|*.html"), parent = self)
		if not path: return
		g.activeFile = path
		self.textField.load_file(path)
#		self.TabsSetup()

	def save(self, event=None, saveAs=False):
		self.textField.OnWrite(None)
		if not g.activeFile == None and not saveAs:
			saveFile = g.activeFile
		else:
			saveFile = wx.SaveFileSelector(_("Save As"), _("text documents(.txt)|*.txt|python scripts(.py)|*.py|html page(.html)|*.html"), parent=self)
			if not saveFile: return
			if os.path.isfile(saveFile):
				msg = wx.MessageBox(_("The file {f} already exists, do you want to replace it?").format(f=saveFile), _("file exists"), style=wx.YES_NO, parent=self)
				if msg==wx.NO:
					return
		with open(saveFile, "w",encoding="utf-8") as file:
			file.write(self.textField.Value)
			self.textField.modified = False
		g.activeFile = saveFile
		if g.newTab:
			backup.backup().delete(g.paths[g.tabIndex])
		speak(_("File saved successfully"))
		self.textField.load_file(g.activeFile)

	def OnExit(self, event=None):
		self.textField.SavePosition()
		if self.textField.modified:
			dialog = wx.MessageDialog(self, _("Do you want to save changes to Untitled?"), g.appInfo.name, style=wx.YES_NO+wx.CANCEL)
			dialog.SetYesNoCancelLabels(_("&save"), _("&dont save"), _("&cancel"))
			result = dialog.ShowModal()
			if result ==wx.ID_YES:
				self.save()
			elif result == wx.ID_NO:
				return wx.Exit()
			elif result == wx.ID_CANCEL: return
		else: return wx.Exit()

	def FirstTab(self):
		if len(g.paths)<1: return speak(_("there is no tabs"))
		if g.tabIndex==0: return speak(_("the focus already on the first tab"))
		g.tabIndex = 0
		self.textField.load_file(g.tabs[g.paths[g.tabIndex]]["path"])
		if not g.activeFile==None:
			fn = os.path.basename(g.activeFile)
		else:
			try:
				fn = os.path.basename(g.paths[g.tabIndex])
			except:
				fn = g.paths[g.tabIndex]
		g.playsound("previous_tab.wav") if get("navigateeffects") else None
		speak(_("{fileName} {path} {firstNumber} of {secondNumber}").format(fileName=fn, firstNumber=g.tabIndex+1, secondNumber=len(g.paths), path="- "+g.paths[g.tabIndex]+"," if not g.tabs[g.paths[g.tabIndex]]["newTab"] else ""))

	def LastTab(self):
		if len(g.tabs)<1: return speak(_("there is no tabs"))
		if g.tabIndex==len(g.paths)-1: return speak(_("the focus already on the last tab"))
		g.tabIndex = len(g.paths)-1
		self.textField.load_file(g.tabs[g.paths[g.tabIndex]]["path"])
		if not g.activeFile==None:
			fn = os.path.basename(g.activeFile)
		else:
			try:
				fn = os.path.basename(g.paths[g.tabIndex])
			except:
				fn = g.paths[g.tabIndex]
		g.playsound("next_tab.wav") if get("navigateeffects") else None
		speak(_("{fileName} {path} {firstNumber} of {secondNumber}").format(fileName=fn, firstNumber=g.tabIndex+1, secondNumber=len(g.paths), path="- "+g.paths[g.tabIndex]+"," if not g.tabs[g.paths[g.tabIndex]]["newTab"] else ""))

	def NextTab(self):
		if len(g.tabs)<1: return speak(_("there is no tabs"))
#		self.textField.SavePosition()
		if g.tabIndex>=len(g.paths)-1:
			g.tabIndex = 0
		else:
			g.tabIndex+=1
		self.textField.load_file(g.tabs[g.paths[g.tabIndex]]["path"])
		if not g.activeFile==None:
			fn = os.path.basename(g.activeFile)
		else:
			try:
				fn = os.path.basename(g.paths[g.tabIndex])
			except:
				fn = g.paths[g.tabIndex]
		g.playsound("next_tab.wav") if get("navigateeffects") else None
		speak(_("{fileName} {path} {firstNumber} of {secondNumber}").format(fileName=fn, firstNumber=g.tabIndex+1, secondNumber=len(g.paths), path="- "+g.paths[g.tabIndex]+"," if not g.tabs[g.paths[g.tabIndex]]["newTab"] else ""))

	def PreviousTab(self):
		if len(g.tabs)<1: return speak(_("there is no tabs"))
#		self.textField.SavePosition()
		if g.tabIndex<=0:
			g.tabIndex = len(g.tabs)-1
		else:
			g.tabIndex-=1
		self.textField.load_file(g.tabs[g.paths[g.tabIndex]]["path"])
		if not g.activeFile==None:
			fn = os.path.basename(g.activeFile)
		else:

			try:
				fn = os.path.basename(g.paths[g.tabIndex])
			except:
				fn = g.paths[g.tabIndex]
		g.playsound("previous_tab.wav") if get("navigateeffects") else None
		speak(_("{fileName} {path} {firstNumber} of {secondNumber}").format(fileName=fn, firstNumber=g.tabIndex+1, secondNumber=len(g.paths), path="- "+g.paths[g.tabIndex]+"," if not g.tabs[g.paths[g.tabIndex]]["newTab"] else ""))

	def RestoreText(self):
		if g.activeFile is None: return speak(_("current active is unsaved tab"))
		try:
			with open(g.activeFile, "r", encoding="utf-8") as f:
				self.textField.Value=f.read()
		except:
			with open(g.activeFile, "r", encoding="ansi") as f:
				self.textField.Value=f.read()
		self.textField.modified = False
		speak(_("text restored"))

	def CloseTab(self):
		if g.activeFile==None and not g.newTab: return speak(_("select a tab first"))
		if g.activeFile==None:
			if not self.textField.Value:
				backup.backup().delete(g.paths[g.tabIndex])
				speak(_("tab closed"))
				self.textField.clear()
				return self.NextTab()
			dialog = wx.MessageDialog(self, _("If you close the tab, you can't get it back, do you want to save to a file?"), g.appInfo.name, style=wx.YES_NO+wx.CANCEL)
			dialog.SetYesNoCancelLabels(_("&save"), _("&dont save"), _("&cancel"))
			result = dialog.ShowModal()
			if result ==wx.ID_YES:
				self.save()
				backup.backup().delete(g.paths[g.tabIndex])
				speak(_("tab closed"))
				self.textField.clear()
				return self.NextTab()
			elif result == wx.ID_NO:
				backup.backup().delete(g.paths[g.tabIndex])
				speak(_("tab closed"))
				self.textField.clear()
				return self.NextTab()
			else: return
		else:
			try:
				with open(g.activeFile, "r", encoding="utf-8") as f:
					content = f.read()
			except:
				with open(g.activeFile, "r", encoding="ansi") as f:
					content = f.read()
			if content==self.textField.Value:
				backup.backup().delete(g.paths[g.tabIndex])
				speak(_("tab closed"))
				self.textField.clear()
				return self.NextTab()
			else:
				dialog = wx.MessageDialog(self, _("If you close the tab, you can't get it back, do you want to save changes?"), g.appInfo.name, style=wx.YES_NO+wx.CANCEL)
				dialog.SetYesNoCancelLabels(_("&save"), _("&dont save"), _("&cancel"))
				result = dialog.ShowModal()
				if result ==wx.ID_YES:
					self.save()
					backup.backup().delete(g.paths[g.tabIndex])
					speak(_("tab closed"))
					self.textField.clear()
					return self.NextTab()
				elif result == wx.ID_NO:
					backup.backup().delete(g.paths[g.tabIndex])
					speak(_("tab closed"))
					self.textField.clear()
					return self.NextTab()
				else: return
		g.UpdateTabs()

	def shortcuts(self, event):
		if event.GetKeyCode() == wx.WXK_F2:
			SwitchLangs()
		if event.altDown:
			if event.GetKeyCode()==wx.WXK_RIGHT:
				self.NextTab()
			elif event.GetKeyCode()==wx.WXK_LEFT:
				self.PreviousTab()
			elif event.GetKeyCode() == wx.WXK_UP:
				self.FirstTab()
			elif event.GetKeyCode() == wx.WXK_DOWN:
				self.LastTab()
			elif event.GetKeyCode() == ord("R"):
				self.RestoreText()
		elif event.controlDown:
			if event.GetKeyCode() == ord("W"):
				self.CloseTab()
#			elif event.GetKeyCode()==ord("I"):
#				text_viewer.viewer(self, _("text info"), _("text info"), self.textField.GetInfo())
		event.Skip()

app=wx.App()
file = None
if len(sys.argv)>=2:
		if os.path.isfile(sys.argv[1]):
			file = sys.argv[1]
		else:
			if not sys.argv[1]=="None":
				ask = wx.MessageDialog(None, _("Cannot find the {f} file\n do you want to create it now?").format(f=sys.argv[1]), _("file not found"), style=wx.YES_NO+wx.CANCEL)
				ask.SetYesNoCancelLabels(_("yes"), _("no"), _("cancel"))
				result = ask.ShowModal()
				if result ==wx.ID_YES:
					file = sys.argv[1]
					open(file, "w", encoding="utf-8").close()
				elif result == wx.ID_CANCEL:
					sys.exit()
notepad(file)
app.MainLoop()


# -*- coding: utf-8 -*-
"""
Created on Sun Jan 19 21:21:13 2020

@author: COM
"""

def seq(alist, item):
    pos = 0
    found = False

    while pos < len(alist) and not found: #  not found: found가 False일 경우
        if alist[pos] == item:
            found = True
        else:
            pos = pos + 1
    return found

poke=["이븐곰","로즈레이드","래비풋"]
print(seq(poke,"이븐곰")) # 리스트에 있을 경우
print(seq(poke,"에이스번")) # 없을 경우


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from collections import OrderedDict

from libs import data_service
from paths import root
from test_programm.image import Image, GroupImage

left_data_geometry = "user_geometry.json"

data = data_service.JsonData(os.path.join(root, "data/models/json"),
                             left_data_geometry)
data.reload()

Image.set_ext(Image, ".png")
Image.set_image_dir(Image, os.path.join(root, "resources/image"))
Image.set_image_select_dir(Image,
                           os.path.join(root,
                                        "resources/image_select"))

class Step():
    def __init__(self, left_names=None, right_names=None,
                 left_geometry_path=None, right_geometry_path=None):
        self._left_names = left_names
        self._right_names = right_names

    def set_left_images(self, *images):
        self._left_images = GroupImage(Image, self.get_geometry_dada, images)

    @property
    def get_geometry_dada(self):
        return "data"

if __name__ == '__main__':
    pass


from django.contrib import admin

from news.models import News, Comment

@admin.register(News)
class NewsAdmin(admin.ModelAdmin):
    fields = ('title',
              'slug',
              'body',
              'image',
              'author',
              'published',
              'created',
              'updated')
    prepopulated_fields = {'slug': ('title',)}
    readonly_fields = ('created',
                       'updated')
    list_display = ('title',
                    'slug',
                    'author',
                    'published',
                    'created',
                    'updated')
    search_fields = ('title',
                     'slug',
                     'body',
                     'author')
    list_filter = ('published',
                   'created',
                   'updated')
    list_editable = ('published',)
    ordering = ('-created',
                '-updated',
                'title')

    def save_model(self, request, obj, form, change):
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        obj.save()

@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    fields = ('text',
              'author',
              'news',
              'published',
              'created',
              'updated')
    readonly_fields = ('created',
                       'updated')
    list_display = ('author',
                    'news',
                    'published',
                    'created',
                    'updated')
    search_fields = ('author',
                     'news')
    list_filter = ('published',
                   'created',
                   'updated')
    list_editable = ('published',)
    ordering = ('-created',
                '-updated')

    def save_model(self, request, obj, form, change):
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        obj.save()


from sqlalchemy import Column, Integer, Text
from project.database.Database import Base, session

class Request(Base):
    __tablename__ = "requests"

    id = Column(Integer, primary_key=True)
    datetime = Column(Text)
    tool = Column(Text)
    first_line_format = Column(Text)
    method = Column(Text)
    scheme = Column(Text)
    host = Column(Text)
    port = Column(Text)
    path = Column(Text)
    http_version = Column(Text)
    headers = Column(Text)
    content = Column(Text)
    timestamp_start = Column(Text)
    timestamp_end = Column(Text)

    def __init__(self,
                 datetime=None,
                 tool=None,
                 first_line_format=None,
                 method=None,
                 scheme=None,
                 host=None,
                 port=None,
                 path=None,
                 http_version=None,
                 headers=None,
                 content=None,
                 timestamp_start=None,
                 timestamp_end=None):
        self.datetime = datetime
        self.tool = tool
        self.first_line_format = first_line_format
        self.method = method
        self.scheme = scheme
        self.host = host
        self.port = port
        self.path = path
        self.http_version = http_version
        self.headers = headers
        self.content = content
        self.timestamp_start = timestamp_start
        self.timestamp_end = timestamp_end

    def insert(self):
        session.add(self)
        session.commit()

    @staticmethod
    def update():
        session.commit()

    @staticmethod
    def find_one(entity_id):
        return Request.query.filter(Request.id == entity_id).first()

    @staticmethod
    def delete(entity_id):
        Request.query.filter(Request.id == entity_id).delete()
        session.commit()


import asyncio

from ..bindings import task_to_future, convert_async_iterable, with_async_locals, restore_async_locals

from System import Object
from Perper.Extensions import PerperContext, PerperStreamExtensions

async def start_stream(delegate, *parameters, action=False, ephemeral=True, packed=False, index=None):
    builder = _create_stream_builder(delegate, action, ephemeral, packed, index)
    return await task_to_future(with_async_locals(lambda _: builder.StartAsync(parameters)))

async def create_blank_stream(*, ephemeral=True, packed=False, index=None):
    builder = _create_stream_builder("", False, ephemeral, packed, index)
    return await task_to_future(with_async_locals(lambda _: builder.StartAsync()))

def declare_stream(delegate, *, action=False, ephemeral=True, packed=False, index=None):
    stream = _create_stream_builder(delegate, action, ephemeral, packed, index)

    async def start(*parameters):
        await task_to_future(with_async_locals(lambda _: stream.StartAsync(parameters)))

    return stream.Stream, start

def _create_stream_builder(delegate, action, ephemeral, packed, index):
    stream_builder = PerperContext.Stream(delegate)
    if not ephemeral:
        stream_builder = stream_builder.Persistent()
    if action:
        stream_builder = stream_builder.Action()
    if packed:
        stream_builder = stream_builder.Packed(1)

    return stream_builder

def replay_stream(stream, replay=True, replay_from=0):
    if replay_from:
        return PerperStreamExtensions.Replay(stream, replay_from)
    else:
        return PerperStreamExtensions.Replay(stream, replay)

def local_stream(stream, local_to_data=True):
    return PerperStreamExtensions.LocalToData(stream, local_to_data)

def enumerate_stream(stream, return_type=Object):
    restore_async_locals()
    stream_enum = PerperStreamExtensions.EnumerateAsync[return_type](stream).GetAsyncEnumerator()
    return convert_async_iterable(stream_enum)

def enumerate_stream_with_keys(stream, return_type=Object):
    restore_async_locals()
    stream_enum = PerperStreamExtensions.EnumerateWithKeysAsync[return_type](stream).GetAsyncEnumerator()
    return convert_async_iterable(stream_enum)

async def query_stream(stream, type_name, sql_condition, *sql_parameters):
    restore_async_locals()
    stream_query = PerperStreamExtensions.Query[Object](stream, type_name, sql_condition, sql_parameters).GetAsyncEnumerator()
    return convert_async_iterable(stream_query)

async def destroy_stream(stream):
    return await task_to_future(with_async_locals(lambda _: PerperStreamExtensions.DestroyAsync(stream)))


import numpy as np

class GPRegression(object):

    def __init__(self,kernel, thetas=[]):
        """
        inputs:
            kernel : the class for kernel.
        """
        self.kernel = kernel(thetas)

    def fit(self, X, y, num_iter=10, eta=0.1):
        """
        In this process, optimize the hyper parameters.
        inputs:
            X : 2d-array. shape=[N, d]
                The explanatory variables.
            y : 1d-array. shape=[N]
                The objective variables.
        returns:
            None
        """
        print("fiting ......")
        self.X = X
        self.y = y

        # optimize thetas
        for i in range(num_iter):
            print("num_iter = {}".format(i), end="\r")
            dl = self.part_l()
            self.kernel.theta += eta * dl
        self.K = self.kernel.make_kernel(X) # kernel_matrix for predict to use for predicting value.
        print("fitting completed")

    def part_l(self):
        N = self.X.shape[0]
        k_theta = self.kernel.make_kernel(self.X)
        k_theta_inv = np.linalg.inv(k_theta)
        dk_dtheta = self.kernel.part_K(self.X)
        dl_1 = - np.trace(np.dot(dk_dtheta, k_theta_inv), axis1=1, axis2=2)
        dl_2_1 = (np.dot(k_theta_inv,self.y.reshape(-1,1)))
        dl_2 = np.dot(np.dot(dl_2_1.T, dk_dtheta).reshape(4,N), dl_2_1) # -> [4,1]
        dl_2 = dl_2.flatten()
        return dl_1 + dl_2

    def predict(self, X_star):
        k_star = self.kernel.make_k_star(self.X, X_star)
        k_dstar = self.kernel.make_kernel(X_star)
        K_inv = np.linalg.inv(self.K)
        m = np.dot(np.dot(k_star.T, K_inv), self.y.reshape(-1,1))
        v = k_dstar - np.dot(np.dot(k_star.T, K_inv), k_star)
        return m, v