#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 - cologler <skyoflw@gmail.com>
# ----------
#
# ----------

import os, time, sys
from enum import Enum
import queue, threading
import urllib3

threadLock = threading.Lock()

class DownloadResult(Enum):
    ConnectError = 0
    ContentError = 1
    NoModify = 2
    Updated = 3

class Downloader(threading.Thread):
    def __init__(self, spider):
        super().__init__()
        self.spider = spider

    def run(self):
        while True:
            next_id = self.spider.queue.get()
            if next_id is None:
                print('[INFO]', 'queue was empty so thread exit.')
                return
            r = self.spider.download(next_id)
            if r == DownloadResult.Updated:
                print('[INFO]', '(%s) updated %s' % (self.spider.name, next_id))
            elif r == DownloadResult.NoModify:
                print('[INFO]', '(%s) ignored %s' % (self.spider.name, next_id))
            elif r == DownloadResult.ContentError:
                print('[INFO]', '(%s) conterr %s' % (self.spider.name, next_id))
            else:
                pass
                #print('[INFO]', '(%s) download %s failed' % (self.spider.name, next_id))

class Spider:
    def __init__(self):
        self.now = time.localtime()
        self.day = 0
        self.out = 'data'
        self.finish = 'finish'
        self.map = {}
        self.finish_items = {}

    @property
    def name(self): raise NotImplementedError('name')

    def items(self):
        if not os.path.isdir(self.out):
            os.mkdir(self.out)
        else:
            for f in os.listdir(self.out):
                yield (self.out, f)
        for store in self.stores:
            if os.path.isdir(store):
                for f in os.listdir(store):
                    yield (store, f)

    def map_files(self):
        if self.finish:
            if os.path.isdir(self.finish):
                for f in os.listdir(self.finish):
                    self.map_to_dict(self.finish_items, f, os.path.join(self.finish, f))
        for r, f in self.items():
            self.map_to_dict(self.map, f, os.path.join(r, f))

    def map_to_dict(self, d, f, path):
        i = int(f[:f.find('.')])
        d[i] = path

    def get_filename(self, id, title):
        title = title.replace('/', '_').replace('\\', '_').replace('|', '_')
        title = title.replace('?', '_').replace('*', '_')
        title = title.replace('>', '_').replace('<', '_')
        return str(id).zfill(6) + '. ' + title + ".txt"

    def need_check(self, id):
        if id in self.finish_items:
            return False
        if not id in self.map:
            return True
        file = self.map[id]
        if not os.path.isfile(file):
            return True
        mtime = os.path.getmtime(file)
        mtime = time.localtime(mtime)
        now = self.now
        if not now.tm_year == mtime.tm_year:
            return True
        return now.tm_yday > mtime.tm_yday + self.day

    def next(self): raise NotImplementedError('next')

    def run(self, thread_count):
        self.queue = queue.Queue()
        count = 0
        for i in self.next():
            if self.need_check(i):
                count += 1
                self.queue.put_nowait(i)
            if count >= 100000:
                self.internal_run(thread_count)
                count = 0
        for x in range(thread_count):
            self.queue.put_nowait(None)
        if count > 0:
            print('[INFO]', '%s items need to download' % (count))
            self.internal_run(thread_count)

    def internal_run(self, thread_count):
        threads = []
        for x in range(thread_count):
            t = Downloader(self)
            t.start()
            threads.append(t)
        #self.queue.join()
        #print('[INFO]', 'queue was clear.')
        for t in threads:
            t.join()
        print('[INFO]', 'all thread done.')

    def run_by_id(self, id):
        r = self.download(id)
        if r == DownloadResult.Updated:
            print(' -updated.')
        elif r == DownloadResult.NoModify:
            print(' -no updated.')
        else:
            print(' -error.')

        input()

    def write(self, path, buff):
        if os.path.isfile(path):
            if os.path.getsize(path) >= len(buff):
                os.utime(path)
                return DownloadResult.NoModify
        with open(path, 'wb') as fp:
            fp.write(buff)
        return DownloadResult.Updated

    def get_url(self, id): raise NotImplementedError('get_url')

    def content_vaild(self, r):
        return r.headers['Content-Type'] == 'text/plain'

    def get_title(self, r):
        text = r.data.decode('gbk', errors='ignore')
        title = text[:text.find('\n')]
        if title[len(title) - 1] == '\r':
            title = title[:-1]
        if title[0] == '《' and title[-1:] == '》':
            title = title[1:-1]
        return title

    def download(self, id):
        http = urllib3.PoolManager(timeout=5.0)
        url = self.get_url(id)
        try:
            r = http.request('GET', url)
        except Exception as e:
            return DownloadResult.ConnectError
        if not r.status == 200:
            return DownloadResult.ConnectError
        if not self.content_vaild(r):
            return DownloadResult.ContentError
        if id in self.map:
            path = self.map[id]
        else:
            title = self.get_title(r)
            filename = self.get_filename(id, title)
            if self.is_completed(id):
                path = os.path.join(self.finish, filename)
            else:
                path = os.path.join(self.out, filename)
        return self.write(path, r.data)

    def is_completed(self, id):
        return False

