# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from os import environ
from django.conf import settings
from django.contrib.messages import constants as messages
from datetime import timedelta
from common.utils import helpers as resolve_env
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

SCHEMA_DIR = os.path.join(BASE_DIR, 'common', 'schemas')

SCHEMA_VERSIONS_DIR = os.path.join(BASE_DIR, 'common', 'schema_versions')

SCHEMA_VERSIONS_FILE_LIST = ["sample.json", "ena_seq.json"]  # files based on schema versions

MANIFEST_PATH = os.path.join(BASE_DIR, 'static', 'assets', 'manifests')
MANIFEST_FILE_NAME = "{0}_MANIFEST_TEMPLATE{1}.xlsx"
MANIFEST_DOWNLOAD_URL =  "/static/assets/manifests/" + MANIFEST_FILE_NAME

SITE_ROOT = os.path.dirname(os.path.realpath(__file__))

PROFILE_LOG_BASE = os.path.join(BASE_DIR, 'profiler')
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = resolve_env.get_env('SECRET_KEY')

LOGIN_URL = '/accounts/auth/'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True if str(resolve_env.get_env('DEBUG')).lower() == 'true' else False

# ALLOWED_HOSTS = [ gethostname(), gethostbyname(gethostname()), ]
ALLOWED_HOSTS = ['127.0.0.1', '0.0.0.0', '.copo-project.org',
                 '.demo.copo-project.org', 'localhost', '.copodev.cyverseuk.org']
ALLOWED_CIDR_NETS = ['10.0.0.0/24']
CORS_ALLOWED_ORIGINS = [
    "http://localhost:8000",
    "http://0.0.0.0:8000",
    "http://0.0.0.0:80",
    "http://127.0.0.1:8000",
    "http://127.0.0.1:8001",
    "https://copo-project.org",
    "http://demo.copo-project.org",
    "https://copodev.cyverseuk.org"

]
DEBUG_PROPAGATE_EXCEPTIONS = True

# Django's base applications definition
DJANGO_APPS = [
    'daphne',
    'django.contrib.admin',
    'django.contrib.sites',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

# user-defined applications definition
PROJECT_APPS = [
    'channels',
    'src.apps.copo_core',
    'src.apps.copo_profile',
    'src.apps.copo_sample',
    'src.apps.copo_login',
    'src.apps.copo_dtol_upload',
    'src.apps.copo_dtol_submission',
    'src.apps.copo_landing_page',
    'src.apps.copo_read_submission',
    'src.apps.copo_assembly_submission',
    'src.apps.copo_seq_annotation_submission',
    'src.apps.copo_barcoding_submission',
    'src.apps.copo_file',
    'src.apps.copo_accession',
    'src.apps.copo_tol_dashboard',
    'src.apps.copo_manifest_wizard',
    'src.apps.api',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.orcid',
    'rest_framework',
    'rest_framework.authtoken',
    'compressor',
    'django_extensions',
    'corsheaders',
    'crispy_forms',
    "crispy_bootstrap5"
]
INSTALLED_APPS = DJANGO_APPS + PROJECT_APPS
ASGI_APPLICATION = 'src.main_config.asgi.application'
#WSGI_APPLICATION = 'src.main_config.wsgi.application'

#CRISPY_TEMPLATE_PACK = 'uni-form'
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
CRISPY_TEMPLATE_PACK = "bootstrap5"
# sass, social accounts...
sass_exe = '/usr/local/bin/sass'
COMPRESS_PRECOMPILERS = (
    ('text/scss', sass_exe + ' --scss  {infile} {outfile}'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    # other finders..
    'compressor.finders.CompressorFinder',
)

SOCIALACCOUNT_PROVIDERS = \
    {'google':
         {'SCOPE': ['profile', 'email'],
          'AUTH_PARAMS': {'access_type': 'online'}}}

MIDDLEWARE = [
    'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django_tools.middlewares.ThreadLocal.ThreadLocalMiddleware',
    'compression_middleware.middleware.CompressionMiddleware',
    'src.apps.copo_core.middlewares.LocksMiddleware.LocksMiddleware',
    'src.apps.copo_core.middlewares.LogUncaughtExceptions.LogUncaughtExceptions',
    'allow_cidr.middleware.AllowCIDRMiddleware'
]

AUTHENTICATION_BACKENDS = (
    # Needed to auth by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',
    # `allauth` specific authentication methods, such as auth by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
)

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',

    )
}

CORS_ORIGIN_WHITELIST = (
    'http://localhost:8000',
    'http://0.0.0.0:8000',
    'http://127.0.0.1:8000',
    'http://127.0.0.1:8001',
)
# CORS_ORIGIN_ALLOW_ALL = True
ACCOUNT_LOGOUT_REDIRECT_URL = '/copo/auth/login'

LOGIN_URL = '/copo/auth/login'

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Etc/GMT+0'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# CSRF_TRUSTED_ORIGINS = ['http://*.copo-project.org', 'https://*.copo-project.org', '127.0.0.1:8000']

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'

# print(STATICFILES_DIRS)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_ROOT = os.path.join(BASE_DIR, resolve_env.get_env('MEDIA_PATH'))
MEDIA_URL = 'media/'

ELASTIC_SEARCH_URL = 'http://localhost:9200/ontologies/plant_ontology/_search'

SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_COOKIE_AGE = 48 * 60 * 60  #

SITE_ID = 1

COPO_URL = 'copo-project.org'

DATA_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024 * 1024 * 2
FILE_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024 * 24

#CACHES = {
#    'default': {
#        'LOCATION': 'copo_cache_table',
#        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
#
#    }
#}

VIEWLOCK_TIMEOUT = timedelta(seconds=1800)

# Enables django-html-validator that automatically checks if the served HTML pages are
# valid for the W3C checkers.
HTMLVALIDATOR_ENABLED = True
HTMLVALIDATOR_VNU_JAR = './tests/utilities/vnu.jar'
HTMLVALIDATOR_DUMPDIR = os.path.join(BASE_DIR, 'html_validators')

# Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
# Solution: Set 'django.db.models.AutoField'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

MESSAGE_TAGS = {
    messages.DEBUG: 'alert-secondary',
    messages.INFO: 'alert-info',
    messages.SUCCESS: 'alert-success',
    messages.WARNING: 'alert-warning',
    messages.ERROR: 'alert-danger',
}

TEMPLATES = [

    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            # insert your TEMPLATE_DIRS here
            #
            os.path.join( BASE_DIR, 'src', 'apps', 'copo_landing_page', 'templates'),
            os.path.join( BASE_DIR, 'src', 'apps', 'copo_core', 'templates', 'copo'),
            os.path.join( BASE_DIR, 'static', 'swagger'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.csrf',
                'django.template.context_processors.request',
                'django.template.context_processors.static',
                'django.contrib.auth.context_processors.auth',
                'src.apps.copo_core.copo_user_status_messages.latest_message'
            ],
            'debug':  DEBUG,
        },
    },
]

ROOT_URLCONF = 'src.main_config.urls'

UPLOAD_PATH = os.path.join(settings.MEDIA_ROOT,'uploads')


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 09:00:00 2020

