# This script takes a file containing ADCG chunks and decompresses them.
# Pillow is required as a dependency.
#
# The decompressed ADCG chunks are output in the working directory with the extension .adcg.
# The decompressed image data is then weaved into a complete image and saved as PNG.
# In files that contain them, ADCG headers are preceded by an AGR1 or AGR2 signature,
# which is followed by 00 00 00 00.
# Some values in the ADCG header are currently unknown.

import io
import mmap
import os
import struct
import subprocess
import sys
from collections import namedtuple
from PIL import Image
from utils import prs

path = os.path.realpath(os.path.dirname(sys.argv[0]))

# Set these to the path and arguments of a utility that accepts a PVR file and output a PNG file.
# It is recommended that the arguments include a switch that suppresses console output, if available.
pvr2png_path = os.path.join(path,os.path.normpath(r".\lib\pvr2png.exe"))
pvr2png_args = ["-q"]

def weave_adcg(input_data,address):
    """Extracts the PVR subtextures from an uncompressed ADCG chunk,
    and attempts to assemble it into a full image based on the properties
    in the ADCG header."""

    ADCGSubTexture = namedtuple("ADCGSubTexture","id offset x y value1")

    with io.BytesIO(input_data) as stream:
        signature = stream.read(4)
        adcg_size = struct.unpack("<I",stream.read(4))[0]
        value1 = stream.read(4) # 00 00 00, followed by a single byte. Possible signed 2-byte value?
        textures_num = struct.unpack("<I",stream.read(4))[0]

        texture_width = struct.unpack("<H",stream.read(2))[0]
        texture_height = struct.unpack("<H",stream.read(2))[0]
        value2 = stream.read(4) # 18 00 00 00. Offset - 8?

        pvr_format = stream.read(4)[0:2]

        total_width = struct.unpack("<H",stream.read(2))[0]
        total_height = struct.unpack("<H",stream.read(2))[0]

        # Initialize output image.
        output_image = Image.new("RGBA",(total_width,total_height))

        textures = []

        for _ in range(textures_num):
            textures.append(ADCGSubTexture(struct.unpack("<I",stream.read(4))[0],
                                           struct.unpack("<I",stream.read(4))[0],
                                           struct.unpack("<H",stream.read(2))[0],
                                           struct.unpack("<H",stream.read(2))[0],
                                           stream.read(4)))

        # Create PVR textures.
        for i,data in enumerate(textures):
            stream.seek(data.offset + 32 + (16 * i))

            try:
                # Texture size is calculated from offset of next texture, plus 16.
                texture_size = textures[i+1].offset - data.offset + 16
                texture_data = stream.read(texture_size)
            except IndexError:
                # For last texture, read to end of file.
                texture_data = stream.read(adcg_size - data.offset + 16)

            chunk_size = struct.pack("<I",len(texture_data) + 8)

            output = b'PVRT' + chunk_size + pvr_format + b'\x00\x00' + struct.pack("<H",texture_width) + struct.pack("<H",texture_height) + texture_data

            with open("~temp.pvr","wb") as output_file:
                output_file.write(output)

            # Convert PVR texture to PNG.
            pvr_convert = subprocess.run([pvr2png_path,"~temp.pvr","~temp.png"] + pvr2png_args,shell=True)
            pvr_convert.check_returncode()

            # Load converted texture into an Image object.
            if os.path.isfile("~temp.png"):
                with Image.open("~temp.png") as png:
                    output_image.paste(png,(data.x,data.y))
            else:
                print(f"Error processing subtexture in ADCG chunk at {address}. Check output.")
                continue

        if os.path.isfile("~temp.pvr"):
            os.remove("~temp.pvr")
        if os.path.isfile("~temp.png"):
            os.remove("~temp.png")

        return output_image

def extract_adcg(input_file,offset=0,end=-1):
    """From input_file, searches for ADCG chunks and decompresses them.
    The original uncompressed ADCG data is saved to file, as its header is
    required to reconstruct the file after editing the image.
    Each chunk is then assembled into a complete image file and saved as PNG.

    If the offset argument is set, start searching that many bytes into the file.
    If the end argument is set, stop searching after this many bytes."""

    adcg_index = 0
    files_written = 0

    with open(input_file,"rb") as f:

        with mmap.mmap(f.fileno(),0,access=mmap.ACCESS_READ) as mm:

            if end < 0:
                end = len(mm)

            while True:
                # Decompress a single ADCG chunk.
                adcg_pos = mm.find(b'ADCG',mm.tell())

                if adcg_pos > end:
                    return files_written

                if adcg_pos != -1:
                    mm.seek(adcg_pos)

                    # Skip offset bytes, but attempt to keep index number accurate.
                    if mm.tell() >= offset:
                        abs_offset = hex(mm.tell())
                        adcg_prs_data = bytearray()

                        while True:
                            buffer = mm.read(4)
                            adcg_prs_data += buffer
                            if buffer == b'EOFC':
                                adcg_prs_data += mm.read(4)
                                break

                        try:
                            adcg_uncompressed = bytes(prs.decompress(adcg_prs_data))
                        except Exception as e:
                            print(e)
                            print(f"Error processing ADCG chunk at {abs_offset}. Continuing with next chunk.")
                            continue

                        # Save uncompressed ADCG data and PNG to file.
                        filename = input_file + "_" + str(adcg_index).zfill(4) + "_" + abs_offset

                        with open(filename + ".adcg","wb") as raw_file:
                            raw_file.write(adcg_uncompressed)

                        output_image = weave_adcg(adcg_uncompressed,abs_offset)

                        with open(filename + ".png","wb") as output_file:
                            output_image.save(output_file)
                            files_written += 1
                            print(f"{output_file.name}: Dimensions: {output_image.size}.")

                    else:
                        print(f"Skipping ADCG chunk {str(adcg_index).zfill(4)} at {hex(mm.tell())}.")
                        mm.seek(4,1)

                    adcg_index += 1

                else:
                    return files_written

def main():

    if len(sys.argv) > 2:
        if len(sys.argv) >= 4:
            files_written = extract_adcg(sys.argv[1],int(sys.argv[2],(16 if sys.argv[2].startswith("0x") else 10)),int(sys.argv[3]))
        elif len(sys.argv) == 3:
            files_written = extract_adcg(sys.argv[1],int(sys.argv[2],(16 if sys.argv[2].startswith("0x") else 10)))
        else:
            files_written = extract_adcg(sys.argv[1])
    elif len(sys.argv) == 2:
        files_written = extract_adcg(sys.argv[1])
    else:
        print("Specify input file containing ADCG data.\nOptional arguments: number of bytes to skip; number of bytes to search. Hex offsets starting with 0x allowed.")
        return

    print(f"\nWrote {files_written} ADCG + PNG file pairs.")

if __name__ == "__main__":
    main()


from model.book import Book
from domain.book import BookDomain

def test_add_book(book_service):
    # 새 책 도메인 생성
    book_domain = BookDomain(title="Test Book", author="Test Author", year=2022)

    # add_book 메서드 호출
    book_service.add_book(book_domain)

    # 데이터베이스에서 추가된 책 조회
    added_books = book_service.get_books()

    # 책이 추가되었는지 확인
    assert len(added_books) == 1
    added_book = added_books[0]

    # 추가된 책의 정보 확인
    assert added_book.title == "Test Book"
    assert added_book.author == "Test Author"
    assert added_book.year == 2022

def test_get_books(book_service):
    # 데이터베이스에 미리 몇 권의 책 추가
    book1 = Book(title="Book 1", author="Author 1", year=2020)
    book2 = Book(title="Book 2", author="Author 2", year=2021)
    book_service.session.add(book1)
    book_service.session.add(book2)
    book_service.session.commit()

    # get_books 메서드 호출
    books = book_service.get_books()

    # 반환된 책 목록 검증
    assert len(books) == 2
    assert books[0].title == "Book 1"
    assert books[1].title == "Book 2"


# 2020.03.10-Homework-kamene ping
from kamene.all import *
from kamene.layers.inet import IP, ICMP
import logging

logging.getLogger('kamene.runtime').setLevel(logging.ERROR)

def qytang_ping(ip):
    ping_pkt = IP(dst=ip) / ICMP()
    ping_result = sr1(ping_pkt, timeout=2, verbose=False)

    if ping_result:
        return ip, 1
    else:
        return ip, 0

if __name__ == '__main__':
    result = qytang_ping('192.168.200.3')  # Linux VM， ping自己的ip地址就不通，shell是可以通的，不知道是为啥？？？
    if result[1]:
        print(result[0], '通')
    else:
        print(result[0], '不通')


class Solution:
    def countHillValley(self, nums: List[int]) -> int:
        n = len(nums)
        groups = []
        i = 0
        while i < n:
            ctr = 1
            while i < n - 1 and nums[i] == nums[i + 1]:
                i += 1
                ctr += 1
            i += 1
            groups.append((nums[i - 1], ctr))
        ctr = 0
        m = len(groups)
        for i in range(1, m - 1):
            left = groups[i][0] > groups[i - 1][0]
            right = groups[i][0] > groups[i + 1][0]
            if not left ^ right:
                ctr += 1
        return ctr


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script to parse the mapping results of KMA, when the ref database is a set of VAMB bins

Created on 5/3/21
@author: V.R.Marcelino
"""

import pandas as pd
from argparse import ArgumentParser
import os

parser = ArgumentParser()
parser.add_argument('-i', '--input_fp', help="""Path to the folder containing KMA res files.""", required=True)
parser.add_argument('-o', '--output_fp', default = 'merged_samples.csv',
                    help='Path to the output file. Default = merged_samples', required=False)

args = parser.parse_args()
in_folder = args.input_fp
output = args.output_fp

#in_folder = "01_KMA"
#output = "merged_samples.csv"

### define how we will aggregate the info
f4agg = {}
f4agg['Depth']= 'sum'
f4agg['Taxonomy']= 'first'

# create new dataframe to store all samples:
all_samples = pd.DataFrame()

# read input files and merge results
for file in os.listdir(in_folder):
    if file.endswith(".res"):
        sample_name = file.split("_mags.res")[0]
        result_fp = os.path.join(in_folder, file)
        out_sample_fp = result_fp + ".summary.csv"

        df = pd.read_csv(result_fp, sep='\t', encoding='latin1')

        # Make 3 new columns for binID, contigIDs and taxonomy
        df[["BinID","contigID","Taxonomy"]] = df["#Template"].str.split('|', expand=True)

        depth_by_tax = df.groupby(by="BinID").agg(f4agg)
        depth_by_tax.rename(columns={'Depth': sample_name}, inplace=True)

        #save this file for reference
        pd.DataFrame.to_csv(depth_by_tax, out_sample_fp, index=True)

        all_samples = pd.concat([all_samples, depth_by_tax], sort=True, axis=1)

# Group taxon ranks
all_samples = all_samples.groupby(by=all_samples.columns, axis = 1).first()

# Fill NaN with zeros:
all_samples = all_samples.fillna(0)

# Save to file
pd.DataFrame.to_csv(all_samples, output, index=True)


import turtle as t
from tkinter import *
from metrorail_network2 import * # use the file that initializes the stations

## Louis: 3728436
## Martin: 3708931

z = []
epsilon = []

beta = open('stationsLoc.dat','r')
for line in beta:
	delta = line[:line.index('\n')]
	exec('z.append({})'.format(delta))

win = t.Screen()
win.title('Please click on origin station')
win.bgpic('CT_RailMap.gif')
win.setup(800,800)

def offsite(gamma):
	print(gamma, "ssss")
	global z
	global epsilon
	for station in z:
		sigma = gamma.upper()
		if station[2].code == sigma:
			if len(epsilon) is 0:
				win.title('Please click on destination station')
				epsilon.append(station[2])
			else:
				win.title('Please click on origin station')
				x = epsilon[0].route_to(station[2])
				print(x)
				epsilon = []
			print(station[2].name)
			return
	print('Not FOUND')

def mapped():
	mu  = Tk()
	mu.title('Choose station manually')
	psi = StringVar()
	iota = Label(mu, text='Enter Station short code :')
	iota.grid(row=1, column=0)
	pi = Entry(mu, textvariable=psi)
	pi.grid(row=1, column=1)
	nu = Button(mu, text='Go', command=lambda:offsite(pi.get()))
	nu.grid(row=1, column = 2)

# on the original picture radius of the circles(station) is 10px
def x_y_co(x, y):
	global epsilon
	for t in z:
		x0 = t[0]-10
		x1 = t[0]+10
		y0 = t[1]-10
		y1 = t[1]+10
		if (x >= x0) and (x <= x1):
			if (y >= y0) and (y <= y1):
				if len(epsilon) is 0:
					epsilon.append(t[2])
					win.title('Please click on destination station')
				else:
					epsilon[0].route_to(t[2])
					epsilon = []
					win.title('Please click on origin station')
				print(t[2].name)
				return
	mapped()
#	print('Map')

win.onscreenclick(x_y_co)
t.mainloop()


from __future__ import print_function
import socket
import select
import json
import copy
import random
from time import sleep

host = '127.0.0.1'
port = 10000
backlog = 10
bufsize = 4096
timeout=0

verbose=3
playersize = 3
socks = []
names=[]
log_data=[]

def connect(size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((host, port))
    s.listen(size)
    print('port:',port)
    print('waiting for',size, 'connection...')
    for i in range(size):
        soc, addr = s.accept()          # 要求が来るまでブロック
        soc.settimeout(timeout)
        socks.append(soc)
        print("conneted ", str(addr),)  # サーバ側の合図
    print('successfully connected with', len(socks), 'clients.')
    s.close()
    return socks

def initialize(size,info):
    #global socks
    random.shuffle(socks)
    tmp = 0
    for soc in socks:
        msg=str({'request':'INITIALIZE','arg':tmp,'info':accessible_info(tmp,info)})
        data=send_recv(msg,soc)
        #print('Client[' + str(tmp) + ']> ', data)
        while data in names:
            data+='*'
        names.append(data)
        tmp += 1

    for i in range(size):
        ret='INITIALIZE '+agent(i)+' '+names[i]
        log(ret)
    return

def request_sell(sock,info):
    command='SELL'
    #print(command)
    msg=str({'request':command,'info':info})
    recv=send_recv(msg,sock)
    result=-1
    try:
        result=int(recv)
    except:
        raise Exception('painting id must be int.')
    return int(recv)

def request_bid(sock,item,info):
    command = 'BID'
    #print(command)
    msg=str({'request':command,'arg':item,'info':info})
    recv=send_recv(msg,sock)
    return int(recv)

"""
def request_finish(sock,winner,cash,info):
    command='FINISH'
    #print(command)
    msg=str({'request':command,'arg':winner,'info':info})
    msg+=agent(winner)+' '+ cash
    sock.send(msg.encode())