class Spider_45txt(Spider):
    def __init__(self):
        super().__init__()

    @property
    def name(self): return '45txt'

    def next(self):
        tag = 'href="http://www.45txt.com/shu/'
        http = urllib3.PoolManager(timeout=5.0)
        r = http.request('GET', 'www.45txt.com/map/1.html')
        text = r.data.decode('gbk', errors='ignore')
        textclip = text[text.find(tag)+len(tag):]
        textclip = textclip[:textclip.find('/')]
        self.max = int(textclip)
        print('[INFO]', 'max value is ' + str(self.max))
        for i in range(1, self.max + 1):
            yield i

    def get_url(self, id):
        return 'http://www.45txt.com/modules/article/txtarticle.php?id=' + str(id)

class Spider_shushuwu(Spider):
    def __init__(self):
        super().__init__()

    @property
    def name(self): return 'shushuwu'

    def next(self):
        tag = 'href="/novel/'
        http = urllib3.PoolManager(timeout=5.0)
        r = http.request('GET', 'www.shushuwu.net/top/postdate_1.html')
        text = r.data.decode('gbk', errors='ignore')
        textclip = text[text.find(tag)+len(tag):]
        textclip = textclip[:textclip.find('/')]
        self.max = int(textclip)
        print('[INFO]', 'max value is ' + str(self.max))
        for i in range(1, self.max + 1):
            yield i

    def get_url(self, id):
        return 'http://www.shushuwu.net/down/' + str(id) + '/all/'

class Spider_qidian(Spider):
    def __init__(self):
        super().__init__()
        self.tags_complete = 'itemprop="updataStatus">已完本'

    @property
    def name(self): return 'qidian'

    def next(self):
        self.max = 99999999
        print('[INFO]', 'max value is ' + str(self.max))
        for i in range(1, self.max + 1):
            yield i

    def get_url(self, id):
        return 'http://download.qidian.com/pda/%s.txt' % id

    def is_completed(self, id):
        http = urllib3.PoolManager(timeout=5.0)
        url = 'www.qidian.com/Book/%s.aspx' % id
        try:
            r = http.request('GET', url)
            html = r.data.decode('utf8')
            return html.find(self.tags_complete) > 0
        except Exception as e:
            return False
        return False

def spiders():
    yield Spider_45txt()
    yield Spider_shushuwu()
    yield Spider_qidian()

def get_spider(source):
    for s in spiders():
        if s.name == source:
            return s

def parse_arg(arg, key, value):
    if arg.startswith(key):
        return arg[len(key):]
    else:
        return value

def main():
    day = '0'
    id = None
    out = 'data'
    finish = 'finish'
    source = '45txt'
    thread_count = '20'
    stores = []
    for arg in sys.argv[1:]:
        source = parse_arg(arg, '-source=', source)
        day = parse_arg(arg, '-d=', day)
        id = parse_arg(arg, '-id=', id)
        out = parse_arg(arg, '-out=', out)
        finish = parse_arg(arg, '-finish=', finish)
        thread_count = parse_arg(arg, '-tc=', thread_count)
        store = parse_arg(arg, '-tc=', None)
        if store:
            stores.append(store.replace('"', ''))
    spider = get_spider(source)
    if not spider:
        print('error source arg')
    else:
        spider.day = int(day)
        spider.out = out.replace('"', '')
        spider.finish = finish.replace('"', '')
        spider.stores = stores
        if not os.path.isdir(spider.out):
            os.mkdir(spider.out)
        if not os.path.isdir(spider.finish):
            os.mkdir(spider.finish)
        if id:
            spider.run_by_id(int(id))
        else:
            spider.map_files()
            spider.run(int(thread_count))

if __name__ == '__main__':
    main()


import datetime
import os
import PIL.ImageGrab
from pynput import keyboard
import PlayerProfile
import DatabaseConnections

