import json
import requests

from neutron._i18n import _

from oslo_config import cfg
from oslo_log import log as logging

from quark.db import ip_types
from quark import exceptions as ex

CONF = cfg.CONF
LOG = logging.getLogger(__name__)

quark_router_opts = [
    cfg.StrOpt('floating_ip_base_url',
               default='http://localhost:8080/v1.0/floating_ips',
               help=_('floating ips base url')),
    cfg.IntOpt('unicorn_api_timeout_seconds', default=2,
               help=_('Number of seconds to wait for a response from the '
                      'server before failing the call'))
]

CONF.register_opts(quark_router_opts, "QUARK")

class UnicornDriver(object):
    def __init__(self):
        pass

    @classmethod
    def get_name(cls):
        return "Unicorn"

    def register_floating_ip(self, floating_ip, port_fixed_ips):
        """Register a floating ip with Unicorn

        :param floating_ip: The quark.db.models.IPAddress to register
        :param port_fixed_ips: A dictionary containing the port and fixed ips
        to associate the floating IP with.  Has the structure of:
        {"<id of port>": {"port": <quark.db.models.Port>,
         "fixed_ip": "<fixed ip address>"}}
        :return: None
        """
        url = CONF.QUARK.floating_ip_base_url
        timeout = CONF.QUARK.unicorn_api_timeout_seconds
        req = self._build_request_body(floating_ip, port_fixed_ips)

        try:
            LOG.info("Calling unicorn to register floating ip: %s %s"
                     % (url, req))
            r = requests.post(url, data=json.dumps(req), timeout=timeout)
        except Exception as e:
            LOG.error("Unhandled Exception caught when trying to register "
                      "floating ip %s with the unicorn API.  Error: %s"
                      % (floating_ip.id, e.message))
            raise ex.RegisterFloatingIpFailure(id=floating_ip.id)

        if r.status_code != 200 and r.status_code != 201:
            msg = "Unexpected status from unicorn API: Status Code %s, " \
                  "Message: %s" % (r.status_code, r.json())
            LOG.error("register_floating_ip: %s" % msg)
            raise ex.RegisterFloatingIpFailure(id=floating_ip.id)

    def update_floating_ip(self, floating_ip, port_fixed_ips):
        """Update an existing floating ip with Unicorn

        :param floating_ip: The quark.db.models.IPAddress to update
        :param port_fixed_ips: A dictionary containing the port and fixed ips
        to associate the floating IP with.  Has the structure of:
        {"<id of port>": {"port": <quark.db.models.Port>,
         "fixed_ip": "<fixed ip address>"}}
        :return: None
        """
        url = "%s/%s" % (CONF.QUARK.floating_ip_base_url,
                         floating_ip["address_readable"])
        timeout = CONF.QUARK.unicorn_api_timeout_seconds
        req = self._build_request_body(floating_ip, port_fixed_ips)

        try:
            LOG.info("Calling unicorn to update floating ip: %s %s"
                     % (url, req))
            r = requests.put(url, data=json.dumps(req), timeout=timeout)
        except Exception as e:
            LOG.error("Unhandled Exception caught when trying to update "
                      "floating ip %s with the unicorn API.  Error: %s"
                      % (floating_ip.id, e.message))
            raise ex.RegisterFloatingIpFailure(id=floating_ip.id)

        if r.status_code != 200 and r.status_code != 201:
            msg = "Unexpected status from unicorn API: Status Code %s, " \
                  "Message: %s" % (r.status_code, r.json())
            LOG.error("register_floating_ip: %s" % msg)
            raise ex.RegisterFloatingIpFailure(id=floating_ip.id)

    def remove_floating_ip(self, floating_ip):
        """Register a floating ip with Unicorn

        :param floating_ip: The quark.db.models.IPAddress to remove
        :return: None
        """
        url = "%s/%s" % (CONF.QUARK.floating_ip_base_url,
                         floating_ip.address_readable)
        timeout = CONF.QUARK.unicorn_api_timeout_seconds

        try:
            LOG.info("Calling unicorn to remove floating ip: %s" % url)
            r = requests.delete(url, timeout=timeout)
        except Exception as e:
            LOG.error("Unhandled Exception caught when trying to un-register "
                      "floating ip %s with the unicorn API.  Error: %s"
                      % (floating_ip.id, e.message))
            raise ex.RemoveFloatingIpFailure(id=floating_ip.id)

        if r.status_code == 404:
            LOG.warn("The floating IP %s does not exist in the unicorn system."
                     % floating_ip.address_readable)
        elif r.status_code != 204:
            msg = "Unexpected status from unicorn API: Status Code %s, " \
                  "Message: %s" % (r.status_code, r.json())
            LOG.error("remove_floating_ip: %s" % msg)
            raise ex.RemoveFloatingIpFailure(id=floating_ip.id)

    @classmethod
    def _build_fixed_ips(cls, port):
        fixed_ips = [{"ip_address": ip.address_readable,
                      "version": ip.version,
                      "subnet_id": ip.subnet.id,
                      "cidr": ip.subnet.cidr,
                      "address_type": ip.address_type}
                     for ip in port.ip_addresses
                     if (ip.get("address_type") == ip_types.FIXED)]
        return fixed_ips

    @classmethod
    def _build_endpoints(cls, port_fixed_ips):
        endpoints = []
        for port_id in port_fixed_ips:
            port = port_fixed_ips[port_id]["port"]
            fixed_ip = port_fixed_ips[port_id]["fixed_ip"]
            endpoint_port = {"uuid": port.id,
                             "name": port.name,
                             "network_uuid": port.network_id,
                             "mac_address": port.mac_address,
                             "device_id": port.device_id,
                             "device_owner": port.device_owner,
                             "fixed_ip": cls._build_fixed_ips(port)}
            endpoints.append({"port": endpoint_port,
                              "private_ip": fixed_ip.address_readable})
        return endpoints

    @classmethod
    def _build_request_body(cls, floating_ip, port_fixed_ips):
        content = {"public_ip": floating_ip["address_readable"],
                   "endpoints": cls._build_endpoints(port_fixed_ips)}
        return {"floating_ip": content}