"""

def accessible_info(player,info):
    ret=copy.deepcopy(info)
    ret.pop('hand_will_receive')
    ret.pop('game_modifier')
    for p in range(info["player_size"]):
        if p!=player:
            ret['player'][p]['hand']=len(info['player'][p]['hand'])
    return ret

def send_recv(msg,sock):
    sock.send(msg.encode())
    try:
        recv=sock.recv(bufsize)
        return recv.decode()
    except socket.timeout:
        sock.close()
        timeout_sock=socks.index(sock)
        #socks.remove(sock)
        print('TIMEOUT Agent['+'{0:02d}'.format(timeout_sock)+']')
        raise Exception('TIMEOUT Agent['+'{0:02d}'.format(timeout_sock)+']')

def broadcast(s):
    #print("BROAD:", s)
    for sock in socks:
        sock.send(s.encode())
    sleep(0.01)
    return

def broadcast_personal(dic,info):
    #print("BROPE:",dic)
    for i in range(info['player_size']):
        ret=accessible_info(i,info)
        dic['info']=ret
        socks[i].send(str(dic).encode())
    sleep(0.01)
    return

def info_cutter(info):
    ret=copy.deepcopy(info)
    ret.pop('game_modifier')
    return ret

def disconnect():
    for i in socks:
        i.send(str({'request':'DISCONNECT'}).encode())
        i.close()
    return

def log(s):
    log_data.append(s)
    if verbose<=3 and ('BID' in s or 'SELL' in s):
        return
    if verbose<=2 and ('PURCHASE' in s):
        return
    if verbose<=1 and ('DEAL' in s or 'ROUNDOVER' in s or 'SETTLE' in s):
        return
    if verbose==0:
        return
    print(s)

def agent(num):
    return "Agent["+"{0:02d}".format(num) + "]"

def get_name(num):
    return names[num]


#!/usr/bin/env python3

"""Sample program which shows how to talk to a bioloid servo."""

import argparse
import os
import sys
import serial
import logging
import time

from bioloid.serial_bus import SerialPort, SerialBus
from bioloid.device_type_parser import DeviceTypeParser
from bioloid.device_type import DeviceTypes
from bioloid.device import Device
from bioloid.log_setup import log_setup

def main():
    default_baud = 1000000
    default_port = os.getenv("BIOLOID_PORT")
    parser = argparse.ArgumentParser(
        prog="bioloid",
        usage="%(prog)s [options] [command]",
        description="Send commands to bioloid devices",
        epilog=("You can specify the default serial port using the " +
                "BIOLOID_PORT environment variable.")
    )
    parser.add_argument(
        "-b", "--baud",
        dest="baud",
        action="store",
        type=int,
        help="Set the baudrate used (default = %d)" % default_baud,
        default=default_baud
    )
    default_port_help = ""
    if default_port:
        default_port_help = " (default '%s')" % default_port
    parser.add_argument(
        "-p", "--port",
        dest="port",
        help="Set the serial port to use" + default_port_help,
        default=default_port
    )
    parser.add_argument(
        "-i", "--id",
        dest="dev_id",
        type=int,
        help="Sets the id of the servo to use",
        default=1
    )
    parser.add_argument(
        "-d", "--debug",
        dest="debug",
        action="store_true",
        help="Enable debug features",
        default=False
    )
    args = parser.parse_args(sys.argv[1:])
    script_dir = os.path.dirname(os.path.realpath(__file__))

    log_setup()
    log = logging.getLogger()
    if args.debug:
        log.setLevel(logging.DEBUG)

    if not args.port:
        log.error("No serial port specified")
        sys.exit(1)

    log.info("Port = %s", args.port)
    log.info("Baud = %d", args.baud)
    log.info("ID   = %d", args.dev_id)

    dev_types = DeviceTypes()
    parser = DeviceTypeParser(dev_types)
    parser.parse_dev_type_files(script_dir)
    try:
        serial_port = SerialPort(port=args.port, baudrate=args.baud)
    except serial.serialutil.SerialException:
        log.error("Unable to open port '%s'", args.port)
        sys.exit(1)
    bus = SerialBus(serial_port, show_packets=args.debug)

    servo_type = dev_types.get("servo")
    if not servo_type:
        log.error("Unable to find device type 'servo'")
        sys.exit(1)
    dev = Device(bus, args.dev_id, servo_type)
    if not dev.ping():
        log.error("Device %d doesn't seem to be responding", args.dev_id)
        sys.exit(1)

    led = dev.get_dev_reg("led")
    goal_position = dev.get_dev_reg("goal-position")
    moving_speed = dev.get_dev_reg("moving-speed")

    moving_speed.set(20)
    log.info("Speed = %.1f", moving_speed.get())

    try:
        for _ in range(10):
            log.info("led on - position 0")
            led.set(1)
            goal_position.set(0)
            time.sleep(2)
            log.info("led off - position 100")
            led.set(0)
            goal_position.set(300)
            time.sleep(2)
    except KeyboardInterrupt:
        pass

main()


# -*- coding: utf-8 -*-
"""
Created on Sun Jan  9 20:42:42 2022