class ImageGrabber(object):

    def __init__(self, alliance):
        self.alliance = alliance
        self.num_saved = 0
        self.db = DatabaseConnections.get_database()

        self._root = r"E:\OneDrive\101_Personal\100_Games\InfinityKingdom\S79\ScreenScraper"
        self._date = datetime.date.today()
        self.path = os.path.join(self._root, str(self._date), self.alliance)

        if os.path.exists(self.path):
            raise ValueError("Path already exists")
        else:
            os.makedirs(self.path)

    def grab_screen(self):
        _path = os.path.join(self.path, "{}.png".format(self.num_saved))
        PIL.ImageGrab.grab().save(
            _path
        )

        try:
            print("capturing")
            p = PlayerProfile.PlayerProfile(_path)
            print(p.name, 'captured')
        except Exception as e:
            print("Unable to calculate values", e)

        self.num_saved += 1

    def key_pressed(self, key):
        if key == keyboard.KeyCode(char="c"):
            self.grab_screen()
        else:
            print("Wrong key pressed, skipping.")

if __name__ == "__main__":
    ig = ImageGrabber("FATE")

    with keyboard.Listener(on_press=ig.key_pressed) as listener:
        listener.join()


def main():
    Lista1=[0,1]
    Lista3=[0]
    Lista2=[]
    i=-1
    while i<0:
        i=int(input())
        if i==0:
            print(Lista2)
        elif i>0:
            if i==1:
                print(Lista3)
            elif i==2:
                print(Lista1)
            elif i>2:
                for j in range (i-2):
                    Lista1.append(Lista1[j]+Lista1[j+1])
                print(Lista1)
if __name__=='__main__':
    main()


import sys

def print_byte_codes(data):
  for n, c in enumerate(data):
    print(f"{c:02X}", end=" ")
    if n % 16 == 7:
      print(" | ", end="")
    if n % 16 == 15:
      print()

def bisync_body(data):
  # escaping
  body = data.replace(b'\x10', b'\x10\x10')
  body = data.replace(b'\x02', b'\x10\x02')
  body = data.replace(b'\x03', b'\x10\x03')
  return body

if __name__ == "__main__":
  # execute only if run as a script
  if len(sys.argv) < 3:
    print(f"Usage: {sys.argv[0]} [input path] [output path]")
  else:
    input_path = sys.argv[1]
    output_path = sys.argv[2]

    # read data
    with open(input_path, "rb") as file:
      byte = file.read()
    print("\nData")
    print_byte_codes(byte)

    # convert data to BISYNC body
    body = bisync_body(byte)

    print("\nBody")
    print_byte_codes(body)
    # write body
    with open(output_path, "wb") as file:
      file.write(body)


# -*- coding: utf-8 -*-
"""
Created on Thu Sep 27 09:34:01 2018

@author: SDEDU
"""
#module
import mymodule
mymodule.greeting('Lee')
mymodule.person1['age']

import platform
x=platform.system()
print(x)

x=dir(platform)
print(x)

#file I/O
open('demofile.txt')
f=open('demofile.txt','r')
print(f.read())

f=open('demofile.txt','r')
print(f.read(5))

f=open('demofile.txt','r')
print(f.readline())

f=open('demofile.txt','r')
for x in f:
    print(x)

f=open('demofile.txt','a') #append
f.write('Now the file has one more line!')
f=open('demofile.txt','r')
f.read()

f=open('demofile.txt','w') #overwrite
f.write('Woops! I have deleted the content!')

f=open('myfile.txt','x') #create

import os
os.remove('demofile.txt') #delete file
os.rmdir('myfolder') #delete folder

#class
class MyClass:
    x=5

cla=MyClass()
cla.x

class Shark:
    def swim(self):
        print('The shartk is swimming.')
    def be_awesome(self):
        print('The shark is being awesome.')
s1=Shark() #개체화
s2=Shark()
s1.swim()
s1.be_awesome()
s2.swim()
s2.be_awesome()

#class with construction
class Person:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def myfunc(self):
        print('hello my name is ' + self.name)
pl=Person('Lee',24)
print(pl.name)
print(pl.age)
pl.myfunc()

class Shark:
    def __init__(self,name):
        self.name=name
    def swim(self):
        print(self.name+' is swimming.')
    def be_awesome(self):
        print(self.name +' is being awesome.')
sammy=Shark('Sammy')
sammy.swim()
sammy.be_awesome()

class Person:
  def __init__(mysillyobject, name, age):
    mysillyobject.name = name
    mysillyobject.age = age

  def myfunc(abc):
    print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

p1.age = 40 #modify

del pl.age #delete
del pl

#Lab 4-1
#Write a class named Korean which has a method called printNationality.
class Korean:
    def __init__(self,name,nationality):
        self.name=name
        self.nationality=nationality
    def printNationality(info):
        print(info.name + ' is from ' +info.nationality)
cont=Korean('Lee','Korea')
cont.printNationality()

#Write a class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle
class Circle:
    def __init__(self,radius):
        self.radius=radius
    def area(info):
        print('radius: ', info.radius,' area: ',((info.radius)*(info.radius)),'pi')
    def perimeter(info):
        print('radius: ', info.radius,' perimeter: ',((info.radius*2)),'pi')