@author:       Genocs
@description:  The hello world for image analysis
"""

from __future__ import absolute_import, division, print_function, unicode_literals

# Import numpy
import numpy as np

# Import OpenCV
import cv2

# Import matplotlib lib
import matplotlib.pyplot as plt

# Import Tesseracts
import pytesseract

# Import utility libraries
import datetime
import time

# get grayscale image
def get_grayscale(image):
    return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# noise removal
def remove_noise(image):
    return cv2.medianBlur(image, 5)

# thresholding
def thresholding(image):
    # threshold the image, setting all foreground pixels to
    # 255 and all background pixels to 0
    return cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

# dilation
def dilate(image):
    kernel = np.ones((5, 5), np.uint8)
    return cv2.dilate(image, kernel, iterations=1)

# erosion
def erode(image):
    kernel = np.ones((5, 5), np.uint8)
    return cv2.erode(image, kernel, iterations=1)

# opening - erosion followed by dilation
def opening(image):
    kernel = np.ones((5, 5), np.uint8)
    return cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)

# canny edge detection
def canny(image):
    return cv2.Canny(image, 100, 200)

# skew correction
def deskew(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.bitwise_not(gray)
    thresh = cv2.threshold(gray, 0, 255,
                           cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
    coords = np.column_stack(np.where(thresh > 0))
    angle = cv2.minAreaRect(coords)[-1]
    if angle < -45:
        angle = -(90 + angle)
    else:
        angle = -angle
    (h, w) = image.shape[:2]
    center = (w // 2, h // 2)
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    rotated = cv2.warpAffine(image,
                             M, (w, h),
                             flags=cv2.INTER_CUBIC,
                             borderMode=cv2.BORDER_REPLICATE)
    return rotated

# template matching
def match_template(image, template):
    return cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)

def show_images(images, cols=1, titles=None):
    assert ((titles is None) or (len(images) == len(titles)))
    n_images = len(images)
    if titles is None:
        titles = ['Image (%d)' % i for i in range(1, n_images + 1)]
    fig = plt.figure()
    for n, (image, title) in enumerate(zip(images, titles)):
        a = fig.add_subplot(cols, np.ceil(n_images / float(cols)), n + 1)
        if image.ndim == 2:
            plt.gray()
        plt.imshow(image)
        a.set_title(title)
    fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)
    plt.show()

t1 = time.time()

img = cv2.imread('.\\data\\image.jpg')

gray = get_grayscale(deskew(img))
# thresh = thresholding(gray)
# rnoise = remove_noise(thresh)
# dilate = dilate(thresh)
# erode = erode(gray)
# opening = opening(gray)
# canny = canny(thresh)

h, w = gray.shape

# Adding custom options
custom_config = r'--oem 1 -c tessedit_char_whitelist=<ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 --psm 6'

boxes = pytesseract.image_to_boxes(gray, config=custom_config)
result = pytesseract.image_to_string(img, config=custom_config)

t2 = time.time()

# get the difference as datetime.timedelta object
diff = (datetime.datetime.fromtimestamp(t1) - datetime.datetime.fromtimestamp(t2))
print('Result is: %s' % result)
# diff is negative as t2 is in the future compared to t2
print('difference is {0} seconds'.format(abs(diff.total_seconds())))

for b in boxes.splitlines():
    b = b.split(' ')
    gray = cv2.rectangle(gray, (int(b[1]), h - int(b[2])), (int(b[3]), h - int(b[4])), (255, 255, 255), 1)

# for b in boxes.splitlines():
#    b = b.split(' ')
#    # text
#    text = b[0]
#
#    # font
#    font = cv2.FONT_HERSHEY_SIMPLEX
#
#    # org
#    org = (int(b[1]), h - int(b[2]))
#
#    # fontScale
#    fontScale = 1
#
#    # Red color in BGR
#    color = (255, 255, 255)
#
#    # Line thickness of 2 px
#    thickness = 1
#    gray = cv2.putText(gray, text, org, font, fontScale, color, thickness, cv2.LINE_AA)

# Use the matplotlib to sho the first trainingset sample
plt.figure()
plt.imshow(gray)
plt.colorbar()
plt.grid(False)
plt.show()

# cv2.imshow('img', canny)
# images = [gray, thresh, rnoise, canny]
# show_images(images, 3, ["gray", "thresh", "rnoise", "canny"])


import urwid

from database import (
    insert_text_and_translation_to_db,
)
import config

class AddTextTranslationForm(urwid.Pile):
    def __init__(self) -> None:
        self.__text_edit = urwid.Edit()
        self.__text_edit_lined = urwid.LineBox(
            self.__text_edit, title="Text", title_attr="text"
        )
        self.__translation_edit = urwid.Edit()
        self.__translation_edit_lined = urwid.LineBox(
            self.__translation_edit, title="Translation", title_attr="translation"
        )
        self.__information_field = urwid.Text("", "center")
        self.__blank = urwid.Divider()

        super().__init__(
            [
                self.__text_edit_lined,
                self.__blank,
                self.__translation_edit_lined,
                self.__blank,
                self.__information_field,
            ]
        )

    def keypress(self, size, key):
        if key == "tab":
            self.__toggle_focus()
        if key == "enter":
            self.__add_unit_to_dictionary()
            return super().keypress(size, key)
        if key == "esc":
            self.__clear__text_widgets()
            self.__information_field.set_text("")
            return super().keypress(size, key)
        else:
            return super().keypress(size, key)

    def __clear__text_widgets(self) -> None:
        self.__text_edit.set_edit_text("")
        self.__translation_edit.set_edit_text("")

    def __toggle_focus(self) -> None:
        if super().get_focus() == self.__text_edit_lined:
            super().set_focus(self.__translation_edit_lined)
        else:
            super().set_focus(self.__text_edit_lined)

    def __add_unit_to_dictionary(self) -> None:
        if (
            self.__text_edit.text.strip() == ""
            or self.__translation_edit.text.strip() == ""
        ):
            self.__information_field.set_text(
                ("error", config.EMPTY_REQUIRED_FIELDS_ERROR)
            )
        else:
            text = self.__text_edit.text.strip()
            translation = self.__translation_edit.text.strip()
            insert_text_and_translation_to_db(text, translation)
            self.__information_field.set_text(
                ("success", config.SAVING_SUCCESS_MESSAGE)
            )
            self.__clear__text_widgets()
            super().set_focus(self.__text_edit_lined)


from tkinter import *
from tkinter import ttk
import os
import subprocess
try:
    from cryptography.fernet import Fernet
except ModuleNotFoundError:
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", "cryptography"])
    from cryptography.fernet import Fernet
# import scripts
import PageViews

class Cipher():
    def __init__(self):
        self.token = None

    def generate_key(self):
        """
        Generates a new encryption key and saves it to the working directory.
        """
        key = Fernet.generate_key()
        with open("secret.key", "wb") as key_file:
            key_file.write(key)

    def load_key(self):
        """
        Loads the secret key from a file in the current working directory.
        """
        return open("secret.key", "rb").read()

    def encryptFile(self, filename, key, data):
        """
        Given a filename path and a key it encrpys and writes to the file.
        """
        f = Fernet(key)
        with open(filename, "wb") as file:
            data = data.encode()
            encrypted_data = f.encrypt(data)
            file.write(encrypted_data)

    def decrypt(self, filename, key):
        """
        Given a filename string path and a key decrypt the file.
        """
        f = Fernet(key)
        with open(filename, "rb") as file:
            # read the encrypted data
            encrypted_data = file.read()
            decrypted_data = f.decrypt(encrypted_data)
        return decrypted_data

class MainGUI():
    def __init__(self):
        self.root = Tk()
        self.entryField = None
        self.crypter = Cipher()

    def _confirmTokenEntry(self):
        token = self.entryField.get()
        if(os.path.isfile("secret.key") is False):
            self.crypter.generate_key()
            key = self.crypter.load_key()
            self.crypter.encryptFile("tokenFile.env", key, token)
            # Next block testing only remove after confirmation.
            # decryptedToken = (self.crypter.decrypt
            # ("tokenFile.env", key).decode("utf-8"))
            # print(decryptedToken)

        else:
            key = self.crypter.load_key()
            self.crypter.encryptFile("tokenFile.env", key, token)

    def _tokenMenu(self):
        gettoken = Toplevel(self.root)
        addTokenLabel = ttk.Label(gettoken, text="Enter Canvas REST Token")
        addTokenLabel.pack()
        self.entryField = Entry(gettoken, show="*")
        self.entryField.pack()
        enterTokenButton = ttk.Button(
            gettoken, text="Enter Token", command=lambda:
            [self._confirmTokenEntry(), gettoken.destroy()])
        enterTokenButton.pack(side="left")
        cancelButton = ttk.Button(
            gettoken, text="Cancel", command=gettoken.destroy)
        cancelButton.pack(side="right")

    # GUI options on select
    def _listSelect(self, event=None):
        selection = self.scriptList.curselection()
        selection = selection[0]
        print(selection)
        if selection == 0:
            self.pageViewsOptions()

    def pageViewsOptions(self):
        # reset selection
        self.optionsFrame.destroy()
        self.GUI_options()

        # draw options and then update root element
        # B = ttk.Button(self.optionsFrame, text="testButton", command=None)
        # B.grid()
        domainEntryLabel = ttk.Label(
            self.optionsFrame, text="""Enter Instance domain
            (e.g canvas.instructure.com)""")
        self.domainEntry = Entry(self.optionsFrame)
        userIDEntryLablel = ttk.Label(
            self.optionsFrame, text="Enter list of users seperated by comma")
        self.userIDEntry = Entry(self.optionsFrame)
        startDateEntryLabel = ttk.Label(self.optionsFrame,
                                        text="""Enter Start Date format yyyy-mm-dd
        Leave blank for all""")
        self.startDateEntry = Entry(self.optionsFrame)
        endDateEntryLabel = ttk.Label(self.optionsFrame,
                                      text="""Enter End Date format yyyy-mm-dd
        Leave blank for all""")
        self.endDateEntry = Entry(self.optionsFrame)

        key = self.crypter.load_key()
        tokenString = self.crypter.decrypt("tokenFile.env", key).decode()

        PV = PageViews.inputAndRun()
        runButton = ttk.Button(self.optionsFrame, text="Run", command=lambda: [PV.inputs(tokenString, self.domainEntry.get(
        ), self.userIDEntry.get(), Start_Date=self.startDateEntry.get(), End_Date=self.endDateEntry.get()), PV.run()])

        domainEntryLabel.grid()
        self.domainEntry.grid()
        userIDEntryLablel.grid()
        self.userIDEntry.grid()
        startDateEntryLabel.grid()
        self.startDateEntry.grid()
        endDateEntryLabel.grid()
        self.endDateEntry.grid()
        runButton.grid()

        self.root.update()

    def GUI_Menu(self):
        menubar = Menu(self.root)
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Set Token", command=self._tokenMenu)

        filemenu.add_separator()

        filemenu.add_command(label="Exit", command=self.root.quit)
        menubar.add_cascade(label="File", menu=filemenu)

        self.root.config(menu=menubar)

        # left hand script list and select
        listFrame = Frame(self.root)
        listFrame.grid(row=1, column=0, rowspan=2,
                       stick="nsew", padx=10, pady=10)
        ttk.Label(listFrame, text="Scripts", background="gray").grid(
            row=0, column=0, stick="nsew")
        self.scriptList = Listbox(listFrame, selectmode="SINGLE", height=30)
        self.scriptList.insert(1, "Page Views")
        self.scriptList.insert(2, "Failed Reports")
        self.scriptList.insert(3, "Hawkspan")
        # bind the button
        self.scriptList.bind('<Double-1>', self._listSelect)
        self.scriptList.grid(row=1, column=0)

        # right center options for selected script
        # This will need to be extensable
    def GUI_options(self):
        self.optionsFrame = Frame(self.root)
        self.optionsFrame.grid(row=1, column=1, stick="nsew", padx=10, pady=10)
        ttk.Label(self.optionsFrame, text="Options", background="lightblue").grid(
            row=0, column=0, stick="nsew")

    # output
    def GUI_output(self):
        outputFrame = Frame(self.root)
        outputFrame.grid(row=2, column=1, stick="nsew", padx=10, pady=10)
        ttk.Label(outputFrame, text="output", background="lightgreen").grid(
            row=0, column=0, stick="nsew")
        outputTextBox = Text(outputFrame, state=NORMAL,
                             height=20).grid(row=1, column=0)

    def RUN_GUI(self):
        self.root.mainloop()

# def main():
#     UI = MainGUI()
#     UI.GUI_Menu()
#     UI.GUI_options()
#     UI.GUI_output()
#     UI.RUN_GUI()

# if __name__ == "__main__":
#     main()


import socket
import json

# This function returns a string
# which contains the messages sent
# by the sender. The protocol is
# that a message ends with a new line
# character "\n"
def get_message(conn):
	length_str = b''
	char = conn.recv(1)
	while char != b'\n':
		length_str += char
		char = conn.recv(1)
	total = int(length_str)
	off = 0
	msg = b''
	while off < total:
		temp = conn.recv(total - off)
		off = off + len(temp)
		msg = msg + temp
	return json.loads(msg.decode('utf-8'))

# Try to define a socket
try:
	s = socket.socket()
	print("Socket Created")
except socket.error as err:
	print("Socket Creation Failed with Error :: ", err)

# Define the port on which the receiver
# will listen to receiver requests
port = 1234

# The host refers to the local IP Address of
# my computer.
host = socket.gethostbyname(socket.gethostname())

# Bind the socket and host on
# which the receiver will accept
# incoming connections
s.bind((host, port))

# Make the recevr listen on the specified
# IP Address and port number for connection
# requests from the sender
s.listen(0)
print("Host ", host, " is listening on ", port)

try:
	while True:
			# conn is a socket new object used for
			# communication between the sender and
			# the receiver. addr is the IP address
			# of the sender.
			conn, addr = s.accept()
			print("Got connection form ", addr)
			message = get_message(conn)
			print("Message from Sender :: ", message)

# A keyboard Interrupt (ctrl + c) ends the socket
except KeyboardInterrupt:
	print("Socket Closed!")
	s.close()


import web

db = web.database(dbn='sqlite',
        db='AuctionBase'
    )

######################BEGIN HELPER METHODS######################

# Enforce foreign key constraints
# WARNING: DO NOT REMOVE THIS!
def enforceForeignKey():
    db.query('PRAGMA foreign_keys = ON')

# initiates a transaction on the database
def transaction():
    return db.transaction()
# Sample usage (in auctionbase.py):
#
# t = sqlitedb.transaction()
# try:
#     sqlitedb.query('[FIRST QUERY STATEMENT]')
#     sqlitedb.query('[SECOND QUERY STATEMENT]')
# except Exception as e:
#     t.rollback()
#     print str(e)
# else:
#     t.commit()
#
# check out http://webpy.org/cookbook/transactions for examples

# returns the current time from your database
def getTime():
    # TODO: update the query string to match
    # the correct column and table name in your database
    query_string = 'select Time from CurrentTime'
    results = query(query_string)
    # alternatively: return results[0]['currenttime']
    return results[0].Time
                                  # column name
# returns a single item specified by the Item's ID in the database
# Note: if the `result' list is empty (i.e. there are no items for a
# a given ID), this will throw an Exception!
def getItemById(item_id):
    # TODO: rewrite this method to catch the Exception in case `result' is empty
    query_string = 'select * from Items where ItemID = $ItemIDVar'
    result = query(query_string, {'ItemIDVar': item_id})
    if len(result) > 0:
        return result[0]
    return None

# wrapper method around web.py's db.query method
# check out http://webpy.org/cookbook/query for more info
def query(query_string, vars = {}):
    return list(db.query(query_string, vars))

#####################END HELPER METHODS#####################
# e.g. to update the current time
def setTime(newTime):
    t = transaction()
    query_string = 'UPDATE CurrentTime SET Time = $newTimeVar'
    try:
        db.query(query_string, {'newTimeVar': newTime})
    except Exception as e:
        t.rollback()
        return False
    else:
        t.commit()
        return True
    return True

def search(searchKeys):
    endingString = []
#    query_string = "SELECT * FROM Items WHERE itemID = $itemID and Seller_UserID = $userID and Currently <= $maxPrice and Currently >= $minPrice "
    query_string = "SELECT * FROM Items WHERE "
    index = 0;
    try:
        for keys in searchKeys:
            if keys != "":
                if index == 0:
                    endingString.append("itemID = " + str(searchKeys[0]))
                if index == 1:
                    endingString.append("Seller_UserID = $userID")
                if index == 2:
                    endingString.append("Currently >= " + str(searchKeys[2]))
                if index == 3:
                    endingString.append("Currently <= " + str(searchKeys[3]))
                if index == 4:
                    endingString.append("Description LIKE $itemDescription")
                if index == 5:
                    if searchKeys[5] == "open":
                        endingString.append("Started <= $time AND Ends > $time AND ((Buy_Price IS NOT NULL AND Currently < Buy_Price) OR Buy_Price IS NULL)")
                    elif searchKeys[5] == "close":
                        endingString.append("(Ends <= $time OR (Buy_Price IS NOT NULL AND Currently >= Buy_Price))")
                    elif searchKeys[5] == "notStarted":
                        endingString.append("Started > $time")
                    else:
                        endingString.append("1 = 1")
            index = index + 1
        ending = " AND ".join(endingString)
        query_string = query_string + ending + ";"
        result = db.query(query_string, {"userID":searchKeys[1], "itemDescription": "%" + searchKeys[4] + "%", "time":getTime()})
    except Exception as e :
        return None
    return result

def getAttributesInfo(attributes, key):
    if (attributes == "Item") :
        #key is item ID
        return getItemById(key)

    if (attributes == "Status"):
        #key is item
        time = getTime()
        # trigger5 is caught
        if key["Started"] > time:
            return ("The bid for this Item Has not started yet")
        # trigger6 is caught
        if key["Ends"] <= time:
            return ("The Bid is currently closed")

        if key["Buy_Price"] != None:
            if float(key["Currently"]) >= float(key["Buy_Price"]):
                return "Current Bid Price has exceeded buy price, Bid Closed"

        return "Open"

    if (attributes == "User"):
        query_3 = 'select * from Users where UserID = $ID'
        result_3 = query(query_3, {'ID': key})
        if len(result_3) > 0:
            return result_3[0]
        else:
            return None

    return None

def addBid (inputArray):
    #inputArray item is organized in following order: itemID, user ID, Price
    t = transaction()
    if ((inputArray[0]=="" or None)or(inputArray[1]=="" or None)or(inputArray[2]=="" or None)):
        return("",False)

    try:
        item = getAttributesInfo("Item",inputArray[0]);
        if item == None:
            raise Exception("Item Not Found for this Item ID")
        user = getAttributesInfo("User",inputArray[1]);
        if user == None or "":
            raise Exception ("User Not Found for this User Id")

        status = getAttributesInfo("Status",item);
        if status != "Open":
            raise Exception(status)

        #catch the exception of trigger3 new amount has to be greater than current amount
        if float(inputArray[2]) <= item["Currently"]:
            message = "Current price for this item is higher than the entered bid price"
            raise Exception (message)

        # trigger 7
        if item["Seller_UserID"] == user:
            raise Exception ("Seller can't bid on the item they sell, you dummy !!!")

        query_string = "INSERT INTO Bids (ItemID, UserID, Amount, Time ) VALUES ($ItemID,$UserID,$Amount,$Time)"
        result = db.query(query_string,{"ItemID": inputArray[0], "UserID": inputArray[1], "Amount": inputArray[2], "Time": getTime()})

    except Exception as e :
        t.rollback()
        return (str(e),False)

    else:
        t.commit();
        return ("", True);

    return

def item(itemID):
    item = getItemById(itemID)
    time = getTime()
    get_bids_query_string = "SELECT * FROM Bids WHERE ItemID = $itemID ORDER BY Amount DESC"
    bids = query(get_bids_query_string,{"itemID": item["ItemID"]})

    get_cats_query_string = "SELECT Category FROM Categories WHERE ItemID = $itemID"
    cats = query(get_cats_query_string,{"itemID": item["ItemID"]})

    status = "Open"
    if item["Started"] > time:
        status = "Not Started"
    if item["Buy_Price"]!=None:
        if item["Currently"] >= item["Buy_Price"]:
            status="Closed"
    if item["Ends"] <= time:
        status = "Closed"

    if len(bids) > 0 and status == "Closed":
        return(status, str(bids[0]["UserID"]), bids, cats)
    return (status,"Nobody has won this item!",bids,cats)


import logging;logging.basicConfig(level=logging.INFO)
import asyncio,os,json,time

from datetime import datetime
from aiohttp import web
from coroweb import add_routes

async def logger_factory(app, handler):
    async def logger(request):
        logging.info('Request: %s %s' % (request.method, request.path))
        # await asyncio.sleep(0.3)
        return (await handler(request))
    return logger

async def response_factory(app, handler):
    async def response(request):
        logging.info('Response handler...')
        global resp
        r = await handler(request)
        if isinstance(r, web.StreamResponse):
            return r
        if isinstance(r, bytes):
            resp = web.Response(body=r)
            resp.content_type = 'application/octet-stream'

        if isinstance(r, str):
            if r.startswith('redirect:'):
                return web.HTTPFound(r[9:])
            resp = web.Response(body=r.encode('utf-8'))
            resp.content_type = 'application/json;charset=UTF-8'
            resp.headers['Location']='http//:8089'

        if isinstance(r, dict):
            template = r.get('__template__')
            if template is None:
                resp = web.Response(body=json.dumps(r, ensure_ascii=False, default=lambda o: o.__dict__).encode('utf-8'))
                resp.content_type = 'application/json;charset=utf-8'

            else:
                resp = web.Response(body=app['__templating__'].get_template(template).render(**r).encode('utf-8'))
                resp.content_type = 'text/html;charset=utf-8'

        if isinstance(r, int) and r >= 100 and r < 600:
            resp = web.Response(text=r)

        if isinstance(r, tuple) and len(r) == 2:
            t, m = r
            if isinstance(t, int) and t >= 100 and t < 600:
                resp = web.Response(text=(t+ str(m)))

        # default:
        # resp = web.Response(body=str(r).encode('utf-8'))
        # resp.content_type = 'text/plain;charset=utf-8'
        # resp.headers['Access-Control-Allow-Origin'] = "*"
        resp.headers['Access-Control-Allow-Origin'] = "*"
        resp.headers['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept"
        resp.headers['Access-Control-Allow-Methods'] = "PUT,POST,GET,DELETE,OPTIONS"
        # resp.headers['Access-Control-Max-Age'] = '1000'
        # resp.headers['Access-Control-Allow-Headers'] = '*'
        return resp

    return response

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    r = web.Response(text=text)
    r.headers['Access-Control-Allow-Origin'] = "*"
    r.headers['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept"

    return r

app = web.Application(middlewares=[
        logger_factory, response_factory
    ])

add_routes(app, 'handlers')

# app.add_routes([web.post('/logIn', handle),
# web.options('/logIn', handle),
#                 web.get('/logIn', handle)])

if __name__ == '__main__':
    web.run_app(app)


from typing import List

from sympy import false, true
import math

class Strutil:

    def get_list(text: str, sep: str = " ", width=10):
        buffer: str = ""
        text_list: List = []

        first = true
        for (i, word) in enumerate(text.split(sep)):
            prev_buffer = buffer
            if i == 0 and len(text.split(sep)) == 1:
                buffer = word
                prev_buffer = word
            elif i == 0 and len(text.split(sep)) > 1:
                buffer = word + sep
                prev_buffer = word + sep
            elif i < (len(text.split(sep)) - 1):
                buffer += word + sep
            else:
                buffer += word

            if len(buffer) > width and first == False:
                if len(prev_buffer) > width and sep == ",":
                    text_list += Strutil.get_list(prev_buffer, " ")
                else:
                    text_list.append(prev_buffer)

                if i < (len(text.split(sep)) - 1):
                    buffer = word.lstrip() + sep
                else:
                    buffer = word.lstrip()

            first = False

        if len(buffer) > width and sep == " ":
            #text_list += Strutil.get_list(buffer, " ")
            text_list.append(buffer[0:width-3] + "...")
        elif len(buffer) > width and sep == ",":
            text_list += Strutil.get_list(buffer, " ")
        else:
            text_list.append(buffer)

        return text_list

    def get_max_length(li1: List, li2: List):
        return max([len(li1), len(li2)])

    def get_value(li: List, idx):
        value: str = ""
        if idx < len(li):
            value = li[idx]

        return value

    def left(fname, size: int = 18, pad="[...]") -> str:
        if len(fname) < size:
            return fname

        num = (size - len(pad)) / 2
        if (num % 2) != 0:
            num += 1
        num = math.floor(num)

        return fname[0:num]

    def right(fname, size: int = 18, pad="[...]") -> str:
        if len(fname) < size:
            return fname

        num = (size - len(pad)) / 2
        num = math.floor(num)

        index1 = len(fname) - num

        return fname[index1:]

    def shorten(fname, size: int = 18, pad="[...]"):
        if len(fname) < size:
            return fname

        return Strutil.left(fname, size, pad) + pad + Strutil.right(fname, size, pad)


from django.conf.urls import url, include
from . import views           # This line is new!
urlpatterns = [
    url(r'^$', views.index),
    url(r'^login$', views.login),
    url(r'^register$', views.register),
    url(r'^success$', views.success),
    url(r'^logout$', views.logout),
    url(r'^course/(?P<id>[0-9]+)$', views.course),
    url(r'^join/(?P<id>[0-9]+)$', views.join),
    url(r'^poke/(?P<id>[0-9]+)$', views.poke)
    # try to understand poke relationship
]


from final.Cambio_pack.Card import Card
import pygame

# Setting up the game window
pygame.init()
screen_width = 1200
screen_height = 700
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Cambio - card game')

# Game Variables
run = True  # Game loop variable
clicked_card = None  # The variable that holds the card that was clicked
clicked = True  # If there is a clicked card or not

# Card stats
card_img = pygame.image.load('images/cards/back.png')
card = Card(13, "Spikes", "Black")

# The game loop
while run:
    pygame.time.delay(50)

    # Searching for quit game
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # Checking for a mouse click
    if event.type == pygame.MOUSEBUTTONDOWN and clicked:

        # If there is clicked card --> extra click will change the card position to the new click location
        if clicked_card is not None:
            if not card.is_card_location_pressed(pygame.mouse.get_pos()):
                temp_pos = (pygame.mouse.get_pos()[0] + 1, pygame.mouse.get_pos()[1] + 1)
                clicked_card.set_pos(temp_pos)
                clicked_card = None
            else:
                clicked_card = None

        # if the click was on the card
        if card.is_card_location_pressed(pygame.mouse.get_pos()) and clicked_card is None:
            clicked_card = card
        clicked = False

    # for preventing long clicking
    if event.type == pygame.MOUSEBUTTONUP:
        clicked = True

    # Checks if there is a Clicked card and the flip the card (visual only)
    if clicked_card is not None:
        card_img = pygame.image.load('images/cards/sk.png')
    else:
        card_img = pygame.image.load('images/cards/back.png')

    window.fill((0, 0, 0))
    window.blit(card_img, card.get_pos())
    pygame.display.update()

pygame.quit()  # Kill Game


import requests

from datetime import date
from datetime import datetime
from datetime import timezone
from datetime import timedelta

url = 'https://maps.googleapis.com/maps/api/directions/json?'
api_key = 'YOUR API KEY'

class Error(Exception):
    pass

class WrongAddress(Error):
    pass

def request_direction():
    origin=input("Where from: ").replace(' ', "+")
    destination = input("Where to: ").replace(' ', "+")
    travel_mode = input("Travel mode, please enter 'driving', 'transit', 'bicycling' or 'walking': ")
    nav_request = "origin={0}&destination={1}&mode={3}&key={2}".format(origin, destination, api_key, travel_mode)
    request = url + nav_request
    response = requests.get(request)
    return response

def arrival_time():
    duration = int(data['routes'][0]['legs'][0]['duration']['value'])
    time_now = datetime.now()
    arrival_time = time_now + (timedelta(seconds = duration))
    return "ARRIVAL TIME: {0}".format(datetime.strftime(arrival_time, "%H:%M:%S"))

while True:
    try:
        data = request_direction().json()
        if data['status'] == 'OK':
            legs = data['routes'][0]['legs'][0]
            break
        elif data['status'] != 'OK':
            raise WrongAddress(data['status'])
    except WrongAddress:
        print("Directions not found. Try again!")
        request_direction()

with open("directions.html", "w") as file:

    file.write('
')
    file.write("START ADDRESS: {0}".format(data['routes'][0]['legs'][0]['start_address']))
    file.write('
')
    file.write("END ADDRESS: {0}".format(data['routes'][0]['legs'][0]['end_address']))
    file.write('
')
    file.write("TOTAL DURATION: {0}".format(data['routes'][0]['legs'][0]['duration']['text']))
    file.write('
')
    file.write(str(arrival_time()))
    file.write('
')
    file.write('
')
    file.write("DIRECTIONS")

    integer_distance = 0
    integer_duration = 0
    integer_instructions = 0

    distance = legs['steps'][integer_distance]['distance']['text']
    duration = legs['steps'][integer_duration]['duration']['text']
    instructions = legs['steps'][integer_instructions]['html_instructions']

    while integer_distance < len(data['routes'][0]['legs'][0]['steps'])and integer_instructions < len(data['routes'][0]['legs'][0]['steps']) and integer_duration < len(data['routes'][0]['legs'][0]['steps']):
        distance = legs['steps'][integer_distance]['distance']['text']
        duration = legs['steps'][integer_duration]['duration']['text']
        instructions = legs['steps'][integer_instructions]['html_instructions']
        file.write('
')
        file.write("---------------------")
        file.write('
')
        file.write("{0}".format(instructions))
        file.write('
')
        file.write("Distance: {0}".format(distance))
        file.write('
')
        file.write("Durations: {0}".format(duration))

        integer_duration+=1
        integer_distance+=1
        integer_instructions+=1

    file.write('
')
    file.write("---------------------")

with open("directions.html", "r") as file:
    for line in file:
        output = line.split('
')
        for line in output:
            print(line)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os, sys, numpy, pyopenjtalk
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtWidgets import QApplication
from PySide2.QtQuick import QQuickView
from PySide2.QtCore import QUrl, QObject, Slot, Property, QThread, Signal, QMutex, QMutexLocker
import simpleaudio as sa
import feedparser
import pprint

class Connect(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.__ply = None
        self.__feed = None
    @Slot(str)
    def talk(self, text):
        self.__talk(text)
    def __talk_async(self, text):
        x, sr = pyopenjtalk.tts(text)
        if self.__ply and self.__ply.is_playing():
            self.__ply.stop()
            self.__ply = None
        self.__ply = sa.play_buffer(x.astype(numpy.int16), 1, 2, sr)
    def __talk(self, text, is_split=True):
        if is_split: self.__talk_split(text)
        else:
            self.__talk_async(text)
            self.__ply.wait_done()
    def __talk_split(self, text):
        for sentence in [line for line in text.split('。') if 0 < len(line)]:
            self.__talk_async(text)
            self.__ply.wait_done()
    @Slot(str)
    def talk_news(self, url):
        if not self.__feed:
            self.__feed = feedparser.parse(url)
        pprint.pprint(self.__feed, depth=1)
        pprint.pprint(self.__feed['feed'], depth=1)
        news_num = len(self.__feed['entries'])
        print(news_num)
        self.__talk(f'{news_num}件のニュースがあります。')
        for entry in self.__feed['entries']:
            pprint.pprint(entry, depth=1)
            self.__talk(entry.title)
    @Slot(str, result=str)
    def make_html(self, url):
        html = ''
        self.__feed = feedparser.parse(url)
        html += f'
'
        for entry in self.__feed['entries']:
#            html += f'
{entry.title}概要{entry.summary}
'
            html += f'
{entry.title}
{entry.summary}

'
        html += f'
'
        return html

def Main():
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()
    connect = Connect()
    ctx = engine.rootContext()
    ctx.setContextProperty("Connect", connect)
    HERE = os.path.dirname(os.path.abspath(__file__))
    UI = os.path.join(HERE, 'talker.qml')
    engine.load(UI)
    if not engine.rootObjects(): sys.exit(-1)
    sys.exit(app.exec_())

if __name__ == '__main__':
    Main()


# This bot checks list of the chats specified below and kicks deleted accounts

from pyrogram import Client
from pyrogram.errors import FloodWait
import time
import yaml

with open("config.yml", 'r') as ymlfile:
    cfg = yaml.load(ymlfile)

api_id = cfg['telegram']['api_id']
api_hash = cfg['telegram']['api_hash']
notify_before = cfg['notifications']['notify_before']
notify_after = cfg['notifications']['notify_after']
notify_before_ids = cfg['notifications']['notify_before_ids']
notify_after_ids = cfg['notifications']['notify_after_ids']
chat_ids = cfg['bot']['chat_ids']
SLEEP_PER_CHAT = cfg['bot']['sleep_per_chat']
SLEEP_AFTER_KICK = cfg['bot']['sleep_after_kick']
MAX_MESSAGE_LENGTH = 4000

def main():
    with Client("my_account", api_id, api_hash) as app:
        overall_kick_count = 0
        report = ""

        if notify_before:
            for user_id in notify_before_ids:
                do_notify_before(user_id, app)

        j = 0
        while j < len(chat_ids):
            chat_id = chat_ids[j]
            j += 1
            chat_id = int(chat_id)
            try:
                chat_info = app.get_chat(chat_id)
            except FloodWait as e:
                print("Getting chat info: Floodwait triggered. Trying again in {} seconds.".format(e.value))
                time.sleep(e.value)
                j -= 1
                continue
            except Exception as ex:
                msg = "Error of type {} occured when getting chat info: {}. Error message:".format(type(ex).__name__, ex.args)
                print(msg)
                report += msg+"\n"
                continue

            print("==========================================")
            print("")
            print("Working on chat {} now".format(chat_info.title))
            report += "=========================== \n {}\n===========================\n".format(chat_info.title)
            member_list = app.get_chat_members(chat_id)
            kick_list = []
            skip_chat = False

            found_self = False
            for member in member_list:
                if member.user.is_self:
                    found_self = True
                    if (not member.status == "administrator" or not member.can_restrict_members) and not member.status == "creator":
                        msg = "⚠⚠⚠ I have no permissions to kick members in {}. Skipping this chat... \n\n".format(chat_info.title)
                        print(msg)
                        report += msg+"\n"
                        skip_chat = True
                if member.user.is_deleted:
                    kick_list.append(member)

            if not found_self:
                msg = "⚠⚠⚠ I'm no member of the group {}! Skipping this chat...\n\n".format(chat_info.title)
                print(msg)
                report += msg+"\n"
                skip_chat = True
            if skip_chat:
                continue

            print("Members to kick from {}".format(chat_info.title))
            kick_count = 0
            i = 0
            while i < len(kick_list):
                member = kick_list[i]
                i +=1
                display_userinfo(member)
                try:
                    app.ban_chat_member(chat_id, member.user.id)
                    app.unban_chat_member(chat_id, member.user.id)
                    time.sleep(SLEEP_AFTER_KICK)
                except FloodWait as e:
                    print("Kicking: Floodwait triggered. Trying again in {} seconds.".format(e.value))
                    time.sleep(e.value)
                    i -= 1
                    continue
                except Exception as ex:
                    msg = "Error of type {} occured when kicking user: {}. Error message:".format(type(ex).__name__, ex.args)
                    print(msg)
                    report += msg+"\n"
                    continue
                kick_count += 1
            overall_kick_count += kick_count

            msg = "Kicked {} deleted accounts from {}".format(kick_count, chat_info.title)
            print(msg)
            report += msg + "\n"

            print("Sleeping for {} seconds before continuing with next chat".format(SLEEP_PER_CHAT))
            time.sleep(SLEEP_PER_CHAT)
            report += "\n\n"
        msg = "Kicked {} users overall.".format(overall_kick_count)
        print(msg)
        report += "\n\n"+msg

        if notify_after:
            for user_id in notify_after_ids:
                do_notify_after(user_id, app, report)

def display_userinfo(chat_member):
    print("Name: {} {} (@{})".format(chat_member.user.first_name, chat_member.user.last_name, chat_member.user.username))
    print("is_deleted: {}".format(chat_member.user.is_deleted))

def do_notify_before(user_id, client):
    client.send_message(int(user_id), "Starting to clean up groups from deleted accounts")

def do_notify_after(user_id, client, report):
        send_message_split(user_id, client, "Sucessfully cleaned up. Full report: {}".format(report))

#sends a message longer than the telegram limit allows by splitting it into multiple. Always uses code formatting for the message
def send_message_split(user_id, client, message):
    current_position = 0
    while current_position < len(message):
        end = min(current_position + MAX_MESSAGE_LENGTH, len(message) - 1)
        text = message[current_position:end]
        if len(text) == 0:
            return
        text = "```" + text + "```"
        current_position = end

        client.send_message(user_id, text, "markdown")

if __name__ == "__main__":
    main()


from dataclasses import dataclass
from enum import Enum
from typing import Optional, List

from hostingde.exceptions import ContextConditionException
from hostingde.model import Model

class DomainContactType(Enum):
    person = 'person'
    org = 'org'
    role = 'role'

@dataclass
class DomainContact(Model):
    id: Optional[str]
    handle: Optional[str]
    type: DomainContactType
    name: str
    organization: Optional[str]
    street: List[str]
    postal_code: Optional[str]
    city: str
    state: str
    country: str
    email_address: str
    phone_number: str
    fax_number: Optional[str]
    sip_uri: Optional[str]
    hidden: Optional[bool]
    usable_by_subaccount: Optional[bool]
    add_date: Optional[str]
    last_change_date: Optional[str]

    def __init__(
        self,
        type: DomainContactType,
        name: str,
        street: List[str],
        city: str,
        country: str,
        email_address: str,
        phone_number: str,
        id: Optional[str] = None,
        handle: Optional[str] = None,
        organization: Optional[str] = None,
        postal_code: Optional[str] = None,
        fax_number: Optional[str] = None,
        sip_uri: Optional[str] = None,
        hidden: bool = False,
        usable_by_subaccount: bool = False,
        add_date: Optional[str] = None,
        last_change_date: Optional[str] = None,
        **kwargs
    ):
        super().__init__(**kwargs)
        self.type = type
        self.name = name
        self.street = street
        self.city = city
        self.country = country
        self.email_address = email_address
        self.phone_number = phone_number
        self.id = id
        self.handle = handle
        self.organization = organization
        self.postal_code = postal_code
        self.fax_number = fax_number
        self.sip_uri = sip_uri
        self.hidden = hidden
        self.usable_by_subaccount = usable_by_subaccount
        self.add_date = add_date
        self.last_change_date = last_change_date

        if self.type == DomainContactType.org and not self.organization:
            raise ContextConditionException('An organization contact requires the "organization" field to be set.')


from __future__ import absolute_import
import os, glob, json, pickle
#================ Environment variables ================
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'
os.environ['AUTOGRAPH_VERBOSITY'] = '0'
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import tensorflow as tf

import SimpleITK as sitk
import numpy as np
from model.resAAETF import resAAE
from tqdm import tqdm
from utils.losses import *
from functools import partial
import random
from sklearn.model_selection import train_test_split
from tensorflow.keras.activations import relu
from tensorflow.keras.losses import MeanSquaredError, BinaryCrossentropy
from utils.noise import addNoise
from utils.filters import *

gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
    try:
        tf.config.experimental.set_memory_growth(gpu, True)
    except:
    # Invalid device or cannot modify virtual devices once initialized.
        pass

config={
    "g_loss_factor":0.001,
    "hidden_D":(8, 16, 16, 32),
    "optD_lr":0.001,
    "optD_beta":0.5,
    "optAE_lr":0.001,
    "optAE_beta":0.9,
    "img_shape": (48, 96, 96, 1),
    "encoded_dim": 16,
    "loss_AE": mixedMSE(filter=gaussianFilter3D(sigma=1, kernel_size=3), alpha=0.5, mode="add"),
    "loss_GD": BinaryCrossentropy(from_logits=False),
    "last_decoder_act": relu,
    "acc": MeanSquaredError(),
    "hidden": (8, 16, 16, 32),
    "d_dropout": 0.1,
    "output_slices": slice(None),
    "batch_size": 16,
    "epochs": 15000
}
#[slice(None), slice(None,15), slice(2,62), slice(2,62), slice(None)]
model = resAAE(**config)
# logdir = r"C:\Users\wangs\Documents\35_um_data_100x100x48 niis\Gan_log\Nongan_AAE-TF-no-noise-8-16-16-32"
logdir = "\data\ray_results"
model.autoencoder.load_weights("/uctgan/data/ray_results/train_8-16-16-32-encoder/autoencoder_epoch_5751.h5")
os.makedirs(logdir, exist_ok=True)
json.dump({k:str(v) for k, v in config.items()}, open(os.path.join(logdir, "config.json"), "w"))
pickle.dump(config, open(os.path.join(logdir, "config.pkl"), "wb"))
#===============set up dataset================
# def read_data(file_ls):
#     dataset = np.zeros(shape=[len(file_ls), 48, 96, 96, 1], dtype=np.float32)

#     for idx, file in enumerate(file_ls):
#         img = sitk.ReadImage(file)
#         img = sitk.GetArrayFromImage(img)
#         # img = addNoise(img, 20, 12)
#         img = img[:,2:98,2:98,np.newaxis].astype(np.float32) / 255.
#         dataset[idx] = img
#     return dataset
datapath = r'..\data\ct\Data'
file_reference = r'..\Training\File_reference.csv'
# datapath = r"/uctgan/data/udelCT"
# file_reference = r"/uctgan/data/Gan_training/File_reference.csv"
# img_ls = glob.glob(os.path.join(datapath, "*.nii.gz"))
# seed = 42
# random.seed(seed)
# np.random.seed(42)
# random.shuffle(img_ls)

# train_img, test_img = train_test_split(img_ls, test_size=0.3, random_state=seed)
# val_img, evl_img = train_test_split(test_img, test_size=0.5, random_state=seed)

# train_set = read_data(train_img)
# val_set = read_data(val_img)
# evl_set = read_data(evl_img)

# np.save(open(os.path.join(datapath, "trainset.npy"), "wb"), train_set)
# np.save(open(os.path.join(datapath, "valset.npy"), "wb"), val_set)
# np.save(open(os.path.join(datapath, "evlset.npy"), "wb"), evl_set)

# import matplotlib.pyplot as plt
# plt.imshow(np.squeeze(train_set[0])[0,...], cmap="gray")

train_set = np.load(open(os.path.join(datapath, "trainset.npy"), "rb"))
val_set = np.load(open(os.path.join(datapath, "valset.npy"), "rb"))
evl_set = np.load(open(os.path.join(datapath, "evlset.npy"), "rb"))

# test = model.train_step(train_set, val_set, 16)
history = model.train(train_set, val_set, 16, 10000, logdir=logdir, logstart=500)


import os
import numpy as np
from scipy import signal
from scipy.io import wavfile
import pandas as pd
from keras.utils import normalize

#each folder name
root_folder_name = './train/'
train_folder_name = root_folder_name+'Train/'
valid_folder_name = root_folder_name+'valid/'
test_folder_name = root_folder_name+'test/'

# array of value
value_array = ['down','go','left','no','off','on','right','stop','up','yes']

def get_file_list(root_folder_name):
    output_file_list = []
    root_folder=os.listdir(root_folder_name)

    for folder_name in root_folder:
        full_folder_name = root_folder_name  +folder_name
        if(not os.path.isdir(full_folder_name)):
            continue
        file_list = os.listdir(full_folder_name)
        for file_name in file_list:
            full_file_name = full_folder_name + '/' + file_name
            output_file_list.append([full_file_name,folder_name,file_name])
    return output_file_list
def file_save(folder_name):
    print(folder_name)
    y_value=[]
    allaboutthis=np.arange(129*126).reshape((1,129*126))
    filelist = get_file_list(folder_name)
    file_len = len(filelist)
    file_idx = 0
    for filename in filelist:
        tempdata = wav2np(filename[0])
        tempdata = tempdata.reshape((1,129*126))
        allaboutthis=np.concatenate((allaboutthis,tempdata))
        for i in range(10):
            if filename[1] == value_array[i] :
                a=[0]*10
                a[i]=1
                y_value.append(a)
                break
            if i == 9:
                print('error - no found folder name')
        file_idx = file_idx+1
        if(file_idx % 100 == 0):
            print(file_idx,'/',file_len)

    dataframe=pd.DataFrame(allaboutthis)
    # filename change x
    #dataframe.to_csv(folder_name+'x_nn.csv')# no nomalize
    dataframe.to_csv(folder_name+'x.csv')# nomalize
    #
    dataframe2=pd.DataFrame(y_value)
    # finename change y
    #dataframe2.to_csv(folder_name+'y_nn.csv')# no nomalize
    #
    dataframe2.to_csv(folder_name+'y.csv')# nomalize

def wav2np(filename):
    sample_rate, samples = wavfile.read(filename)
    frequencies, times, spectrogram = signal.stft(samples, fs=sample_rate)
    spectrogram = np.abs(spectrogram)
    # nomalize
    #spectrogram = normalize(spectrogram)
    if len(frequencies) != 129:
        print("fre : ",filename," ",len(frequencies))
    if len(times) > 126:
        print("tim : ",filename," ",len(times))

    if len(spectrogram[0]) is not 126:
        a=np.full((129,126-len(spectrogram[0])),0.0)
        spectrogram = np.hstack((spectrogram,a))
    return spectrogram

def main():
    file_save(train_folder_name)
    print('train fin')
    file_save(valid_folder_name)
    print('valid fin')
    file_save(test_folder_name)
    print('all fin')

if __name__=='__main__':
    main()


from __future__ import annotations

import sys

import tqdm
from pysam import VariantFile

import ugvc.vcfbed.pysam_utils as pu

def filterOverlappingNoneGVCFs(input_gvcf: str, output_gvcf: str) -> tuple(int, int):
    """Filters non-called variants that overlap other variants from DeepVariant gVCFs.
    In the context of GLNexus joint calling, non-called deletion variants (./.) that
    overlap called variants can generate missed variant calls in joint calling.
    For now we introduced a hack that removed missed-genotype variants
    that overlap called variants.

    Parameters
    ----------
    input_gvcf : str
        input gvcf
    output_gvcf : str
        cleaned up gvcf

    Returns
    -------
    tuple(int,int)
        Number of written, number of removed records

    """
    with VariantFile(input_gvcf) as vcf_in, VariantFile(output_gvcf, mode="w", header=vcf_in.header) as vcf_out:

        # once we read a variant that can overlap later variants, we keep a buffer
        # of overlapping variants
        buffer: list = []
        buffer_chrom = ""
        buffer_span = 0

        # special logic is applied to the buffer only if it contains a homozyous alt variant
        called_var_in_buffer = False
        count_skipped = 0
        count_written = 0
        for rec in tqdm.tqdm(vcf_in):
            # if we finished the block of overlapping variants - we dump the buffer
            if rec.chrom != buffer_chrom or rec.pos > buffer_span:  # if we are out of the buffer
                while buffer:
                    tmp = buffer.pop(0)
                    if not called_var_in_buffer or tmp.samples[0]["GT"] != (None, None):
                        vcf_out.write(tmp)
                        count_written += 1
                    # skip all variants that overlap called alt and have GT not called
                    else:  # (tmp.samples[0]['GT']==(None,None)):
                        count_skipped += 1
                        continue
                    buffer_chrom = ""
                    buffer_span = 0
                called_var_in_buffer = False
            # now for the new deletion
            dels_in_rec = pu.is_deletion(rec)
            lens_in_rec = pu.indel_length(rec)
            max_del_lens = max([lens_in_rec[i] for i, x in enumerate(dels_in_rec) if x] + [0])
            if buffer:  # either it is covered by the buffer
                buffer.append(rec)
                if max_del_lens > 0:
                    buffer_span = max(buffer_span, rec.pos + max_del_lens)
            elif max_del_lens > 0:  # or if it is a deletion - we will append it to the buffer
                buffer.append(rec)
                buffer_chrom = rec.chrom
                buffer_span = rec.pos + max_del_lens
            else:
                vcf_out.write(rec)
                count_written += 1
            if buffer and (rec.samples[0]["GT"][0] is not None) and (rec.samples[0]["GT"] != (0, 0)):
                called_var_in_buffer = True

        # dump buffer at the end
        while buffer:
            tmp = buffer.pop(0)
            if not called_var_in_buffer or tmp.samples[0]["GT"] != (None, None):
                vcf_out.write(tmp)
                count_written += 1
            # skip all variants that overlap called alt and have GT not called
            else:  # (tmp.samples[0]['GT']==(None,None)):
                count_skipped += 1
                continue
    return count_written, count_skipped

if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.stderr.write("Usage: cleanup_gvcf_before_calling.py input_gvcf output_gvcf")
        sys.exit(1)
    else:
        result = filterOverlappingNoneGVCFs(sys.argv[1], sys.argv[2])
        sys.stderr.write(f"Written {result[0]} records, removed {result[1]} records")


from elasticsearch import Elasticsearch
from elasticsearch import helpers
import csv
import os
import time
import json
import random
import requests

datapath = '/home/ubuntu/data/lianailianmeng'
os.chdir(datapath)
blocklen = 500

class Lianaizhuli_ES:
    # es = Elasticsearch([{"host": "119.29.67.239", "port": 9218, "timeout": 3600}])
    es = Elasticsearch([{"host": "182.254.227.188", "port": 9218, "timeout": 3600}])

    def __init__(self):
        # self.es.indices.delete(index='userinfo')
        # self.es.indices.delete(index='userzhifu')
        # self.es.indices.delete(index='tuweiqinghua')
        # self.es.indices.delete(index='jinpushequ')
        # self.es.indices.delete(index='kefu')
        if self.es.indices.exists(index='kefu') is not True:
            lianaizhuli_index = {
                "settings": {
                    "number_of_shards": 1,
                    "number_of_replicas": 1,
                },
                "properties": {
                    "title": {
                        "type": "text",
                        "fields": {
                            "cn": {
                                "type": "text",
                                "analyzer": "ik_smart"
                            },
                            "en": {
                                "type": "text",
                                "analyzer": "english"
                            }
                        }
                    }
                }
            }
            # ret_userhis = self.es.indices.create(index='userhis', body=lianaizhuli_index, ignore=400)
            # print(ret_userhis)
            # ret_userinfo = self.es.indices.create(index='userinfo', body=lianaizhuli_index, ignore=400)
            # print(ret_userinfo)
            # ret_userzhifu = self.es.indices.create(index='userzhifu', body=lianaizhuli_index, ignore=400)
            # print(ret_userzhifu)
            # ret_tuweiqinghua = self.es.indices.create(index='tuweiqinghua', body=lianaizhuli_index, ignore=400)
            # print(ret_tuweiqinghua)
            # ret_jinpushequ = self.es.indices.create(index='jinpushequ', body=lianaizhuli_index, ignore=400)
            # print(ret_jinpushequ)
            # ret_kefu = self.es.indices.create(index='kefu', body=lianaizhuli_index, ignore=400)
            # print(ret_kefu)
            actions = []
            # with open('tuweiqinghua.json', 'r') as f:
            #     for line in f:
            #         item = json.loads(line.strip())
            #         action = {
            #             "_index": "tuweiqinghua",
            #             "_type": "tuweiqinghua",
            #             "_source": item,
            #             '_id':item['chatId']
            #         }
            #         actions.append(action)
            # random.shuffle(actions)
            # while len(actions):
            #     helpers.bulk(self.es, actions[:blocklen])
            #     actions = actions[blocklen:]
            # with open('jinpushequ.json', 'r') as f:
            #     for line in f:
            #         item = json.loads(line.strip())
            #         action = {
            #             "_index": "jinpushequ",
            #             "_type": "jinpushequ",
            #             "_source": item,
            #             '_id':item['id']
            #         }
            #         actions.append(action)
            # random.shuffle(actions)
            # while len(actions):
            #     helpers.bulk(self.es, actions[:blocklen])
            #     actions = actions[blocklen:]
            print('创建结束！')

    def add(self):
        return None

    def delete(self):
        return None

    def updata(self):
        return None

# LAES = Lianaizhuli_ES()


from datetime import datetime

now = datetime.now()

current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
from operator import or_
from xml.dom import minidom
file = minidom.parse('ord.xml')
# print('hello world')
AddOrder = file.getElementsByTagName('AddOrder')
DeleteOrder = file.getElementsByTagName('DeleteOrder')
# print(AddOrder[0].attributes['book'].value)
# for elem in DeleteOrder:
#     print(elem.attributes['orderId'].value)

books = dict()
for ele in AddOrder:
    # print(ele.attributes['book'])
    if ele.attributes['book'].value not in books.keys():
        if ele.attributes['operation'].value=="SELL":
            books[ele.attributes['book'].value]=([],[(ele.attributes['volume'].value,ele.attributes['price'].value)])
        else :
            books[ele.attributes['book'].value]=([(ele.attributes['volume'].value,ele.attributes['price'].value)],[])
    else:
        if ele.attributes['operation'].value=="SELL":
            books[ele.attributes['book'].value][1].append((ele.attributes['volume'].value,ele.attributes['price'].value))
        else :
            books[ele.attributes['book'].value][0].append((ele.attributes['volume'].value,ele.attributes['price'].value))

# output:
# print(books)
for key in books.keys():
    print("book: "+key)
    print("BUY--SELL")
    print("=="*20)
    buy=books[key][0]
    sell=books[key][1]
    i=0
    while i<len(buy) or i<len(sell):
        if i<len(buy):
            print(buy[i][0]+"@"+buy[i][1],end="")
        print("--",end="")
        if i<len(sell):
            print(sell[i][0]+"@"+sell[i][1],end="")
        print('')
        i+=1

now = datetime.now()

current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)


import time

import dgl
import dgl.nn as dglnn

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchmetrics.functional as MF
from ogb.nodeproppred import DglNodePropPredDataset
from dgl.data import AsNodePredDataset
from dgl.data import RedditDataset
import GPUtil

class GNNModel(nn.Module):
    def __init__(self,  gnn_layer: str, n_layers: int, layer_dim: int,
                 input_feature_dim: int, n_classes: int, n_linear: int):
        super().__init__()

        assert n_layers >= 1, 'GNN must have at least one layer'
        dims = [input_feature_dim] + [layer_dim] * (n_layers-1) + [n_classes]
        print(dims)

        self.convs = nn.ModuleList()
        self.norm = nn.ModuleList()

        self.n_layers = n_layers
        self.n_linear = n_linear

        for idx in range(n_layers):
            if idx < n_layers - n_linear:
                if gnn_layer == 'gat':
                    # use 2 aattention heads
                    # layer = dglnn.GATConv(dims[idx], dims[idx+1], 1)  # pylint: disable=no-member
                    layer = dglnn.AGNNConv(learn_beta=False, allow_zero_in_degree=True)
                elif gnn_layer == 'gcn':
                    layer = dglnn.GraphConv(dims[idx], dims[idx+1], allow_zero_in_degree=True)  # pylint: disable=no-member
                elif gnn_layer == 'sage':
                    # Use mean aggregtion
                    # pylint: disable=no-member
                    layer = dglnn.SAGEConv(dims[idx], dims[idx+1],
                                            aggregator_type='mean')
                else:
                    raise ValueError(f'unknown gnn layer type {gnn_layer}')
                self.convs.append(layer)
            else:
                self.convs.append(nn.Linear(dims[idx], dims[idx+1]))

            if idx < n_layers - 1:
                self.norm.append(nn.LayerNorm(dims[idx+1], elementwise_affine=True))

    def forward(self, graph, features):
        h = features
        for idx in range(self.n_layers):

            h = F.dropout(h, p=0.1)
            if idx < self.n_layers - self.n_linear:
                # graph->graph[idx] for minibatch training
                h = self.convs[idx](graph, h)
                if h.ndim == 3:  # GAT produces an extra n_heads dimension
                    h = h.mean(1)
            else:
                h = self.convs[idx](h)

            if idx < self.n_layers - 1:
                h = self.norm[idx](h)
                h = F.relu(h, inplace=True)

        return h

class SAGE(nn.Module):
    def __init__(self, in_feats, n_hidden, n_classes):
        super().__init__()
        self.layers = nn.ModuleList()
        self.layers.append(dglnn.SAGEConv(in_feats, n_hidden, "mean"))
        self.layers.append(dglnn.SAGEConv(n_hidden, n_hidden, "mean"))
        self.layers.append(dglnn.SAGEConv(n_hidden, n_hidden, "mean"))
        self.layers.append(dglnn.SAGEConv(n_hidden, n_classes, "mean"))
        self.dropout = nn.Dropout(0.5)

    def forward(self, sg, x):
        h = x
        for l, layer in enumerate(self.layers):
            h = layer(sg, h)
            if l != len(self.layers) - 1:
                h = F.relu(h)
                h = self.dropout(h)
        return h

class GCN(nn.Module):
    def __init__(self, in_size, hid_size, out_size):
        super().__init__()
        self.layers = nn.ModuleList()
        # three-layer GraphSAGE-mean
        self.layers.append(dglnn.GraphConv(in_size, hid_size, activation=F.relu, allow_zero_in_degree=True))
        self.layers.append(dglnn.GraphConv(hid_size, hid_size, activation=F.relu, allow_zero_in_degree=True))
        self.layers.append(dglnn.GraphConv(hid_size, hid_size, activation=F.relu, allow_zero_in_degree=True))
        self.layers.append(dglnn.GraphConv(hid_size, out_size, allow_zero_in_degree=True))
        self.dropout = nn.Dropout(0.5)

    def forward(self, sg, x):
        h = x
        for l, layer in enumerate(self.layers):
            h = layer(sg, h)
            if l != len(self.layers) - 1:
                h = F.relu(h)
                h = self.dropout(h)
        return h

dataset = dgl.data.AsNodePredDataset(DglNodePropPredDataset("ogbn-products"))
# dataset = AsNodePredDataset(RedditDataset())
graph = dataset[
    0
]  # already prepares ndata['label'/'train_mask'/'val_mask'/'test_mask']

model = GNNModel('sage ', 3, 128, graph.ndata['feat'].size(1), dataset.num_classes, 0).to("cuda:0")
opt = torch.optim.Adam(model.parameters(), lr=0.003, weight_decay=5e-4)

num_partitions = 50
sampler = dgl.dataloading.SAINTSampler(mode='node', budget=8000)
# Assume g.ndata['feat'] and g.ndata['label'] hold node features and labels
dataloader = dgl.dataloading.DataLoader(
    graph,
    torch.arange(num_partitions).to("cuda:0"),
    sampler,
    device="cuda:0",
    use_uva=True,
)
durations = []
best_val_acc = 0
peak_memory = 0
for epoch in range(100):
    t0 = time.time()
    model.train()
    for it, sg in enumerate(dataloader):
        x = sg.ndata["feat"]
        y = sg.ndata["label"]
        m = sg.ndata["train_mask"].bool()
        y_hat = model(sg, x)
        loss = F.cross_entropy(y_hat[m], y[m])
        opt.zero_grad()
        loss.backward()
        opt.step()
        if it % 20 == 0:
            acc = MF.accuracy(
                y_hat[m],
                y[m],
                task="multiclass",
                num_classes=dataset.num_classes,
            )
            GPUs = GPUtil.getGPUs()
            if GPUs[0].memoryUsed > peak_memory:
                peak_memory = GPUs[0].memoryUsed
            print("Loss", loss.item(), "Acc", acc.item(), "GPU Mem", peak_memory, "MB")

    tt = time.time() - t0
    print("Run time for epoch# %d: %.2fs" % (epoch, tt))
    durations.append(tt)

    model.eval()
    with torch.no_grad():
        val_preds, test_preds = [], []
        val_labels, test_labels = [], []
        for it, sg in enumerate(dataloader):
            x = sg.ndata["feat"]
            y = sg.ndata["label"]
            m_val = sg.ndata["val_mask"].bool()
            m_test = sg.ndata["test_mask"].bool()
            y_hat = model(sg, x)
            val_preds.append(y_hat[m_val])
            val_labels.append(y[m_val])
            test_preds.append(y_hat[m_test])
            test_labels.append(y[m_test])
        val_preds = torch.cat(val_preds, 0)
        val_labels = torch.cat(val_labels, 0)
        test_preds = torch.cat(test_preds, 0)
        test_labels = torch.cat(test_labels, 0)
        val_acc = MF.accuracy(
            val_preds,
            val_labels,
            task="multiclass",
            num_classes=dataset.num_classes,
        )
        if val_acc.item() > best_val_acc:
            best_val_acc = val_acc.item()
        test_acc = MF.accuracy(
            test_preds,
            test_labels,
            task="multiclass",
            num_classes=dataset.num_classes,
        )
        print("Validation acc:", val_acc.item(), "Test acc:", test_acc.item())

print(
    "Average run time for last %d epochs: %.2fs standard deviation: %.3f"
    % ((epoch - 3), np.mean(durations[4:]), np.std(durations[4:]))
)
print("Best validation acc:", best_val_acc)


import pyglet
import math
import time
import json
import base
from base import Game

class Point:
    pass

class Entity:
    """
    All entities(such as towers and creeps) have the same
    properties, like x and y coordinates and stuff like that.
    """
    def __init__(self, name, x=0, y=0):
        self.name = name
        self.xp = 0
        self.level = 1

        self.alive = True

        self.x = x
        self.y = y
        self.radius = 5

        self.r = 255
        self.g = 255
        self.b = 255

    def render(self):
        pyglet.graphics.draw(6, pyglet.gl.GL_POLYGON,
                             ('v2f', (self.x - 10, self.y - 4,
                             self.x, self.y - 12,
                             self.x + 10, self.y - 4,
                             self.x + 10, self.y + 4,
                             self.x, self.y + 12,
                             self.x - 10, self.y + 4)),
                             ('c3B', (
                              self.r, self.g, self.b,
                              self.r, self.g, self.b,
                              self.r, self.g, self.b,
                              self.r, self.g, self.b,
                              self.r, self.g, self.b,
                              self.r, self.g, self.b))
                             )

    def dist(self, ent):
        return math.sqrt(math.pow(self.x - ent.x, 2) +
                         math.pow(self.y - ent.y, 2))

    def angle(self, ent):
        return math.atan2(ent.y - self.y, ent.x - self.x)

    def update(self):
        pass

class Creep(Entity):
    defs = json.load(open('res/defs/creeps.json'))

    def __init__(self, name, path):
        self.sprite = pyglet.sprite.\
                      Sprite(pyglet.resource.image("%s.png" % name),
                      batch=Game.batch)
        path = self._toObj(path)
        Entity.__init__(self, name, path[0].x, path[0].y)
        self.sprite.x = self.x
        self.sprite.y = self.y

        try:
            tmp = name.split('.')
            if len(tmp) > 1:
                name = tmp[0]
                self.level = int(tmp[1])
        except:
            pass

        self.name = name
        self.path = path
        self.r = 200
        self.g = 40
        self.b = 20

        self.speed = Creep.defs[name]['speed']
        self.hp = Creep.defs[name]['hp'] * self.level
        self.gold = Creep.defs[name]['gold'] * self.level
        self.radius = Creep.defs[name]['radius']

        self.alive = False
        self.path_point = 1
        self.reached_end = False

    def update(self):
        if self.alive is False:
            return

        #Update the position, in function of path point
        angle = self.angle(self.path[self.path_point])
        xdif = self.speed * math.cos(angle)
        ydif = self.speed * math.sin(angle)

        self.sprite.y = self.sprite.y + ydif
        self.sprite.x = self.sprite.x + xdif
        self.x = self.sprite.x
        self.y = self.sprite.y

        #Reach point?
        if self.dist(self.path[self.path_point]) < 5:
            self.path_point += 1

        #End of the line?
        if self.path_point == len(self.path):
            self.alive = False
            self.reached_end = True

    def render(self):
        #Entity.render(self)
        self.sprite.draw()
        pyglet.text.Label("%s Lv.%d - %d" % (self.name, self.level, self.hp),
                          font_name='Arial',
                          font_size=8,
                          x=self.x, y=self.y + 10,
                          anchor_x='center', anchor_y='center').draw()

    def _toObj(self, path):
        points = list()

        for point in path:
            P = Point()
            P.x = point['x']
            P.y = point['y']
            points.append(P)

        return points

class Tower(Entity):
    defs = json.load(open('res/defs/towers.json'))

    def __init__(self, name, x=0, y=0):
        name = int(name)
        T = Tower.defs['towers'][name]

        Entity.__init__(self, T['name'], x, y)
        self.r = 40
        self.g = 40
        self.b = 200

        self.cooldown = T['cooldown']
        self.cooldown_timer = 0
        self.bullet = None
        self.range = T['range']

    def not_shooting(self):
        if self.bullet is None:
            return True
        return False

    def shoot(self, target):
        if self.bullet is None:
            if time.time() - self.cooldown_timer > self.cooldown:
                self.cooldown_timer = time.time()
                self.bullet = Bullet("bang", target, self.x, self.y)

    def render(self):
        Entity.render(self)
        pyglet.text.Label("%s lv%d" % (self.name, self.level),
                          font_name='Arial',
                          font_size=8,
                          x=self.x, y=self.y + 10,
                          anchor_x='center', anchor_y='center').draw()

        #Target died before bullet reached it
        if self.bullet is not None and self.bullet.target.alive is False:
            self.bullet = None

        #Remove bullets
        if self.bullet is not None and self.bullet.alive is False:
            self.bullet = None

        if self.bullet is not None:
            self.bullet.render()
            self.bullet.update()

class Bullet(Entity):
    def __init__(self, name, ent, x=0, y=0, speed=6):
        Entity.__init__(self, name, x, y)
        self.r = 40
        self.g = 40
        self.b = 0

        self.speed = speed
        self.target = ent
        self.damage = 20

    def render(self):
        pyglet.graphics.draw(1, pyglet.gl.GL_POINTS,
                             ('v2f', (self.x, self.y))
                             )

    def update(self):
        #Update the position, in function of target's position
        angle = self.angle(self.target)
        xdif = self.speed * math.cos(angle)
        ydif = self.speed * math.sin(angle)

        self.y = self.y + ydif
        self.x = self.x + xdif

        #Impact?
        if self.dist(self.target) < self.target.radius:
            self.alive = False
            self.target.hp -= self.damage

            if self.target.hp <= 0:
                self.target.alive = False


from bottle import route, run, template, request, static_file
import json

ID = "xtable1"

@route('/js/<filename>')
def send_static(filename):
	return static_file(filename, root="./js")

@route('/css/<filename>')
def send_static(filename):
	return static_file(filename, root="./css")

@route("/table")
def index():
	with open("./" + ID + ".json", "r", encoding='utf-8') as infile:
		data = json.load(infile)
	table = "
\n"
	for a, b in sorted(data.items()):
		if a == "caption":
			table += "\t
<input type='text' value='{}'>
\n".format(b)
		if a == "headers":
			table += "\t
\n"
			for _, c in sorted(b.items()):
				table += "\t\t<input type='text' value='{}'>	\n".format(c)
			table += "\t
\n"
		if a == "rows":
			for _, c in sorted(b.items()):
				table += "\t
\n"
				for _, d in sorted(c.items()):
					table += "\t\t<input type='text' value='{}'>	\n".format(d)
				table += "\t
\n"

	table += "
"
	return template("index.html", table=table)

@route("/table", method="POST")
def do_table_post():
	with open(ID + ".json", "w", encoding='utf-8') as outfile:
		json.dump(request.json, outfile, indent="\t", ensure_ascii=False)

run(host="localhost", port=80, server="tornado")


import pdb
import os
import collections
import datetime
import itertools

import numpy as N
import matplotlib as M
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

import evac.utils as utils
from evac.datafiles.gribfile import GribFile
from evac.datafiles.narrfile import NARRFile

outroot = "/Users/john.lawson/data/figures"
narrroot = '/Users/john.lawson/data/AprilFool/NARR'
# The grib table is messed up
# Zstr = "Total precipitation anomaly of at least 10 mm"
Zstr = "HGT"
Zlv = "level 500"

CASES_narr = collections.OrderedDict()
CASES_narr[datetime.datetime(2016,3,31,0,0,0)] = datetime.datetime(2016,3,31,12,0,0)
CASES_narr[datetime.datetime(2017,5,1,0,0,0)] = datetime.datetime(2017,5,1,12,0,0)
CASES_narr[datetime.datetime(2017,5,2,0,0,0)] = datetime.datetime(2017,5,2,12,0,0)
CASES_narr[datetime.datetime(2017,5,4,0,0,0)] = datetime.datetime(2017,5,4,12,0,0)

# Load tornado report CSV to plot lat/lon

# Load severe hail reports, or draw a swathe of SVR reports with Python?
# Could plot hail reports as proxy for mesocyclonic activity.

fig,_axes = plt.subplots(ncols=4,nrows=4,figsize=(12,10))
fig_fname = "case_outline.png"
fig_fpath = os.path.join(outroot,fig_fname)
axes = _axes.flat

# For each case...
for caseutc, plotutc in CASES_narr.items():
    casestr = utils.string_from_time('dir',plotutc,strlen='hour')
    narr_fname = f'merged_AWIP32.{casestr}.3D'
    narr_fpath = os.path.join(narrroot,narr_fname)

    # Load NARR data
    # G = GribFile(fpath)
    G = NARRFile(narr_fpath)
    data_925 = G.get("HGT",level="level 925")[0,0,:,:]
    data_500 = G.get("HGT",level="level 500")[0,0,:,:]

    # lats = G.lats
    # lons = G.lons

    # Plot 500 hPa height, 925 hPa height from NARR
    ax = next(axes)
    m = create_bmap(50.0,-55.0,25.0,-130.0,ax=ax)
    x,y = m(G.lons,G.lats)
    m.drawcoastlines()
    m.drawmapboundary(fill_color='gray')
    m.fillcontinents(color="lightgray",lake_color="gray")
    m.drawstates()
    m.drawcountries()

    kws = {'linewidths':0.7}

    # mediumorchid
    # purple
    m.contour(x,y,data_500,colors='k',levels=N.arange(4000,6000,60),**kws)
    m.contour(x,y,data_925,colors='mediumorchid',levels=N.arange(0,2000,40),**kws)

    # Plot shear and CAPE from EE3km
    fcst_data, fcst_lats, fcst_lons = load_fcst_dll(fcst_vrbl,fcst_fmt,
                            validutc,caseutc,initutc,mem)
    fcst_fpath = get_extraction_fpaths(vrbl=fcst_vrbl,fmt=fcst_fmt,
                                    validutc=validutc,caseutc=caseutc,initutc=initutc,
                                    mem=mem)

    # maybe boundaries/theta-e?

    # Thumbnail of reflectivity with reports (tornado and/or hail)

    fig.savefig(fig_fpath)
    pdb.set_trace()

fig.savefig(fig_fpath)
plt.close(fig)