@author: AJ
"""

from random import choice
from experta import *
from experta.utils import unfreeze

import nlp
import prediction_guesser

def fire_message(text):
    #will be used to pass chatbot dialogue to ui
    print(text)

class Chatbot(KnowledgeEngine):
    @DefFacts()
    def needed_data(self):
        yield Fact(request=False, reqs=None)

    @Rule(AND(NOT(Fact(intent='book')),
              NOT(Fact(intent='cancel')),
              NOT(Fact(intent='delay'))),
          Fact(intent=MATCH.intent))
    def chat(self, intent):
        fire_message(nlp.speak(intent))

    @Rule(AS.intent << Fact(intent='book'),
          AS.active << Fact(request=False, reqs=None),
          Fact(message=MATCH.message))
    def booking(self, active, message, intent):
        #define appropriate params [param_name, value, entity_type, question]
        reqs = [["start", None, "GPE", "Where are you travelling from?"],
                 ["destination", None, "GPE", "Where would you like to travel to?"],
                 ["date", None, "DATE", "What date are you travelling?"],
                 ["time", None, "TIME", "What time do you want to travel?"]]
        self.modify(active, request=True, reqs='book')

        fire_message(nlp.speak('book'))
        message = unfreeze(message)
        returned_params = nlp.response(reqs, message, None, intent) #parse input for named entities

        is_valid = not any(None in l for l in returned_params)

        self.declare(Fact(params=returned_params))
        self.declare(Fact(valid=is_valid))

    @Rule(AS.intent << Fact(intent='bookreturn'),
          AS.active << Fact(request=False, reqs=None),
          Fact(message=MATCH.message))
    def booking_return(self, active, message, intent):
        #define appropriate params [param_name, value, entity_type, question]
        reqs = [["start", None, "GPE", "Where are you travelling from?"],
                 ["destination", None, "GPE", "Where would you like to travel to?"],
                 ["date", None, "DATE", "What date are you travelling?"],
                 ["time", None, "TIME", "What time do you want to travel?"],
                 ["return_date", None, "DATE", "What date do you want to return?"],
                 ["return_time", None, "TIME", "What time do you want to return?"]]
        self.modify(active, request=True, reqs='bookreturn')

        fire_message(nlp.speak('bookreturn'))
        message = unfreeze(message)
        returned_params = nlp.response(reqs, message, None, 'book') #parse input for named entities

        is_valid = not any(None in l for l in returned_params)

        self.declare(Fact(params=returned_params))
        self.declare(Fact(valid=is_valid))

    @Rule(AS.intent << Fact(intent='delay'),
          AS.active << Fact(request=False, reqs=None),
          Fact(message=MATCH.message))
    def delaying(self, active, message, intent):
        #define appropriate params [param_name, value, entity_type, question]
        reqs = [["destination", None, "GPE", "Where is your train now?"],
                 ["time", None, "GPE", "Where are you travelling to?"],
                 ["time", None, "TIME", "How long are you delayed?"]]
        self.modify(active, request=True, reqs='delay')

        fire_message(nlp.speak('delay'))
        message = unfreeze(message)
        returned_params = nlp.response(reqs, message, None, intent) #parse input for named entities

        is_valid = not any(None in l for l in returned_params)

        self.declare(Fact(params=returned_params))
        self.declare(Fact(valid=is_valid))

    @Rule(Fact(request=True, reqs=MATCH.reqs),
          AS.validity << Fact(valid=False),
          Fact(params=MATCH.params),
          AS.cur_intent << Fact(intent=MATCH.intent),
          AS.old_params << Fact(params=MATCH.params))
    def req_inprocess(self, reqs, validity, params, cur_intent, old_params):
        params = unfreeze(params)
        returned_params = None
        for req in params:
            while req[1] == None:
                fire_message(req[3])
                message = input()
                returned_params = nlp.response(params, message, req[3], cur_intent)
                if returned_params == 'CANCEL':
                    self.modify(cur_intent, intent='cancel')
                    return
                if req[1] == None:
                    fire_message(nlp.speak('datanotfound'))
        self.modify(old_params, params=returned_params)
        is_valid = not any(None in l for l in returned_params)
        self.modify(validity, valid=is_valid)

    @Rule(AND(Fact(reqs='book'),
             Fact(valid=True)),
             Fact(params=MATCH.params))
    def find_ticket(self, params):
        params = unfreeze(params)
        #with all parameters, begin web scraping for ticket
        fire_message(nlp.find_ticket(params[0][1], params[1][1], params[2][1], params[3][1]))
        engine.reset() #reset facts for next interaction

    @Rule(AND(Fact(reqs='bookreturn'),
             Fact(valid=True)),
             Fact(params=MATCH.params))
    def find_return(self, params):
        params = unfreeze(params)
        #with all parameters, begin web scraping for ticket
        fire_message(nlp.find_return(params[0][1], params[1][1], params[2][1], params[3][1], params[4][1], params[5][1]))
        engine.reset() #reset facts for next interaction

    @Rule(AND(Fact(reqs='delay'),
             Fact(valid=True)),
             Fact(params=MATCH.params))
    def find_delay(self, params):
        params = unfreeze(params)
        fire_message(prediction_guesser.get_prediction(params[0][1], params[1][1], params[2][1]))
        engine.reset()

    @Rule(AND(Fact(intent='cancel'),
      Fact(request=True)),
          salience=100)
    def cancel(self):
        fire_message(nlp.speak("cancel"))
        engine.reset()
        #self.declare(Fact(request=False, reqs=None)) #cancel current transaction

    @Rule(AND(Fact(intent='cancel'),
      Fact(request=False)))
    def wtf(self):
        fire_message(nlp.speak("notunderstood"))

engine = Chatbot()
engine.reset()
fire_message(nlp.speak("greeting"))
while True:
    msg = nlp.parse_input(input())
    engine.declare(Fact(intent=msg[0]))
    engine.declare(Fact(message=msg[1]))
    engine.run()
    engine.reset()


import json, argparse
import logging, sys, datetime, os
from shutil import copy
from pydal.helpers.classes import RecordDeleter, RecordUpdater
from pydal.objects import LazySet
from applications.vidjil.models.VidjilAuth import PermissionEnum

class MigrateLogger():

    def __init__(self, level=logging.INFO):
        log = logging.getLogger('vidjil_migrate')
        log.setLevel(level)
        log.propagate = False
        #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        formatter = logging.Formatter('%(levelname)s\t- %(message)s')
        ch = logging.StreamHandler(sys.stdout)
        ch.setFormatter(formatter)
        log.addHandler(ch)
        self.log = log

    def info(self, text):
       self.log.info(text)

    def debug(self, text):
        self.log.debug(text)

    def error(self, text):
        self.log.error(text)

    def getLogger(self):
        return self.log

def get_dict_from_row(row):
    '''
    Create a dict element from a Row element
    while filtering out some key pydal helper fields
    '''
    ex_fields = ['id', 'uuid']
    ex_types = [RecordDeleter, RecordUpdater, LazySet]

    my_dict = {}
    for key in row.keys():
        if ((key not in ex_fields) and (type(row[key]) not in ex_types)):
            tmp = row[key]
            if isinstance(tmp, datetime.datetime) or isinstance(tmp, datetime.date):
                tmp = tmp.__str__()
            my_dict[key] = tmp
    return my_dict

def reencode_dict(data):
    '''
    Recursively reencode the values and keys of a dict to utf-8.
    Takes a dict loaded from json, assumes all keys are strings.
    Values may be any type, only unicode values are reencoded
    '''
    if type(data) == dict:
        tmp = {}
        for key in data:
            val = data[key]
            tmp[key.encode('utf-8')] = reencode_dict(val)
        return tmp
    elif type(data) == unicode:
        return data.encode('utf-8')
    else:
        return data

class IdMapper():

    def __init__(self, log):
        self.log = log
        self.mapping = {}

    def getMatchingId(self, oid):
        if oid not in self.mapping:
            self.log.debug('id %d not in mapping, returning it' % oid)
            self.log.debug("mapping: " + str(self.mapping.keys()))
            return oid
        return self.mapping[oid]

    def setMatchingId(self, old_id, new_id):
        self.mapping[old_id] = new_id
        self.log.debug("mapped: %d to %d" % (old_id, new_id))

class ConfigMapper(IdMapper):

    def __init__(self, log, cfile=None):
        IdMapper.__init__(self, log)
        if cfile is not None:
            self.load(cfile)

    def load(self, cfile):
        self.mapping = {}
        with open(cfile, 'r') as cfg:
            config_map = json.load(cfg, encoding='utf-8')
            for key in config_map:
                self.mapping[long(key)] = config_map[key]
            self.log.info("mapping loaded")
            self.log.debug("mapping: " + str(self.mapping.keys()))

class Extractor():

    def __init__(self, db, log):
        self.log = log
        self.log.info("initialising extractor")
        self.db = db

    def populateSets(self, rows):
        self.log.debug("populate sets")
        sets = {}
        sample_set_ids = []
        for row in rows:
            self.log.debug("populating : %d, sample_set: %d" % (row.id, row.sample_set_id))
            sets[row.id] = get_dict_from_row(row)
            sample_set_ids.append(row.sample_set_id)
        return sets, sample_set_ids

    def getSequenceFiles(self, sample_set_ids):
        db = self.db
        rows = db((db.sample_set_membership.sample_set_id.belongs(sample_set_ids))
                & (db.sequence_file.id == db.sample_set_membership.sequence_file_id)
               ).select(db.sample_set_membership.ALL, db.sequence_file.ALL)
        return rows

    def populateSequenceFiles(self, rows):
        self.log.debug("populate sequence_files")
        memberships = {}
        sequence_files = {}
        for row in rows:
            ssm_id = row.sample_set_membership.id
            sf_id = row.sequence_file.id
            self.log.debug("populating sequence file: %d, membership: %d" % (sf_id, ssm_id))
            memberships[ssm_id] = get_dict_from_row(row.sample_set_membership)
            sequence_files[sf_id] = get_dict_from_row(row.sequence_file)
        return sequence_files, memberships

    def getTableEntries(self, table, ref_field, values):
        db = self.db
        rows = db(db[table][ref_field].belongs(values)).select(db[table].ALL)
        return rows

    def populateEntries(self, rows, etype=''):
        self.log.debug("populate %ss" % etype)
        data = {}
        for row in rows:
            my_dict = get_dict_from_row(row)
            self.log.debug("populating entry: %s" % str(my_dict))
            data[row.id] = my_dict
        return data

class GroupExtractor(Extractor):

    def __init__(self, db, log):
        Extractor.__init__(self, db, log)

    def getAccessible(self, table, groupid):
        db = self.db
        rows = db((db[table].id == db.auth_permission.record_id)
                & (db.auth_permission.table_name == table)
                & (db.auth_permission.name == PermissionEnum.access.value)
                & (db.auth_permission.group_id == groupid)
               ).select(db[table].ALL)
        return rows

class SampleSetExtractor(Extractor):

    def __init__(self, db, log):
        Extractor.__init__(self, db, log)

    def getAccessible(self, table, ids):
        db = self.db
        rows = db(db[table].id.belongs(ids)).select(db[table].ALL)
        return rows

class Importer():

    def __init__(self, groupid, db, log, config_mapper):
        self.log = log
        self.log.info("initialising importer")
        self.groupid = groupid
        self.db = db
        self.mappings = {'config': config_mapper}
        self.mappings['sample_set'] = IdMapper(self.log)

    def importSampleSets(self, stype, sets):
        db = self.db
        self.log.debug("import sets")
        for sid in sets:
            self.log.debug("importing set: %s" % sid)
            sset = sets[sid]
            ssid = db.sample_set.insert(sample_type = stype)
            self.log.debug("new sample_set %d" % ssid)
            self.mappings['sample_set'].setMatchingId(sset['sample_set_id'], ssid)
            sset['sample_set_id'] = ssid
            nid = db[stype].insert(**sset)
            self.log.debug("new %s: %d" % (stype, nid))
            db.auth_permission.insert(group_id=self.groupid,
                                      name=PermissionEnum.access.value,
                                      table_name=stype,
                                      record_id=nid)
            self.log.debug("associated set %d to group %d" % (nid, self.groupid))

    def importTable(self, table, values, ref_fields={}, map_val=False):
        db = self.db
        self.log.debug("import %ss" % table)
        for vid in values:
            self.log.debug("importing %s: %s" % (table, vid))
            val = values[vid]
            for key in ref_fields:
                ref_key = ref_fields[key]
                matching_id = self.mappings[key].getMatchingId(val[ref_key])
                self.log.debug("%s replacing %s: %d with %d" % (table, ref_key, val[ref_key], matching_id))
                val[ref_key] = matching_id
            oid = db[table].insert(**val)
            self.log.debug("new %s: %d" % (table, oid))
            if map_val:
                if table not in self.mappings:
                    self.mappings[table] = IdMapper(self.log)
                self.mappings[table].setMatchingId(long(vid), oid)

def copy_files(data, src, dest, log=MigrateLogger()):
    file_fields = {'results_file': 'data_file',
            'analysis_file': 'analysis_file',
            'fused_file': 'fused_file'}

    if not os.path.exists(dest):
        os.makedirs(dest)

    for t in file_fields:
        for entry in data[t]:
            if (data[t][entry][file_fields[t]] is not None):
                log.debug("Copying %s" % data[t][entry][file_fields[t]])
                copy(src + '/' + data[t][entry][file_fields[t]], dest + '/' + data[t][entry][file_fields[t]])

def export_peripheral_data(extractor, data_dict, sample_set_ids, log=MigrateLogger()):
    sequence_rows = extractor.getSequenceFiles(sample_set_ids)
    data_dict['sequence_file'], data_dict['membership'] = extractor.populateSequenceFiles(sequence_rows)

    results_rows = extractor.getTableEntries('results_file', 'sequence_file_id', data_dict['sequence_file'].keys())
    data_dict['results_file'] = extractor.populateEntries(results_rows, 'results_file')

    task_ids = [r['scheduler_task_id'] for k, r in data_dict['results_file'].iteritems()]
    task_rows = extractor.getTableEntries('scheduler_task', 'id', task_ids)
    data_dict['scheduler_task'] = extractor.populateEntries(task_rows, 'scheduler_task')

    run_rows = extractor.getTableEntries('scheduler_run', 'task_id', task_ids)
    data_dict['scheduler_run'] = extractor.populateEntries(run_rows, 'scheduler_run')

    analysis_rows = extractor.getTableEntries('analysis_file', 'sample_set_id', sample_set_ids)
    data_dict['analysis_file'] = extractor.populateEntries(analysis_rows, 'analysis_file')

    fused_rows = extractor.getTableEntries('fused_file', 'sample_set_id', sample_set_ids)
    data_dict['fused_file'] = extractor.populateEntries(fused_rows, 'fused_file')

    return data_dict

def export_group_data(filesrc, filepath, groupid, log=MigrateLogger()):
    log.info("exporting group data")
    ext = GroupExtractor(db, log)

    tables = {}

    patient_rows = ext.getAccessible('patient', groupid)
    tables['patient'], patient_ssids = ext.populateSets(patient_rows)

    run_rows = ext.getAccessible('run', groupid)
    tables['run'], run_ssids = ext.populateSets(run_rows)

    generic_rows = ext.getAccessible('generic', groupid)
    tables['generic'], generic_ssids = ext.populateSets(generic_rows)

    sample_set_ids = patient_ssids + run_ssids + generic_ssids

    tables = export_peripheral_data(ext, tables, sample_set_ids, log=log)

    if not os.path.exists(filepath):
        os.makedirs(filepath)

    with open(filepath + '/export.json', 'w') as outfile:
        json.dump(tables, outfile, ensure_ascii=False, encoding='utf-8')

    log.info("copying files from %s to %s" % (filesrc, filepath))
    copy_files(tables, filesrc, filepath + '/files', log=log)
    log.info("done")

def export_sample_set_data(filesrc, filepath, sample_type, sample_ids, log=MigrateLogger()):
    log.info("exporting sample set data")
    ext = SampleSetExtractor(db, log)

    tables = {}

    rows = ext.getAccessible(sample_type, sample_ids)
    tables[sample_type], sample_set_ids = ext.populateSets(rows)

    tables = export_peripheral_data(ext, tables, sample_set_ids, log=log)

    if not os.path.exists(filepath):
        os.makedirs(filepath)

    with open(filepath + '/export.json', 'w') as outfile:
        json.dump(tables, outfile, ensure_ascii=False, encoding='utf-8')

    log.info("copying files from %s to %s" % (filesrc, filepath))
    copy_files(tables, filesrc, filepath + '/files')

    log.info("done")

def import_data(filesrc, filedest, groupid, config=None, dry_run=False, log=MigrateLogger()):
    log.info("importing data")
    data = {}
    with open(filesrc + '/export.json', 'r') as infile:
        tmp = json.load(infile, encoding='utf-8')
        data = reencode_dict(tmp)

    config_mapper = ConfigMapper(log)
    if config:
        config_mapper.load(config)
    imp = Importer(groupid, db, log, config_mapper)

    try:
        set_types = ['patient', 'run', 'generic']
        for stype in set_types:
            if stype in data:
                imp.importSampleSets(stype, data[stype])

        imp.importTable('sequence_file', data['sequence_file'], map_val=True)
        imp.importTable('sample_set_membership', data['membership'], {'sample_set': 'sample_set_id', 'sequence_file': 'sequence_file_id'})
        imp.importTable('scheduler_task', data['scheduler_task'], map_val=True)
        imp.importTable('scheduler_run', data['scheduler_run'], {'scheduler_task': 'task_id'})
        imp.importTable('results_file', data['results_file'], {'sequence_file': 'sequence_file_id', 'scheduler_task': 'scheduler_task_id', 'config': 'config_id'})
        imp.importTable('analysis_file', data['analysis_file'], {'sample_set': 'sample_set_id'})
        imp.importTable('fused_file', data['fused_file'], {'sample_set': 'sample_set_id', 'config': 'config_id'})

        if dry_run:
            db.rollback()
            log.info("dry run successful, no data saved")
        else:
            db.commit()
            log.info("copying files from %s to %s" % (filesrc, filedest))
            copy_files(data, filesrc + '/files', filedest, log=log)
            log.info("done")
    except:
        log.error("something went wrong, rolling back")
        db.rollback()
        log.error("rollback was successful")
        raise

def main():
    parser = argparse.ArgumentParser(description='Export and import data')
    subparsers = parser.add_subparsers(help="Select operation mode", dest='command')

    exp_parser = subparsers.add_parser('export', help='Export data from the DB into a JSON file')
    exp_subparser = exp_parser.add_subparsers(dest='mode', help='Select data selection method')

    ss_parser = exp_subparser.add_parser('sample_set', help='Export data by sample-set ids')
    ss_parser.add_argument('sample_type', type=str, choices=['patient', 'run', 'generic'], help='Type of sample')
    ss_parser.add_argument('ssids', metavar='ID', type=long, nargs='+', help='Ids of sample sets to be extracted')

    group_parser = exp_subparser.add_parser('group', help='Extract data by groupid')
    group_parser.add_argument('groupid', type=long, help='The long ID of the group')

    import_parser = subparsers.add_parser('import', help='Import data from JSON into the DB')
    import_parser.add_argument('--dry-run', dest='dry', action='store_true', help='With a dry run, the data will not be saved to the database')
    import_parser.add_argument('--config', type=str, dest='config', help='Select the config mapping file')
    import_parser.add_argument('groupid', type=long, help='The long ID of the group')

    parser.add_argument('-p', type=str, dest='filepath', default='./', help='Select the file destination')
    parser.add_argument('-s', type=str, dest='filesrc', default='./', help='Select the file source')
    parser.add_argument('--debug', dest='debug', action='store_true', help='Output debug information')

    args = parser.parse_args()

    log = MigrateLogger()
    if args.debug:
        log.log.setLevel(logging.DEBUG)

    if args.command == 'export':
        if args.mode == 'group':
            export_group_data(args.filesrc, args.filepath, args.groupid, log)
        elif args.mode == 'sample_set':
            export_sample_set_data(args.filesrc, args.filepath, args.sample_type, args.ssids, log)
    elif args.command == 'import':
        if args.dry:
            log.log.setLevel(logging.DEBUG)
        import_data(args.filesrc, args.filepath, args.groupid, args.config, args.dry, log)

if __name__ == '__main__':
    main()


#!python
r"""Pac-Man - Random Search"""
__author__ = 'Koosha Marashi'
__email__ = 'km89f@mst.edu'

#import used packages
import random
import json
import time
import argparse
import os
import sys
from decimal import Decimal

DIRECTORY = os.path.dirname(os.path.abspath(__file__))
NUMBER_OF_GHOSTS = 3
GAME_CONTINUES = 0
GAME_OVER = 1
EMPTY = 0
PILL = 1
WALL = 2
PRINT = True
#Allowed movements of the units [x,y]
PACMAN_MOVES = [[0,0],[0,1],[0,-1],[1,0],[-1,0]]
GHOST_MOVES = [[0,1],[0,-1],[1,0],[-1,0]]

class Config:
    """Handle configurations"""

    def parseCfg(self,cfgFilePath):
        """Read JSON formatted .cfg file and import configurations"""
        with open(cfgFilePath) as cfgFile:
            config = json.load(cfgFile)
        # Key: Description
        # output folder: Relative path of output files
        # log file: Name of log file to write
        # highest score game world file: Name of wld file to write the highest-score-game-sequence all-time-step world file
        # random generator seed type: Type of seed used for random number generator. Should be 'time' to use system epoch time in milliseconds, or 'int' for manually feeding the seed.
        # random generator seed: If randomSeedType is equal to 'int' then would be used as seed of random number generator
        # number of runs: Total number of runs
        # number of evaluations: Number of fitness evaluations per run
        # world width: number of columns in the grid of the world
        # world height: number of rows in the grid of the world
        # pill density percentage: cell-wise probability of having a pill

        if config['random generator seed type'] == 'time':
            # Get system epoch time
            config['random generator seed'] = round(time.time() * 1000)
        elif config['random generator seed type'] == 'int':
            # Use manually provided seed
            pass
        return config

class WriteToFile(object):
    """Write outputs to file"""
    def __init__(self,config):
        self.config = config
    def writeHeaderToLog(self):
        """Overwrite header information to log file"""
        logFileObject = open(os.path.join(DIRECTORY,self.config['output folder'],self.config['log file']),'w')
        logFileObject.write('World grid size: W = ' + str(Decimal(self.config['world width'])) + ', H = ' + str(Decimal(self.config['world width'])) + '\n')
        logFileObject.write('Pill density: ' + str(Decimal(self.config['pill density percentage'])) + '%' + '\n')
        logFileObject.write('Random number generator seed: ' + str(Decimal(self.config['random generator seed'])) + '\n')
        logFileObject.write('Number of runs: ' + str(Decimal(self.config['number of runs'])) + '\n')
        logFileObject.write('Number of fitness evaluations per run: ' + str(Decimal(self.config['number of evaluations'])) + '\n')
        logFileObject.close()

    def writeResultsLabelToLog(self):
        """Append results header to log file"""
        logFileObject = open(os.path.join(DIRECTORY,self.config['output folder'],self.config['log file']),'a')
        logFileObject.write('\nResult Log\n')
        logFileObject.close()

    def writeRunLabelToLog(self,run):
        """Append run label to log file"""
        logFileObject = open(os.path.join(DIRECTORY,self.config['output folder'],self.config['log file']),'a')
        logFileObject.write('\nRun ' + str(run) + '\n')
        logFileObject.close()

    def writeResultsToLog(self,eval,*args):
        """Append results to log file"""
        logFileObject = open(os.path.join(DIRECTORY,self.config['output folder'],self.config['log file']),'a')
        logFileObject.write(str(eval))
        for arg in args:
            logFileObject.write('\t' + str(arg))
        logFileObject.write('\n')
        logFileObject.close()

    def writeToWorldFile(self,pacmanSeq,ghostsSeq,pills):
        """Overwrite final results of the highest score game to wld file"""
        logFileObject = open(os.path.join(DIRECTORY,self.config['output folder'],self.config['highest score game world file']),'w')
        totalTime = 2 * self.config['world width'] * self.config['world height']
        logFileObject.write(str(Decimal(self.config['world width'])) + '\n')
        logFileObject.write(str(Decimal(self.config['world height'])) + '\n')
        for index in range(len(pacmanSeq)):
            logFileObject.write('m ' + str(pacmanSeq[index].x) + ' ' + str(pacmanSeq[index].y) + '\n')
            for i,ghost in enumerate(ghostsSeq[index]):
                logFileObject.write(str(i + 1) + ' ' + str(ghost.x) + ' ' + str(ghost.y) + '\n')
            if index == 0:
                for pill in pills:
                    logFileObject.write('p ' + str(pill[0]) + ' ' + str(pill[1]) + '\n')
            logFileObject.write('t ' + str(totalTime - index) + ' ' + str(pacmanSeq[index].score) + '\n')
        logFileObject.close()

class Pacman(object):
    """object of Ms. Pac-Man"""
    def __init__(self,world,config,**kwargs):
        self.x = 0
        self.y = config['world height'] - 1
        self.score = 0
        for key, value in kwargs.items():
            if key == 'x':
                self.x = value
            elif key == 'y':
                self.y = value
            elif key == 'score':
                self.score = value

    def move(self,world,direction,config):
        """"""
        self.x += direction[0]
        self.y += direction[1]
        self.x = max(0,min(self.x,config['world width'] - 1))
        self.y = max(0,min(self.y,config['world height'] - 1))

class Ghost(object):
    """object of the ghosts"""
    def __init__(self,world,config,**kwargs):
        self.x = config['world width'] - 1
        self.y = 0
        self.score = 0
        for key, value in kwargs.items():
            if key == 'x':
                self.x = value
            elif key == 'y':
                self.y = value
            elif key == 'score':
                self.score = value

    def move(self,world,direction,config):
        """"""
        self.x += direction[0]
        self.y += direction[1]
        self.x = max(0,min(self.x,config['world width'] - 1))
        self.y = max(0,min(self.y,config['world height'] - 1))

class World(object):
    """object of the world grid"""
    def __init__(self,config):
        """"""
        self.grid = [[EMPTY for x in range(config['world height'])] for x in range(config['world width'])]
        self.nInitialPills = 0
        if config['pill density percentage'] != 0:
            while self.nInitialPills == 0:
                for i in range(config['world width']):
                    for j in range(config['world height']):
                        if random.random() < (config['pill density percentage'] / 100):
                            self.grid[i][j] = PILL
                            self.nInitialPills += 1
        self.nRemainingPills = self.nInitialPills

class GPac:
    """class of methods for simulating Pac-Man"""
    def pacmanController(self,world,unit,config,mode = 'random'):
        """control movement of Ms. Pac-Man"""
        if mode == 'random':
            validMoves = []
            for move in PACMAN_MOVES:
                if 0 <= unit.x + move[0] < config['world width'] and 0 <= unit.y + move[1] < config['world height']:
                    validMoves.append(move)
            unit.move(world,random.choice(validMoves),config)

    def ghostController(self,world,unit,config,mode = 'random'):
        """control movement of the ghosts"""
        if mode == 'random':
            validMoves = []
            for move in GHOST_MOVES:
                if 0 <= unit.x + move[0] < config['world width'] and 0 <= unit.y + move[1] < config['world height']:
                    validMoves.append(move)
            unit.move(world,random.choice(validMoves),config)

    def playGame(self,time,world,pacman,ghosts,config):
        """simulate one turn of the game until a game-over condition occurs"""
        gameState = GAME_CONTINUES
        self.pacmanController(world,pacman,config)
        for ghost in ghosts:
            self.ghostController(world,ghost,config)
        if any(pacman.x == ghost.x and pacman.y == ghost.y for ghost in ghosts):
            #Game-over
            gameState = GAME_OVER
        elif world.grid[pacman.x][pacman.y] == PILL:
            world.grid[pacman.x][pacman.y] = EMPTY
            world.nRemainingPills -= 1
        pacman.score = int((1 - world.nRemainingPills / world.nInitialPills) * 100)
        for ghost in ghosts:
            ghost.score = -pacman.score
        if world.nRemainingPills == 0:
            gameState = GAME_OVER
            pacman.score *= 1 + time / (2 * config['world width'] * config['world height'])
            pacman.score = int(pacman.score)
            for ghost in ghosts:
                ghost.score = -pacman.score
        return gameState

    def drawWorld(self,world,pacman,ghosts,config):
        """Draw the world. Used for visualization and debugging"""
        sys.stdout.write((2 * config['world width'] + 1) * '-' + '\n')
        for j in reversed(range(config['world height'])):
            sys.stdout.write('|')
            for i in range(config['world width']):
                if any(ghost.x == i and ghost.y == j for ghost in ghosts):
                    cell = 'G'
                elif pacman.x == i and pacman.y == j:
                    cell = 'P'
                elif world.grid[i][j] is PILL:
                    cell = '+'
                else:
                    cell = ' '
                sys.stdout.write(cell + '|')
            sys.stdout.write('\n')
            sys.stdout.write((2 * config['world width'] + 1) * '-' + '\n')
        sys.stdout.write('\n')

    def runExperiment(self,config):
        """Main method for running the experiment"""
        random.seed(a = config['random generator seed'])
        log = WriteToFile(config)
        log.writeHeaderToLog()
        log.writeResultsLabelToLog()
        globalBestFitness = 0
        for run in range(config['number of runs']):
            log.writeRunLabelToLog(run + 1)
            localBestFitness = 0
            for eval in range(config['number of evaluations']):
                if PRINT:
                    progress = 100 * round((run * config['number of evaluations'] + eval + 1) /
                                           (config['number of runs'] * config['number of evaluations'] ),4)
                    progress = min(progress,100)
                    sys.stdout.flush()
                    sys.stdout.write('\r')
                    _ = sys.stdout.write("[%-20s] %5.1f%%" % ('='*int(progress / 5),progress))

                time = 2 * config['world width'] * config['world height']
                world = World(config)

                pills = []
                for i in range(config['world width']):
                    for j in range(config['world height']):
                        if world.grid[i][j] == PILL:
                            pills.append([i,j])
                pacman = Pacman(world,config)
                ghosts=[]
                for index in range(NUMBER_OF_GHOSTS):
                    ghosts.append(Ghost(world,config))

                pacmanSeq = []
                ghostsSeq = []
                pacmanSeq.append(Pacman(world,config,x = pacman.x,y = pacman.y,score = pacman.score))
                ghostsSeq.append([Ghost(world,config,x = ghost.x,y = ghost.y,score = ghost.score) for ghost in ghosts])
                gameState = GAME_CONTINUES
                while time != 0 and gameState != GAME_OVER:
                    time -= 1
                    gameState = self.playGame(time,world,pacman,ghosts,config)
                    pacmanSeq.append(Pacman(world,config,x = pacman.x,y = pacman.y,score = pacman.score))
                    ghostsSeq.append([Ghost(world,config,x = ghost.x,y = ghost.y,score = ghost.score) for ghost in ghosts])
                if localBestFitness == 0 or localBestFitness < pacman.score:
                    localBestFitness = pacman.score
                    localHighestScoreGamePills = pills
                    localHighestScoreGamePacmanSeq = pacmanSeq
                    localHighestScoreGameGhostsSeq = ghostsSeq
                    log.writeResultsToLog(eval + 1,localBestFitness)
            if globalBestFitness == 0 or globalBestFitness < localBestFitness:
                globalBestFitness = localBestFitness
                globalHighestScoreGamePills = localHighestScoreGamePills
                globalHighestScoreGamePacmanSeq = localHighestScoreGamePacmanSeq
                globalHighestScoreGameGhostsSeq = localHighestScoreGameGhostsSeq
        log.writeToWorldFile(globalHighestScoreGamePacmanSeq,globalHighestScoreGameGhostsSeq,globalHighestScoreGamePills)

# Optional config file used by"-config" flag
parser = argparse.ArgumentParser(description='Simulates Pac-Man game where controllers decide movements randomly.')
parser.add_argument("-config",default=os.path.join('config','default.cfg'),help='config file path',metavar='Path')
args = parser.parse_args()

# Instantiate Config class to load and parse configurations (if no config is specified,default is used)
config = Config()
configDict = config.parseCfg(os.path.join(DIRECTORY,args.config))

if PRINT:
    print('\n')
    print('-----------------------------')
    print('|          Progress         |')
    print('-----------------------------')

#Instantiate GPac class to simulate Pac-Man game
gpac = GPac()
gpac.runExperiment(configDict)

if PRINT:
    print('\n')


import tensorflow as tf
from sparkflow.tensorflow_async import SparkAsyncDLModel
from google.protobuf import json_format
from pyspark.ml.pipeline import PipelineModel
import json

def load_tensorflow_model(
        path,
        inputCol,
        tfInput,
        tfOutput,
        predictionCol='predicted',
        tfDropout=None,
        toKeepDropout=False):
    with tf.Session(graph=tf.Graph()) as sess:
        new_saver = tf.train.import_meta_graph(path + '.meta')
        split = path.split('/')
        if len(split) > 1:
            new_saver.restore(sess, tf.train.latest_checkpoint("/".join(split[:-1])))
        else:
            new_saver.restore(sess, tf.train.latest_checkpoint(split[0]))
        vs = tf.trainable_variables()
        weights = sess.run(vs)
        json_graph = json_format.MessageToJson(tf.train.export_meta_graph())

    weights = [w.tolist() for w in weights]
    json_weights = json.dumps(weights)
    return SparkAsyncDLModel(
        inputCol=inputCol, modelJson=json_graph, modelWeights=json_weights,
        tfInput=tfInput, tfOutput=tfOutput, predictionCol=predictionCol, tfDropout=tfDropout, toKeepDropout=toKeepDropout
    )

def attach_tensorflow_model_to_pipeline(
        path,
        pipelineModel,
        inputCol,
        tfInput,
        tfOutput,
        predictionCol='predicted',
        tfDropout=None,
        toKeepDropout=False ):
    spark_model = load_tensorflow_model(path, inputCol, tfInput, tfOutput, predictionCol, tfDropout, toKeepDropout)
    return PipelineModel(stages=[pipelineModel, spark_model])


import discord
from discord.ext import commands
from random import randint as rand
import time
import json

intents=discord.Intents.all()
allowed_mentions=discord.AllowedMentions(everyone=False, users=True, roles=False)

bot = commands.Bot(command_prefix='=', intents=intents, allowed_mentions=allowed_mentions)
token = open('token.txt', "r").readline()
startTime = time.time()

def isMod(ctx):
    try:
        return ctx.author.guild_permissions.manage_channels
    except AttributeError:
        return False

@bot.event
async def on_ready():
    game = discord.Game("=help")
    await bot.change_presence(activity=game, status=discord.Status.idle)
    print(f'logged in as {bot.user}')

@bot.event
async def on_message(message):
    if message.author.bot or not message.guild:
        return

    with open('phrases.json', 'r') as f:
        data = json.load(f)

    if str(message.guild.id) not in data:
        pass
    else:
        for phrase in data[str(message.guild.id)]:
            if phrase in message.content.lower():
                await message.channel.send(data[str(message.guild.id)][phrase])

    await bot.process_commands(message)

@bot.event
async def on_command_error(ctx, exception):
	error = str(exception).lower().replace("\"","`")
	await ctx.send(f'{error}.\npro tip: ```you can use =help to view a list of commands or get extra information.```')

@bot.command()
async def ping(ctx):
    await ctx.send(f"{round(bot.latency * 1000)}ms")

@bot.command()
async def info(ctx):
    seconds = time.time() - startTime
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    w, d = divmod(d, 7)
    uptime_str = f'{int(w)}w : {int(d)}d : {int(h)}h : {int(m)}m : {int(s)}s'

    e = discord.Embed(title="Information about me",
                      url="https://github.com/RKREEE/FaithBot",
                      colour=discord.Colour(0xaa7bff))
    e.set_thumbnail(url=bot.user.avatar_url_as(format="png"))
    e.add_field(name="Info", value=f"Name: {bot.user}\nID: {bot.user.id}", inline=False)
    e.add_field(name="Uptime", value=uptime_str, inline=True)
    e.add_field(name="Guild Count", value=f"{len(bot.guilds)} guilds with {len(bot.users)} users", inline=True)

    await ctx.send(embed=e)

@bot.command()
async def findseed(ctx):
    eyes = 0
    for i in range(12):
        if rand(1,10) == 10:
            eyes += 1
    await ctx.send(f'{ctx.author.mention} your seed is a {eyes} eye')

    with open('findseedstats.json', 'r') as f:
        data = json.load(f)

    if str(ctx.guild.id) not in data or data[str(ctx.guild.id)]["best"] < eyes:
        data[str(ctx.guild.id)] = {"best": eyes, "user": str(ctx.author.id)}

    with open("findseedstats.json", 'w') as f:
        json.dump(data, f, indent=4)

    with open("findseedUsers.json", "r") as f:
        data = json.load(f)

    if str(ctx.author.id) not in data:
        data[str(ctx.author.id)] = {f"{str(eyes)} eyes": "1"}
    elif f"{str(eyes)} eyes" not in data[str(ctx.author.id)]:
        data[str(ctx.author.id)][f"{str(eyes)} eyes"] = "1"
    else:
        data[str(ctx.author.id)][f"{str(eyes)} eyes"] = str(int(data[str(ctx.author.id)][f"{str(eyes)} eyes"]) + 1)

    with open("findseedUsers.json", "w") as f:
        json.dump(data, f, indent=4)

@bot.command()
async def bestseed(ctx):
    with open('findseedstats.json', 'r') as f:
        data = json.load(f)

    if str(ctx.guild.id) not in data:
        await ctx.send(f"**{ctx.guild.name}** doesnt have a seed history")
    else:
        num = data[str(ctx.guild.id)]["best"]
        member = bot.get_user(int(data[str(ctx.guild.id)]["user"]))
        await ctx.send(f'**{ctx.guild.name}** has a best seed of {num} eyes, set by **{member.display_name}#{member.discriminator}**')

@bot.command()
async def findseedstats(ctx, user: discord.User = None):
    if user == None:
        user = ctx.author
    user = bot.get_user(user.id)

    with open('findseedUsers.json', 'r') as f:
        data = json.load(f)

    if str(user.id) not in data:
        await ctx.send(f"{user.display_name}#{user.discriminator} hasnt used findseed yet")
    else:
        total = 0
        for i in range(13):
            try:
                total += int(data[str(user.id)][f'{i} eyes'])
            except KeyError:
                continue

        e = discord.Embed(title=f"{user.display_name}\'s findseed stats from {total:,} seeds", colour=discord.Colour(0xaa7bff))

        for x in data[str(user.id)]:
            try:
                e.add_field(name=f"{str(x)}:", value=f"{int(data[str(user.id)][f'{x} eyes']):,}", inline=True)
            except KeyError:
                e.add_field(name=f"{str(x)} eyes:", value="0", inline=True)

        await ctx.send(embed=e)

@bot.command()
async def addphrase(ctx, phrase :str = None, reaction :str = None):
    if isMod(ctx) != False:
        with open('phrases.json', 'r') as f:
            data = json.load(f)

        if str(ctx.guild.id) not in data:
            data[str(ctx.guild.id)] = {}
        if phrase != None and reaction != None:
            data[str(ctx.guild.id)][phrase] = reaction
        elif phrase != None and reaction == None:
            await ctx.send('what do you want me to reply with?')
            return
        elif phrase == None and reaction == None:
            await ctx.send(f'hint:\n```=addphrase \"the phrase\" \"the reply\"```')
            return

        with open('phrases.json', 'w') as f:
            json.dump(data, f, indent=4)

        await ctx.send(f'{phrase} has been added as a phrase for this server')
    else:
        await ctx.send(f'you dont have permission to use this command')

@bot.command()
async def removephrase(ctx, phrase: str):
    if isMod(ctx) != False:
        with open('phrases.json', 'r') as f:
            data = json.load(f)

        try:
            data[str(ctx.guild.id)].pop(phrase)
        except KeyError:
            await ctx.send(f'i cant find `{phrase}`, are you sure you spelt it correctly?')
            return

        with open('phrases.json', 'w') as f:
            json.dump(data, f, indent=4)

        await ctx.send(f'{phrase} has been removed from this server')
    else:
        await ctx.send('you dont have permission to use this command')
bot.run(token)


# -*- coding: utf-8 -*-
"""
Created on Tue Feb 28 16:34:19 2017