cir=Circle(5)
cir.area()
cir.perimeter()

#Write a class named Rectangle constructed by a length and width and a method which will compute the area of a rectangle.
class Rectangle:
    def __init__(self,length,width):
        self.length=length
        self.width=width
    def area(info):
        area=info.length*info.width
        print(info.length,' * ',info.width,' = ',area )
rec=Rectangle(5,4)
rec.area()

#Write a class which has two methods get_String and print_String. get_String accept a string from the user and print_String print the string in upper case.
class upperPrint:
    def __init__(self):
        self.UpInfo=""
    def get_String(self,string):
        self.UpInfo=(string).upper()
    def print_String(self):
        print(self.UpInfo)
upP=upperPrint()
upP.get_String('abcdef')
upP.print_String()
#Write a class to reverse a string word by word. Input string : 'hello .py' Expected Output : '.py hello'
class reverseString:
    def __init__(self,info):
        self.info=info
    def output(self):
        for i in range(-1,-len(self.info),-1):
            print(self.info[i],end='')

rS=reverseString('hello.py')
rS.output()


from tkinter import *

root = Tk()   #making our root window 'root'

x = StringVar()
x.set(0)

gradeEntry = Entry(root)
gradeEntry.place(x=50, y=100, height=25, width=100)
gradeLabel = Label(root, text="Grade (0-100)")
gradeLabel.place(x=50, y=135, height=25, width=100)

weightEntry = Entry(root)
weightEntry.place(x=200, y=100, height=25, width=100)
weightLabel = Label(root, text="Weight (0-100)")
weightLabel.place(x=200, y=135, height=25, width=100)

def calc():
    global x
    try:
        y = int(gradeEntry.get())
        z = int(weightEntry.get()) / 100
        a = round((float(x.get()) + y*z ), 2)
        x.set(a)

    except:
        print("sfas")

calcButton = Button(root, text = "Add to grade", command = calc)
calcButton.place(x=350, y=100, height=25, width=75)

finalLabel = Label(root, textvariable=x, font=("default", 40))
finalLabel.place(x=250, y=250, height=100, width=100)

root.mainloop() #runs main root window


from utils import detector_utils as detector_utils
from utils import predictor_utils as predictor_utils

from utils.hiragana import hiragana
from utils.kanji import kanji
import cv2
import tensorflow as tf
import datetime
import argparse
import numpy as np
from scipy.signal import savgol_filter
from PIL import ImageFont, ImageDraw, Image
import numpy