import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import seaborn as sns
from PIL import Image
import os
# ignore warnings
import warnings
warnings.filterwarnings("ignore")
print(os.listdir("../input"))
train_len = len(os.listdir("../input/train"))
test_len = len(os.listdir("../input/test"))
print("Train size is {}, test size is {}".format(train_len, test_len))
train_df = pd.read_csv("../input/train_labels.csv")
train_df.head()
negative_cases_train = train_df[train_df["label"] == 0]
postive_cases_train = train_df[train_df["label"] == 1]
print("Postive cases {:,}, negative cases {:,} in training set".format(len(postive_cases_train), len(negative_cases_train)))
# now lets write a helper function to show some images
def show(df):
    fig, ax = plt.subplots(2,5, figsize=(20,5))
    for i, row in enumerate(df.itertuples()):
        path = os.path.join('../input/train/', row.id)
        img = Image.open(path+'.tif')
        w,h = img.size
        cropped = img.crop((w//2 - 32//2, h//2 - 32//2, w//2 + 32//2, h//2 + 32//2))
        box = patches.Rectangle((32,32),32,32,linewidth=2,edgecolor='r', facecolor='none')
        ax[0,i].imshow(img)
        ax[0,i].add_patch(box)
        ax[0,i].set_title("Label: {}".format(row.label))
        ax[1,i].imshow(cropped)
        ax[0,0].set_ylabel('Sample', size='large')
        ax[1,0].set_ylabel('Cropped', size='large')
show(negative_cases_train[0:5])
show(postive_cases_train[0:5])
def load(row):
    path = os.path.join('../input/train/', row.id)
    img = Image.open(path+'.tif')
    a = np.array(img)
    row['image'] = a
    row['image_flattened'] = a.flatten()
    return row
def distribution_plot(sample_size=100):
    neg_sample = train_df.loc[train_df.label == 0][0:sample_size]
    pos_sample = train_df.loc[train_df.label == 1][0:sample_size]
    neg_sample = neg_sample.apply(load, axis=1)
    pos_sample = pos_sample.apply(load, axis=1)
    print("Positive samples size {}".format(len(pos_sample)))
    print("Negative samples size {}".format(len(neg_sample)))
    neg = neg_sample.image_flattened.values.tolist()
    pos = pos_sample.image_flattened.values.tolist()
    plt.figure("Distribution")
    sns.distplot(np.concatenate(neg), label='Negative')
    sns.distplot(np.concatenate(pos), label='Positive')
    plt.legend()
    plt.show()
distribution_plot()
distribution_plot(1000)


# 몸무게와 키를 입력받고 BMI가 20.0이상이고 25미만이면
# 표준입니다 라고 출력을 하고 아니면 체중관리가 필요합니다 라고
# 출력하는 프로그램

# BMI = 몸무게 / (키 * 키)
# 키를 m로 환산해야 한다.

# 내 코드
weight = float(input('몸무게를 입력하세요 : '))
height = float(input('키를 입력하세요 : '))
BMI = weight / (height/100) ** 2
print('BMI 값 : ', BMI)

if 20.0 <= BMI < 25.0:
    print('몸무게가 표준입니다.')
else:
    print('체중관리가 필요합니다.')

# 풀이
height = float(input('키(cm)를 입력 : '))
weight = float(input('몸무게(kg)를 입력 : '))
height /= 100
BMI = weight / height ** 2
print('BMI 값 : ', BMI)

if BMI >= 20.0 and BMI <= 25.0:
    print('표준입니다.')
else:
    print('체중관리가 필요합니다.')


NOTAS = [0, 4, 3, 2]

NOMBRE = ["Hugo", "Jorge", "Haberto", "Larry"]
APELLIDO = ["Norrea", "Nitales", "Camelo", "Caverga"]

for i in range(len(NOMBRE)):
    print(NOMBRE[i], APELLIDO[i], NOTAS[i])
    if (NOTAS[i] < 3):
        print("perdio\n")
    else:
        print("paso\n")


from typing import List

from anytree import Node

def flatten(node: Node, attr: str = 'name') -> List[List]:
    result = []
    for child in node.children:
        if child.is_leaf:
            result.append([getattr(node, attr), getattr(child, attr)])
        else:
            result += [[getattr(node, attr)] + subpath for subpath in flatten(child, attr)]
    return result


import distro, math, numpy

def _solver(stats):
    (mu, sig2) = distro.extractStats(stats, [distro.Stat.Mu, distro.Stat.Sig2])
    m = mu
    s = math.sqrt(3*sig2/math.pi**2)
    return (m,s)

distro.register(
    name        = 'Logistic',
    domain      = distro.Domain.Continuous,
    params      = ('m','s'),
    paramSolver = _solver,
    cdf         = lambda x, m, s : 1/(1+math.exp(-(x-m)/s)),
    sample      = lambda m, s: numpy.random.logistic(m,s),
    fittingFns  = {
        distro.Stat.Skew: lambda m,s : 0,
        distro.Stat.Kurt: lambda m,s : 1.2+3,
        distro.Stat.Med:  lambda m,s : m
    }
)


# Updated Animation Starter Code from cs website
import time
from createStuff import *
from tkinter import *
from PIL import ImageTk,Image
from roads import *
from sideRoads import *
from intersections import *
from startScreen import *

#framework from cs website
def init(data, roads, intersecs, set, error, errorMsg):
    data.yellowTime = 1
    data.roads = roads
    #intersecs is a dictionary with keys = tuple of intersection location and
    #value = intersections. this way you can look up if an intersection
    #already exists
    data.intersecs = intersecs

    #drawing out your custom intersections
    data.increment = 20
    data.tmpStartX = 0
    data.tmpStartY = 0
    data.tmpEndX = data.tmpStartX
    data.tmpEndY = data.tmpStartY
    data.tmpDir = None
    data.rate = 4
    data.speedLim = 5

    data.tmpCar = None
    data.crashes = 0 #num times cars run into each other
    data.maxBack = 0
    data.weightBack = 1
    data.weightAvgWait = 1
    #timer
    data.t = 0

    #syntax for imgs from https://www.c-sharpcorner.com/blogs/basics-for-displaying-image-in-tkinter-python and from course website
    # images from https://www.google.com/url?sa=i&source=images&cd=&cad=rja&uact=8&ved=2ahUKEwjuxora1YrfAhXvwVkKHQXDCOkQjRx6BAgBEAU&url=https%3A%2F%2Fpixabay.com%2Fen%2Ftraffic-light-yellow-traffic-lights-149582%2F&psig=AOvVaw02XfkJTMU_gd2fvVC1QYNd&ust=1544167324032447

    data.yellowLightImg = PhotoImage(file="imgs/yellowLight.gif")
    data.redLightImg = PhotoImage(file="imgs/redLight.gif")
    data.greenLightImg = PhotoImage(file="imgs/greenLight.gif")

    # data.intersecRad = 40
    #     #center of the intersection
    # data.intersecX = data.width//2
    # data.intersecY = data.height//2
    #
    data.intersecRad = 40

    data.set = set

    data.screen = "startScreen"
    #screen can also be "setScreen"

    data.error = error
    data.errorMsg = errorMsg

def mousePressed(event, data):
    if data.set:
        mousePressedC (event, data)
def avgTimeSpentWaiting ():
    if SideIntersection.totalCars == 0:
        return None
    return SideIntersection.totalTimeWaiting/SideIntersection.totalCars

def curMaxBackup (data):
    m = 0
    for road in data.roads:
        roadBackup = road.backupNum()
        if  roadBackup > m:
            m = roadBackup
    return m

def keyPressed(event, data):
    if data.set:
        if data.screen == "startScreen":
            keyPressedStart (event, data)
        elif data.screen == "setScreen":
            keyPressedC (event, data)

    # if event.keysym == "d":
    #     print (SideIntersection.totalTimeWaiting)
    #     print (SideIntersection.totalCars)
    #     print (avgTimeSpentWaiting())

def timerFired(data):
    curMax = curMaxBackup (data)
    if curMax > data.maxBack:
        data.maxBack = curMax #update the maximum backup
    if not data.set:
        for road in data.roads:
            road.timerFiredRoad(data, time.time())
        for i in data.intersecs:
            data.intersecs[i].timerFiredIntersec (data)
        data.t += 1

def redrawAll(canvas, data):
    if not data.error:
        canvas.create_rectangle(0, 0, data.width, data.height,
                                    fill='black', width=0)
        drawTmp (canvas, data)
        for road in data.roads:
            road.drawAllRoad(canvas, data)
        if data.screen == "startScreen" and data.set:
            redrawAllStart(canvas, data)
        if not data.set:
            for i in data.intersecs:
                    data.intersecs[i].drawAllIntersec(data, canvas)
    else:
        canvas.create_text (data.width//8, data.height//4, text = data.errorMsg, fill = "red", font="Times 20 bold", anchor = "nw")

def setTheLights(data, lights):
    j = 0
    for i in data.intersecs:
        data.intersecs[i].NSTime = lights [j][0]
        data.intersecs[i].EWTime = lights [j][1]
        j += 1

####################################
# use the run function as-is from the 112 website
####################################

def run(set, width=300, height=300, lights = None, roads = [], intersecs = {}, error = False, errorMsg = "", slow = False):
    def redrawAllWrapper(canvas, data):

        canvas.delete(ALL)
        canvas.create_rectangle(0, 0, data.width, data.height,
                                fill='white', width=0)
        redrawAll(canvas, data)
        canvas.update()
    def inputRate ():
        data.rate= int(inputR.get())
    def inputSpeedLim ():
        data.speedLim = int(inputSpeedL.get())
    def inputWeightBack ():
        data.weightBack = int(inputWeightB.get())
    def inputWeightAvgWait ():
        data.weightAvgWait = int(inputWeightW.get())

    def mousePressedWrapper(event, canvas, data):
        mousePressed(event, data)
        redrawAllWrapper(canvas, data)

    def keyPressedWrapper(event, canvas, data):
        keyPressed(event, data)
        redrawAllWrapper(canvas, data)

    def timerFiredWrapper(canvas, data):
        timerFired(data)
        redrawAllWrapper(canvas, data)
        # pause, then call timerFired again
        canvas.after(data.timerDelay, timerFiredWrapper, canvas, data)
    # Set up data and call init
    class Struct(object): pass
    data = Struct()
    data.width = width
    data.height = height
    if not slow: data.timerDelay = 1 # milliseconds
    if slow: data.timerDelay = 20 # wtf this is faster teehee.... try making delay just increase m?
    root = Tk()
    #syntax for the background color from https://stackoverflow.com/questions/2744795/background-color-for-tk-in-python
    #function and button to close window from https://stackoverflow.com/questions/9987624/how-to-close-a-tkinter-window-by-pressing-a-button/9987684
    def close_window ():
        root.destroy()

    root ["bg"] = "black"
    root.resizable(width=False, height=False) # prevents resizing window
    init(data, roads, intersecs, set, error, errorMsg)

    #button and text syntax from Edward Lu (elu2)
    rateFrame = Frame (root, borderwidth = 2, relief = "solid")

    realRateFrame =  Frame (rateFrame, borderwidth = 2, relief = "solid")
    inputR = Entry (realRateFrame, borderwidth = 2, relief = "solid")
    buttonRate = Button (realRateFrame, command = inputRate, width = 20, height = 1,
        text = "secs between cars")
    speedFrame = Frame (rateFrame, borderwidth = 2, relief = "solid")
    inputSpeedL = Entry (speedFrame, borderwidth = 2, relief = "solid")
    buttonSpeed = Button (speedFrame, command = inputSpeedLim, width = 20, height = 1,
        text = "speed limit")
    weightBFrame = Frame (rateFrame, borderwidth = 2, relief = "solid")
    inputWeightB= Entry (weightBFrame, borderwidth = 2, relief = "solid")
    buttonWeightB = Button (weightBFrame, command = inputWeightBack, width = 20, height = 1,
        text = "weight # backup")
    weightWFrame = Frame (rateFrame, borderwidth = 2, relief = "solid")
    inputWeightW = Entry (weightWFrame, borderwidth = 2, relief = "solid")
    buttonWeightW = Button (weightWFrame, command = inputWeightAvgWait, width = 20, height = 1,
        text = "weight avg waitTime")

    if data.set:
        text = "done drawing roads"
    else:
        text = "new simulation"

    button = Button (rateFrame, text = text, width = 20, command = close_window)

    if not data.set:
        setTheLights(data, lights)
    # create the root and the canvas
    canvas = Canvas(root, width=data.width, height=data.height)
    canvas.configure(bd=0, highlightthickness=0)

    canvas.pack(side = RIGHT)
    if data.set:
        rateFrame.pack (side = LEFT, fill = Y)
        realRateFrame.pack (side = TOP)
        inputR.pack (side = TOP)
        buttonRate.pack (side = TOP)
        speedFrame.pack (side = TOP)
        inputSpeedL.pack (side = TOP)
        buttonSpeed.pack (side = TOP)
        weightBFrame.pack (side = TOP)
        inputWeightB.pack (side = TOP)
        buttonWeightB.pack (side = TOP)
        weightWFrame.pack (side = TOP)
        inputWeightW.pack (side = TOP)
        buttonWeightW.pack (side = TOP)

    rateFrame.pack (side = LEFT, fill = Y)
    button.pack (side = LEFT)

    # set up events
    root.bind("<Button-1>", lambda event:
                            mousePressedWrapper(event, canvas, data))
    root.bind("<Key>", lambda event:
                            keyPressedWrapper(event, canvas, data))
    timerFiredWrapper(canvas, data)
    # and launch the app
    # def destroy():
    #     #function to destroy window from https://stackoverflow.com/questions/8009176/function-to-close-the-window-in-tkinter
    #     root.destroy()
    root.quit()

    root.mainloop()  # blocks until window is closed
    if not data.set:
        return (SideIntersection.totalTimeWaiting, SideIntersection.totalCars, avgTimeSpentWaiting(), data.maxBack)
    else:
        replaceIntersections(data)
        return (data.roads, data.intersecs, data.error, data.errorMsg, data.weightBack, data.weightAvgWait)
    print("bye!")


#===============================================================================
# Imports
#===============================================================================

from ..util import (
    prompt_for_directory,
    list_directories_by_latest,
)

from ..wintypes import (
    cast,
    byref,
    errcheck,
    create_unicode_string,

    Union,
    Structure,

    CDLL,
    BOOL,
    USHORT,
    ULONG,
    PVOID,
    SIZE_T,
    HMODULE,
    SRWLOCK,
    POINTER,
    CFUNCTYPE,
    LIST_ENTRY,
    RTL_BITMAP,
    UNICODE_STRING,
    PUNICODE_STRING,
)

from .Allocator import (
    ALLOCATOR,
    PALLOCATOR,
    PPALLOCATOR,
    GET_OR_CREATE_GLOBAL_ALLOCATOR
)

from .Rtl import (
    PPRTL,
)

#===============================================================================
# Enums
#===============================================================================

TracerReleaseBinaries = 0
TracerDebugBinaries = 1
TracerPGInstrumentedBinaries = 3
TracerPGOptimizedBinaries = 4

#===============================================================================
# Globals
#===============================================================================
TRACER_REGISTRY_KEY = 'Software\\Tracer'

INTERMEDIATE_PATH = {
    TracerReleaseBinaries: 'x64\\Release',
    TracerDebugBinaries: 'x64\\Debug',
    TracerPGInstrumentedBinaries: 'x64\\PGInstrument',
    TracerPGOptimizedBinaries: 'x64\\PGOptimize',
}

#===============================================================================
# Aliases
#===============================================================================

#===============================================================================
# Helpers
#===============================================================================
def get_intermediate_path(winreg, key):

    load_debug = bool(winreg.QueryValueEx(key, 'LoadDebugLibraries')[0])
    load_pgi = bool(winreg.QueryValueEx(key, 'LoadPGInstrumentedLibraries')[0])
    load_pgo = bool(winreg.QueryValueEx(key, 'LoadPGOptimizedLibraries')[0])

    if load_pgo:
        index = TracerPGOptimizedBinaries
    elif load_pgi:
        index = TracerPGInstrumentedBinaries
    elif load_debug:
        index = TracerDebugBinaries
    else:
        index = TracerReleaseBinaries

    return INTERMEDIATE_PATH[index]

def get_tracer_config_dll_path():
    from ..path import join_path
    from ..util import import_winreg

    winreg = import_winreg()
    registry = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
    key = winreg.OpenKey(registry, TRACER_REGISTRY_KEY)

    intermediate_path = get_intermediate_path(winreg, key)

    installation_dir = winreg.QueryValueEx(key, 'InstallationDirectory')[0]
    winreg.CloseKey(key)

    dll_base_directory = join_path(installation_dir, intermediate_path)

    path = join_path(dll_base_directory, 'TracerConfig.dll')
    return path

def load_tracer_config_dll():
    path = get_tracer_config_dll_path()
    dll = CDLL(path)
    return dll

#===============================================================================
# Structures
#===============================================================================

class TRACER_PATHS(Structure):
    _fields_ = [
        ('SizeOfStruct', USHORT),
        ('NumberOfDllPaths', USHORT),
        ('NumberOfPtxPaths', USHORT),
        ('Padding', USHORT),
        ('InstallationDirectory', UNICODE_STRING),
        ('BaseTraceDirectory', UNICODE_STRING),
        ('PythonDirectory', UNICODE_STRING),
        ('DebuggerSettingsXmlPath', UNICODE_STRING),
        ('AsmDllPath', UNICODE_STRING),
        ('RtlDllPath', UNICODE_STRING),
        ('TracerCoreDllPath', UNICODE_STRING),
        ('PythonDllPath', UNICODE_STRING),
        ('TracerHeapDllPath', UNICODE_STRING),
        ('TraceStoreDllPath', UNICODE_STRING),
        ('DebugEngineDllPath', UNICODE_STRING),
        ('StringTableDllPath', UNICODE_STRING),
        ('PythonTracerDllPath', UNICODE_STRING),
        ('TlsTracerHeapDllPath', UNICODE_STRING),
        ('InjectionThunkDllPath', UNICODE_STRING),
        ('TracedPythonSessionDllPath', UNICODE_STRING),
        ('TraceStoreSqlite3ExtDllPath', UNICODE_STRING),
        ('PythonTracerInjectionDllPath', UNICODE_STRING),
        ('TraceStoreKernelsPtxPath', UNICODE_STRING),
        ('TracerInjectionDllsBitmap', RTL_BITMAP),
        ('TracerInjectionDlls', ULONG),
    ]
PTRACER_PATHS = POINTER(TRACER_PATHS)

class TRACER_FLAGS(Structure):
    _fields_ = [
        ('DebugBreakOnEntry', ULONG, 1),
        ('LoadDebugLibraries', ULONG, 1),
        ('LoadPGInstrumentedLibraries', ULONG, 1),
        ('LoadPGOptimizedLibraries', ULONG, 1),
        ('DisableTraceSessionDirectoryCompression', ULONG, 1),
        ('DisablePrefaultPages', ULONG, 1),
        ('DisableFileFlagOverlapped', ULONG, 1),
        ('DisableFileFlagSequentialScan', ULONG, 1),
        ('EnableFileFlagRandomAccess', ULONG, 1),
        ('EnableFileFlagWriteThrough', ULONG, 1),
        ('EnableWorkingSetTracing', ULONG, 1),
        ('EnablePerformanceTracing', ULONG, 1),
        ('EnableLoaderTracing', ULONG, 1),
        ('EnableSymbolTracing', ULONG, 1),
        ('EnableTypeInfoTracing', ULONG, 1),
        ('EnableAssemblyTracing', ULONG, 1),
        ('IgnoreModulesInWindowsSystemDirectory', ULONG, 1),
        ('IgnoreModulesInWindowsSxSDirectory', ULONG, 1),
        ('DisableAsynchronousInitialization', ULONG, 1),
        ('InjectionThunkDebugBreakOnEntry', ULONG, 1),
        ('TraceStoreSqlite3ModuleDebugBreakOnEntry', ULONG, 1),
    ]
PTRACER_FLAGS = POINTER(TRACER_FLAGS)

class TRACER_RUNTIME_PARAMETERS(Structure):
    _fields_ = [
        ('GetWorkingSetChangesIntervalInMilliseconds', ULONG),
        ('GetWorkingSetChangesWindowLengthInMilliseconds', ULONG),
        ('WsWatchInfoExInitialBufferNumberOfElements', ULONG),
        ('CapturePerformanceMetricsIntervalInMilliseconds', ULONG),
        ('CapturePerformanceMetricsWindowLengthInMilliseconds', ULONG),
        ('ConcurrentAllocationsCriticalSectionSpinCount', ULONG),
        ('IntervalFramesPerSecond', ULONG),
        ('Unused', ULONG),
    ]

class TRACE_SESSION_DIRECTORY(Structure):
    _fields_ = [
        ('ListEntry', LIST_ENTRY),
        ('Directory', UNICODE_STRING),
        ('Context', PVOID),
    ]
PTRACE_SESSION_DIRECTORY = POINTER(TRACE_SESSION_DIRECTORY)

class TRACE_SESSION_DIRECTORIES(Structure):
    _fields_ = [
        ('ListHead', LIST_ENTRY),
        ('Lock', SRWLOCK),
        ('Count', ULONG),
    ]
PTRACE_SESSION_DIRECTORIES = POINTER(TRACE_SESSION_DIRECTORIES)

class TRACER_CONFIG(Structure):
    _fields_ = [
        ('Size', USHORT),
        ('NumberOfElementsPerTraceStore', USHORT),
        ('SizeOfTraceStoreStructure', USHORT),
        ('Padding', USHORT),
        ('MaximumTraceStoreId', ULONG),
        ('MaximumTraceStoreIndex', ULONG),
        ('Flags', TRACER_FLAGS),
        ('RuntimeParameters', TRACER_RUNTIME_PARAMETERS),
        ('Allocator', PALLOCATOR),
        ('TlsTracerHeapModule', HMODULE),
        ('ListEntry', LIST_ENTRY),
        ('Paths', TRACER_PATHS),
        ('TraceSessionDirectories', TRACE_SESSION_DIRECTORIES),
        ('CuDeviceOrdinal', ULONG),
        ('Padding2', ULONG),
    ]

    def trace_store_directories(self):
        base = self.Paths.BaseTraceDirectory.Buffer
        return list_directories_by_latest(base)

    def choose_trace_store_directory(self):
        base = self.Paths.BaseTraceDirectory.Buffer
        return prompt_for_directory(base)

PTRACER_CONFIG = POINTER(TRACER_CONFIG)
PPTRACER_CONFIG = POINTER(PTRACER_CONFIG)

#===============================================================================
# Function Types
#===============================================================================

INITIALIZE_TRACER_CONFIG = CFUNCTYPE(
    PTRACER_CONFIG,
    PALLOCATOR,
    PUNICODE_STRING
)

CREATE_AND_INITIALIZE_TRACER_CONFIG_AND_RTL = CFUNCTYPE(
    BOOL,
    PALLOCATOR,
    PUNICODE_STRING,
    PPTRACER_CONFIG,
    PPRTL,
)

CREATE_AND_INITIALIZE_ALLOCATOR = CFUNCTYPE(BOOL, PPALLOCATOR)
GET_OR_CREATE_GLOBAL_ALLOCATOR = CFUNCTYPE(BOOL, PPALLOCATOR)

INITIALIZE_TRACER_CONFIG.errcheck = errcheck
CREATE_AND_INITIALIZE_TRACER_CONFIG_AND_RTL.errcheck = errcheck
CREATE_AND_INITIALIZE_ALLOCATOR.errcheck = errcheck
GET_OR_CREATE_GLOBAL_ALLOCATOR.errcheck = errcheck

DEBUG_BREAK = CFUNCTYPE(None)

#===============================================================================
# Binding
#===============================================================================

TracerConfigDll = load_tracer_config_dll()

CreateAndInitializeAllocator = CREATE_AND_INITIALIZE_ALLOCATOR(
    ('CreateAndInitializeDefaultHeapAllocator', TracerConfigDll),
    ((1, 'Allocator'),),
)

GetOrCreateGlobalAllocator = GET_OR_CREATE_GLOBAL_ALLOCATOR(
    ('GetOrCreateGlobalAllocator', TracerConfigDll),
    ((1, 'Allocator'),),
)

InitializeTracerConfig = INITIALIZE_TRACER_CONFIG(
    ('InitializeTracerConfig', TracerConfigDll),
    (
        (1, 'Allocator'),
        (1, 'RegistryKey'),
    ),
)

CreateAndInitializeTracerConfigAndRtl = (
    CREATE_AND_INITIALIZE_TRACER_CONFIG_AND_RTL(
        ('CreateAndInitializeTracerConfigAndRtl', TracerConfigDll),
        (
            (1, 'Allocator'),
            (1, 'RegistryKey'),
            (1, 'TracerConfig'),
            (1, 'Rtl'),
        ),
    )
)

_DebugBreak = DEBUG_BREAK(
    ('_DebugBreak', TracerConfigDll),
)

def load_tracer_config():
    allocator = PALLOCATOR()
    CreateAndInitializeAllocator(byref(allocator))
    registry_key = create_unicode_string(TRACER_REGISTRY_KEY)

    return InitializeTracerConfig(allocator, byref(registry_key)).contents

def load_tracer_config_and_rtl():
    allocator = PALLOCATOR()
    CreateAndInitializeAllocator(byref(allocator))
    registry_key = create_unicode_string(TRACER_REGISTRY_KEY)

    rtl = PRTL()
    tracer_config = PTRACER_CONFIG()

    success = CreateAndInitializeTracerConfigAndRtl(
        allocator,
        byref(registry_key),
        byref(tracer_config),
        byref(rtl),
    )

    return (tracer_config.contents, rtl.contents)

def debugbreak():
    _DebugBreak()

# vim:set ts=8 sw=4 sts=4 tw=80 ai et                                          :


"""
Números Primos
Para um número ser primo ele deve atender as regras:
1) Maior do que 1
2) Divisível apenas por 1 e Divisível apenas por ele mesmo

Encontre os numeros primos menor que 100
"""

numbers_primos = [
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
    43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
]
numbers_not_primos = [n for n in range(2, 100) if n not in numbers_primos]

qty_dividers = lambda number: len([n for n in range(1, 100) if (number % n) == 0])

def check_primo(number):
    return False if number < 1 else qty_dividers(number) == 2

if __name__ == '__main__':
    assert all(check_primo(n) for n in numbers_primos)
    assert not all(check_primo(n) for n in numbers_not_primos)


# This is based in large parts on the amazon_kclpy sample application:
# https://github.com/awslabs/amazon-kinesis-client-python/blob/master/samples/sample_kclpy_app.py

import time

from amazon_kclpy import kcl
from amazon_kclpy.v2 import processor

from miracle.bucket import create_bucket
from miracle.crypto import create_crypto
from miracle.log import (
    configure_logging,
    create_raven,
    create_stats,
)

CHECKPOINT_RETRIES = 4
CHECKPOINT_RETRY_WAIT = 1.5
CHECKPOINT_SECONDS = 60.0

def run_kcl_process(func, batch_size=None):  # pragma: no cover
    configure_logging()
    processor = RecordProcessor(func, batch_size=batch_size)
    kcl_process = Process(processor)
    kcl_process.run()

class Process(kcl.KCLProcess):

    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)
        self.raven = self.processor.raven

    def _perform_action(self, action):
        try:
            action.dispatch(self.checkpointer, self.processor)
        except Exception:
            self.raven.captureException()

class RecordProcessor(processor.RecordProcessorBase):

    def __init__(self, func, batch_size=None,
                 _bucket=None, _crypto=None, _raven=None, _stats=None):
        self.name = func.__module__ + ':' + func.__qualname__
        self.func = func.__get__(self)
        self.batch_size = batch_size if batch_size else 100
        self.last_checkpoint = None
        self.max_seq = (None, None)
        self.shard_id = None
        self.metric_tags = ['name:%s' % self.name, 'shard:%s' % self.shard_id]

        self.bucket = create_bucket(_bucket=_bucket)
        self.crypto = create_crypto(_crypto=_crypto)
        self.raven = create_raven(transport='threaded', _raven=_raven)
        self.stats = create_stats(_stats=_stats)

    def initialize(self, initialize_input):
        self.last_checkpoint = time.time()
        seq = initialize_input.sequence_number
        seq = int(seq) if seq is not None else None
        self.max_seq = (seq, initialize_input.sub_sequence_number)
        self.shard_id = initialize_input.shard_id
        self.metric_tags = ['name:%s' % self.name, 'shard:%s' % self.shard_id]
        try:
            self.bucket.ping(self.raven)
        except Exception:  # pragma: no cover
            self.raven.captureException()
            raise

    def _checkpoint(self, checkpointer, delay=CHECKPOINT_SECONDS, force=False):
        now = time.time()
        if ((now - self.last_checkpoint) < delay) and not force:
            return False

        for num in range(1, CHECKPOINT_RETRIES + 1):
            tags = self.metric_tags + ['try:%s' % num]
            try:
                with self.stats.timed('stream.checkpoint', tags=tags):
                    checkpointer.checkpoint(self.max_seq[0], self.max_seq[1])
                    self.last_checkpoint = time.time()
                return True
            except kcl.CheckpointError as exc:
                if not (exc.value == 'ThrottlingException' and
                        num < CHECKPOINT_RETRIES):
                    self.raven.captureException()
                    return False

            # Exponential backoff, at most 45 seconds in total.
            time.sleep((num ** 2) * delay)

    def _update_max_seq(self, seq, sub_seq):
        # seq can be None for a fresh shard
        seq = int(seq) if seq is not None else None
        # Coerce sub_seq to int, to avoid int/None comparisions
        sub_seq = sub_seq if sub_seq else 0
        if (self.max_seq == (None, None) or
                (seq is not None and seq > self.max_seq[0]) or
                (seq == self.max_seq[0] and sub_seq > self.max_seq[1])):
            self.max_seq = (seq, sub_seq)
            return True
        return False

    def process_records(self, process_records_input):
        try:
            records = process_records_input.records
            with self.stats.timed('stream.process', tags=self.metric_tags):
                for i in range(0, len(records), self.batch_size):
                    seq, sub_seq = self.func(records[i:i + self.batch_size])
                    self._update_max_seq(seq, sub_seq)

            self._checkpoint(process_records_input.checkpointer)
            self.stats.increment('stream.records',
                                 len(records), tags=self.metric_tags)
        except Exception:
            self.raven.captureException()

    def shutdown(self, shutdown_input):
        try:
            if shutdown_input.reason == 'TERMINATE':
                self._checkpoint(shutdown_input.checkpointer, force=True)
        except Exception:
            self.raven.captureException()


from telebot.types import CallbackQuery

from _bot import bot
from utils.db import AccountsDB

def delete_account(call: CallbackQuery, data: dict):
    doc_id = data['doc_id'][0]

    AccountsDB().remove(doc_id=doc_id)

    bot.edit_message_text(
        text=f'{call.message.html_text}\n\n'
             f'<b>账号已删除</b>',
        chat_id=call.from_user.id,
        message_id=call.message.message_id,
        parse_mode='HTML'
    )


"""
FileI/O - JSON Pickling!

It's just another data format, like CSV. It's anothe rway of
representing data. JSON was created to send JS code from one PC to another
over the web. It's now all over the place. Python even has a module called json
that we can import.

json.dumps() -- formats a python object as a STRING of JSON. It returns a STRING!
This means that None will be changed to null, single quotes will change to
double quotes, tuples will be turned to lists. Otherwise, it's basically the same.

Once in JSON, you could save it to a file by using file.write just using json.dumps(),
or create an API, etc. for a Java front end or backend could read.

However, this only works easily with BUILT-IN types . If we try to do it with a
custom class, it's much harder.

*** SCROLL DOWN FOR JSONPICKLE! ***

"""
# import json

# j = json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])

# print(j)  # This is easy since it's converting built-in types.

# Much harder if trying to do a custom class. It doesn't really know what to do.
# What you could do is:

import json

# class Cat:
#     def __init__(self, name, breed):
#         self.name = name
#         self.breed = breed
# c = Cat("Charles", "Tabby")

# j = json.dumps(c.__dict__)  # {"name": "Charles", "breed": "Tabby"}

"""
JSONPICKLE
If you want to be able to look at your pickled data, JSON isn't going to cut
it for us. Instead, you can look at jsonpickle module. Library that is like pickle
but instead it works with JSON. Serializes/de-serializes complex data into JSON.

jsonpickle.encode(object)
jsonpickle.decode()

The main difference btw Pickle is that the data is stored in a way that OTHER
languages could take it and parse this and use it if we needed to.

"""
import jsonpickle

class Cat:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed
#c = Cat("Charles", "Tabby")

#frozen = jsonpickle.encode(c)
#print(frozen)  # {"py/object": "__main__.Cat", "breed": "Tabby", "name": "Charles"}

# The __main__.Cat is useful. Let's first store into a file instead:
# with open("cat.json", "w") as file:
#     frozen = jsonpickle.encode(c)
#     file.write(frozen)
# The cat.json file now has: {"py/object": "__main__.Cat", "breed": "Tabby", "name": "Charles"}

# Next, the cool thing is when we want to DECODE (be sure to comment out ENCODE!):
with open("cat.json", "r") as file:
    contents = file.read()
    unfrozen = jsonpickle.decode(contents)
    print(unfrozen)  # <__main__.Cat object at 0x10ce63080>
# If our Cat Class had methods, we could start calling methods on this Cat object. COOL!


##### 编写一个程序，比较用户输入的文件是否相同，如果不同，显示出所有不同处的行号

#- f.readline()
#- open()
#- differ
file1 = input('请输入第一个文件名')
file2 = input('请输入第二个文件名')

def file_compare(file1,file2):
    f1 = open(file1)
    f2 = open(file2)

    count =  1#统计行数
    differ = []#统计不一样的数量
    for line1 in f1:

        line2=f2.readline()
        if line1 !=line2:
            differ.append(count)
        count+=1
    f1.close()
    f2.close()
    return  differ
differ = file_compare(file1,file2)
if len(differ) == 0:
    print('两个文件相同')
else:
    print('两个文件公有%d不同'%len(differ))
    for each in differ:
        print('第%d行不同'%each)


import pytest

from cohortextractor.expressions import format_expression, InvalidExpressionError

def test_basic_expression_rewritting():
    output, names = format_expression(
        "foo AND (bar > 3 OR baz = 'hello')",
        name_map={
            "foo": "table1.foo",
            "bar": "table2.bar",
            "baz": "other",
            "unused": "no",
        },
        empty_value_map={"foo": 0, "bar": 0, "baz": "", "unused": ""},
    )
    assert output == "( table1.foo != 0 ) AND ( table2.bar > 3 OR other = 'hello' )"
    assert names == {"foo", "bar", "baz"}

def test_validation():
    kwargs = dict(name_map={"a": "a", "b": "b"}, empty_value_map={"a": 0, "b": 0})
    with pytest.raises(InvalidExpressionError):
        format_expression("a AND AND b", **kwargs)
    with pytest.raises(InvalidExpressionError):
        format_expression("(a AND b", **kwargs)
    with pytest.raises(InvalidExpressionError):
        format_expression("a > > b", **kwargs)

def test_validate_string():
    kwargs = dict(name_map={}, empty_value_map={})
    with pytest.raises(ValueError):
        format_expression('"no spaces"', **kwargs)
    with pytest.raises(ValueError):
        format_expression('"no$special$chars"', **kwargs)
    with pytest.raises(ValueError):
        format_expression('"all_ok_characters_but_just_a_bit_too_long"', **kwargs)
    assert format_expression('"quoted"', **kwargs)[0] == "'quoted'"
    assert format_expression('""', **kwargs)[0] == "''"


"""
Implements the gridworld MDP.

Matthew Alger, 2015
matthew.alger@anu.edu.au
"""

import numpy as np
import numpy.random as rn
from . import human_model
from . import human_model1

class Crossworld(object):
    """
	Gridworld MDP.
	"""

    def __init__(self, discount, wind=0.2, behavegood=True):
        """
		grid_size: Grid size. int.
		wind: Chance of moving randomly. float.
		discount: MDP discount. float.
		-> Gridworld
		"""

        self.behave = behavegood
        self.actions = (0, 1, 2)

        self.n_actions = len(self.actions)
        self.grid_size = 10;  ##### assume 10 steps
        self.grid_size_h = 10;  # 10 grids for predestrain position
        self.grid_size_v = 3;  # 3 grids for predestrain velocity

        self.n_states = self.grid_size * self.grid_size_h * self.grid_size_v;
        self.wind = wind
        self.discount = discount

        # Preconstruct the transition probability array.
        self.transition_probability = np.array(
            [[[self._transition_probability(i, j, k)
               for k in range(self.n_states)]
              for j in range(self.n_actions)]
             for i in range(self.n_states)])

    def __str__(self):
        return "Gridworld({}, {}, {})".format(self.grid_size, self.wind,
                                              self.discount)

    def feature_vector(self, i, feature_map="ident"):
        """
		Get the feature vector associated with a state integer.

		i: State int.
		feature_map: Which feature map to use (default ident). String in {ident,
			coord, proxi}.
		-> Feature vector.
		"""

        if feature_map == "coord":
            f = np.zeros(self.grid_size)
            x, y = i % self.grid_size, i // self.grid_size
            f[x] += 1
            f[y] += 1
            return f
        if feature_map == "proxi":
            f = np.zeros(self.n_states)
            x, y = i % self.grid_size, i // self.grid_size
            for b in range(self.grid_size):
                for a in range(self.grid_size):
                    dist = abs(x - a) + abs(y - b)
                    f[self.point_to_int((a, b))] = dist
            return f
        # Assume identity map.
        f = np.zeros(self.n_states)
        f[i] = 1
        return f

    def feature_matrix(self, feature_map="ident"):
        """
		Get the feature matrix for this gridworld.

		feature_map: Which feature map to use (default ident). String in {ident,
			coord, proxi}.
		-> NumPy array with shape (n_states, d_states).
		"""

        features = []
        for n in range(self.n_states):
            f = self.feature_vector(n, feature_map)
            features.append(f)
        return np.array(features)

    def int_to_point(self, i):
        """
	  Convert a state int into the corresponding coordinate.

	  i: State int.
	  -> (x, y, v) int tuple.
	  (000)->(001)->(011)->(111)
	  """

        tempx = i // (self.grid_size_h * self.grid_size_v);
        tempy = (i % (self.grid_size_h * self.grid_size_v)) // self.grid_size_v;
        temyz = (i % (self.grid_size_h * self.grid_size_v)) % self.grid_size_v;
        return (tempx, tempy, temyz)

    def point_to_int(self, p):
        """
		Convert a coordinate into the corresponding state int.

		p: (x, y, v) tuple.
		-> State int.
		"""

        return p[0] * self.grid_size_h * self.grid_size_v + p[1] * self.grid_size_v + p[2]

    def neighbouring(self, i, k):
        """
		Get whether two points neighbour each other. Also returns true if they
		are the same point.

		-> bool.
		"""
        xi, pi, vi = self.int_to_point(i)
        xk, pk, vk = self.int_to_point(k)

        if xk >= xi and xk - xi <= 3 and (
                (pi + vi) == pk or (pi + vi > self.grid_size_h - 1 and pk == self.grid_size_h - 1)):
            return True
        return False

    def _transition_probability(self, i, j, k):
        """
		Get the probability of transitioning from state i to state k given
		action j.

		i: State int.
		j: Action int.
		k: State int.
		-> p(s_k | s_i, a_j)
		"""

        xi, pi, vi = self.int_to_point(i)
        yj = self.actions[j]
        xk, pk, vk = self.int_to_point(k)

        if not self.neighbouring(i, k):
            return 0.0

        accurate_prob = 0.8   ## self.wind is default as 0.2
        uncertain_0 = 1 - 0.8
        uncertain_1 = uncertain_0 / 2

        human_actions = 3

        if (xi == self.grid_size - 1 or xi + yj > self.grid_size - 1) and xk == self.grid_size - 1:
            return 1.0 / human_actions
        if xi + yj == self.grid_size - 1:
            if xk == self.grid_size - 1:
                return accurate_prob / human_actions
            elif xk == self.grid_size - 2:
                return uncertain_0 / human_actions

        if yj == 0:
            if xk == xi:
                return accurate_prob / human_actions
            elif xk - xi == 1:
                return uncertain_0 / human_actions
        elif yj == 1:
            if xk == xi:
                return uncertain_1 / human_actions
            elif xk - xi == 1:
                return accurate_prob / human_actions
            elif xk - xi == 2:
                return uncertain_1 / human_actions
        elif yj == 2:
            if xk - xi == 1:
                return uncertain_1 / human_actions
            elif xk - xi == 2:
                return accurate_prob / human_actions
            elif xk - xi == 3:
                return uncertain_1 / human_actions

        return 0.0

    # def reward(self, action_int, nextstate_int):
    # 	"""
    # 	Reward for being in state state_int.

    # 	state_int: State integer. int.
    # 	-> Reward.
    # 	"""
    # 	xi, pi, vi = self.int_to_point(nextstate_int)
    # 	if xi==(len(self.grid_size)-2) and (pi ==len(size)//2 or pi ==len(size)//2+1):
    # 		# if hit people, get a negative reward
    # 		if action_int==0:
    # 			return -51.0;
    # 		return -50.0
    # 	elif xi = len(self.grid_size)-1
    # 		# if reach the end, get a positive reward
    # 		if action_int==0:
    # 			return 4.0
    # 		return 5.0
    # 	if action_int==0:
    # 		return -1.0;

    # 	return 0.0

    def reward(self, nextstate_int):
        """
		Reward for being in state state_int.

		state_int: State integer. int.
		-> Reward.
		"""
        if self.behave:
            xi, pi, vi = self.int_to_point(nextstate_int)
            if xi == (self.grid_size - 3) and (pi == self.grid_size_h // 2 or pi == self.grid_size_h // 2 + 1):
                return -10
            if xi == (self.grid_size - 2) and (pi == self.grid_size_h // 2 or pi == self.grid_size_h // 2 + 1):
                # if hit people, get a negative reward
                return -20
            if xi == (self.grid_size - 2) and (pi == self.grid_size_h // 2 - 1):
                # if hit people, get a negative reward
                return -10

            elif xi == self.grid_size - 1:
                # if reach the end, get a positive reward
                return 5
            return 0
        else:
            xi, pi, vi = self.int_to_point(nextstate_int)
            if xi == (self.grid_size - 3) and (pi == self.grid_size_h // 2 or pi == self.grid_size_h // 2 + 1):
                return 10
            if xi == (self.grid_size - 2) and (pi == self.grid_size_h // 2 or pi == self.grid_size_h // 2 + 1):
                # if hit people, get a negative reward
                return 20
            if xi == (self.grid_size - 2) and (pi == self.grid_size_h // 2 - 1):
                # if hit people, get a negative reward
                return 10

            elif xi == self.grid_size - 1:
                # if reach the end, get a positive reward
                return -5
            return 0

    def average_reward(self, n_trajectories, trajectory_length, policy):
        """
		Calculate the average total reward obtained by following a given policy
		over n_paths paths.

		policy: Map from state integers to action integers.
		n_trajectories: Number of trajectories. int.
		trajectory_length: Length of an episode. int.
		-> Average reward, standard deviation.
		"""

        trajectories = self.generate_trajectories(n_trajectories,
                                                  trajectory_length, policy)
        rewards = [[r for _, _, r in trajectory] for trajectory in trajectories]
        rewards = np.array(rewards)

        # Add up all the rewards to find the total reward.
        total_reward = rewards.sum(axis=1)

        # Return the average reward and standard deviation.
        return total_reward.mean(), total_reward.std()

    def optimal_policy(self, state_int):
        """
		The optimal policy for this gridworld.

		state_int: What state we are in. int.
		-> Action int.
		"""

        sx, sy, sv = self.int_to_point(state_int)
        if sx == 8 and (sy == 4 or sy == 5):
            return 0
        else:
            return rn.randint(1, 3)

    def optimal_policy_deterministic(self, state_int):
        raise NotImplementedError(
            "Optimal policy is not implemented for crossworld.")

    def generate_trajectories(self, n_trajectories, trajectory_length, policy,
                              random_start=False):
        """
		Generate n_trajectories trajectories with length trajectory_length,
		following the given policy.

		n_trajectories: Number of trajectories. int.
		trajectory_length: Length of an episode. int.
		policy: Map from state integers to action integers.
		random_start: Whether to start randomly (default False). bool.
		-> [[(state int, action int, reward float)]]
		"""

        trajectories = []

        for _ in range(n_trajectories):
            if random_start:

                sx = rn.randint(self.grid_size)
                self.h1 = human_model.Human(rn.randint(0, 10), 0)
                sy, sv = self.h1.next_state()
            else:
                ### call human class
                if rn.random() < 0.5:
                    self.h1 = human_model.Human()
                else:
                    self.h1 = human_model.Human()

                sy, sv = self.h1.next_state()
                # print("position:",pos,"speed:",speed)
                sx = 0;

            trajectory = []
            for _ in range(trajectory_length):
                if rn.random() < self.wind:
                    action = self.actions[rn.randint(0, 3)]
                else:
                    # Follow the given policy.
                    action = self.actions[policy(self.point_to_int((sx, sy, sv)))]
                # print(action)
                if (0 <= sx + action < self.grid_size):
                    next_sx = sx + action
                    next_sy, next_sv = self.h1.next_state()
                # next_sy = sy
                # next_sv = sv
                else:
                    next_sx = sx
                    next_sy, next_sv = self.h1.next_state()

                state_int = self.point_to_int((sx, sy, sv))
                action_int = self.actions.index(action)
                next_state_int = self.point_to_int((next_sx, next_sy, next_sv))
                reward = self.reward(next_state_int)
                trajectory.append((state_int, action_int, reward))
                # print(next_sx,next_sy,next_sv)
                sx = next_sx
                sy = next_sy
                sv = next_sv

            trajectories.append(trajectory)
        # print("traj->\n")
        # print (sx)
        # print(np.array(trajectories)[:, 0, 0])

        ########################import real data#################

        # data = np.loadtxt("pass_disc_break_variables.txt", skiprows=0)
        # data = data.astype(np.int64)

        return np.array(trajectories)


from typing import List

from flask import Blueprint, render_template, request, jsonify
from flask_login import current_user

from configuration.main_configuration import logger
from src.decorator.admin_required import admin_required
from src.dto.ResponseLog import ResponseLog
from src.dto.SearchLogParameter import SearchLogParameter

admin_page = Blueprint('admin_page', __name__,
                       template_folder='templates')

@admin_page.route('/admin-panel', methods=["GET", "POST"])
@admin_required
def admin_panel_page():
    parameter = SearchLogParameter(" ", 1, " ")
    offset = 0
    response_log_list: List[ResponseLog] = logger.get_logs_by_parameters(offset, parameter)

    return render_template('admin_panel.html', log_list=response_log_list)

@admin_page.route('/admin-panel/load-more-posts')
@admin_required
def load_more_posts():
    page = request.args.get('page', 1, int)
    offset = int(page)

    parameter = SearchLogParameter(" ", 1, " ")
    response_log_list: List[ResponseLog] = logger.get_logs_by_parameters(offset, parameter)

    return jsonify(logs=list(map(lambda log: log.get_json(), response_log_list)))


import app
import uiPickMoney
import grp
import mouseModule
import player
import net
import offlineshop
import ui
import item
import dbg
import uiCommon
import uiToolTip
import localeInfo
import ime

import constInfo
import time
import chat

import uishopsearch
import uiofflineshop_history

try:
	app.WJ_ENABLE_TRADABLE_ICON
except Exception:
	app.WJ_ENABLE_TRADABLE_ICON = False

PAGE_MYSHOP = 0
PAGE_BUILDER = 1
PAGE_SAFEBOX = 2
PAGE_SHOP = 3
PAGE_HISTORY = 4

OFFLINESHOP_SLOT_COUNT = 10 * 8
CACHE_ITEMS_ID = {}

PATH_SHOP = "cream/"
PATH_ROOT = "cream/shopeditor/"
PATH_ROOT_BUILD = "cream/shopbuilder/"
PATH_ROOT_SEARCH = "cream/searchshop/"

def IsEditOrBuildMode():
	interface = offlineshop.GetOfflineshopBoard()
	if not interface:
		return False
	return interface.IsBuildingShop()

def IsBuildingShop():
	interface = offlineshop.GetOfflineshopBoard()
	if not interface:
		return False
	return interface.IsBuildingShop()

def IsSaleSlot(win,slot):
	interface = offlineshop.GetOfflineshopBoard()
	if not interface:
		return False

	return False

def MakeRadioButton(parent, x, y, path, up, over, down):
	button = ui.RadioButton()
	button.SetParent(parent)
	button.SetPosition(x, y)
	button.SetUpVisual(path + up)
	button.SetOverVisual(path + over)
	button.SetDownVisual(path + down)
	button.Show()
	return button

class OfflineShopRenewal(ui.ScriptWindow):
	def __init__(self, wndBind):
		ui.ScriptWindow.__init__(self)
		offlineshop.SetOfflineshopBoard(self)

		self.ShopSafeboxItems = []
		self.ShopSafeboxValuteAmount = 0
		self.ShopSafeboxValuteText = None
		self.shopOfflinePopup = None

		self.ShopItemForSale = []
		self.ShopItemSold = []

		self.ShopOpenInfo = {}

		self.wndOffShop = wndBind

	# NOTIFICATION FUNC
	def SendNotification(self, dwItemID, dwItemPrice, dwItemCount):
		item.SelectItem(dwItemID)
		itemName = item.GetItemName()

		if self.shopOfflinePopup == None:
			self.shopOfflinePopup = uiCommon.ShopOfflinePopup()

		self.shopOfflinePopup.AddNotification(dwItemID, itemName, dwItemPrice, dwItemCount)

	def ShopFilterResult(self , size):
		self.wndOffShop.wndSearchShop.ShopFilterResult(size)

	def ShopFilterResultItem_Alloc(self):
		self.wndOffShop.wndSearchShop.ShopFilterResultItem_Alloc()

	def ShopFilterResultItem_SetValue( self,  key, index, *args):
		self.wndOffShop.wndSearchShop.ShopFilterResultItem_SetValue(key, index, *args)

	def ShopFilterResult_Show(self):
		self.wndOffShop.wndSearchShop.ShopFilterResult_Show()

	def SearchFilter_BuyFromSearch(self, ownerid, itemid):
		self.wndOffShop.wndSearchShop.SearchFilter_BuyFromSearch(ownerid, itemid)

	def IsBuildingShop(self):
		if self.wndOffShop.IsShow() == False:
			return False

		return self.wndOffShop.wBoard[PAGE_BUILDER].IsShow() or self.wndOffShop.wBoard[PAGE_MYSHOP].IsShow()

	def ShopBuilding_AddItem(self, win, slot):
		if player.GetItemIndex(win, slot) ==0:
			return

		if win == player.INVENTORY and player.IsEquipmentSlot(slot):
			return

		if self.IsForSaleSlot(win, slot):
			return

		itemIndex = player.GetItemIndex(win, slot)
		if itemIndex == 0:
			return False

		item.SelectItem(itemIndex)

		_, size = item.GetItemSize()

		page, pos = self.wndOffShop.GetEmptyPosition(size)
		if pos < 0:
			return

		if self.__IsSaleableSlot(win, slot):
			price = self.wndOffShop.LoadInputPrice(player.GetItemIndex(win, slot))

			bCanSkipDlg = False
			self.wndOffShop.OpenInputPriceDialog(win, slot, page, pos, False, bCanSkipDlg)

	def IsForSaleSlot(self,win,slot):
		if self.wndOffShop.IsShow() == False:
			return

		if self.wndOffShop.wBoard[PAGE_BUILDER].IsShow():
			if self.wndOffShop.PriceInputBoard:
				if self.wndOffShop.PriceInputBoard.sourceWindowType == win and self.wndOffShop.PriceInputBoard.sourceSlotPos == slot:
					return True

			for page in xrange(2):
				for privatePos, (itemWindowType, itemSlotIndex, priceInfo) in self.wndOffShop.itemStockBuilder[page].items():
					if itemWindowType == win and itemSlotIndex == slot:
						return True
		elif self.wndOffShop.wBoard[PAGE_MYSHOP].IsShow():
			if self.wndOffShop.PriceInputBoard:
				if self.wndOffShop.PriceInputBoard.sourceWindowType == win and self.wndOffShop.PriceInputBoard.sourceSlotPos == slot:
					return True

		return False

	def __IsSaleableSlot(self, win , pos):
		if win == player.INVENTORY:
			if player.IsEquipmentSlot(pos):
				return False

		if self.IsBuildingShop() and self.IsForSaleSlot(win, pos):
			return False

		if not win in (player.INVENTORY, player.DRAGON_SOUL_INVENTORY):
			return False

		itemIndex = player.GetItemIndex(win,pos)
		if itemIndex == 0:
			return False

		item.SelectItem(itemIndex)
		if item.IsAntiFlag(item.ITEM_ANTIFLAG_MYSHOP) or item.IsAntiFlag(item.ITEM_ANTIFLAG_GIVE):
			return False

		return True

	def IsForAuctionSlot(self, win,slot):
		return False

	def IsBuildingAuction(self):
		return False

	def Destroy(self):
		self.ClearDictionary()

		self.wndOffShop = None
		self.shopOfflinePopup = None
		offlineshop.SetOfflineshopBoard(None)

	def OpenShop( self, owner_id, duration, count, name):
		self.ShopItemSold 		= []
		self.ShopItemForSale 	= []

		self.ShopOpenInfo["owner_id"]	= owner_id
		self.ShopOpenInfo["duration"]	= duration
		self.ShopOpenInfo["count"]		= count
		self.ShopOpenInfo["name"]		= name
		self.ShopOpenInfo["my_shop"]	= False

	def OpenShopItem_Alloc(self):
		self.ShopItemForSale.append({})

	def OpenShopItem_SetValue( self, key,	index,	*args):
		if key == "id":
			self.ShopItemForSale[index][key] = args[0]

		elif key == "vnum" or key == 'trans':
			self.ShopItemForSale[index][key] = args[0]

		elif key == "count":
			self.ShopItemForSale[index][key] = args[0]

		elif key == "attr":
			if not key in self.ShopItemForSale[index]:
				self.ShopItemForSale[index][key] = {}

			attr_index = args[0]
			attr_type  = args[1]
			attr_value = args[2]

			self.ShopItemForSale[index][key][attr_index] = {}
			self.ShopItemForSale[index][key][attr_index]["type"]  = attr_type
			self.ShopItemForSale[index][key][attr_index]["value"] = attr_value

		elif key == "socket":
			if not key in self.ShopItemForSale[index]:
				self.ShopItemForSale[index][key] = {}

			socket_index = args[0]
			socket_val	 = args[1]

			self.ShopItemForSale[index][key][socket_index] = socket_val

		elif key == "price":
			self.ShopItemForSale[index][key] = args[0]

	def OpenShop_End(self):
		self.wndOffShop.RefreshOpenShopPage()

		if not self.wndOffShop.IsShow():
			self.wndOffShop.Show()

	def OpenShopOwner_Start( self, owner_id, duration , count , name):
		self.ShopItemSold 		= []
		self.ShopItemForSale 	= []
		self.MyShopOffers		= []

		self.ShopOpenInfo["owner_id"]	= owner_id
		self.ShopOpenInfo["duration"]	= duration
		self.ShopOpenInfo["count"]		= count
		self.ShopOpenInfo["name"]		= name
		self.ShopOpenInfo["my_shop"]	= True

	def OpenShopOwner_End(self):
		self.wndOffShop.RefreshMyShopPage()

		if not self.wndOffShop.IsShow():
			self.wndOffShop.Show()

	def OpenShopOwnerItemSold_Alloc( self ):
		self.ShopItemSold.append({})

	def OpenShopOwnerItemSold_SetValue( self,  key , index , *args):
		if key == "id":
			self.ShopItemSold[index][key] = args[0]

		elif key == "vnum" or key == 'trans':
			self.ShopItemSold[index][key] = args[0]

		elif key == "count":
			self.ShopItemSold[index][key] = args[0]

		elif key == "attr":
			if not key in self.ShopItemSold[index]:
				self.ShopItemSold[index][key] = {}

			attr_index = args[0]
			attr_type  = args[1]
			attr_value = args[2]

			self.ShopItemSold[index][key][attr_index] = {}
			self.ShopItemSold[index][key][attr_index]["type"]  = attr_type
			self.ShopItemSold[index][key][attr_index]["value"] = attr_value

		elif key == "socket":
			if not key in self.ShopItemSold[index]:
				self.ShopItemSold[index][key] = {}

			socket_index = args[0]
			socket_val	 = args[1]

			self.ShopItemSold[index][key][socket_index] = socket_val

		elif key == "price":
			self.ShopItemSold[index][key] = args[0]

	def OpenShopOwnerItemSold_Show(self):
		pass

	def OpenShopOwnerItem_Alloc(self):
		self.ShopItemForSale.append({})

	def OpenShopOwnerItem_SetValue( self, key, index, *args):
		if key == "id":
			self.ShopItemForSale[index][key] = args[0]

		elif key == "vnum" or key == 'trans':
			self.ShopItemForSale[index][key] = args[0]

		elif key == "count":
			self.ShopItemForSale[index][key] = args[0]

		elif key == "attr":
			if not key in self.ShopItemForSale[index]:
				self.ShopItemForSale[index][key] = {}

			attr_index = args[0]
			attr_type  = args[1]
			attr_value = args[2]

			self.ShopItemForSale[index][key][attr_index] = {}
			self.ShopItemForSale[index][key][attr_index]["type"]  = attr_type
			self.ShopItemForSale[index][key][attr_index]["value"] = attr_value

		elif key == "socket":
			if not key in self.ShopItemForSale[index]:
				self.ShopItemForSale[index][key] = {}

			socket_index = args[0]
			socket_val	 = args[1]

			self.ShopItemForSale[index][key][socket_index] = socket_val

		elif key == "price":
			self.ShopItemForSale[index][key] = args[0]

	def OpenShopOwnerNoShop(self):
		for v in self.wndOffShop.wBoard.values():
			v.Hide()

		self.wndOffShop.ResetCreateShopPage()

		if not self.wndOffShop.IsShow():
			self.wndOffShop.Show()

	def ShopSafebox_Clear(self):
		self.ShopSafeboxItems = []

	def ShopSafebox_SetValutes(self, yang):
		self.ShopSafeboxValuteAmount = yang
		self.wndOffShop.wndTextYang.SetText("|cFF20B2AA" + localeInfo.NumberToMoneyString(yang))

	def ShopSafebox_AllocItem(self):
		self.ShopSafeboxItems.append({})

	def ShopSafebox_SetValue(self, key , *args):
		elm = self.ShopSafeboxItems[-1]

		if key in ("id", "vnum", "count", 'trans'):
			elm[key] = args[0]

		elif key == "socket":
			if not key in elm:
				elm[key] = [0 for x in xrange(player.METIN_SOCKET_MAX_NUM)]
			elm[key][args[0]] = args[1]

		elif key in ("attr_type", "attr_value"):
			if not 'attr' in elm:
				elm['attr'] = {}

			if not args[0] in elm['attr']:
				elm['attr'][args[0]] = {}

			elm['attr'][args[0]][key.replace('attr_','')] = args[1]

	def ShopSafebox_RefreshEnd(self):
		self.wndOffShop.RefreshSafeboxPage()

class OfflineShopWindow(ui.ScriptWindow):
	def __init__(self):
		ui.ScriptWindow.__init__(self)

		self.bIsLoaded = False

		self.wndShop = OfflineShopRenewal(self)
		self.wndShop.Hide()

		self.wndSearchShop = uishopsearch.ShopSearch()
		self.wndSearchShop.Hide()

		self.xShopStart = 0
		self.yShopStart = 0

		self.ShopOpenID = 0

		self.__Reinit()
		self.__Reinit2(True)
		self.__LoadWindow()

		self.SetCenterPosition()

	def SetItemToolTip(self, tooltip):
		self.tooltipItem = tooltip
		if self.wndHistory:
			self.wndHistory.SetItemToolTip(tooltip)

	def BindInterface(self, interface):
		self.interface = interface

		if self.wndSearchShop:
			self.wndSearchShop.SetInterface(interface)

	def __Reinit2(self, isDestroy = False):
		self.wBoard = {}
		self.wBar = {}
		self.dictName = {}
		self.itemStock = {}

		self.ClearStockBuilder(isDestroy)

	def __Reinit(self):
		self.MyShopEditNameDlg = None
		self.WithdrawQuestionDialog = None
		self.QuestionDialog = None
		self.PriceInputBoard = None
		self.ShopName = None
		self.tooltipItem = None
		self.interface = None

		self.PageGrid = 0

	def OnPressEscapeKey(self):
		if self.NameEdit.IsFocus():
			self.NameEdit.KillFocus()
			return False

		if self.QuestionDialog:
			if self.QuestionDialog.IsShow():
				return False

		if self.WithdrawQuestionDialog:
			return False

		self.Close()
		return True

	def Destroy(self):
		self.ClearDictionary()
		self.CloseDialogs(True)

		self.__Reinit()
		self.__Reinit2(True)

		if self.wndShop:
			self.wndShop.Destroy()
			self.wndShop = None

		if self.wndHistory:
			self.wndHistory.Clear()
			self.wndHistory.Destroy()
			self.wndHistory = None

		if self.wndSearchShop:
			self.wndSearchShop.Destroy()
			self.wndSearchShop.Hide()
			self.wndSearchShop = None

	def CloseDialogs(self, isDestroy=False):
		if self.WithdrawQuestionDialog:
			self.WithdrawQuestionDialog.Close()
			self.WithdrawQuestionDialog = None

		if self.QuestionDialog:
			self.OnCloseQuestionDialog()

		self.CancelInputPrice(isDestroy)

	def ClearStockBuilder(self, isDestroy=False):
		self.itemStockBuilder = {}
		self.itemStockBuilder[0] = {}
		self.itemStockBuilder[1] = {}
		self.itemStockBuilder[2] = {}
		self.itemStockBuilder[3] = {}

		self.RefreshItemSlotInv(isDestroy)

	if app.WJ_ENABLE_TRADABLE_ICON:
		def OnTop(self):
			if self.interface == None:
				return

			if self.wBoard[PAGE_BUILDER].IsShow() or self.wBoard[PAGE_MYSHOP].IsShow():
				self.interface.SetOnTopWindow(player.ON_TOP_WND_SHOP)
			else:
				self.interface.SetOnTopWindow(player.ON_TOP_WND_NONE)

			self.interface.RefreshMarkInventoryBag()

	def Close(self, isDestroy=False):
		self.CancelInputPrice()
		self.ClearStockBuilder(isDestroy)
		self.CloseDialogs(isDestroy)

		if app.WJ_ENABLE_TRADABLE_ICON:
			if self.interface:
				self.interface.SetOnTopWindow(player.ON_TOP_WND_NONE)
				if not isDestroy:
					self.interface.RefreshMarkInventoryBag()

		if self.MyShopEditNameDlg:
			self.MyShopEditNameDlg.Hide()
			self.MyShopEditNameDlg = None

		offlineshop.SendCloseBoard()
		self.Hide()

	def Open(self):
		offlineshop.SendCloseBoard()
		offlineshop.SendOpenShopOwner()

	def Show(self):
		self.__LoadWindow()
		ui.ScriptWindow.Show(self)

		self.SetTop()
		(self.xShopStart, self.yShopStart, z) = player.GetMainCharacterPosition()

	def __del__(self):
		ui.ScriptWindow.__del__(self)
		self.wndShop = None

	def __LoadWindow(self):
		if self.bIsLoaded:
			return

		self.bIsLoaded = True
		offlineshop.RefreshItemNameMap()

		self.AddFlag("movable")
		self.__InitPage(369, 410, PAGE_MYSHOP, "Edit Shop", PATH_ROOT_BUILD + "bg.dds")
		self.__InitPage(369, 405, PAGE_BUILDER, "Builder Private Shop", PATH_ROOT_BUILD + "bg.dds")
		self.__InitPage(369, 385, PAGE_SAFEBOX, "Safebox Shop", PATH_ROOT_BUILD + "bg.dds")
		self.__InitPage(369, 340, PAGE_SHOP, "Name's Shop", PATH_ROOT_BUILD + "bg.dds")
		self.__InitPage(320, 336 + 100, PAGE_HISTORY, "History Shop", PATH_ROOT_BUILD + "bg.dds")

		self.itemSlot = []
		for xPage in xrange(2):
			itemSlot = ui.GridSlotWindow()
			itemSlot.SetParent(self)
			itemSlot.SetPosition(23, 79)
			itemSlot.ArrangeSlot(0, 10, 8, 32, 32, 0, 0)
			itemSlot.SetSlotBaseImage("d:/ymir work/ui/public/Slot_Base.sub", 1.0, 1.0, 1.0, 1.0)

			itemSlot.SetSelectItemSlotEvent(ui.__mem_func__(self.SelectItemSlot))
			itemSlot.SetOverInItemEvent(ui.__mem_func__(self.OverInItem))
			itemSlot.SetOverOutItemEvent(ui.__mem_func__(self.OverOutItem))
			itemSlot.SetSelectEmptySlotEvent(ui.__mem_func__(self.SelectEmptySlot))
			itemSlot.SetUnselectItemSlotEvent(ui.__mem_func__(self.UseItemSlot))
			itemSlot.SetUseSlotEvent(ui.__mem_func__(self.UseItemSlot))
			itemSlot.SetGridSpecial(10, 8)
			itemSlot.Hide()

			if xPage == 0:
				itemSlot.Show()

			self.itemSlot.append(itemSlot)

	def __ChangePage(self, page):
		self.CancelInputPrice()

		for index in xrange(len(self.wBoard)):
			if not self.wBoard.has_key(index):
				continue

			if index == page:
				self.wBoard[page].Show()
				self.SetSize(self.wBoard[page].GetWidth(), self.wBoard[page].GetHeight())
			else:
				self.wBoard[index].Hide()

		for idxPage in xrange(len(self.dictPages)):
			if page == PAGE_HISTORY:
				break

			if page == PAGE_SHOP:
				self.dictPages[idxPage].SetPosition(17 + 27*idxPage, 35)
			elif page == PAGE_SAFEBOX:
				self.dictPages[idxPage].SetPosition(17 + 27*idxPage, 35)
			elif page == PAGE_BUILDER:
				self.dictPages[idxPage].SetPosition(17 + 27*idxPage, 35)
			else:
				self.dictPages[idxPage].SetPosition(35 + 30*idxPage, 351)

			self.dictPages[idxPage].SetParent(self.wBoard[page])

		if app.WJ_ENABLE_TRADABLE_ICON:
			self.OnTop()

		if page == PAGE_HISTORY:
			for slot in self.itemSlot:
				slot.Hide()

			self.wndHistory.Show()
		else:
			self.wndHistory.Hide()
			self.itemSlot[self.PageGrid].Show()

	def __InitPage(self, width, height, page, title, bg = PATH_ROOT + "bg.dds"):
		if page == PAGE_HISTORY:
			self.wBoard[page] = ui.Board()
			self.wBoard[page].SetParent(self)
			self.wBoard[page].SetSize(width, height)
			self.wBoard[page].AddFlag("not_pick")
			self.wBoard[page].Show()

		else:
			self.wBoard[page] = ui.ExpandedImageBox()
			self.wBoard[page].SetParent(self)
			self.wBoard[page].AddFlag("not_pick")
			self.wBoard[page].LoadImage(bg)
			self.wBoard[page].Show()

		self.wBar[page] = ui.TitleBar()
		self.wBar[page].SetParent(self.wBoard[page])
		self.wBar[page].MakeTitleBar(self.wBoard[page].GetWidth() - 12, "red")
		self.wBar[page].SetPosition(6, 6)
		self.wBar[page].SetCloseEvent(ui.__mem_func__(self.Close))
		self.dictName[page] = ui.MakeTextLineNew(self.wBar[page], 0, 4, title)
		self.dictName[page].SetWindowHorizontalAlignCenter()
		self.dictName[page].SetHorizontalAlignCenter()
		self.wBar[page].Show()

		self.SetSize(self.wBoard[page].GetWidth(), self.wBoard[page].GetHeight())

		if page == PAGE_BUILDER:
			self.NameSlotBar = ui.MakeImageBox(self.wBoard[page], PATH_ROOT_BUILD + "field_name.dds", 0, 35)
			self.NameSlotBar.SetWindowHorizontalAlignCenter()

			self.NameEdit = ui.EditLine()
			self.NameEdit.SetParent(self.NameSlotBar)
			self.NameEdit.SetMax(40)
			self.NameEdit.SetSize(self.NameSlotBar.GetWidth(), 15)
			self.NameEdit.SetPosition(8, 7)
			self.NameEdit.SetLimitWidth(self.NameEdit.GetWidth())
			self.NameEdit.SetEscapeEvent(ui.__mem_func__(self.OnPressNameEscapeKey))
			self.NameEdit.SetOutline()
			self.NameEdit.Show()

			self.btnGoSafeboxCRT = ui.MakeButton(self.wBoard[page], 315, 35, "Safebox", PATH_ROOT_BUILD, "btn_cosmetic_norm.dds", "btn_cosmetic_hover.dds", "btn_cosmetic_down.dds")
			self.btnCreateOk = ui.MakeButton(self.wBoard[page], 150, 350, False, PATH_ROOT_BUILD, "btn_norm.dds", "btn_hover.dds", "btn_down.dds")

			self.btnCreateOk.SetText("OK")

			self.btnGoSafeboxCRT.SetEvent(ui.__mem_func__(self.ManageWindow))
			self.btnCreateOk.SetEvent(ui.__mem_func__(self.OnCreateShop))
		elif page == PAGE_MYSHOP:
			self.wndSlotTotalYang = ui.MakeImageBox(self.wBoard[page], PATH_ROOT + "field_total_cost.dds", 20, 37)

			self.wndTotalPrice = ui.MakeTextLineNew(self.wndSlotTotalYang, 6, 7, "Total worth: |cffffcc00 Yang")
			self.wndTotalPrice.SetWindowHorizontalAlignLeft()
			self.wndTotalPrice.SetHorizontalAlignLeft()

			self.wndBoardRefill = ui.MakeImageBox(self.wBoard[page], PATH_ROOT + "field_time.dds", 155, 354)

			self.btnRefill = ui.MakeButton(self.wBoard[page], 155 - 30, 354, "Refill Time", PATH_ROOT, "btn_refill_time_norm.dds", "btn_refill_time_hover.dds", "btn_refill_time_down.dds")
			self.btnRefill.SetEvent(ui.__mem_func__(self.AskIncreaseTimeShop))

			self.wndRemainTime = ui.MakeTextLineNew(self.wndBoardRefill, 0, 6, "Left: 0 Day")
			self.wndRemainTime.SetWindowHorizontalAlignCenter()
			self.wndRemainTime.SetHorizontalAlignCenter()

			self.btnCloseShop = ui.MakeButton(self.wBoard[page], 315, 37, "Close Shop", PATH_ROOT, "btn_close_shop_norm.dds", "btn_close_shop_hover.dds", "btn_close_shop_down.dds")
			self.btnCloseShop.SetEvent(ui.__mem_func__(self.AskClosePrivateShop))

			self.btnChangeName = ui.MakeButton(self.wBoard[page], 275, 37, "Change Name", PATH_ROOT, "btn_teleport_norm.dds", "btn_teleport_hover.dds", "btn_teleport_down.dds")
			self.btnChangeName.SetEvent(ui.__mem_func__(self.ChangeNameShop))

			self.btnHistory = ui.MakeButton(self.wBoard[page], 235, 37, "History", PATH_ROOT, "btn_history_norm.dds", "btn_history_hover.dds", "btn_history_down.dds")
			self.btnHistory.SetEvent(ui.__mem_func__(self.ManageHistoryWindow))

			self.btnGoToSafebox = ui.MakeButton(self.wBoard[page], 196, 37, "Safebox", PATH_ROOT_BUILD, "btn_cosmetic_norm.dds", "btn_cosmetic_hover.dds", "btn_cosmetic_down.dds")
			self.btnGoToSafebox.SetEvent(ui.__mem_func__(self.ManageWindow))

			self.dictPages = {}

			self.dictPages[0] = MakeRadioButton(self.wBoard[page], 0, 0, PATH_SHOP + "pages/", "page_1_norm.png", "page_1_over.png", "page_1_down.png")
			self.dictPages[0].SetToolTipText("1. Inventory")

			self.dictPages[1] = MakeRadioButton(self.wBoard[page], 0, 0, PATH_SHOP + "pages/", "page_2_norm.png", "page_2_over.png", "page_2_down.png")
			self.dictPages[1].SetToolTipText("2. Inventory")

			for idxPage in xrange(len(self.dictPages)):
				self.dictPages[idxPage].SetEvent(ui.__mem_func__(self.SetPageGrid), idxPage)

			self.dictPages[0].Down()

		elif page == PAGE_SAFEBOX:
			self.btnGoBack = ui.MakeButton(self.wBoard[page], 315, 35, "Go Back", PATH_ROOT_BUILD, "btn_cosmetic_norm.dds", "btn_cosmetic_hover.dds", "btn_cosmetic_down.dds")
			self.btnGoBack.SetEvent(ui.__mem_func__(self.ManageWindow))

			self.btnWithdrawYang = ui.MakeButton(self.wBoard[page], 190, 355, False, PATH_ROOT_SEARCH, "btn_filter_norm.dds", "btn_filter_hover.dds", "btn_filter_down.dds")
			self.btnWithdrawYang.SetText("Pay Out Yang")

			self.btnWithdrawYang.SetEvent(ui.__mem_func__(self.WithdrawMoney))

			self.wndYangField = ui.MakeImageBox(self.wBoard[page], PATH_ROOT + "field_yang.dds", 30, 353)
			self.wndTextYang = ui.MakeTextLineNew(self.wndYangField, 8, 6, "|cFF20B2AA0 Yang")
			self.wndTextYang.SetWindowHorizontalAlignRight()
			self.wndTextYang.SetHorizontalAlignRight()
		elif page == PAGE_HISTORY:
			self.btnHistory2 = ui.MakeButton(self.wBoard[page], 23, 35, "Go Back", PATH_ROOT_BUILD, "btn_cosmetic_norm.dds", "btn_cosmetic_hover.dds", "btn_cosmetic_down.dds")
			self.btnHistory2.SetEvent(ui.__mem_func__(self.ManageHistoryWindow))

			self.wndHistory = uiofflineshop_history.HistoryWindow()
			self.wndHistory.SetParent(self.wBoard[page])
			self.wndHistory.SetSize(303, 336 - 89 + 100)
			self.wndHistory.SetPosition(8, 80)
			self.wndHistory.Hide()

			self.HistoryScrollBar = ui.ScrollBarNew()
			self.HistoryScrollBar.SetParent(self.wBoard[page])
			self.HistoryScrollBar.SetScrollBarSize(226 + 26 + 100)
			self.HistoryScrollBar.SetPosition(306, 79)
			self.wndHistory.SetScrollBar(self.HistoryScrollBar)
			self.HistoryScrollBar.Show()

			self.wndItemNameHistory = ui.MakeTextLineNew(self.wBoard[page], 16, 60, "ItemName")
			self.wndTimeHistory = ui.MakeTextLineNew(self.wBoard[page], 150, 60, "Reason")
			self.wndPriceHistory = ui.MakeTextLineNew(self.wBoard[page], 270, 60, "Price")

			self.wndNoSellHistory = ui.MakeTextLineNew(self.wBoard[page], 0, 200, "No items founded in history.")
			self.wndNoSellHistory.SetWindowHorizontalAlignCenter()
			self.wndNoSellHistory.SetHorizontalAlignCenter()
			self.wndNoSellHistory.Show()

	def OpenSearch(self):
		if self.wndSearchShop.IsShow() == False:
			self.wndSearchShop.Show()
		else:
			self.wndSearchShop.Hide()

	def ManageHistoryWindow(self):
		if self.wBoard[PAGE_MYSHOP].IsShow():
			self.__ChangePage(PAGE_HISTORY)
		else:
			self.__ChangePage(PAGE_MYSHOP)
			self.RefreshItemSlot()

	def ManageWindow(self):
		if self.wBoard[PAGE_SAFEBOX].IsShow():
			offlineshop.SendCloseBoard()
			offlineshop.SendOpenShopOwner()
		else:
			offlineshop.SendCloseBoard()
			offlineshop.SendSafeboxOpen()

	def SetPageGrid(self, page):
		if self.wBoard[PAGE_HISTORY].IsShow():
			return

		if page < 0 or page > 1:
			return

		self.PageGrid = page

		for idxPage in xrange(len(self.dictPages)):
			if idxPage == page:
				self.dictPages[idxPage].Down()
			else:
				self.dictPages[idxPage].SetUp()

		self.RefreshItemSlot()

	def ChangeNameShop(self):

		if self.MyShopEditNameDlg == None:
			self.MyShopEditNameDlg	= uiCommon.InputDialogWithDescription()
			self.MyShopEditNameDlg.SetMaxLength(35)
			self.MyShopEditNameDlg.SetDescription(localeInfo.OFFLINESHOP_EDIT_SHOPNAME_DESCRIPTION)
			self.MyShopEditNameDlg.SetAcceptEvent(self.__OnAcceptChangeShopNameDlg)
			self.MyShopEditNameDlg.SetCancelEvent(self.__OnCancelChangeShopNameDlg)
			self.MyShopEditNameDlg.SetTitle(localeInfo.OFFLINESHOP_EDIT_SHOPNAME_TITLE)

		self.MyShopEditNameDlg.inputValue.SetText("")
		self.MyShopEditNameDlg.Open()

	def __OnAcceptChangeShopNameDlg(self):
		newname = self.MyShopEditNameDlg.GetText()
		self.MyShopEditNameDlg.Hide()

		offlineshop.SendChangeName(newname)

	def __OnCancelChangeShopNameDlg(self):
		self.MyShopEditNameDlg.Hide()

	def OnPressNameEscapeKey(self):
		if self.OnPressEscapeKey():
			return

		if self.NameEdit.IsShowCursor() or self.NameEdit.GetText() != "":
			self.NameEdit.SetText("")
			self.NameEdit.SetEndPosition()

	def RefreshOpenShopPage(self):
		wasOpen = (self.IsShow() and self.wBoard[PAGE_SHOP].IsShow())

		name = self.wndShop.ShopOpenInfo["name"]
		ownerName	= name[:name.find('@')] if '@' in name else "NONAME"
		name		= name[name.find('@')+1:] if '@' in name else name

		if self.ShopOpenID != self.wndShop.ShopOpenInfo["owner_id"]: # FIXME_01
			self.SetPageGrid(0)

		self.ShopOpenID = self.wndShop.ShopOpenInfo["owner_id"] # FIXME_01

		self.dictName[PAGE_SHOP].SetText(ownerName + "'s Shop")
		self.__ChangePage(PAGE_SHOP)

		self.RefreshItemSlot()

		if len(self.wndShop.ShopItemForSale) <= 0:
			self.Close()
			return

	def RefreshMyShopPage(self):
		wasOpen = (self.wBoard[PAGE_MYSHOP].IsShow())
		self.__ChangePage(PAGE_MYSHOP)

		wndRemainTimeLeft = self.wndShop.ShopOpenInfo["duration"]
		self.wndRemainTime.SetText("|cffff6060Left: %s|r" % (localeInfo.SecondToDHM(wndRemainTimeLeft * 60)))

		name = self.wndShop.ShopOpenInfo["name"]

		if '@' in name:
			name = name[name.find('@')+1:]

		self.ShopName = name
		self.NameEdit.SetText(self.ShopName)

		self.RefreshItemSlot()

		self.wndHistory.Clear()
		self.HistoryScrollBar.Hide()

		if len(self.wndShop.ShopItemSold) == 0:
			self.wndNoSellHistory.Show()
		else:
			self.wndNoSellHistory.Hide()

		for idx, item in enumerate(self.wndShop.ShopItemSold):
			self.wndHistory.AppendItem(idx, item)

	def ResetCreateShopPage(self):
		self.ClearStockBuilder()

		self.__ChangePage(PAGE_BUILDER)
		self.RefreshItemSlot()

	def RefreshSafeboxPage(self):
		wasOpen = (self.wBoard[PAGE_SAFEBOX].IsShow())
		self.__ChangePage(PAGE_SAFEBOX)

		self.RefreshItemSlot()

	def SetPrivateShopBuilderItemNew(self, invenType, invenPos, price):
		itemVnum = player.GetItemIndex(invenType, invenPos)
		if 0 == itemVnum:
			return

		item.SelectItem(itemVnum)
		self.tooltipItem.ClearToolTip()
		self.tooltipItem.AppendSellingPrice(price)

		metinSlot = []
		for i in xrange(player.METIN_SOCKET_MAX_NUM):
			metinSlot.append(player.GetItemMetinSocket(invenPos, i))
		attrSlot = []
		for i in xrange(player.ATTRIBUTE_SLOT_MAX_NUM):
			attrSlot.append(player.GetItemAttribute(invenPos, i))

		self.tooltipItem.AddItemData(itemVnum, metinSlot, attrSlot)

	def OverInItem(self, slotIndex):
		if None == self.tooltipItem:
			return

		if self.wBoard[PAGE_BUILDER].IsShow():
			if slotIndex in self.itemStockBuilder[self.PageGrid]:
				window, pos, price = self.itemStockBuilder[self.PageGrid][slotIndex]
				self.SetPrivateShopBuilderItemNew(window, pos, price)
		elif slotIndex in self.itemStock:
			id, vnum, count, trans, price, sockets, attrs = self.itemStock[slotIndex]

			self.tooltipItem.ClearToolTip()
			self.tooltipItem.AddItemData(vnum, sockets, attrs)

			if self.wBoard[PAGE_SAFEBOX].IsShow() == False:
				self.tooltipItem.AppendPrice(price)

			if trans !=0 and trans != -1:
				self.tooltipItem.AppendTransmutation(0,0, trans)

			if self.wBoard[PAGE_MYSHOP].IsShow():
				self.tooltipItem.AppendSpace(5)
				self.tooltipItem.AppendTextLine("|Ekey_ctrl|e + |Ekey_rclick|e - Remove")

				self.tooltipItem.AppendSpace(5)
				self.tooltipItem.AppendTextLine("|Ekey_rclick|e - Edit Price")
			elif self.wBoard[PAGE_SAFEBOX].IsShow():
				self.tooltipItem.AppendSpace(5)
				self.tooltipItem.AppendTextLine("|Ekey_rclick|e - Get item")

	def OverOutItem(self):
		if None != self.tooltipItem:
			self.tooltipItem.HideToolTip()

	def GetEmptyPosition(self, size):
		for page in xrange(2):
			iPos = self.itemSlot[page].GetEmptyGrid(size)
			if iPos >= 0:
				return (page, iPos)

		return (-1, -1)

	def GetGridCachePosItemID(self, size, item_id):
		for page in xrange(len(self.itemSlot)):
			if not CACHE_ITEMS_ID.has_key(page):
				continue

			if CACHE_ITEMS_ID[page].has_key(item_id):
				return (page, CACHE_ITEMS_ID[page][item_id])

		return (self.GetEmptyPosition(size))

	def RefreshItemSlot(self):
		items = []
		if self.wBoard[PAGE_MYSHOP].IsShow() or self.wBoard[PAGE_SHOP].IsShow():
			items = self.wndShop.ShopItemForSale
		elif self.wBoard[PAGE_SAFEBOX].IsShow():
			items = self.wndShop.ShopSafeboxItems

		for itemSlotIdx in xrange(len(self.itemSlot)):
			for index in xrange(OFFLINESHOP_SLOT_COUNT):
				self.itemSlot[itemSlotIdx].ClearSlot(index)

			self.itemSlot[itemSlotIdx].ClearGrid()
			self.itemSlot[itemSlotIdx].Hide()

		self.itemSlot[self.PageGrid].Show()

		TotalPrice = 0
		self.itemStock = {}

		if self.wBoard[PAGE_BUILDER].IsShow():
			for page in xrange(2):
				for i in xrange(OFFLINESHOP_SLOT_COUNT):

					if not i in self.itemStockBuilder[page]:
						self.itemSlot[page].ClearSlot(i)
						continue

					window, pos, price = self.itemStockBuilder[page][i]
					vnum = player.GetItemIndex(window, pos)

					if vnum <= 0:
						continue

					self.itemSlot[page].SetItemSlot(i, vnum, player.GetItemCount(window, pos))

					item.SelectItem(vnum)
					_, size = item.GetItemSize()
					self.itemSlot[page].PutItemGrid(i, size)

			self.itemSlot[self.PageGrid].RefreshSlot()
			return

		for index in xrange(len(items)):
			itemVnum = items[index]["vnum"]
			itemCount = items[index]["count"]

			if itemVnum <= 0:
				continue

			item.SelectItem(itemVnum)
			_, size = item.GetItemSize()

			PageItemSlot, iPos = self.GetGridCachePosItemID(size, items[index]["id"])

			if iPos < 0:
				chat.AppendChat(1, "Some items may to not show on grid, the reason should be insufficient space.")
				return

			self.itemSlot[PageItemSlot].PutItemGrid(iPos, size)

			itemCountGrid = itemCount if itemCount > 1 else 0
			self.itemSlot[PageItemSlot].SetItemSlot(iPos, itemVnum, itemCountGrid)

			sockets = [items[index]["socket"][num] for num in xrange(player.METIN_SOCKET_MAX_NUM)]
			attrs	= [(items[index]["attr"][num]['type'], items[index]["attr"][num]['value']) for num in xrange(player.ATTRIBUTE_SLOT_MAX_NUM)]

			ItemPrice = 0
			if items[index].has_key("price"):
				ItemPrice = int(items[index]["price"])
				TotalPrice += int(items[index]["price"])

			transmutation = 0
			if items[index].has_key("trans"):
				transmutation = items[index]["trans"]

			if PageItemSlot == self.PageGrid:
				self.itemStock[iPos] = (items[index]["id"], itemVnum, itemCount, transmutation, ItemPrice, sockets, attrs)

			if not CACHE_ITEMS_ID.has_key(PageItemSlot):
				CACHE_ITEMS_ID[PageItemSlot] = {}

			CACHE_ITEMS_ID[PageItemSlot][items[index]["id"]] = iPos

		self.wndTotalPrice.SetText("|cFFF1E6C0Total worth: |cffffcc00" + str(localeInfo.NumberToMoneyString(TotalPrice)))

		if self.PriceInputBoard and self.wBoard[PAGE_MYSHOP].IsShow():
			CurrentPageGrid = self.PriceInputBoard.CurrentPageGrid
			targetSlotPos = self.PriceInputBoard.targetSlotPos
			isEditMode = self.PriceInputBoard.isEditMode

		self.itemSlot[self.PageGrid].RefreshSlot()

	def SelectItemSlot(self, itemSlotIndex):
		if constInfo.GET_ITEM_QUESTION_DIALOG_STATUS() == 1:
			return

		if mouseModule.mouseController.isAttached():
			mouseModule.mouseController.DeattachObject()

		if self.itemStock.has_key(itemSlotIndex) == False:
			return

		if self.wBoard[PAGE_BUILDER].IsShow():
			return

		id, vnum, count, trans, price, sockets_v, attrs_s = self.itemStock[itemSlotIndex]
		if app.IsCanOpenRender() and app.ENABLE_RENDER_TARGET:
			self.interface.OpenRenderTargetWindow(0, player.GetItemIndex(itemSlotIndex))

		if self.wBoard[PAGE_MYSHOP].IsShow() or self.wBoard[PAGE_SAFEBOX].IsShow():
			if app.IsPressed(app.DIK_LALT):
				sockets = {}
				for num in xrange(player.METIN_SOCKET_MAX_NUM):
					sockets[num] = (int(sockets_v[num]), 1)

				attrs = {}
				for num in xrange(player.ATTRIBUTE_SLOT_MAX_NUM):
					attrs[num] = (int(attrs_s[num][0]), int(attrs_s[num][1]))

				#link = player.GetItemShopOfflineLink(vnum, sockets, attrs)
				ime.PasteString(link)

	def UseItemSlot(self, slotIndex):
		if constInfo.GET_ITEM_QUESTION_DIALOG_STATUS() == 1:
			return

		if mouseModule.mouseController.isAttached():
			mouseModule.mouseController.DeattachObject()

		if self.QuestionDialog:
			self.OnCloseQuestionDialog()

		if self.wBoard[PAGE_BUILDER].IsShow():
			if slotIndex in self.itemStockBuilder[self.PageGrid]:
				invenType, invenPos, price = self.itemStockBuilder[self.PageGrid][slotIndex]
				del self.itemStockBuilder[self.PageGrid][slotIndex]

				self.RefreshItemSlot()
				self.RefreshItemSlotInv()
			return
		else:
			if self.itemStock.has_key(slotIndex) == False:
				return

			id, vnum, count, trans, price, sockets, attrs = self.itemStock[slotIndex]

			if self.wBoard[PAGE_SAFEBOX].IsShow():
				offlineshop.SendSafeboxGetItem(id)
				self.ClearCachePos(self.PageGrid, id)
				return

			if self.wBoard[PAGE_MYSHOP].IsShow() and (app.IsPressed(app.DIK_LCONTROL) or app.IsPressed(app.DIK_RCONTROL)) == False:
				self.OpenInputPriceDialog(vnum, count, id, slotIndex, True)
				return

			item.SelectItem(vnum)
			QuestionDialog = uiCommon.QuestionDialog()

			if self.wBoard[PAGE_SHOP].IsShow():
				if count > 1:
					text = "Do you want to buy %s %dx for %s?" % (item.GetItemName(), count, localeInfo.NumberToMoneyString(price))
				else:
					text = "Do you want to buy %s for %s?" % (item.GetItemName(), localeInfo.NumberToMoneyString(price))
			elif self.wBoard[PAGE_MYSHOP].IsShow():
				offlineshop.SendRemoveItem(id)
				self.ClearCachePos(self.PageGrid, id)
				return
			else:
				return

			QuestionDialog.SetText(text)
			QuestionDialog.SetAcceptEvent(ui.__mem_func__(self.OnCancelShopItem))
			QuestionDialog.SetCancelEvent(ui.__mem_func__(self.OnCloseQuestionDialog))
			QuestionDialog.Open()
			self.QuestionDialog = QuestionDialog
			self.QuestionDialog.slotIndex = slotIndex
			self.QuestionDialog.itemStock = self.itemStock[slotIndex]

		constInfo.SET_ITEM_QUESTION_DIALOG_STATUS(1)

	def OnCancelShopItem(self):
		if not self.QuestionDialog:
			return True

		id, vnum, count, trans, price, sockets, attrs = self.QuestionDialog.itemStock

		if self.wBoard[PAGE_MYSHOP].IsShow():
			offlineshop.SendRemoveItem(id)
			self.ClearCachePos(self.PageGrid, id)
		elif self.wBoard[PAGE_SHOP].IsShow():
			offlineshop.SendBuyItem(self.wndShop.ShopOpenInfo["owner_id"], id)
		else:
			offlineshop.SendSafeboxGetItem(id)
			self.ClearCachePos(self.PageGrid, id)

		constInfo.SET_ITEM_QUESTION_DIALOG_STATUS(0)
		self.OnCloseQuestionDialog()
		return True

	def OnCloseQuestionDialog(self):
		if self.QuestionDialog == None:
			return

		self.QuestionDialog.Close()

		self.QuestionDialog.itemStock = None
		self.QuestionDialog = None
		constInfo.SET_ITEM_QUESTION_DIALOG_STATUS(0)

	def SelectEmptySlot(self, selectedSlotPos):
		if self.wBoard[PAGE_SAFEBOX].IsShow() or self.wBoard[PAGE_SHOP].IsShow():
			self.OverOutItem()
			if mouseModule.mouseController.isAttached():
				mouseModule.mouseController.DeattachObject()
			return

		isAttached = mouseModule.mouseController.isAttached()
		if isAttached:
			attachedSlotType = mouseModule.mouseController.GetAttachedType()
			attachedSlotPos = mouseModule.mouseController.GetAttachedSlotNumber()
			mouseModule.mouseController.DeattachObject()

			attachedInvenType = player.SlotTypeToInvenType(attachedSlotType)
			self.OpenInputPriceDialog(attachedInvenType, attachedSlotPos, self.PageGrid, selectedSlotPos)

			if app.ENABLE_SPECIAL_STORAGE_SYSTEM:
				if player.SLOT_TYPE_INVENTORY != attachedSlotType and\
					player.SLOT_TYPE_DRAGON_SOUL_INVENTORY != attachedSlotType and\
					player.SLOT_TYPE_SKILLBOOK_INVENTORY != attachedSlotType and\
					player.SLOT_TYPE_UPPITEM_INVENTORY != attachedSlotType and\
					player.SLOT_TYPE_GHOSTSTONE_INVENTORY != attachedSlotType and\
					player.SLOT_TYPE_GENERAL_INVENTORY != attachedSlotType:
					return

	def OpenInputPriceDialog(self, window, slot, page, EmptyGridPos, editMode = False, skipDlg = False):
		if self.PriceInputBoard:
			return

		if editMode == False:
			itemVNum = player.GetItemIndex(window, slot)
			itemCount = player.GetItemCount(window, slot)
			item.SelectItem(itemVNum)

			if item.IsAntiFlag(item.ANTIFLAG_GIVE) or item.IsAntiFlag(item.ANTIFLAG_MYSHOP):
				chat.AppendChat(chat.CHAT_TYPE_INFO, localeInfo.PRIVATE_SHOP_CANNOT_SELL_ITEM)
				return
		else:
			itemVNum = window
			itemCount = slot

		PriceInputBoard = uiCommon.MoneyInputDialogNew(itemVNum)
		PriceInputBoard.SetAcceptEvent(ui.__mem_func__(self.AcceptInputPrice))
		PriceInputBoard.SetCancelEvent(ui.__mem_func__(self.CancelInputPrice))
		PriceInputBoard.Open()

		self.PriceInputBoard = PriceInputBoard
		self.PriceInputBoard.itemVNum = itemVNum
		self.PriceInputBoard.sourceWindowType = window
		self.PriceInputBoard.sourceSlotPos = slot
		self.PriceInputBoard.targetSlotPos = EmptyGridPos
		self.PriceInputBoard.page = page
		self.PriceInputBoard.CurrentPageGrid = self.PageGrid

		self.PriceInputBoard.isEditMode = editMode

		if editMode == False:
			price = self.LoadInputPrice(player.GetItemIndex(window, slot))
			count = player.GetItemCount(window, slot)

			if price > 0:
				if count > 1:
					self.PriceInputBoard.SetValue(str(price*count))
				else:
					self.PriceInputBoard.SetValue(str(price))

				self.PriceInputBoard.inputValue.SetEndPosition()

		self.RefreshItemSlotInv()

		if skipDlg:
			self.AcceptInputPrice()

	def AcceptInputPrice(self):
		if not self.PriceInputBoard:
			return True

		Text = self.PriceInputBoard.inputValue.GetText()

		if not Text:
			return True

		if int(Text) <= 0:
			return True

		attachedInvenType = self.PriceInputBoard.sourceWindowType
		sourceSlotPos = self.PriceInputBoard.sourceSlotPos
		targetSlotPos = self.PriceInputBoard.targetSlotPos
		targetPage = self.PriceInputBoard.page
		isEditMode = self.PriceInputBoard.isEditMode

		yang = long(Text)
		count = player.GetItemCount(attachedInvenType, sourceSlotPos)
		if count > 1:
			yang = yang/count
		else:
			yang

		self.SaveInputPrice(player.GetItemIndex(attachedInvenType, sourceSlotPos), yang)

		self.OverOutItem()

		if self.wBoard[PAGE_BUILDER].IsShow():
			for page in xrange(2):
				for privatePos, (itemWindowType, itemSlotIndex, priceInfo) in self.itemStockBuilder[page].items():
					if itemWindowType == attachedInvenType and itemSlotIndex == sourceSlotPos:
						del self.itemStockBuilder[page][privatePos]

			self.itemStockBuilder[targetPage][targetSlotPos] = (attachedInvenType, sourceSlotPos, long(Text))
		else:
			if isEditMode:
				offlineshop.SendEditItem(self.PriceInputBoard.page, long(Text))
			else:
				offlineshop.SendAddItem(attachedInvenType,  sourceSlotPos, long(Text))

		self.PriceInputBoard = None

		self.RefreshItemSlot()
		self.RefreshItemSlotInv()
		return True

	def RefreshItemSlotInv(self, isDestroy=False):
		if isDestroy:
			return

		if self.interface == None:
			return

		if self.interface.wndInventory:
			self.interface.wndInventory.RefreshItemSlot()

		# if self.interface.wndSpecialStorage:
			# self.interface.wndSpecialStorage.RefreshItemSlot()

	def CancelInputPrice(self, isDestroy = False):
		if self.PriceInputBoard:
			self.PriceInputBoard.Destroy()

		self.PriceInputBoard = None

		if not isDestroy:
			self.RefreshItemSlot()
			self.RefreshItemSlotInv()
		return True

	def SaveInputPrice(self, vnum, price):
		import os
		path = "offlineshop"

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

		n = path + "/" + str(vnum) + ".txt"
		f = file(n, "w+")
		f.write(str(price))
		f.close()

	def LoadInputPrice(self, vnum):
		import os
		path = "offlineshop"

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

		oldPrice = 0

		n = path + "/" + str(vnum) + ".txt"

		if os.path.exists(n):
			fd = open( n,'r')
			oldPrice = int(fd.readlines()[0])

		return oldPrice

	def AskClosePrivateShop(self):
		if self.QuestionDialog:
			self.OnCloseQuestionDialog()

		if not self.QuestionDialog:
			QuestionDialog = uiCommon.QuestionDialog()
			QuestionDialog.SetText(localeInfo.PRIVATE_SHOP_CLOSE_QUESTION)
			QuestionDialog.SetAcceptEvent(ui.__mem_func__(self.OnClosePrivateShop))
			QuestionDialog.SetCancelEvent(ui.__mem_func__(self.OnCloseQuestionDialog))
			self.QuestionDialog = QuestionDialog

		self.QuestionDialog.Open()
		return True

	def OnClosePrivateShop(self):
		offlineshop.SendForceCloseShop()
		global CACHE_ITEMS_ID
		CACHE_ITEMS_ID = {}
		constInfo.SET_ITEM_QUESTION_DIALOG_STATUS(0)
		self.OnCloseQuestionDialog()
		return True

	def WithdrawMoney(self):
		if self.WithdrawQuestionDialog:
			return

		shopMoney = self.wndShop.ShopSafeboxValuteAmount
		if shopMoney <= 0:
			return

		WithdrawQuestionDialog = uiCommon.MoneyInputDialog()
		WithdrawQuestionDialog.SetTitle(localeInfo.EXCHANGE_MONEY)
		WithdrawQuestionDialog.SetMoneyHeaderText("Sum: ")
		WithdrawQuestionDialog.SetAcceptEvent(ui.__mem_func__(self.SumWithdraw))
		WithdrawQuestionDialog.SetCancelEvent(ui.__mem_func__(self.CloseSumWithdraw))
		WithdrawQuestionDialog.Open()
		WithdrawQuestionDialog.SetMaxLength(len(str(shopMoney)))
		WithdrawQuestionDialog.SetValue(shopMoney)
		WithdrawQuestionDialog.inputValue.SetEndPosition()

		self.WithdrawQuestionDialog = WithdrawQuestionDialog

	def SumWithdraw(self):
		if not self.WithdrawQuestionDialog:
			return

		shopMoney = int(self.WithdrawQuestionDialog.GetText())

		if len(self.WithdrawQuestionDialog.GetText()) <= 0:
			return

		if int(self.WithdrawQuestionDialog.GetText()) > self.wndShop.ShopSafeboxValuteAmount:
			shopMoney = self.wndShop.ShopSafeboxValuteAmount

		offlineshop.SendSafeboxGetValutes(shopMoney)

		self.WithdrawQuestionDialog.Close()
		self.WithdrawQuestionDialog = None

	def CloseSumWithdraw(self):
		if not self.WithdrawQuestionDialog:
			return False

		self.WithdrawQuestionDialog.Close()
		self.WithdrawQuestionDialog = None
		return True

	def OnCreateShop(self):
		if not self.NameEdit.GetText():
			return

		if 0 == len(self.itemStockBuilder):
			return

		itemLst = []

		for page in xrange(4):
			for privatePos, (itemWindowType, itemSlotIndex, itemPrice) in self.itemStockBuilder[page].items():
				tupleinfo = (itemWindowType, itemSlotIndex, itemPrice)
				itemLst.append(tupleinfo)

		if (len(itemLst) == 0):
			chat.AppendChat(1, "You can't create an empty shop")
			return

		totaltime = 7200 # 5Days

		itemTuple = tuple(itemLst)
		offlineshop.SendShopCreate(self.NameEdit.GetText(), totaltime, 30000, itemTuple)

	def OnUpdate(self):
		if self.wBoard[PAGE_SHOP].IsShow():
			USE_SHOP_LIMIT_RANGE = 1500

			(x, y, z) = player.GetMainCharacterPosition()
			if abs(x - self.xShopStart) > USE_SHOP_LIMIT_RANGE or abs(y - self.yShopStart) > USE_SHOP_LIMIT_RANGE:
				self.Close()

	def AskIncreaseTimeShop(self):
		if self.QuestionDialog:
			self.OnCloseQuestionDialog()

		if not self.QuestionDialog:
			QuestionDialog = uiCommon.QuestionDialog()
			QuestionDialog.SetText("Do you want to refill time with 1 day for 1kk?")
			QuestionDialog.SetAcceptEvent(ui.__mem_func__(self.OnRefillShopTime))
			QuestionDialog.SetCancelEvent(ui.__mem_func__(self.OnCloseQuestionDialog))
			self.QuestionDialog = QuestionDialog

		self.QuestionDialog.Open()
		return True

	def GetMaxRefill(self, ex_day):
		while True:
			if self.wndShop.ShopOpenInfo["duration"] + ex_day > 7200:
				ex_day -= 1
				continue

			break

		return ex_day

	def OnRefillShopTime(self):
		Extend1Day = self.GetMaxRefill(1440)

		if Extend1Day <= 0:
			chat.AppendChat(1, "Shop time must be under 5 days.")
			self.OnCloseQuestionDialog()
			return

		offlineshop.SendExtendTime(Extend1Day)

		constInfo.SET_ITEM_QUESTION_DIALOG_STATUS(0)
		self.OnCloseQuestionDialog()
		return True

	def ClearCachePos(self, page, id):
		if CACHE_ITEMS_ID.has_key(page):
			if CACHE_ITEMS_ID[page].has_key(id):
				del CACHE_ITEMS_ID[page][id]