@author: kurner
"""

import os
import os.path
import requests
import xml.etree.ElementTree as ET

PROJECT = "/Users/kurner/Downloads/session10"

if not os.path.abspath(".") != PROJECT:
    os.chdir(PROJECT)

#get_url = ("https://developer.trimet.org/ws/V1/trips/tripplanner/"
#           "fromplace/pdx/toplace/zoo/appId/8....")

#r = requests.get(get_url)
#print(dir(r))
#print(r.status_code)
#print(r.text)

ns = {"model":"http://maps.trimet.org/maps/model/xml"}

# root =  ET.fromstring(r.text)

tree = ET.parse("trimet_trip_plan.xml")
root = tree.getroot()

itineraries = root.findall("model:itineraries", ns)

for itinerary in itineraries[0].findall("model:itinerary", ns):
    td = itinerary.find("model:time-distance", ns)
    date  = td.find("model:date", ns).text
    start = td.find("model:startTime", ns).text
    end = td.find("model:endTime", ns).text
    duration = td.find("model:duration", ns).text
    distance = td.find("model:distance", ns).text
    print("----")
    print("Date:", date)
    print("Start Time:", start)
    print("End Time:", end)
    print("Duration:", duration)
    print("Distance:", distance)

    for idx, leg in enumerate(itinerary.findall("model:leg", ns)):
        print("Leg ", idx)
        mode = leg.attrib['mode']
        leg_start, leg_end = "", ""

        td = False
        td = leg.find("model:time-distance", ns)
        if td and mode !="Walk":
            leg_start = td.find("model:startTime", ns).text
            leg_end   = td.find("model:endTime", ns).text

        start_from = leg.find("model:from", ns)
        start_stopId = start_from.find("model:stopId", ns).text
        start_dest = start_from.find("model:description", ns).text

        end_at = leg.find("model:to", ns)
        if mode != "Walk":
            end_stopId = end_at.find("model:stopId", ns).text
            route = leg.find("model:route", ns).find("model:name", ns).text
        else:
            end_stopId = "N/A"
            route = "On foot"
        end_dest = end_at.find("model:description", ns).text

        print("Mode : {}".format(route))
        print("Start: {:8} {:>8} {}".format(leg_start, start_stopId, start_dest))
        print("End  : {:8} {:>8} {}".format(leg_end, end_stopId, end_dest))


from utils import read_file

def get_views(pos, grid):
    x, y = pos

    right = grid[x][y + 1 :]
    left = grid[x][:y][::-1]

    grid_t = list(map(list, zip(*grid)))
    up = grid_t[y][:x][::-1]
    down = grid_t[y][x + 1 :]

    return up, down, left, right

def is_visible(pos, grid):
    x, y = pos
    for v in get_views(pos, grid):
        if max(v) < grid[x][y]:
            return True

    return False

def takeuntil(pred, lst):
    for l in lst:
        yield l
        if pred(l):
            break

def visible_score(pos, grid):
    x, y = pos

    pred = lambda h: h >= grid[x][y]
    score = 1
    for v in get_views(pos, grid):
        nvis = len(list(takeuntil(pred, v)))
        score *= nvis

    return score

def check_interiors(grid):
    bounds = ((1, len(grid[0]) - 1), (1, len(grid) - 1))

    count = 0
    for x in range(*bounds[0]):
        for y in range(*bounds[1]):
            if is_visible((x, y), grid):
                count += 1

    return count

def view_interiors(grid):
    bounds = ((1, len(grid[0]) - 1), (1, len(grid) - 1))

    return [
        visible_score((x, y), grid)
        for x in range(*bounds[0])
        for y in range(*bounds[1])
    ]

if __name__ == "__main__":
    grid = [list(map(int, x)) for x in read_file("data/08.txt")[:-1]]

    print(check_interiors(grid) + len(grid) * 2 + (len(grid) - 2) * 2)

    print(max(view_interiors(grid)))


import helpFunctions as hf
import matplotlib.pyplot as plt
import numpy as np
from scipy import misc
from PIL import Image

dirIn = '/home/mehmet/Desktop/DTU_Spring/Math_Modelling/cn/Exercises/Exercise_1/ex1_campusnet/data/'

multiIm, annotationIm = hf.loadMulti('multispectral_day20.mat' , 'annotation_day20.png', dirIn)

my_array = annotationIm[:,:,0]
im = Image.fromarray(annotationIm[:,:,0].reshape((514,514)).astype('uint8')*255)
im.save("grey_scale.png")

my_array2 = annotationIm[:,:,1]
im = Image.fromarray(my_array2.reshape((514,514)).astype('uint8')*255)
im.save("second.png")

my_array3 = annotationIm[:,:,2]
im = Image.fromarray(my_array3.reshape((514,514)).astype('uint8')*255)
im.save("third.png")

##############################################################################################################################
#1. Calculate the threshold value t for all spectral bands for day 1
#to do: for day 1.
multiIm, annotationIm = hf.loadMulti('multispectral_day01.mat' , 'annotation_day01.png', dirIn)
[fatPix, fatR, fatC] = hf.getPix(multiIm, annotationIm[:,:,1])
[meatPix, meatR, meatC] = hf.getPix(multiIm, annotationIm[:,:,2])
thresholds_day20 = np.array([20, 13, 19, 22, 22, 22, 22, 25, 41, 52, 57, 64, 70, 69, 67, 59, 59, 49, 2.5])
thresholds_day01 = np.array([19, 13, 20, 23, 23, 27, 25, 29, 48, 54, 58, 64, 69, 69, 67, 63, 61, 53, 4 ])
def error_rate_fat(fatPix,layerNo):
        #returns the failure rate of the assumption
        return (fatPix[:,0].shape[0]-fatPix[fatPix[:,layerNo]>=20,0].shape[0])/fatPix[:,0].shape[0]
##############################################################################################################################
#2. Calculate the error rate for each spectral band.
for i in range(19):
        error_rate_fat(fatPix,i)
        h = hf.showHistograms(multiIm, annotationIm[:,:,1:3], i, 1)
##############################################################################################################################
#3. Identify the spectral band, which has the best discriminative properties for meat and fat
[fatPix, fatR, fatC] = hf.getPix(multiIm, annotationIm[:,:,1]);
[meatPix, meatR, meatC] = hf.getPix(multiIm, annotationIm[:,:,2]);
plt.plot(np.mean(meatPix,0),'b')
plt.plot(np.mean(fatPix,0),'r')
plt.show()#spectral distrubution
"""
We guess that the third mean difference is the biggest one. So it is a good candidate for training day.
"""

"""
We can see the biggest difference between the means is seen at day 3. However, we can do another better
determination via both increasing the difference between means and decreasing the variance in the groups.
Because the whole idea behind the LDA is this 2 principles. (mu1 - mu2)²/(s1² + s2²). The largest spectrum
is defined as our training set.
"""
def best_band(meatPix, fatPix):
	numerator = (np.mean(meatPix,0) - np.mean(fatPix,0))**2
	denomunator = np.std(meatPix,0)**2 + np.std(fatPix,0)**2

	values = numerator/denomunator
	return np.argmax(values)

"""
We were right. It is the third day has the best indicators.
"""
##############################################################################################################################
#4. Classify the entire image of the salami for day 1, and visualise it

"""
SIMPLEST MODEL (thresholding)
We implement our simplest model to day1. While doing this we do it on the third picture(450 nm).