detection_graph, sess = detector_utils.load_inference_graph()
hiragana_model= predictor_utils.load_hiragana_model()
kanji_model= predictor_utils.load_kanji_model()
katakana_model=None

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('-sth', '--scorethreshold', dest='score_thresh', type=float,
                        default=0.8, help='Score threshold for displaying bounding boxes')
    parser.add_argument('-fps', '--fps', dest='fps', type=int,
                        default=1, help='Show FPS on detection/display visualization')
    parser.add_argument('-src', '--source', dest='video_source',
                        default=0, help='Device index of the camera.')
    parser.add_argument('-wd', '--width', dest='width', type=int,
                        default=480, help='Width of the frames in the video stream.')
    parser.add_argument('-ht', '--height', dest='height', type=int,
                        default=640, help='Height of the frames in the video stream.')
    parser.add_argument('-ds', '--display', dest='display', type=int,
                        default=1, help='Display the detected images using OpenCV. This reduces FPS')

    arrayDrawed = []

    modifiedPoints = []
    drawedPoints = []
    lineCounts = -1
    isStart = False

    args = parser.parse_args()
    print(args.video_source)
    cap = cv2.VideoCapture(0)
    codec = 0x47504A4D  # MJPG
    cap.set(cv2.CAP_PROP_FPS, 30.0)
    cap.set(cv2.CAP_PROP_FOURCC, codec)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)

    start_time = datetime.datetime.now()
    num_frames = 0
    im_width, im_height = (cap.get(3), cap.get(4))
    num_hands_detect = 1

    cv2.namedWindow('Single-Threaded Detection', cv2.WINDOW_NORMAL)

    # kalman ##########################################################
    kalman = cv2.KalmanFilter(4, 2)
    """
        - dynamParams: This parameter states the dimensionality of the state
        - MeasureParams: This parameter states the dimensionality of the measurement
        - ControlParams: This parameter states the dimensionality of the control
        - vector.type: This parameter states the type of the created matrices that should be CV_32F or CV_64F
    """
    kalman.measurementMatrix = np.array([[1,0,0,0],[0,1,0,0]],np.float32)
    kalman.transitionMatrix = np.array([[1,0,1,0],[0,1,0,1],[0,0,1,0],[0,0,0,1]],np.float32)
    kalman.processNoiseCov = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]],np.float32) * 0.003 # lưu ý
    # kalman.processNoiseCov = np.array([[3,0,0,0],[0,3,0,0],[0,0,3,0],[0,0,0,3]],np.float32) * 0.0003 # lưu ý

    check = False # to check hội tụ
    countPassedPoint = 0 # làm thời gian chờ để hiện điểm

    isFirstPoint = False
    countListPoints = -1
    isBacked = True
    #################################################################
    l = 2020 # left, right, top, bottom to crop image and predict
    r = 0
    t = 2020
    b = 0

    #################################################################
    pixelDraw = 5
    pre_predict = -1

    is_start_time_back = -1 # tính giờ cho back nếu lớn hơn 1,5s xóa hết
    is_start_time_write = -1
    while True:
        # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
        ret, image_np = cap.read()
        if not ret:
            continue
        image_np = cv2.flip(image_np, 1)

        try:
            image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)
        except:
            print("Error converting to RGB")

        # actual detection
        boxes, scores, classes = detector_utils.detect_objects(
            image_np, detection_graph, sess)

        # DRAWWWW
        (left, right, top, bottom) = (boxes[0][1] * im_width, boxes[0][3] * im_width,
                                          boxes[0][0] * im_height, boxes[0][2] * im_height)

        cv2.putText(image_np, str(scores[0]), (30,30), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,222))

        if (classes[0] == 5 or classes[0] == 6 or classes[0] == 7) and scores[0] > args.score_thresh:
            is_start_time_back = -1
            ## kalman #####################################################
            p = np.array([np.float32(left+(right-left)/8), np.float32(top+(bottom-top)/8)])
            ptemp = np.array([np.float32(left+(right-left)/8), np.float32(top+(bottom-top)/8)]) # thằng này không đổi để chờ hội tụ
            coor = (int(left+(right-left)/8),int(top+(top-bottom)/8))
            isBacked = True
            kalman.correct(p)
            p = kalman.predict()
            # print(p)
            # if(classes[0] == 7 and (pre_predict == 5 or pre_predict == 6)): # kiểu thứ 3 đầu ngón qua bên phải
            #     p = np.array([np.float32(left+(right-left)/8*7), np.float32(top+(bottom-top)/8)])
            #     ptemp = np.array([np.float32(left+(right-left)/8*7), np.float32(top+(bottom-top)/8)]) # thằng này không đổi để chờ hội tụ
            #     coor = (int(left+(right-left)/8*7),int(top+(top-bottom)/8))
            #     while(abs(int(p[0])-coor[0]) > 0.1 and abs(int(p[1])-coor[1]) > 0.1):
            #         arrayDrawed.append((int(p[0]),int(p[1])))
            #         kalman.correct(ptemp)
            #         p = kalman.predict()
            while(abs(int(p[0])-coor[0]) > 0.1 and abs(int(p[1])-coor[1]) > 0.1 and check == False):
                kalman.correct(ptemp)
                p = kalman.predict()

            check = True
            cv2.line(image_np, (int(p[0]),int(p[1])), (int(p[0]),int(p[1])), (255, 255, 0), 30)
            # if(is_start_time_write == -1):
                # is_start_time_write = datetime.datetime.now()
            # else:
            #     if((datetime.datetime.now()-is_start_time_write).total_seconds()>1.5):
            arrayDrawed.append((int(p[0]),int(p[1])))

        elif classes[0] == 4 and scores[0] > args.score_thresh:
            is_start_time_back = -1
            is_start_time_write = -1
            check = False
            isBacked = True
            isFirstPoint = False
            countPassedPoint = 0

            if(len(arrayDrawed) > 0): # có thì mới add được
                modifiedPoints.append(arrayDrawed)
            arrayDrawed = []

        elif ((classes[0] == 3 or classes[0] == 2)  and scores[0] > args.score_thresh): # check and stop

            is_start_time_write = -1
            is_start_time_back = -1
            check = False
            isBacked = True
            # print(l,r,t,b)
            if(len(arrayDrawed) > 0): # có thì mới add được
                modifiedPoints.append(arrayDrawed)
            for modifiedPoint in modifiedPoints:
                for i in range(1,len(modifiedPoint)):
                    if(l > modifiedPoint[i-1][0]):
                        l = modifiedPoint[i-1][0]
                    if(r < modifiedPoint[i-1][0]):
                        r = modifiedPoint[i-1][0]
                    if(t > modifiedPoint[i-1][1]):
                        t = modifiedPoint[i-1][1]
                    if(b < modifiedPoint[i-1][1]):
                        b = modifiedPoint[i-1][1]
                    # cv2.line(image_np, modifiedPoint[i], modifiedPoint[i-1], (0, 255, 0), 15)
                if(l > modifiedPoint[len(modifiedPoint)-1][0]):
                    l = modifiedPoint[len(modifiedPoint)-1][0]
                if(r < modifiedPoint[len(modifiedPoint)-1][0]):
                    r = modifiedPoint[len(modifiedPoint)-1][0]
                if(t > modifiedPoint[len(modifiedPoint)-1][1]):
                    t = modifiedPoint[len(modifiedPoint)-1][1]
                if(b < modifiedPoint[len(modifiedPoint)-1][1]):
                    b = modifiedPoint[len(modifiedPoint)-1][1]
            if(r-l > 0 and b-t > 0):
                img = numpy.zeros([b-t+30, r-l+30, 3])

                for modifiedPoint in modifiedPoints:
                    for i in range(1,len(modifiedPoint)):
                        cv2.line(img, (modifiedPoint[i][0]-l+15,modifiedPoint[i][1]-t+15), (modifiedPoint[i-1][0]-l+15,modifiedPoint[i-1][1]-t+15), (255,255,255), 15)
                        # print((modifiedPoint[i][0]-l,modifiedPoint[i][1]-t))
                cv2.imwrite('img.jpg', img)
                # print(hiragana[predictor_utils.predict_all(img, hiragana_model)])
                print(kanji[predictor_utils.predict_all(img, kanji_model=kanji_model)])

            l = 2020 # left, right, top, bottom to crop image and predict
            r = 0
            t = 2020
            b = 0

            # cv2.imshow('st2',image_np[t:b,l:r])
            # print(hiragana[predictor_utils.predict_all()])
            arrayDrawed = []
            modifiedPoints = []
            # isStart = False
            # check = False
        elif classes[0] == 1  and scores[0] > args.score_thresh:
            is_start_time_write = -1
            check = False
            if(is_start_time_back == -1): # nếu chưa back trước lần nào thì gán
                is_start_time_back = datetime.datetime.now()
                if(isBacked == True):
                    if(len(arrayDrawed) > 0): # có thì mới add được # kiểm tra xem đã vẽ gì chưa để add vào trước khi xóa
                        modifiedPoints.append(arrayDrawed)
                        arrayDrawed = [] # pop rồi nhưng thằng này vẫn vẽ ??:D??
                    if(len(modifiedPoints) > 0): # if empty không cần pop
                        modifiedPoints.pop(-1)
                    isBacked = False
            else:
                if((datetime.datetime.now()-is_start_time_back).total_seconds()>1.5):
                    arrayDrawed = []
                    modifiedPoints = []

        pre_predict = classes[0]

        # print(modifiedPoints)

        for modifiedPoint in modifiedPoints:
            for i in range(1,len(modifiedPoint)):
                cv2.line(image_np, modifiedPoint[i], modifiedPoint[i-1], (0, 255, 0), pixelDraw)

        for i in range(1,len(arrayDrawed)):
            cv2.line(image_np, arrayDrawed[i], arrayDrawed[i-1], (0, 255, 0), pixelDraw)

        detector_utils.draw_box_on_image(
            num_hands_detect, args.score_thresh, classes, scores, boxes, im_width, im_height, image_np)

        # Calculate Frames per second (FPS)
        num_frames += 1
        elapsed_time = (datetime.datetime.now() -
                        start_time).total_seconds()
        fps = num_frames / elapsed_time

        if (args.display > 0):
            # Display FPS on frame
            if (args.fps > 0):
                detector_utils.draw_fps_on_image(
                    "FPS : " + str(int(fps)), image_np)

            cv2.imshow('Single-Threaded Detection', cv2.cvtColor(
                image_np, cv2.COLOR_RGB2BGR))

            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break
        else:
            print("frames processed: ",  num_frames,
                  "elapsed time: ", elapsed_time, "fps: ", str(int(fps)))