"""
middle = (annotationIm[:,:,2]*1 + annotationIm[:,:,1]*1 + annotationIm[:,:,0]*1)

def classify(threshold, multiIm):
	from scipy.misc import toimage
	meat_anno = np.zeros((514,514))
	fat_anno =  np.zeros((514,514))
	for x in range(514):
		for y in range(514):
			if middle[x][y] ==1:
				if multiIm[:,:,2][x][y] >=20:
					meat_anno[x][y] = 0
					fat_anno[x][y] = 1
				else:
					meat_anno[x][y] = 1
					fat_anno[x][y] = 0

thresholds_day01 = np.array([19, 13, 20, 23, 23, 27, 25, 29, 48, 54, 58, 64, 69, 69, 67, 63, 61, 53, 4 ])
for value in thresholds_day01:
	classify(value, multiIm, )

from scipy.misc import toimage
img = toimage(fat_anno)
img.save("third.png")

img2 = toimage(meat_anno)
img2.save("meatDay1Layer3.png")
##############################################################################################################################
#1. Calculate the multivariate linear discriminant function as described in (23) for day 1.

import numpy as np
from scipy import misc
from PIL import Image

dirIn = '/home/mehmet/Desktop/DTU_Spring/Math_Modelling/cn/Exercises/Exercise_1/ex1_campusnet/data/'

multiIm, annotationIm = hf.loadMulti('multispectral_day01.mat' , 'annotation_day01.png', dirIn)
[fatPix, fatR, fatC] = hf.getPix(multiIm, annotationIm[:,:,1]);
[meatPix, meatR, meatC] = hf.getPix(multiIm, annotationIm[:,:,2]);

imageFat = np.zeros((multiIm.shape[0], multiIm.shape[1]))
imageMeat = np.zeros((multiIm.shape[0], multiIm.shape[1]))
middle = (annotationIm[:,:,2]*1 + annotationIm[:,:,1]*1 + annotationIm[:,:,0]*1)

def lda_amount(typePix, meatPix, fatPix, multiIm, x, y):
	from numpy.linalg import inv
	covMatrixFat = np.cov(np.transpose(fatPix)) #cov matrix
	covMatrixMeat = np.cov(np.transpose(meatPix))

	numo = ( (fatPix.shape[0]-1)*covMatrixFat+(meatPix.shape[0]-1)*covMatrixMeat)
	deno = fatPix.shape[0] + meatPix.shape[0]-2
	covMatrix = numo/deno

	mean = np.mean(typePix,0)
	prior = typePix.shape[0]/(meatPix.shape[0] + fatPix.shape[0])

	first1 = np.transpose(multiIm[x,y,:])
	first2 = inv(covMatrix)
	first = np.dot(np.dot( first1, first2  ),mean)

	second = np.dot(1/2*np.dot(np.transpose(mean), inv(covMatrix)), mean)

	third = np.log(prior)

	return  (first - second +third)

for i in range(multiIm.shape[0]):
	for j in range(multiIm.shape[1]):

		if not middle[i,j] ==1:
			print(i,j)
			continue

		valueFat = lda_amount(fatPix, meatPix, fatPix, multiIm, i, j)
		valueMeat = lda_amount(meatPix, meatPix, fatPix, multiIm, i, j)
		print(valueMeat , valueFat)
		if middle[i,j] ==1:
			if valueFat > valueMeat :
				imageFat[i,j] = 1
			else:
				imageMeat[i,j] = 1

from scipy.misc import toimage
img = toimage(imageFat)
img.save("day1Fat.png")
img2 = toimage(imageMeat)
img2.save("day1Meat.png")

##############################################################################################################################
#2. Calculate the error rate (disagreement between the model and the annotations) for the training set.

def error_rate():
	import numpy as np
	from scipy import misc
	from PIL import Image
	import helpFunctions as hf
	import matplotlib.pyplot as plt
	dirIn = '/home/mehmet/Desktop/DTU_Spring/Math_Modelling/cn/Exercises/Exercise_1/ex1_campusnet/data/'

	multiIm, annotationIm = hf.loadMulti('multispectral_day01.mat' , 'annotation_day01.png', dirIn)
	[fatPix, fatR, fatC] = hf.getPix(multiIm, annotationIm[:,:,1]);
	[meatPix, meatR, meatC] = hf.getPix(multiIm, annotationIm[:,:,2]);

	imageFat = np.zeros((multiIm.shape[0], multiIm.shape[1]))
	imageMeat = np.zeros((multiIm.shape[0], multiIm.shape[1]))

	annoFat = annotationIm[:,:,1]
	annoMeat = annotationIm[:,:,2]
	for i in range(multiIm.shape[0]):
			for j in range(multiIm.shape[1]):
				if not middle[i,j] ==1:
					print(i,j)
					continue

				valueFat = lda_amount(fatPix, meatPix, fatPix, multiIm, i, j)
				valueMeat = lda_amount(meatPix, meatPix, fatPix, multiIm, i, j)
				print(valueMeat , valueFat)
				if middle[i,j] ==1:
					if valueFat > valueMeat :
						imageFat[i,j] = 1

					else:
						imageMeat[i,j] = 1

	errorFatArray = annoFat[(imageFat ==0) & (annoFat==1)]

	return errorFatArray.shape


import os
import numpy as np
from matplotlib import pyplot as plt
import cv2
img_array = []
path = '/home/ash/labelme/IIIT_Labels/seq_5/SegmentationClassVisualization/'
files = sorted(os.listdir(path))[60:240]
for file in files:
    img = cv2.imread(os.path.join(path,file))
    img_array.append(img)
    size = (img.shape[1],img.shape[0])

fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('banner_vid.mp4',fourcc,20.0,size)
for i in range(len(img_array)):
    out.write(img_array[i])
out.release()


from django.shortcuts import render, redirect
from courses.models import Directions

def index(request):
    template = 'landing/app.html'

    directions = Directions.objects.all()
    if request.method == 'POST':
        course_name = request.POST.get('course_name')
        select_course = request.POST.get('select_course')
        if course_name and select_course:
            # Оба значения переданы, перенаправляем на другой метод с двумя параметрами
            return redirect('courses:courses-search', course_name=course_name, select_course=select_course)
        elif course_name:
            # Передано только значение course_name
            return redirect('courses:courses-search', course_name=course_name, select_course=None)
        elif select_course:
            # Передано только значение select_course
            return redirect('courses:courses-search', course_name=None, select_course=select_course)
        else:
            # Не передано ни одно значение
            return redirect('courses:courses-search', course_name=None, select_course=None)
    context = {
    'request': request,
    'directions': directions
    }
    return render(request, template, context)


def middle(nums, left, right, lSum, rSum):
    mid = (left + right) // 2
    lSumNew = sum(n['weight'] for n in nums[left:mid])
    rSumNew = sum(n['weight'] for n in nums[mid + 1:right])
    if lSum + lSumNew <= 0.5 and rSum + rSumNew <= 0.5:
        return nums[mid]['value']
    else:
        if lSum + lSumNew > 0.5:
            return middle(nums, left, mid, lSum, rSum + rSumNew)
        else:
            return middle(nums, mid + 1, right, lSum + lSumNew, rSum)

if __name__ == '__main__':
    def getValue(elem):
        return elem['value']

    nums = [{'value': 1, 'weight': 0.1},
            {'value': 4, 'weight': 0.2},
            {'value': 2, 'weight': 0.3},
            {'value': 5, 'weight': 0.4}]
    nums.sort(key=getValue)
    print(nums)

    if sum(num['weight'] for num in nums) == 1:
        print(middle(nums, 0, len(nums), 0, 0))
    else:
        print('input wrong: ', sum(nums))


#참고 : https://velog.io/@waoderboy/알고리즘-백준-16236-아기상어-파이썬
from collections import deque
import sys

n = int(sys.stdin.readline())
graph = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
x,y = 0,0
cnt,t = 0,0
move = ((1,0),(-1,0),(0,1),(0,-1))
size = 2
for i in range(n):
    for j in range(n):
        if graph[i][j] == 9:
            x,y = j, i
            graph[y][x] = 0

def bfs(x, y):
    visited = [[0]*n for _ in range(n)]
    queue = deque([(x,y)])
    fishs = []
    visited[y][x] = 1

    while queue:
        x, y = queue.popleft()

        for dx,dy in move:
            nx = x + dx
            ny = y + dy

            if 0<=nx<n and 0<=ny<n and visited[ny][nx] == 0:
                if size > graph[ny][nx] and graph[ny][nx] != 0:
                    visited[ny][nx] =  visited[y][x] + 1
                    fishs.append((nx, ny,visited[ny][nx] - 1))
                elif size == graph[ny][nx] or graph[ny][nx] == 0:
                    visited[ny][nx] =  visited[y][x] + 1
                    queue.append((nx,ny))

    return sorted(fishs, key = lambda x: (x[2], x[1], x[0]))

while True:
    fishs = deque(bfs(x,y))

    if not fishs:
        break

    x, y, dist = fishs.popleft()
    t += dist
    cnt += 1
    if size == cnt:
        size += 1
        cnt = 0

    graph[y][x] = 0

print(t)


from pydub import AudioSegment
from tqdm import tqdm
import os

def create_translated_audio(result_diarize, audio_files, Output_name_file):
    total_duration = result_diarize['segments'][-1]['end'] # in seconds

    # silent audio with total_duration
    combined_audio = AudioSegment.silent(duration=int(total_duration * 1000))
    print(round((total_duration / 60),2), 'minutes of video')

    for line, audio_file in tqdm(zip(result_diarize['segments'], audio_files)):
        start = float(line['start'])

        # Overlay each audio at the corresponding time
        try:
          audio = AudioSegment.from_file(audio_file)
          ###audio_a = audio.speedup(playback_speed=1.5)
          start_time = start * 1000  # to ms
          combined_audio = combined_audio.overlay(audio, position=start_time)
        except:
          print(f'ERROR AUDIO FILE {audio_file}')

    os.system("rm -rf audio/*")

    # combined audio as a file
    combined_audio.export(Output_name_file, format="wav") # best than ogg, change if the audio is anomalous


import pandas as p
import numpy as n
import  matplotlib.pyplot as plot
from sklearn import metrics

data1=p.read_csv("ww.csv")

num = list(n.array(list(range(0,105,5)))/100)
num1=[]
for i in num:
    data1["data1_pr_ran"] = (data1["y_pred_random_forest"]>=i).astype(int)

    tp=sum((data1["y_act"]==1) & (data1["data1_pr_ran"]==1))
    tn=sum((data1["y_act"]==0) & (data1["data1_pr_ran"]==0))
    fp=sum((data1["y_act"]==0) & (data1["data1_pr_ran"]==1))
    fn=sum((data1["y_act"]==1) & (data1["data1_pr_ran"]==0))

    tpr=tp/(tp+fn)
    fpr=fp/(fp+tn)

    num1.append([tpr,fpr])

graph=p.DataFrame(num1,columns=["x","y"])

from numpy import trapz
ds=trapz(graph.x,graph.y)
print(abs(round(ds)))

plot.scatter(graph.y,graph.x)
plot.show()

#character error

from nltk.metrics import edit_distance

letter1="this is a boy"
letter2="this is a girl"

print("character_error:" , edit_distance(letter1,letter2)/len(letter1))

#word error

word=letter1.split()
word1=letter2.split()

print("word_error:",edit_distance(word,word1)/len(word))

#prc

x_kaar=n.array([1,0,0,0,0,1])

y_pro=n.array([0.4,0.7,0.3,0.8,0.2,0.9])

print('prc rate:', metrics.average_precision_score(x_kaar,y_pro))

#mean absoulte error

value=0
len_val=len(data1)

for i,val in data1.iterrows():
    result = val["y_act"]-val["y_pred_random_forest"]
    value+=result

value=value/len_val

print("man absoulte value:",value)

#mean squre error
to=0
for i,val in data1.iterrows():
    result = val["y_act"]-val["y_pred_random_forest"]
    result*=result
    to+=result

print("mean squre error:",to)


from karel.stanfordkarel import *

"""
File: StoneMasonKarel.py
------------------------
When you finish writing code in this file, StoneMasonKarel should
solve the "repair the quad" problem from Assignment 1. You
should make sure that your program works for all of the
sample worlds supplied in the starter folder.
"""

def main():
    while front_is_clear():
        climb_fix()
        return_to_ground()
        move_to_column()
    # Due to fencepost error issue, the last column remains unrepaired.
    climb_fix()
    return_to_ground()

def climb_fix():
    """
    This function helps Karel climb to the top of the column while repairing the column at each step.
    Pre-condition: Karel is standing at the bottom of the unrepaired column, facing east.
    Post-condition: Karel is standing at the top of the repaired column, facing north.
    """
    turn_left()
    while front_is_clear():
        if no_beepers_present():
            put_beeper()
            move()
        else:
            move()
    """
    Due to the fencepost error, the last square remains unchecked.
    if there is no beeper at the last step i.e. the top of the column, putting the last beeper will be missed.
    so the last beeper should be put there.
    """
    if no_beepers_present():
        put_beeper()

def return_to_ground():
    """
    This function return Karel to the ground.
    Pre-condition: Karel is standing at the top of the repaired column, facing north.
    Post-condition: Karel is standing at the bottom of the repaired column, facing east.
    """
    turn_around()
    while front_is_clear():
        move()
    turn_left()

def turn_around():
    turn_left()
    turn_left()

def move_to_column():
    for j in range(4):
        move()

# There is no need to edit code beyond this point

if __name__ == "__main__":
    run_karel_program()


# coding: utf8
from __future__ import unicode_literals

from ...symbols import ORTH, LEMMA, NORM

_exc = {}
_abbrev_exc = [

    # http://www.eki.ee/itstandard/2000/FDCC.shtml
    # Weekdays abbreviations
    {ORTH: "E", LEMMA: "esmaspäev", NORM: "esmaspäev"},
    {ORTH: "T", LEMMA: "teisipäev", NORM: "teisipäev"},
    {ORTH: "K", LEMMA: "kolmapäev", NORM: "kolmapäev"},
    {ORTH: "N", LEMMA: "neljapäev", NORM: "neljapäev"},
    {ORTH: "R", LEMMA: "reede", NORM: "reede"},
    {ORTH: "L", LEMMA: "laupäev", NORM: "laupäev"},
    {ORTH: "P", LEMMA: "pühapäev", NORM: "pühapäev"},

    # http://www.eki.ee/itstandard/2000/FDCC.shtml
    # Months abbreviations
    {ORTH: "jaan", LEMMA: "jaanuar", NORM: "jaanuar"},
    {ORTH: "veebr", LEMMA: "veebruar", NORM: "veebruar"},
    {ORTH: "märts", LEMMA: "märts", NORM: "märts"},
    {ORTH: "mär", LEMMA: "märts", NORM: "märts"},
    {ORTH: "apr", LEMMA: "aprill", NORM: "aprill"},
    {ORTH: "mai", LEMMA: "mai", NORM: "mai"},
    {ORTH: "juuni", LEMMA: "juuni", NORM: "juuni"},
    {ORTH: "juun", LEMMA: "juuni", NORM: "juuni"},
    {ORTH: "juuli", LEMMA: "juuli", NORM: "juuli"},
    {ORTH: "juul", LEMMA: "juuli", NORM: "juuli"},
    {ORTH: "aug", LEMMA: "august", NORM: "august"},
    {ORTH: "augu", LEMMA: "august", NORM: "august"},
    {ORTH: "sept", LEMMA: "september", NORM: "september"},
    {ORTH: "septe", LEMMA: "september", NORM: "september"},
    {ORTH: "okt", LEMMA: "oktoober", NORM: "oktoober"},
    {ORTH: "okto", LEMMA: "oktoober", NORM: "oktoober"},
    {ORTH: "nov", LEMMA: "november", NORM: "november"},
    {ORTH: "nove", LEMMA: "november", NORM: "november"},
    {ORTH: "dets", LEMMA: "detsember", NORM: "detsember"},
    {ORTH: "detse", LEMMA: "detsember", NORM: "detsember"},

    # http://www.eki.ee/dict/qs2006/lyhendid.html
    {ORTH: "näd", LEMMA: "nädal", NORM: "nädal"},
    {ORTH: "a", LEMMA: "aasta", NORM: "aasta"},
    {ORTH: "al", LEMMA: "alates", NORM: "alates"},
    {ORTH: "AS", LEMMA: "aktsiaselts", NORM: "aktsiaselts"},
    {ORTH: "dir", LEMMA: "direktor", NORM: "direktor"},
    {ORTH: "dr", LEMMA: "doktor", NORM: "doktor"},
    {ORTH: "OÜ", LEMMA: "osaühing", NORM: "osaühing"},
    {ORTH: "nr", LEMMA: "number", NORM: "number"},
    {ORTH: "nt", LEMMA: "näiteks", NORM: "näiteks"},
    {ORTH: "n-ö", LEMMA: "nii-öelda", NORM: "nii-öelda"},
    {ORTH: "pms", LEMMA: "peamiselt", NORM: "peamiselt"},
    {ORTH: "nn", LEMMA: "niinimetatud", NORM: "niinimetatud"},
    {ORTH: "vt", LEMMA: "vaata", NORM: "vaata"},
    {ORTH: "u", LEMMA: "umbes", NORM: "umbes"},
    {ORTH: "tn", LEMMA: "tänav", NORM: "tänav"},
    {ORTH: "mnt", LEMMA: "maantee", NORM: "maantee"},
    {ORTH: "pst", LEMMA: "puiestee", NORM: "puiestee"},
    {ORTH: "ptk", LEMMA: "peatükk", NORM: "peatükk"},
    {ORTH: "saj", LEMMA: "sajand", NORM: "sajand"},
]
for abbrev_desc in _abbrev_exc:
    abbrev = abbrev_desc[ORTH]
    for orth in (abbrev, abbrev.capitalize(), abbrev.upper()):
        _exc[orth] = [{ORTH: orth, LEMMA: abbrev_desc[LEMMA], NORM: abbrev_desc[NORM]}]
        _exc[orth + '.'] = [{ORTH: orth + '.', LEMMA: abbrev_desc[LEMMA], NORM: abbrev_desc[NORM]}]

TOKENIZER_EXCEPTIONS = _exc


N = int(input())
if N % 2 != 0:
    print(0)
else:
    calArr = [0 for _ in range(31)]
    calArr[0] = 1
    calArr[2] = 3

    for i in range(4, N + 1, 2):
        calArr[i] = calArr[i - 2] * 3
        for j in range(i - 4, -1, -2):
            calArr[i] += calArr[j] * 2

    print(calArr[N])

백준/Gold/2133. 타일 채우기/타일 채우기.py


'''
1/3/2018
Send t parameter by url, just change first two letters, ex:
5E9AF59D2467
# http://www.tjfdc.com.cn/Pages/fcdt/HouseInfo.aspx?t=7D4E9AF59D2467&loupan=经纬城市绿洲武清二期&projectname=学知华庭31号楼

Error:UnicodeEncodeError: 'gbk' codec can't encode character '\xa0'
change from
f1.write(myNote.encode('gbk'))
to
f1.write(myNote.encode('gbk','ignore'))
or
str2.replace(u'\xa0', u'')

Error:python write() argument must be str, not bytes
change from
open("temp.txt", "a")
to
open("temp.txt", "wb+")  or ab+
'''
from splinter.browser import Browser
from bs4 import BeautifulSoup
import time
import os

class singleprice:

    fileName='single.csv'

    chromeDriverpath = 'C:\Program Files\Java\webdriver\chromedriver.exe'  # Web driver path
    executable_path = {'executable_path': chromeDriverpath}  # DO NOT change it
    browser = Browser('chrome', **executable_path)  # DO NOT change it

    def __init__(self):
        #self.browser.visit(self.url)
        a=1

    def getinfo(self,url):
        time.sleep(2)
        try:
            self.browser.visit(url)

            innerhtml = self.browser.html
            soup = BeautifulSoup(innerhtml, "lxml")
            soup.replaceWith
            strTotal = ''
            for elem in soup.find_all('td'):
                str1 = elem.text
                str2 = str1.replace('\n', '')  # remove \n
                str3 = str2.strip()  # remove space
                strTotal = strTotal + str3 + ','
            strTotal = strTotal + '\n'
            self.writeLog(strTotal)
        except Exception:
            None

    def writeLog(self,myNote):
        #time1=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        # Open and rewite, add file from beginning with 'w', add file from the end with 'a'
        f1 = open(self.fileName, 'ab+')
        #f1.write(str(myNote))
        #f1.write(str(myNote).encode('utf-8'))
        #string.replace(u’\xa0’, u’ ‘)
        f1.write(str(myNote).encode('gbk','ignore'))
        f1.write(str(myNote).encode('gbk', 'ignore'))
        f1.close()

    def getByCode(self,urlStart,urlEnd):
        url=''
        # Number+Letter
        # Range from 0 to 9
        for i in range(0,10):
            url=str(i)
            for j in range(65, 91):
                print("getting id "+str(i)+chr(j))
                url=urlStart+str(i)+chr(j)+urlEnd
                self.getinfo(url)
        # Letter+Number
        for i in range(65, 91):
            url=str(i)
            for j in range(0, 10):
                print("getting id "+chr(i)+str(j))
                url=urlStart+chr(i)+str(j)+urlEnd
                self.getinfo(url)

        # Letter+Letter
        for i in range(65, 91):
            url=str(i)
            for j in range(65, 91):
                print("getting id "+chr(i)+chr(j))
                url=urlStart+chr(i)+chr(j)+urlEnd
                self.getinfo(url)

        # Number+Number
        for i in range(0, 10):
            url = str(i)
            for j in range(0, 10):
                print("getting id " + str(i) + str(j))
                url = urlStart + str(i) + str(j) + urlEnd
                self.getinfo(url)


# Задача 3.1.
# Создайте класс матрицы (или таблицы)

#    существуют следующие методы матрицы:
#       * принимать новые значения,
#       * заменять существующие значения,
#       * выводить число строк и колонок.
import pprint
import random

class Matrix:

    def create_matrix():
        """Задаем параметры матрицы"""
        r = 0
        N = int(input('Ведите количество строк матрицы: '))
        M = int(input('Ведите количество столбцов матрицы: '))
        array = []
        for i in range(N):
            array.append([])
            for j in range(M):
                array[i].append(random.randint(0,100))
                r += 1
        pprint.pprint(array)
        return array

    def add_matrix():
        """Принять новое значение"""
        m = Matrix.create_matrix()
        for i in range(len(m)):
            n = 0
            for j in m[i]:
               if j == 0:
                  m[i][n] = random.randint(1,9)
                  print(' ')
                  print(f"В строке под индексом {i} значение под индексом {n} заменено")
                  n +=1
               else:
                  n+=1
        print('')
        pprint.pprint(m)

    def change_matrix():
        """Заменить объект в матрице"""
        m = Matrix.create_matrix()
        x = int(input('Ведите индекс строки матрицы: '))
        y = int(input('Ведите индекс столбца матрицы: '))
        n = int(input('Ведите новое число: '))
        m[x][y] = n
        print('В ячейке', x, y, 'элемент заменен на ', n)
        pprint.pprint(m)

    def size_matrix():
        """Узнать размер матрицы"""
        m = Matrix.create_matrix()
        x = len(m)
        y = len(m[0])
        print ('Количество строк равно:', x)
        print ('Количество столбцов равно:', y)

Matrix.change_matrix()


from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from typing import Union
from pydantic import BaseModel
import requests
import random
from package1 import poke_api

class Quiz(BaseModel):
    name: str
    ans_img: str
    shadow_img: str

app = FastAPI()
URL = "https://pokeapi.co/api/v2/pokemon/"

origins = [
    "http://localhost:5173",
    "http://127.0.0.1:5173",
    "http://localhost:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers={"*"},
)

@app.exception_handler(RequestValidationError)
async def handler(request:Request, exc:RequestValidationError):
    print(exc)
    return JSONResponse(content={}, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)

@app.get("/")
def hello():
    return {
        "message": "Hello World!"
    }

@app.get("/{id}")
def name(id: int):
    res = requests.get(URL+str(id))
    name = poke_api.get_name(res)
    return {
        "name": name
    }

@app.get("/quiz/")
def quiz():
    id: int = random.randint(1,1010)
    res = requests.get(URL+str(id))
    name = poke_api.get_name(res)
    ans_img = poke_api.get_image(res)
    ans_img_encoded = poke_api.decode_image(ans_img)
    shadow_img = poke_api.fill_image_to_black(ans_img)
    shadow_img_encoded = poke_api.decode_shadow_image(shadow_img)
    return {
        "id": id,
        "name": name,
        "ans_img": ans_img_encoded,
        "shadow_img": shadow_img_encoded
    }

@app.get("/all/")
def name_all():
    name_list = poke_api.get_name_all()
    return {
        "result": name_list
    }


import numpy as np

input = """\
7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1