from core.decorators import instance, command, event
from core.command_param_types import Any
from core.private_channel_manager import PrivateChannelManager

@instance()
class PrivateChannelController:
    def __init__(self):
        pass

    def inject(self, registry):
        self.bot = registry.get_instance("bot")
        self.private_channel_manager = registry.get_instance("private_channel_manager")
        self.character_manager = registry.get_instance("character_manager")

    @command(command="join", params=[], access_level="all",
             description="Join the private channel")
    def join_cmd(self, channel, sender, reply, args):
        self.private_channel_manager.invite(sender.char_id)

    @command(command="leave", params=[], access_level="all",
             description="Leave the private channel")
    def leave_cmd(self, channel, sender, reply, args):
        self.private_channel_manager.kick(sender.char_id)

    @command(command="invite", params=[Any("character")], access_level="all",
             description="Invite a character to the private channel")
    def invite_cmd(self, channel, sender, reply, args):
        char = args[0].capitalize()
        char_id = self.character_manager.resolve_char_to_id(char)
        if sender.char_id == char_id:
            self.private_channel_manager.invite(sender.char_id)
        elif char_id:
            self.bot.send_private_message(char_id, "You have been invited to the private channel by <highlight>%s<end>." % sender.name)
            self.private_channel_manager.invite(char_id)
            reply("You have invited <highlight>%s<end> to the private channel." % char)
        else:
            reply("Could not find character <highlight>%s<end>." % char)

    @event(PrivateChannelManager.JOINED_PRIVATE_CHANNEL_EVENT, "Notify private channel when someone joins")
    def private_channel_joined_event(self, event_type, event_data):
        char_name = self.character_manager.get_char_name(event_data.char_id)
        self.bot.send_private_channel_message("<highlight>%s<end> has joined the private channel." % char_name)

    @event(PrivateChannelManager.LEFT_PRIVATE_CHANNEL_EVENT, "Notify private channel when someone leaves")
    def private_channel_left_event(self, event_type, event_data):
        char_name = self.character_manager.get_char_name(event_data.char_id)
        self.bot.send_private_channel_message("<highlight>%s<end> has left the private channel." % char_name)