22 13 17 11  0
 8  2 23  4 24
21  9 14 16  7
 6 10  3 18  5
 1 12 20 15 19

 3 15  0  2 22
 9 18 13 17  5
19  8  7 25 23
20 11 10 24  4
14 21 16 12  6

14 21 17 24  4
10 16 15  9 19
18  8 23 26 20
22 11 13  6  5
 2  0 12  3  7"""

# with open("2021/day04/data.txt") as fh:
#     input = fh.read()

board_data_list = []

for i, line in enumerate(input.splitlines()):
    if i == 0:
        draw_nums = list(map(int, line.split(",")))
        continue
    if line:
        board_data_list.append(list(map(int, line.split())))

all_board_data = np.array(board_data_list)
boards = np.array_split(all_board_data, all_board_data.shape[0] / 5)

def calc_answer(arr, draw):
    answer = draw * np.sum(arr[arr != -1])
    print(answer)

def play():
    for draw in draw_nums:
        for board in boards:
            if draw in board:
                board[board == draw] = -1

                for row in board:
                    if np.all(row == -1):
                        # we have a winner
                        return calc_answer(board, draw)
                for col in board.transpose():
                    if np.all(col == -1):
                        # we have a winner
                        return calc_answer(board, draw)

                # if np.all(board.diagonal() == -1):
                #     # we have a winner
                #     ...
                #     raise(SystemExit)
                # if np.all(np.fliplr(board).diagonal() == -1):
                #     # we have a winner
                #     ...
                #     raise(SystemExit)

return_value = play()


from product import Product
import random
from datetime import datetime
from user import Customer

class Orders:
    def __init__(self):
        self.__item = {}

    @property
    def item(self):
        return self.__item

    @item.setter
    def item(self, item):
        self.__item = item

    def add_menu(self, choose):
        """
        This function will add item into customer cart. it will get input if product's id ,
        and then check whether that product is available or not
        :param choose:
        :return:
        """
        for data in Product().readfile():
            if choose == data["id"]:
                amount = int(input(f"How many {data['menu']} do you want?: "))
                if Product().check_stock(int(data["stock"]), amount):  # check whether menu available or not
                    Product().update_stock(int(data["stock"]), amount)  # update stock
                    self.__item.update({data["menu"]: {"id": data["id"],  # update cart
                                                       "quantity": amount,
                                                       "subtotal": int(data["price"]) * amount}})
                    print(f"Add {amount} {data['menu']} to the cart.")
                    return self.__item
                else:
                    return False

    def delete(self):
        """
        This function will delete unwanted item from customer cart
        :return:
        """
        choose = input("Which one do you want to delete?: ")
        for menu, info in self.__item.copy().items():
            # check whether product that customer chooses is in the cart or not
            if choose == info["id"]:
                # check whether customer really want to remove item
                sure = input(f"Are you sure do you want to remove {menu}?(y/n) ")
                if sure == "y":
                    self.__item.pop(menu)  # remove unwanted menu from cart
                    print(f'{menu} has been removed.')
                    break
                elif sure == "n":
                    break

    def cancel(self):
        self.__item.clear()  # delete all orders
        print("Cancel successfully.")

    def subtotal(self):
        total_price = 0
        for menu, info in self.__item.items():
            total_price += int(info["subtotal"])
        return total_price

    def discount(self):
        if self.subtotal() >= 300:  # check whether customer purchase more than 300 or not.
            dis = self.subtotal() * 0.1
            return dis
        return 00.00

    def total(self):
        if self.subtotal() >= 300:
            total = self.subtotal() - self.discount()
            return total
        return self.subtotal()

    def get_id_order(self):
        upper_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        number = '1234567890'
        use_for = upper_case + number
        length = 15
        id_order = ''.join(random.sample(use_for, length))  # create order id's for customer.
        return id_order

    def receipt(self):
        """
        This function will print receipt for customer
        :return:
        """
        now = datetime.now()
        day = now.date()
        time = now.strftime("%H:%M")
        with open("order_receipt.txt", "w") as f:  # write receipt in text file
            f.write(f"\n")
            f.write(" " * 28 + "B A K E  M Y  D A Y\n\n")
            f.write(" " * 21 + "Thank you for ordering our product!\n\n")
            f.write(f"Order #{self.get_id_order()}\n\n")
            f.write("Menu" + " " * 30 + "Quantity" + " " * 30 + "Price\n")
            f.write("-" * 80 + "\n")
            for k, v in self.__item.items():
                f.write(f"{k}".ljust(37, " ") + f"{v['quantity']}".ljust(35, " ") + f"{v['subtotal']}.-\n")
            f.write("-" * 80 + "\n")
            pay = input("Do you want to pay by Bank Transfer(b) or Credit Card(c)?: ")
            while True:
                if pay == 'b':
                    f.write(f"Subtotal: {self.subtotal():.2f}฿".ljust(58, " ") + f"Payment: Bank Transfer\n")
                    break
                elif pay == 'c':
                    f.write(f"Subtotal: {self.subtotal():.2f}฿".ljust(58, " ") + f"Payment: Credit Card\n")
                    break
                elif not pay == 'b' or 'c':
                    print("Please enter b or c only")
                    pay = input("Do you want to pay by Bank Transfer(b) or Credit Card(c)?: ")
            f.write(f"Shipping fee: 0.00฿" + " ".ljust(39, " ") + f"Order date: {day}\n")
            f.write(f"Discount: {self.discount():.2f}฿".ljust(58, " ") + f"Time: {time}\n")
            f.write(f"Total: {self.total():.2f}฿\n\n")
            f.write(f"Shipping to:\n")
            c = Customer()
            c.customer_detail()
            f.write(f"{c.name.title()}\n")
            f.write(f"{c.phone}\n")
            f.write(f"{c.address.title()}\n")
            f.write("-" * 80 + "\n")
            f.write(" " * 24 + "H A V E  A  N I C E  D A Y!")