'''
Given a string str. The task is to find the maximum occurring character in the string str.
If more than one character occurs maximum number of time then print the lexicographically smaller character.

Input:
The first line of input contains an integer T denoting the number of test cases.
Each test case consist of a string in 'lowercase' only in a separate line.

Output:
For each testcase, in a new line, print the lexicographically smaller character which occurred the maximum number of time.

User Task:
The task is to complete the function getMaxOccuringChar() which returns the character which is most occuring.

Constraints:
1 ≤ T ≤ 30
1 ≤ |s| ≤ 100

Example:
Input:
2
testsample
output
Output:
e
t

Explanation:
Testcase 1: e is the character which is having highest frequency.
Testcase 2: t and u are the characters with the same frequency, but t is lexicographically smaller.

'''
def getMaxOccurringChar(s):

    occurences=[0 for i in range(256)]

    for char in s:
        occurences[ord(char)] += 1

    max_occurence=0
    character='~'

    #we are iterating upto 256 because we want lexicographically smaller character of occurences of two character is same
    for i in range(256):
        if(occurences[i] > max_occurence):
            character = chr(i)
            max_occurence = occurences[i]
    return character

s = "testsample"
print(getMaxOccurringChar(s))


#!/usr/bin/env python2
from argparse import ArgumentParser
from matplotlib import pylab as py
p = ArgumentParser()
p.add_argument('tra_file')
a = p.parse_args()

f = open(a.tra_file)
headings = []
times = []

for line in f:
	if line.startswith('CC AS'):
		headings.append(float(line.split()[4]))
	elif line.startswith('TI'):
		times.append(float(line.split()[1]))

f.close()

py.plot(times,headings)
py.ylabel('heading (degrees)')
py.xlabel('time (seconds)')
py.show()


import plotly.express as px
import pandas as pd

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options

def makeTestFigure():
    df = pd.DataFrame({
        "Fruit": ["Apples1", "Oranges", "Bananas", "Apples1", "Oranges", "Bananas"],
        "Amount": [4, 1, 2, 2, 4, 5],
        "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
    })

    fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")

    return fig


import jwt
from aiohttp import web
from aiohttp.web_response import json_response

from api.db.tables import users

async def jwt_auth_middleware(app, handler):
    """ Jwt Token Middleware that takes JWT token from Authorization header
    and validate logged user

    :param app: web Application
    :param handler: function that handle input Request
    :return:
    """
    async def middleware(request: web.Request):
        request.app['user'] = None
        jwt_config = request.app['config']['jwt_auth']
        jwt_token = request.headers.get('Authorization')
        if jwt_token:
            try:
                payload = jwt.decode(
                    jwt=jwt_token,
                    key=jwt_config['jwt_secret'],
                    algorithms=[jwt_config['jwt_algorithm']]
                 )
            except (jwt.DecodeError, jwt.ExpiredSignatureError):
                return json_response({'message': 'Token is invalid'}, status=400)
            async with app['db'].acquire() as connection:
                cursor = await connection.execute(
                    users.select()
                        .where(users.c.id == payload['user_id'])
                )
                user = await cursor.fetchone()
                request.app['user'] = dict(user)
        return await handler(request)
    return middleware


# Your name Kevin Khomiakov
# Your class-section 1

# Your program!

# inputting the number of dollars, foreign currency and fee

dollar = input('Please enter number of US dollars: ')
foreign = input('1 USD = ? foreign: ')
fee = input('Fee for buying currency (in USD): ')

# converting dollars to galleons

galleon = int((float(dollar) - float(fee)) * float(foreign))

# printing the result

print('You have', galleon, 'full unit(s) of foreign currency')


# %%
import pandas as pd
import os
from time import time
import json
import argparse
from sklearn.model_selection import GridSearchCV
from models.fasttext_model import FasttextModel

columns = [
        'location_traffic_convenience', 'location_distance_from_business_district', 'location_easy_to_find',
        'service_wait_time', 'service_waiters_attitude', 'service_parking_convenience', 'service_serving_speed',
        'price_level', 'price_cost_effective', 'price_discount',
        'environment_decoration', 'environment_noise', 'environment_space', 'environment_clean',
        'dish_portion', 'dish_taste', 'dish_look', 'dish_recommendation',
        'others_overall_experience', 'others_willing_to_consume_again'
    ]
def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("column", choices=columns, type=str)
    return parser.parse_args()

def main():
    # args = parse_args()
    folder = "./temp"
    # column = args.column
    column = [
       'others_overall_experience', 'others_willing_to_consume_again'
    ]
    filename = "./data/char.total.csv"
    params_folder = "./params/fasttext"
    if not os.path.exists(params_folder):
        os.makedirs(params_folder)

    df = pd.read_csv(filename)
    X = df["content"]
    for c in column:
        print("*"*20 + f"{c}" + "*"*25)
        y = df[c].values

        # %%
        params = {
            "lr": [0.5],
            "ngrams": [3, 4, 5],
            "min_count": [1, 2, 3, 4, 5, 8, 10],
            "ws": [4, 5, 6, 7],
            "dim": [50, 100, 150],
            "epoch": [20],
            "folder": ["./temp"]
        }
        params_importance = ["ngrams", "min_count", "ws", "dim"]

        best_params = {
            "lr": 0.5,
            "epoch": 20,
            "folder": "./temp"
        }
        for p in params_importance:
            temp_params = {k: [best_params[k]] for k in best_params}
            temp_params[p] = params[p]
            fastmodel = FasttextModel()
            model = GridSearchCV(
                fastmodel,
                param_grid=temp_params,
                scoring="f1_macro",
                cv=3,
                refit=False
            )
            start = time()
            model.fit(X, y)
            best_params = model.best_params_d

            # %%
            print(f"grid search on {p} cost time {(time() - start) / 60} min")
            print(model.best_params_)
            result_filename = os.path.join("./logs/", f"{c}-{len(os.listdir('./logs'))}.csv")
            r = pd.DataFrame(model.cv_results_)
            print(r)
            r.to_csv(result_filename)
        # %%
            with open(os.path.join(params_folder, f"{c}.json"), "w") as f:
                f.write(json.dumps(model.best_params_))

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='BranchKind',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=200, verbose_name='Name')),
            ],
            options={
                'verbose_name': 'BranchKind',
                'verbose_name_plural': 'BranchKinds',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Establishment',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=200, verbose_name='Name')),
                ('branchKind', models.ForeignKey(related_name='Establishment_BranchKind', verbose_name='Tipo de Estabelecimento', to='establishment.BranchKind')),
                ('owner', models.ForeignKey(related_name='Establishment_User', verbose_name='Dono', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'verbose_name': 'establishment',
                'verbose_name_plural': 'establishments',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Food',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=200, verbose_name='Nome')),
                ('title', models.CharField(max_length=200, null=True, verbose_name='T\xedtulo', blank=True)),
                ('content', models.TextField(max_length=500, null=True, verbose_name='Conte\xfado', blank=True)),
                ('priority', models.IntegerField(null=True, verbose_name='Prioridade', blank=True)),
                ('image', models.ImageField(upload_to=b'uploads', null=True, verbose_name='Imagem', blank=True)),
                ('price', models.DecimalField(max_digits=6, decimal_places=2)),
                ('establishment', models.ForeignKey(to='establishment.Establishment')),
            ],
            options={
                'verbose_name': 'Food',
                'verbose_name_plural': 'Foods',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='FoodRequest',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('datetime', models.DateTimeField()),
                ('state', models.IntegerField(choices=[(0, b'CANCELED'), (1, b'PENDING'), (2, b'ACCEPTED'), (3, b'DELIVERED'), (4, b'COMPLETE')])),
                ('client', models.ForeignKey(related_name='FoodRequest_Client', verbose_name='Cliente', to=settings.AUTH_USER_MODEL)),
                ('establishment', models.ForeignKey(related_name='FoodRequest_Establishment', verbose_name='Estabelecimento', to='establishment.Establishment')),
                ('foods', models.ManyToManyField(related_name='FoodRequest_Client', verbose_name='Cliente', to='establishment.Food')),
            ],
            options={
                'verbose_name': 'FoodRequest',
                'verbose_name_plural': 'FoodRequests',
            },
            bases=(models.Model,),
        ),
    ]