class Libros:
    def __init__(self,titulo,autor,num_pagina):
        self.titulo = titulo                               #Atributo 1
        self.autor  = autor                                #Atributo 2
        self.num_pag = num_pagina                          #Atributo 3
    def __repr__(self):
        return f'El libro "{self.titulo}" por {self.autor}.Cuenta con {self.num_pag} páginas'       #Retornar una cadena
class Usuarios:
    def __init__(self,nombre,apellido):
        self.nombre = nombre                               #Atributo 1
        self.apellido = apellido                           #Atributo 2
        self.Historial_Prestamo = []                       #Atributo 3 lista vacia, servira para almacenar todos los historiales
    def __repr__(self):
        return f'{self.nombre} {self.apellido}'                   #Retornar una cadena de texto

    def Agregar_HU(self,r_prestamo):                           #metodo, cada vez que se llame este comportamineto dependiendo del objeto este hara:
        self.Historial_Prestamo.append(r_prestamo)             # agregar un Registramos historial , con el argumento que le den

    def mostrar_historial(self):                          #metodo sin solicitar un argumento nuevo
        if len(self.Historial_Prestamo) > 0:              #Si la cantidad de elmentos del array es mayor que 0:
            for x in self.Historial_Prestamo:             #Recorrera casa elemnto que este en el array, y lo imprimira por pantalla
                print('°/',x)
        else:                                             #Caso contrario , imprimira un mensaje
            print('No hay ningun historial del usuario')
class Prestamos:
    def __init__(self,usuario,libro,f_prestamo,f_devolucion):
        self.Registro_prestamo = []                      #Atributo 1
        self.usuario = usuario                           #Atributo 2
        self.libro = libro                               #Atributo 3
        self.f_prestamo = f_prestamo                     #Atributo 4
        self.f_devolver = f_devolucion                   #Atributo 5
        self.Entregas_Anonimas = []                      #Atributo 6 .Listas vacia , cuando el usuario no se encuntre en la lista, se agregar el historia
    def __repr__(self) -> str:
        return f'{self.usuario.nombre} {self.usuario.apellido} {self.libro} {self.f_prestamo} {self.f_devolver}'
    def añadir_his_ah_usuario(self,usuario):          # mandele el dato al usario de su registro
        registro =  f'El usuario {self.usuario.nombre} {self.usuario.apellido}  pidio prestado: {self.libro}, el dia {self.f_prestamo}.Fecha ah devolver: {self.f_devolver}'
        usuario.Agregar_HU(registro)
        self.Registro_prestamo.append(registro)

    def añadir_hist_devolucion(self,usuario = 'anonimo'):
        if usuario != 'anonimo':
            registro =  f'El usuario {self.usuario} devolvio el {self.libro}, el dia {self.f_prestamo}.'
            usuario.Agregar_HU(registro)
            self.Registro_prestamo.append(registro)
        else:
            registro =  f'El libro {self.libro.titulo} fue devuelo el dia {self.f_prestamo} por un usuario desconocido/anonimo.'
            self.Entregas_Anonimas.append(registro)
            self.Registro_prestamo.append(registro)
class Catalogo_Bib:
    def __init__(self):
        self.lista_librosCB = []                                # Atributo alamacenmineto para los objeto libros que se creen
        self.Estado_librosCB_D = {}                             # Atributo de almancenamineto que se tendra cada objeto del libro como clave y en valor Tre or False # Si esta disponible o no
        self.lista_UsuariosR = []                               # Atributo alamacenmineto para los objeto libros que se creen
    def Agregar_LCB(self,libro):
        self.lista_librosCB.append(libro)                       #Agregar al array a el objeto libro crado
        self.Estado_librosCB_D[libro] = True                    #Agregar al diccionario el libro como clave y como valor "defaut " True
    def Agregar_UCB(self,usuario):
        self.lista_UsuariosR.append(usuario)                    #Agregar al array el cada objeto usuario creado
    def Eliminar_LCB(self,ide):
        self.Estado_librosCB_D.pop(self.lista_librosCB[ide])       #Eliminar libro del diccionario de disponibilidad
        self.lista_librosCB.remove(self.lista_librosCB[ide])       #Eliminar libro de lista
    def Cambiar_Estado(self,libro):                               #Cambiar estado del libro true:disponible, false: no disponible
        if self.Estado_librosCB_D[libro] == False:
            self.Estado_librosCB_D[libro] = True
        else:
            self.Estado_librosCB_D[libro] = False
    def Libros_disponibles(self):                                #Entegar una lista de los libros disponibles

        contador = 0                                         #Creamos una varibale acumulador con valor inicial 0
        log = len(self.Estado_librosCB_D)                    #Contar los elemntos del diccionario
        libros_disponibles = []                              # un array vacion , para almacenar los libros disponibles
        if log > 0:                                                                  #Si la longitud del libro es mayor que 0 , recorrera con un for cada clave 'libro'
            for i in self.Estado_librosCB_D:
                contador += 1                                                        #por caa ciclo que se haga se sumara 1
                if self.Estado_librosCB_D[i] == True:                                # Si el liblo que se esta con el valor True:  colocaremos el libro en lista 'libros_disponibles'
                    libros_disponibles.append(f'{contador}. {self.lista_librosCB[contador -1]}')        # para agregar , se busca en la lista general donde esten todos los libros y llamamos el libro que se encuntre en el idex indicado , por ello creamos el contador

            if len(libros_disponibles) >0:                        # Luego que se termine el for s verifica si se agregar elmentos a la lista , y si hay entonces
                return libros_disponibles                      #Retornara una lista
            else:
                return '0'                                   # En caso de no enontrar ningun dato retornar un string '0'
        else:
            return '0'                               # En caso de que la longitud del diccionario sea 0 este retornna un string '0'

    def Mostra_libros(self):
        if len(self.lista_librosCB) > 0:
            for i in range(len(self.lista_librosCB)):
                print(i+1,'.-',self.lista_librosCB[i])
        else:
            return -1                                        # Si no encuntra ningun libro por mostrar , retornara -1
    def Buscar_usuario(self, nombre, apellido):
        # Buscar al usuario ingresado en la lista de usuarios registrados
        for usuario in self.lista_UsuariosR:
            if usuario.nombre == nombre and usuario.apellido == apellido:
                return self.lista_UsuariosR.index(usuario)                     # Si se encuentra al usuario, devolver su índice en la lista

        return -1  # Si no se encuentra al usuario, devolver -1
    def Buscar_libro(self,titulo,autor):
        for libro in self.lista_librosCB:
            if libro.titulo == titulo and libro.autor == autor:
                return self.lista_librosCB.index(libro)
        return -1 # En caso de no encontra el libro

Catalogo = Catalogo_Bib()
salir = True
while salir == True:
    print(' ¬ '*30,'\n','\t'*4,'Bienvenido','\n',' ¬ '*30)
    print('1.Registrar Usuario')
    print('2.Añadir libro al catalogo')
    print('3.Eliminar libro al catalogo')
    print('4.Solicitar libro.')
    print('5.Devolución de libro')
    print('6.Libros disponibles')
    print('7.Veer historial del Usuario')
    print('8.Salir')
    opcion = input('Ingrese un numero: ')
    print('° '*30)
    if opcion == '1':
        print('Porfavor ingrese los siguientes datos para completar sus registro:')
        while True:
            nombre = input('Ingrese el nombre: ')
            apellido = input('Ingrese el apellido: ')
            Persona = Usuarios(nombre,apellido)
            Catalogo.Agregar_UCB(Persona)
            print(f'El usuario {Persona.nombre} {Persona.apellido} ah sido ingresado al sistema')
            respuesta = input('¿Desea agregar otro usuario? (si)(no): ').lower()
            if respuesta == 'si' or respuesta =='no':
                if respuesta == 'no':
                    break
            else:
                print('Error.dato invalido.Salida forzada')
                break
    if opcion == '2':
        print('Para registrar libro agrege los suiguientes datos:')
        while True:
            Titulo = input('Ingrese el titulo: ')
            Autor = input('Ingrese el autor: ')
            Num_pagina = input('Ingrese el num. de páginas: ')
            libro = Libros(Titulo,Autor,Num_pagina)
            Catalogo.Agregar_LCB(libro)
            print(libro,'Ha sido ingresado al sistema')
            respuesta = input('¿Desea agregar otro libro? (si)(no): ').lower()
            if respuesta == 'si' or respuesta =='no':
                if respuesta == 'no':
                    break
            else:
                print('Error.Dato invalido.Salida Forzada ')
                break
    if opcion == '3':
        if Catalogo.Mostra_libros() != -1:
            print('Contamos con los siguientes libros:')
            while True:
                respuesta = (int(input('Ingrese el id del libro ah eliminar.Para salir ingrese (0): '))-1)
                if respuesta <= len(Catalogo.lista_librosCB) and respuesta != 0:
                    alerta = input('Estas seguro de eliminar este libro (si)(no):')
                    if alerta == 'si':
                        Catalogo.Eliminar_LCB(respuesta)
                        print('El libro ah sido eliminado del sisteme')
                    else:
                        break
                else:
                    break
        else:
            print('No hay registro de libros en el Catalogo')

    if opcion == '4':
        if len(Catalogo.lista_librosCB) > 0:
            print('¿Que libro quieres solicitar?.Contamos con los suiguientes libro: ')
            for x in range(len(Catalogo.lista_librosCB)):
                print(x+1,'¬.',Catalogo.lista_librosCB[x])
            while True:
                ide = int(input('Ingrese el ide del libro ah solicitar: '))-1
                if ide <= len(Catalogo.lista_librosCB) and ide >= 0:
                    s_libro = Catalogo.lista_librosCB[ide]
                    if Catalogo.Estado_librosCB_D[s_libro] == True:
                        print('El libro se encuentra disponible.Porfavor ingrese los suiguientes datos.\n')
                        nombre = input('Ingrese el nombre: ')
                        apellido = input('Ingrese el apellido: ')
                        index = Catalogo.Buscar_usuario(nombre, apellido)
                        if index != -1:
                            usuario = Catalogo.lista_UsuariosR[index]
                            fecha_prestamos = input('Ingrese la fecha del Prestamo   : ')
                            fecha_devolucion = input('Ingrese la fecha del devolucion : ')
                            Prestar_libro = Prestamos(usuario,s_libro,fecha_prestamos,fecha_devolucion)
                            Prestar_libro.añadir_his_ah_usuario(usuario)                                   # en el objeto prestamos le pedimos que relice la accion , entregandole el usuario ,para que el usuario tenga el registro
                            Catalogo.Cambiar_Estado(s_libro)                                                 # en el objeto de catalogo , cambiamos el estaddo del libro ah false( de que ya no esta disponible)
                            print('Se ha relializado el registro correctamente')
                            respuesta = input('Desea hacer otro registro?(si)(no): ')
                            if respuesta == 'si' or respuesta == 'no':
                                if respuesta == 'no':
                                    break
                            else:
                                print('Error.salida forzada')
                                break
                        else:
                            print('Lo sentimos el usuario ingresado no se encuentra en el sistema.')
                            break
                    else:
                        print('Libro no disponible :(')
                        break
                else:
                    print('Error.El numero ingresado esta fuera de rango')
                    break
        else:
            print('Lo sentimos no contamos con ningun libro en el catalgo ahún.')
    if opcion == '5':
        while True:
            if len(Catalogo.lista_librosCB) > 0:
                print('\n----Ingrese los datos. para completar la devolucion de libro---\n')
                print('Estos son los libros que se encuntrarn prestados: ')
                for libro in Catalogo.Estado_librosCB_D:
                    if Catalogo.Estado_librosCB_D[libro] == False:
                        print('  ¬ ',libro)
                titulo = input('Ingrese el titulo del libro: ')
                autor = input('Ingrese el nombre del author: ')
                index = Catalogo.Buscar_libro(titulo, autor)
                if index != 1:
                    d_libro = Catalogo.lista_librosCB[index]
                    d_nombre = input('Ingrese el nombre del usuario   :')
                    d_apellido =input('Ingrese el apellido del usuario  :')
                    index_us = Catalogo.Buscar_usuario(nombre,apellido)
                    if index_us != 1:
                        continue
                    else:
                        print('AVERTENCIA: Este usuario no se encuentra en en el sistema.Por ende se registrara como anonimo')
                    fecha_prestamo = input('Ingrese la fecha en que fue prestado:')
                    fecha_devolucion = input('Ingrese la fecha entrega :')
                    index_us = Catalogo.Buscar_usuario(nombre,apellido)
                    if index_us != 1:
                        d_usuario = Catalogo.lista_UsuariosR[index_us]
                        Devolucion = Prestamos(d_usuario,d_libro,fecha_prestamo,fecha_devolucion)
                        Devolucion.añadir_hist_devolucion(d_usuario)
                        Catalogo.Cambiar_Estado(d_libro)
                        print('Se completo el registro de devolución')
                        print(Devolucion,'\n')
                        r = input('Desea agregar otra devolución (si)(no): ').lower()
                        if r == 'si' or r == 'no':
                            if r == 'no':
                                break
                        else:
                            print('Error.')
                            break
                    else:
                        Devolucion = Prestamos('anonimo',d_libro,fecha_prestamo,fecha_devolucion)
                        Catalogo.Cambiar_Estado(d_libro)
                        print('Se completo el registro de devolución, pero como no conside con los datos ingresados del usuario , fue registrado en formato anonimo.')
                        break
                else:
                    print('El libro no se encuentra dento del sistema del catalogo.Vuelva')
                    r = print('Desea volver intentarlo? (si)para continuar (no) para volver al menu:  ')
                    if r == 'si':
                        continue
                    elif r == 'no' or r != 'si':
                        break
            else:
                print('Tenemos todos los libros disponibles. Por ende no hay registro para devolver nada ')
                break
    if opcion == '6':
        if '0' == Catalogo.Libros_disponibles():
            print('No hay libros disponibles')
        else:
            for i in Catalogo.Libros_disponibles():
                print(i)
        r = input('Para volver al menu presione ''enter'' o escriba algo:')
    if opcion == '7':
        print('Ingrese los siguientes datos para ver el historial del usuario')
        nombre = input('Ingrese el nombre: ')
        apellido = input('Ingrese el apellido: ')
        index = Catalogo.Buscar_usuario(nombre, apellido)
        if index != -1:
            usuario = Catalogo.lista_UsuariosR[index]
            print(f'El historial del usuario {usuario}:')
            usuario.mostrar_historial()
        else:
            print('No se encuentra dicho usuario')

            r = input('¿Desea veer la lista de usarios ingresados en sistema?(si)(no): ')
            if r =='si':
                log = len(Catalogo.lista_UsuariosR)
                if log > 0:
                    for x in range(log):
                        print(x+1,'¬.',Catalogo.lista_UsuariosR[x].nombre, Catalogo.lista_UsuariosR[x].nombre)
                else:
                    print('No hay usuario Registrado')
    if opcion == '8':
        break
    if opcion not in ['1','2','3','4','5','6','7','8']:
        print('Error!.Ingrese un numero valido')


import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sb
from sympy import S, symbols, printing

sb.set()
matplotlib.use('TkAgg')

situation = 'real'  # real / sim

if situation == 'real':
    csv_file = 'constant-motion.csv'  # csv file name
    csv_data = pd.read_csv(csv_file, sep=';', usecols=[0, 1])  # read csv file
    csv_data = csv_data.dropna()  # drop NaN values
    time_data = csv_data['Time']  # define time_data
    location_data = csv_data['Location']  # define location_data
else:
    frequency = 1 / 10  # frequency of spark
    timer = 1  # total time of motion in seconds
    deviation = .1  # deviation from perfection  by integer value in a range
    #                 for example deviation=10 means range of [value-5, value+5]
    error_rate = 1  # amount of data will be manipulated in data set by percentage
    expected_velocity = 1  # expected velocity in cm/s
    time_data = np.arange(start=frequency, stop=timer + frequency, step=frequency)
    # spark simulation in "timer" seconds, respect to frequency = 1/period
    location_data = np.multiply(expected_velocity, time_data)
    # perfect location data with respect to expected_velocity
    # using the formula x=vt
    location_data = location_data.astype(float)
    # set location_data array as float data array
    choice_array = np.random.choice(location_data.size, round(location_data.size * error_rate), replace=False)
    # make random location choices with respect to error_rate variable defined above
    location_data.flat[choice_array] += np.random.uniform(low=-float(deviation / 2),
                                                          high=float(deviation / 2),
                                                          size=round(location_data.size * error_rate))
    # deviate the chosen locations from perfection with respect to the variable "deviation".

data_dict = {
    "location": location_data,
    "time": time_data
}
# define a dict for pandas DataFrame

data = pd.DataFrame(data_dict)  # create a pandas DataFrame
reg = np.polyfit(data['time'], data['location'], deg=1)  # define linear regression polynomial
trend = np.polyval(reg, data['time'])  # passing the time values on linear regression polynomial
plt.scatter(x=data['time'], y=data['location'])  # scatter simulated/real life graph

# create latex equation for display the linear regression polynomial
t = symbols("t")
poly = sum(S("{:6.2f}".format(v)) * t ** i for i, v in enumerate(reg[::-1]))
eq_latex = printing.latex(poly)

# plot all the data
plt.plot(data['time'], trend, 'r', label="${}$".format(eq_latex))

plt.legend(fontsize="small")  # font size

print("Slope of the linear regression line is: {}".format(reg[0]))
# print slope

plt.show()  # show plot


import requests
import json
from urllib import parse
import sqlite3
import xml.etree.ElementTree as Et
from html import unescape
import re
import logging
from pypinyin import lazy_pinyin, Style
from utility import tool
import time
api = "https://www.youtube.com/api/timedtext?lang={}&v={}&fmt=srv1"
# fmt = ["zh-CN", "zh-TW", "en"]

__s = tool.Session()

def to_bili(sou):
    _bili = {
        "font_size": 0.4,
        "font_color": "#FFFFFF",
        "background_alpha": 0.5,
        "background_color": "#9C27B0",
        "Stroke": "none",
        "body": []
    }
    _per = {"from": 0, "to": 7, "location": 2, "content": ""}
    _sou = Et.fromstring(sou)
    _lines = _sou.findall("text")
    # last = 0
    for _ in _lines:
        start = float(_.get("start"))
        dur = float(_.get("dur"))
        end = start + dur
        start, end = round(start, 2), round(end, 2)
        if _.text is None:
            continue
        _sub = unescape(_.text)
        _sub = re.sub("\\[Music\\]|\\[Applause\\]|\\[Laughter\\]",
                      "", _sub).replace("\n", " ")
        _per["from"], _per["to"], _per["content"] = start, end, _sub
        last_json = _per.copy()
        _bili["body"].append(last_json)
        # print(round(start, 2), round(end, 2))
        # if round(end - start, 3) < 0.5:
        #     raise Exception("internal too short")
        # if last > start:
        #     raise Exception("time error")
        # last = end
    # print(json.dumps(_bili, ensure_ascii=False))
    return json.dumps(_bili, ensure_ascii=False)

def get_sub(video_id, lan):
    _url = api.format(lan.replace("-US", ""), video_id)
    _sou = __s.get(url=_url, useProxy=True).text
    if len(_sou) == 0:
        return None
    _return = to_bili(_sou)
    return _return

def send_subtitle(bvid, lan, cid, cookie, fix=False, vid=None, add=None):
    logger = tool.getLogger()
    _api = "https://api.bilibili.com/x/v2/dm/subtitle/draft/save"
    csrf = cookie["bili_jct"]
    s = tool.Session()
    s.cookies.update(cookie)
    if not fix:
        sou = get_sub(vid, lan)
    else:
        sou = add
    if sou is None:
        return False
    send_data = {"type": 1,
                 "oid": cid,
                 "bvid": bvid,
                 "lan": lan,
                 "data": sou,
                 "submit": "true",
                 "sign": "false",
                 "csrf": csrf
                 }
    # print(re.findall("bili_jct=(.*?);", cookie)[0])
    # print(parse.urlencode(send_data))
    # print(json.dumps(send_data, ensure_ascii=False))
    # s.verify = False
    _res = s.post(url=_api, data=send_data).json()
    if _res["code"] != 0:
        logger.error(str(bvid) + json.dumps(_res))
        return False
    logger.info(
        f"subtitle success BV[{bvid}], Lan[{lan}], fix[{fix}], cid[{cid}]")
    return True

def fix_sub(cookie):
    logger = tool.getLogger()
    csrf = cookie["bili_jct"]
    s = tool.Session()
    s.cookies.update(cookie)
    wait_api = "https://api.bilibili.com/x/v2/dm/subtitle/search/author/list?status=3&page=1&size=100"
    res = s.get(wait_api).json()["data"]["subtitles"]
    if res is None:
        return
    for _ in res:
        tmp_url = f"https://api.bilibili.com/x/v2/dm/subtitle/show?oid={_['oid']}&subtitle_id={_['id']}"
        data = s.get(tmp_url).json()["data"]
        reject_comment = data["reject_comment"].split(':')[-1].split(',')
        subtitle_url = data["subtitle_url"]
        sub = s.get(subtitle_url).text
        for i in reject_comment:
            if "zh" in _["lan"]:
                sub = sub.replace(i, "".join(lazy_pinyin(
                    i.replace('#', ""), style=Style.TONE)))
            else:
                sub = sub.replace(i, "#".join(i))
        if send_subtitle(_["bvid"], lan=_["lan"], cid=_["oid"], cookie=cookie, fix=True, add=sub):
            res = s.post("https://api.bilibili.com/x/v2/dm/subtitle/del",
                         data={"oid": _["oid"],
                               "csrf": csrf,
                               "subtitle_id": _["id"]}
                         ).json()
            if res["code"] != 0:
                logger.error(res["message"])
            else:
                logger.info(f"fix done:{_['oid']}")
        time.sleep(10)
        # break

if __name__ == "__main__":
    # res = get_sub("qaIghx4QRN4", "en")
    # print(res)
    # res = send_subtitle(vid="wxStlzunxCw", aid=46961283, lan="zh-CN")
    # print(res)
    # fix_sub()
    pass


import socket
s=socket.socket()
port=12345
s.connect(('127.0.0.1',port))

ip_add=raw_input("Enter the ip_address:")
s.send(ip_add)

c=s.recv(1024)
print("class=",c)
s.close()


#!/usr/bin/env python

import glob
import os
import os.path
import numpy as np
import settings
import function_list as ff
import pandas as pd
from sklearn.model_selection import train_test_split
cg = settings.Experiment()

# siemens 304225 is not in the infarction movie set
patient_list = ff.find_all_target_files(['ucsd_bivent/*','ucsd_lvad/*','ucsd_ccta/*','ucsd_toshiba/*','ucsd_tavr_1/*','ucsd_pv/*','ucsd_siemens/2*'],os.path.join(cg.nas_patient_dir))
print(patient_list.shape)

np.random.shuffle(patient_list)
a = np.array_split(patient_list,10)

# split train and test by 7:3
train = []
for i in range(0,7):
    aa = a[i]
    for j in aa:
        parts = j.split(os.path.sep)
        patient_name = parts[-2]+'_'+parts[-1]
        train.append(patient_name)

train = np.asarray(train)

test = []
for i in range(7,10):
    aa = a[i]
    for j in aa:
        parts = j.split(os.path.sep)
        patient_name = parts[-2]+'_'+parts[-1]
        test.append(patient_name)
test = np.asarray(test)

np.save(os.path.join(cg.nas_main_dir,'train_patient_list'),train)
np.save(os.path.join(cg.nas_main_dir,'test_patient_list'),test)


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 15 19:44:59 2018

@author: asthasyal
"""
import tarfile
import pandas as pd
from tabulate import tabulate
from io import StringIO
import datetime
from time import time
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from math import sqrt
import scipy.stats as stats
from sklearn.preprocessing import MinMaxScaler
from sklearn.naive_bayes import GaussianNB
import numpy as np

dataPath = r'C:\\Users\\asthasyal\\Documents\\TstatProject\\data\\'
outputPath = r'C:\\Users\\asthasyal\\Documents\\TstatProject\\result\\labelleddata.txt'
fileName = 'tstat.dtn05.nersc.gov.testb'
fileExt = '.all.csv.tar.gz'
tar = tarfile.open(dataPath+fileName+fileExt, "r:gz")
f = tar.extractfile(fileName+'.all.csv')
Data = f.read()
newDF = pd.read_csv(StringIO(Data.decode('utf-8')),sep=',',header='infer')
del Data
print (len(newDF))

newDF.index=pd.RangeIndex(len(newDF.index))

newDF['first:29']=pd.to_numeric(newDF['first:29']/1000).round(0).astype(int)
newDF['first:29']=pd.to_datetime(newDF['first:29'],unit='s')

newDF['last:30']=pd.to_numeric(newDF['last:30']/1000).round(0).astype(int)
newDF['last:30']=pd.to_datetime(newDF['last:30'],unit='s')

newDF=newDF.set_index(pd.DatetimeIndex(newDF['first:29'])).sort_index()
dateFrom = datetime.datetime(2018, 1, 1, 5, 0, 0) #8 to 7 30
dateTo = datetime.datetime(2018, 6, 1, 17, 0, 0)

dateFrom = newDF['first:29'].iloc[0] # first date and time in the column
dateTo = newDF['first:29'].iloc[-1]# last date and time

selDF=newDF.set_index(pd.DatetimeIndex(newDF['first:29'])).sort_index().loc[dateFrom:dateTo]
selDF['throughput']=(selDF['s_bytes_all:23']*8) / (selDF['durat:31'] / 1000)
selDF['throughput']=selDF['throughput'].round(2)

selDF['throughput'] = selDF['throughput']+1
selDF['throughput'] = selDF['throughput'].apply(np.log10)

# computing short lived and long lived flows
selDF['flows_permin']=(selDF['throughput']/8) *(60*1000)
selDF['flows_permin']=selDF['flows_permin'].round(2)
threshold=selDF['flows_permin'].mean()
selDF['cluster']=0

features=['s_bytes_all:23','durat:31','throughput','flows_permin','c_rtt_avg:45','c_rtt_min:46','c_rtt_max:47','c_rtt_std:48',\
          'c_rtt_cnt:49','s_rtt_avg:52', 's_rtt_min:53','s_rtt_max:54', 's_rtt_std:55', 's_rtt_cnt:56']

dataDF=selDF[features]
scaler = MinMaxScaler()
scaler.fit(dataDF)
scaleDF=scaler.transform(dataDF)

X = scaleDF
y_pred = pd.DataFrame(KMeans(n_clusters=2, random_state=10).fit_predict(X))
y_pred.columns=['cluster']
n_neighbors = 10
n_components = 2

y_pred = y_pred.reset_index(drop=True)
dataDF = dataDF.reset_index(drop=True)

selDF['cluster']= y_pred['cluster'].values
dataDF['cluster']= y_pred['cluster'].values

clusterDF1= dataDF.loc[dataDF['cluster']==0]
clusterDF2= dataDF.loc[dataDF['cluster']==1]
summaryDF1=clusterDF1.describe()
summaryDF2=clusterDF2.describe()
outpath1=r'C:\\Users\\asthasyal\\Documents\\TstatProject\\result\\Flowspermin_Cluster1.txt'
outpath2=r'C:\\Users\\asthasyal\\Documents\\TstatProject\\result\\Flowspermin_Cluster2.txt'
with open(outpath1, 'w') as f:
        f.write('Summary for cluster 1 of: '+ fileName+'\n')
        j=0
        for i in range(9,111,9):
            whatP = summaryDF1.iloc[:,j:i]
            f.write(tabulate( whatP, headers= whatP.columns,tablefmt='psql',floatfmt=('.4f')))
            f.write('\n\n')
            j = i
f.close()

with open(outpath2, 'w') as f1:
        f1.write('Summary for cluster 2 of: '+ fileName+'\n')
        j=0
        for i in range(9,111,9):
            whatP = summaryDF2.iloc[:,j:i]
            f1.write(tabulate( whatP, headers= whatP.columns,tablefmt='psql',floatfmt=('.4f')))
            f1.write('\n\n')
            j = i
f1.close()


class Solution:
    def decodeString(self, s: str) -> str:
        stack = []
        for index, i in enumerate(s):

            if i != ']':
                stack.append(i)
            else:
                temp_string = ''
                while stack[-1] != '[':
                    k = stack.pop(-1)
                    temp_string= k + temp_string
                stack.pop(-1)
                i = ''
                while len(stack) > 0 and stack[-1].isnumeric():
                    i=(stack[-1])+i
                    stack.pop(-1)
                temp_string = int(i)*temp_string
                stack.append(temp_string)
        string_2b_returned=''
        for strings in stack:
            string_2b_returned+=strings
        return string_2b_returned


import discord
from discord.ext import commands

# Replace TOKEN with your bot's token
TOKEN = 'YOUR_BOT_TOKEN_HERE'

# Create a Discord client
client = commands.Bot(command_prefix='!')

# Event that runs when the bot is ready
@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

# Event that runs when a message is received
@client.event
async def on_message(message):
    # Ignore messages sent by the bot itself
    if message.author == client.user:
        return

    # Respond to the "!hello" command
    if message.content.startswith('!hello'):
        await message.channel.send('Hello!')

# Run the bot with the specified token
client.run(TOKEN)


from datetime import datetime

from django.forms import ModelForm

from iot_cultivation_statistics.stats.models import Plant, Measurement, PlantSettings

class PlantForm(ModelForm):
    class Meta:
        model = Plant
        fields = ['name']

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(PlantForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        plant = super(PlantForm, self).save(False)
        if commit:
            plant.user = self.user
            plant.save()
        PlantSettings.objects.create(plant=plant)
        return plant

class MeasurementForm(ModelForm):
    class Meta:
        model = Measurement
        fields = ['date', 'temperature', 'air_humidity', 'soil_humidity', 'insolation']

    def __init__(self, *args, **kwargs):
        self.plant = kwargs.pop('plant')
        super(MeasurementForm, self).__init__(*args, **kwargs)
        self.fields['date'].required = False
        self.fields['date'].initial = datetime.now()

    def clean_date(self):
        date = self.cleaned_data.get('date', None)
        if not date:
            date = datetime.now()
        return date

    def save(self, commit=True):
        measurement = super(MeasurementForm, self).save(False)
        if commit:
            measurement.plant = self.plant
            measurement.save()
        return measurement


# Controlling the mouse

from pynput.mouse import Button, Controller

mouse = Controller()

# Read pointer position
print('The current pointer position is {0}'.format(
    mouse.position))

# Set pointer position
mouse.position = (10, 20)
print('Now we have moved it to {0}'.format(
    mouse.position))

# Move pointer relative to current position
mouse.move(5, -5)

# Press and release
mouse.press(Button.left)
mouse.release(Button.left)

# Double click; this is different from pressing and releasing
# twice on Mac OSX
mouse.click(Button.left, 2)

# Scroll two steps down
mouse.scroll(0, 2)

# Monitoring the mouse

from pynput import mouse

def on_move(x, y):
    print('Pointer moved to {0}'.format(
        (x, y)))

def on_click(x, y, button, pressed):
    print('{0} at {1}'.format(
        'Pressed' if pressed else 'Released',
        (x, y)))
    if not pressed:
        # Stop listener
        return False

def on_scroll(x, y, dx, dy):
    print('Scrolled {0} at {1}'.format(
        'down' if dy < 0 else 'up',
        (x, y)))

# Collect events until released
with mouse.Listener(
        on_move=on_move,
        on_click=on_click,
        on_scroll=on_scroll) as listener:
    listener.join()

# ...or, in a non-blocking fashion:
listener = mouse.Listener(
    on_move=on_move,
    on_click=on_click,
    on_scroll=on_scroll)
listener.start()


class Skill:
    def __init__(self,
                abbr, name, descr,
                attack=0,
                def_act=0,
                remana=0,
                cost=0):

        self.abbr    = abbr
        self.name    = name
        self.descr   = descr

        self.attack  = attack
        self.def_act = def_act

        self.remana  = remana

        self.cost    = cost

    def take_sacrifice(self, user):
        user.stamina -= self.cost


import asyncio

from loader import bot
from messages import MESSAGES
from home_parser import MyHomeParser

async def check_new_houses(sleep_time: int):
    while True:
        await asyncio.sleep(sleep_time)
        with open('data/url.txt', 'r') as f:
            url = f.read()
        p = MyHomeParser(url)
        if p.status == 200:
            print(f'status code: {p.status}')
        else:
            print(f'Oh shit... We have a problem, status code: {p.status}')
            continue
        p.get_cards()
        p.get_homes_id()
        p.get_homes_url()
        if p.homes_url and p.homes_id:
            p.save_to_csv()
        else:
            continue
        urls_str = '\n'.join(p.homes_url)
        msg = f"{MESSAGES['house_is_found']}\n\n{urls_str}"
        with open('data/users_id.txt', 'r') as f:
            users = f.readlines()
        for user in users:
            try:
                await bot.send_message(user, msg)
            except Exception as e:
                print(e)


n = int(input())
def Sum(n):
    a = []              #Tạo 1 list
    k = 0               #Khởi tạo giá trị ban đầu để tính tổng các ước số
    for i in range (1,n):
        if n % i == 0:  #Tìm ước số
            a.append(i) #Thêm ước số vừa tìm được vào list a đã khởi tạo
    for j in a:         #Lấy các ước số trong list a ra
        k = k + j       #Cộng các ước số lại với nhau
    return k            #Trả về giá trị tổng các ước số sau khi cộng xong
print(Sum(n))           #Xuất kết quả


"""Rank docs with query-content score and query-title score"""

import tensorflow as tf
import numpy as np
import pandas as pd

def convert_sparse_matrix_to_sparse_tensor(X):
    """Convert Scipy.sparse.csr_matrix to tf.SparseTensor."""
    coo = X.tocoo()
    indices = np.mat([coo.row, coo.col]).transpose()
    return tf.SparseTensor(indices, coo.data, coo.shape)

def num2onehot(x):
    vec = np.zeros(76437)
    vec[x] = 1
    return vec

# def dataset_input_fn():
# load query scores
with np.load('../../data/retriever/query_scores_sparse.npz') as loader:
    all_title_scores = loader['title_scores']  # list of csr_matrix
    all_doc_scores = loader['doc_scores']  # list of csr_matrix
    labels = loader['labels']
    labels = np.array([num2onehot(x) for x in labels])  #
    # labels = pd.get_dummies(labels).values

# def parser(doc_scores, title_scores, label):
#     doc_scores = convert_sparse_matrix_to_sparse_tensor(doc_scores)
#     title_scores = convert_sparse_matrix_to_sparse_tensor(title_scores)
#
#     return doc_scores, title_scores, label

# build feature matrix from sparse matrices, shape(num_examples, 152874), first half columns
# represent title scores, second half doc scores.
# put all_title_scores and all_doc_scores into vector of shape(152874)
doc_scores = []
title_scores = []
for single_title_scores, single_doc_scores in zip(all_title_scores, all_doc_scores):
    dense_title_scores = single_title_scores.toarray().reshape(76437,).tolist()
    title_scores.append(dense_title_scores)
    dense_doc_scores = single_doc_scores.toarray().reshape(76437,).tolist()
    doc_scores.append(dense_doc_scores)
doc_scores = np.array(doc_scores)
title_scores = np.array(title_scores)

# use placeholder to build dataset instead of directly using numpy arrays to
# save memory
doc_scores_placeholder = tf.placeholder(doc_scores.dtype, doc_scores.shape)
title_scores_placeholder = tf.placeholder(title_scores.dtype, title_scores.shape)
labels_placeholder = tf.placeholder(labels.dtype, labels.shape)

assert all_title_scores.shape[0] == labels.shape[0]

# dataset from placeholder recommended.
dataset = tf.data.Dataset.from_tensor_slices((doc_scores_placeholder, title_scores_placeholder, labels_placeholder))
# dataset from numpy arrays not recommended if dataset is large.
# dataset = tf.data.Dataset.from_tensor_slices((doc_scores, title_scores, labels))

# nomalization on dataset, transform label to one-hot vector
# dataset = dataset.map(parser)
# shuffle
# dataset = dataset.shuffle(buffer_size=10000)
# batch
dataset = dataset.batch(20)
iterator = dataset.make_initializable_iterator()
next_batch = iterator.get_next()

sess = tf.Session()

# Initialize the iterator
sess.run(iterator.initializer,
         feed_dict={doc_scores_placeholder: doc_scores,
                    title_scores_placeholder: title_scores,
                    labels_placeholder: labels})

# # training loop
# for i in range(2):
#     doc_scores, title_scores, labels = sess.run(next_batch)
#     print(doc_scores.shape, title_scores.shape, labels.shape)

# parameters
learning_rate = 0.1
training_epoch = 2
batch_size = 20
display_step = 1

num_docs = 76437
#
x1 = tf.placeholder(tf.float32, [None, num_docs])
x2 = tf.placeholder(tf.float32, [None, num_docs])
y = tf.placeholder(tf.float32, [None, num_docs])
#
# # variables
W = tf.Variable(0., dtype=tf.float32, name='title_weight')
# constants
C = tf.constant(1., dtype=tf.float32)
#
# # calculate predictions
pred = tf.nn.softmax(x1 * W + x2 * (C - W))
#
# loss function
loss = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
#
# # optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
# init
init = tf.global_variables_initializer()

for epoch in range(training_epoch):
    sess.run(init)
    avg_loss = 0.
    total_batch = int(len(labels) // batch_size + 1)
    for index in range(total_batch):
        batch_x1, batch_x2, batch_y = sess.run(next_batch)
        _, loss = sess.run([optimizer, loss], feed_dict={x1: batch_x1, x2: batch_x2, y: batch_y})
        avg_loss += loss / total_batch
    if (epoch + 1) % display_step == 0:
        print('Epoch:', '%04d' % (epoch + 1), 'cost=', '{:.9f}'.format(avg_loss))
print('Optimization Finished!')
print(W)
#

# w = tf.Variable("weight", shape=2, dtype=tf.float32, initializer=)


# O(n)
def solution(n, lost, reserve):
    d = [1] * (n+2)
    for i in reserve:
        d[i] += 1
    for i in lost:
        d[i] -= 1
    for i in range(1, n+1):
        if d[i] == 2 and d[i-1] == 0:
            d[i-1] = 1
            d[i] = 1
            continue
        if d[i] == 2 and d[i+1] == 0:
            d[i+1] = 1
            d[i] = 1
    ans = 0
    for i in range(1, n+1):
        if d[i]:
            ans += 1
    return ans

# O(klogk) k: min(lost길이, reserve 길이)
def solution2(n, lost, reserve):
    s = set(lost) & set(reserve)
    l = set(lost) - s
    r = set(reserve) - s
    for x in sorted(r):
        if x - 1 in l:
            l.remove(x - 1)
        elif x + 1 in l:
            l.remove(x + 1)
    return n - len(l)


from django.shortcuts import render, get_object_or_404
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from django.contrib import messages
from django.http import HttpResponse

from django.contrib.auth.models import User
from dashboard.models import Project
from .models import ProjectStripeDetails
# from profile.models import UserStripeDetails

import stripe
import json

stripe.api_key = settings.STRIPE_SECRET_KEY
wh_secret = settings.STRIPE_WH_SECRET

@require_POST
@csrf_exempt
def stripe_webhooks(request):
  """
  Stripe webhooks when creating a subscription and initiating payment
  """
  payload = request.body
  sig_header = request.META['HTTP_STRIPE_SIGNATURE']
  event = None

  try:
    event = stripe.Webhook.construct_event(
      payload, sig_header, wh_secret
    )
    print("Event constructed accordingly")
  except ValueError as e:
    # Invalid payload
    return HttpResponse(status=400)
  except stripe.error.SignatureVerificationError as e:
    # Invalid signature
    return HttpResponse(status=400)

  # Handle the event
  if event.type == 'payment_intent.succeeded':
    payment_intent = event.data.object # contains a stripe.PaymentIntent
    print('PaymentIntent was successful!')
  elif event.type == 'payment_method.attached':
    payment_method = event.data.object # contains a stripe.PaymentMethod
    print('PaymentMethod was attached to a Customer!')
  # create stripe subscription details
  elif event.type == 'charge.succeeded':
    create_stripe_subscription(request, event.data.object)

  # ... handle other event types
  else:
    print('Unhandled event type {}'.format(event.type))

  return HttpResponse(status=200)

def create_stripe_subscription(request, charge):
  """
  Record to store subscription details
  (Used to retrieve subscription status)
  """
  pi = stripe.PaymentIntent.retrieve(
    charge.payment_intent,
    expand=['invoice']
    )

  sub = stripe.Subscription.retrieve(
    pi.invoice.subscription,
  )

  project = get_object_or_404(Project, id=sub.metadata.project_id)

  obj, created = ProjectStripeDetails.objects.get_or_create(
    project = project,
    customer_id = sub.customer,
    stripe_sub = sub.id,
  )

  # Set project subscription status to True
  # Inital page will load correctly
  project.has_subscription = True
  project.save()

  return HttpResponse(status=200)


from django.conf.urls.defaults import patterns, include, url
from mentalnote.api import *

# Uncomment the next two lines to enable the admin
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'DJStatusForMe.views.home', name='home'),
    # url(r'^DJStatusForMe/', include('DJStatusForMe.foo.urls')),
    url(r'^mentalnote/$', 'mentalnote.views.index'),
    url(r'^mentalnote/(?P<note_id>\d+)/$', 'mentalnote.views.detail'),
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
    # Add api urls automatically generated by tastypie
    url(r'^api/', include(api.urls)),
)


from bs4 import BeautifulSoup
import requests
import datetime
from concurrent.futures import ThreadPoolExecutor
import time
import ast

class Scrapper():

    def __init__(self):
        self.url = "https://igg-games.com/"
        self._url = 'https://igg-games.com/'
        self.all_content = []
        self.licznik = 1
        self.pages = 0
        self._last_url_seen = ""

    def get_content(self, url="https://igg-games.com/"):

        """
        Content from a whole page
        """
        if url not in self._last_url_seen:
            print(f'Function was called: {self.licznik}/{self.pages} times.')
            self.licznik += 1
            response = requests.get(url).text
            soup = BeautifulSoup(response, features='html.parser')
            content = [link for link in [article.find('a').get('href') for article in soup.find_all('article')]]
            content_all = [link for link in [article for article in soup.find_all('article')]]

            for article in content_all:
                link = article.find('a').get('href')
                categories = [category.text for category in article.find_all('a', rel="category tag")]
                self.all_content.append([link, categories])
            self._last_url_seen = url
        time.sleep(0.2)

    def get_content_from_multiple_pages(self, pages, type='multi'):
            self.pages = pages
            pages = ['https://igg-games.com/page/{}'.format(i) for i in range(1, pages+1)]
            if type == 'normal':
                for page in pages:
                    self.get_content(url=page)
            if type == 'multi':
                with ThreadPoolExecutor(max_workers=4) as pool:
                    pool.map(self.get_content, pages)

    def save_in_file(self):
        with open(f"save-{datetime.datetime.now().strftime('%Y-%m-%d--%H-%M-%S')}.txt", 'a') as f:
            for i in self.all_content:
                f.write(str(i) + '\n')

    def get_content_by_categories(self, categories:list, type='any'):
        categories = [category.lower() for category in categories]
        output = []
        with open('list.txt', 'r') as f:
            txt_list = f.read().splitlines()
            new_txt_list = [ast.literal_eval(entry) for entry in txt_list]

        for entry in new_txt_list:
            cat = []
            for category in entry[1]:
                cat.append(category.lower())
            entry = [entry[0], cat]

            if type == 'any':
                if any(category in categories for category in entry[1]):
                    output.append(entry)

            if type == 'all':
                if all(category in entry[1] for category in categories):
                    output.append(entry)

            elif not categories:
                output.append(entry)

        with open(f"save-{'-'.join(categories)}-{type}.txt", 'a') as f:
            for i in output:
                f.write(str(i) + '\n')

    def run(self, mode='scan page'):
        """
        'scan page' - scan a page and save all links in a file
        'sort content' - sort content from a file
        """
        if mode == 'scan page':
            scrapper.get_content_from_multiple_pages(pages=50, type='multi')
            scrapper.save_in_file()
        if mode ==  'sort content':
            scrapper.get_content_by_categories(categories=['Adventure'], type='all')

    def show_genres(self):
        string = """
        Action, Adult, Adventure, Anime,
        Building,
        Casual,
        Eroge,
        Hack and Slash, Hidden Object, Horror,
        Management, Mature,
        Nudity,
        Open World / Sandbox,
        Point & Click, Puzzle,
        Racing, RPG, RTS,
        Sci-fi, Shooter, Simulation, Sport, Strategy, Survival,
        Text-Based, Tower Defense, Turn-Based,
        Visual Novel,
        """

        print(string)

if __name__ == "__main__":
    scrapper = Scrapper()
    scrapper.run(mode='sort content')


from datetime import timedelta

from flask import current_app, request

from vtaskr.libs.flask.utils import ResponseAPI, get_bearer_token
from vtaskr.libs.redis import rate_limited
from vtaskr.users.persistence import TokenDB

from .. import V1, logger, openapi, users_bp

api_item = {
    "post": {
        "description": "Secure user auth with 2FA confirmation",
        "summary": "To confirm 2FA auth",
        "operationId": "postConfirm2FA",
        "responses": {
            "200": {
                "description": "no response content",
                "content": {},
            },
            "400": {
                "description": "Bad request format",
                "content": {
                    "application/json": {
                        "schema": {"$ref": "#/components/schemas/APIError"}
                    }
                },
            },
        },
        "requestBody": {
            "description": "Code to confirm user identity",
            "content": {
                "application/json": {
                    "schema": {
                        "type": "object",
                        "properties": {
                            "code_2FA": {
                                "type": "string",
                                "example": "1A2b3C",
                            },
                        },
                        "required": [
                            "code_2FA",
                        ],
                    }
                }
            },
            "required": True,
        },
    },
}
openapi.register_path(f"{V1}/users/2fa", api_item)

@users_bp.route(f"{V1}/users/2fa", methods=["POST"])
@rate_limited(logger=logger, hit=3, period=timedelta(seconds=60))
def confirm_2fa():
    """
    URL to confirm 2FA auth - Token required

    Need a valid temp token and a code
    Return a 200
    """
    sha_token = get_bearer_token(request)
    if not sha_token:
        return ResponseAPI.get_error_response("Invalid token", 401)

    payload: dict = request.get_json()

    try:
        code = payload.get("code_2FA")
    except AttributeError:
        return ResponseAPI.get_error_response("Bad request", 400)

    try:
        with current_app.sql.get_session() as session:
            token_db = TokenDB()
            token = token_db.get_token(session, sha_token)

            if code and token.is_temp_valid() and token.validate_token(code):
                session.commit()
                data = {}
                return ResponseAPI.get_response(data, 200)
            else:
                return ResponseAPI.get_error_response("Invalid 2FA code", 401)
    except Exception as e:
        logger.error(str(e))
        return ResponseAPI.get_error_response("Internal error", 500)


import time

import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow_datasets as tfds
from tqdm import tqdm

# NUM_VAL_IMAGES = 1000
NUM_VAL_IMAGES = 50000

def _get_imagenet_val_set():
    dataset = tfds.load('imagenet2012', data_dir="/root/tensorflow_datasets/",
                        download=False, shuffle_files=False,
                        as_supervised=True)["validation"]

    dataset = dataset.take(NUM_VAL_IMAGES)

    # Fetch labels
    labels = []
    for y in tqdm(dataset.map(lambda x, y: y), desc="Fetching ground truth labels"):
        labels.append(y.numpy())

    # Image stream
    images = dataset.map(lambda x, y: x).batch(1).prefetch(100)

    return images, labels

def _make_predictions(model, images, labels, model_name):
    time_start = time.time()
    softmax = model.predict(images)
    pred = np.argmax(softmax, axis=1)
    pred_time = (time.time() - time_start) / pred.shape[0]

    # Compute the time it takes to read the softmax
    time_start = time.time()
    sm_confidences = np.take_along_axis(softmax, pred[:, None], axis=-1)
    supervisor_time = (time.time() - time_start) / pred.shape[0]

    np.testing.assert_array_equal(sm_confidences.flatten(), np.max(softmax, axis=1).flatten())

    res_frame = pd.DataFrame({'index': list(range(pred.shape[0])),
                              'prediction': pred.flatten(),
                              'ground_truth': labels,
                              'sm_confidence': sm_confidences.flatten(),
                              'pred_time': pred_time,
                              'supervisor_time': supervisor_time})

    res_frame.to_csv(f"/generated/predictions_and_uncertainties/imagenet_{model_name}.csv", index=False)

def make_predictions():
    images, labels = _get_imagenet_val_set()

    remote_model = tf.keras.applications.EfficientNetV2L()
    _make_predictions(remote_model, images, labels, "remote")
    del remote_model

    local_model = tf.keras.applications.MobileNetV3Small()
    _make_predictions(local_model, images, labels, "local")
    del local_model

if __name__ == "__main__":
    make_predictions()


''' R-4.4
Draw the recursion trace for the execution of function reverse(S, 0, 5)
(Code Fragment 4.10) on S = [4, 3, 6, 2, 6].
'''

def reverse(S, start, stop):
    '''Reverse elements implicit slice S[start:stop].'''
    if start < stop - 1:
        S[start], S[stop - 1] = S[stop - 1], S[start]
        reverse(S, start+1, stop-1)

S = [4, 3, 6, 2, 6]
reverse(S, 0, 5)
print(S)

''' Recursion trace for an execution of reverse(S, 0, 5) with input
parameters S = [4, 3, 6, 2, 6],

reverse(S, 0, 5) -> S[6, 3, 6, 2, 4]

    reverse(S, 1, 4) -> S[6, 2, 6, 3, 4]

        reverse(S, 2, 3) -> does nothing

Note that in this recursion, the swaps happen before the next recursive call,
and the return is None.
The results generated by each recursive call is shown on the right of the
respective calls.
'''


#step2
from gensim import corpora, models, similarities
dictionary = corpora.Dictionary.load('question.dict')
corpus = corpora.MmCorpus('question.mm')

tfidf = models.TfidfModel(corpus)
corpus_tfidf = tfidf[corpus]

lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=50)
index1 = similarities.MatrixSimilarity(lsi[corpus_tfidf])
lsi.save('model.lsi')
index1.save('questions.index')


## This is going to be the GameRoom
from player import Player
from human import Human
from AI import AI

class Gameroom():
    def __init__(self):

        self.display_welcome()
        self.display_rules()
        self.select_game_mode()
        self.play_round()
         # Here the Player One Select the gesture
        # self.player_one.gesture = self.player_one.gesture_list[self.display_options()]
        # From here the machine takes the turn
        #print(self.player_one.gesture)

    def display_welcome(self):
        print('Welcome to Rock, Paper, Scissors, Lizard, Spock, or RPSLS for short!')

        input('press the enter key to continue.')

    def display_rules(self):
        print ('I will now explain the rules of RPSLS.')
        print('you will be able to choose a one or two player game')
        print('you will have the ability to choose one of the five gestures.')
        print('If you have the winning gesture, you will be awarded a score point.')
        print('There is a total of five rounds. whoever scores the most points will win the game.')
        print('The winning combinations are as follows')
        print ('rock crushes scissors')
        print('scissors cut paper')
        print('paper covers rock')
        print('rock crushes lizard')
        print('lizard poisons spock')
        print('spock smashes scissors')
        print('scissors decapitates lizard')
        print('lizard eats paper')
        print('paper disproves spock')
        print('spock vaporizes rock')
        input('\n'+'\n'+'Once you have read and understand the rules, please hit the enter key')

    def select_game_mode(self):
        self.selected_option = int(input("Please select 1. for Player Vs Player or 2. For Player Vs Machine (Single Mode: ): "))
        if self.selected_option == 1:  #user has selected 2 Players
           self.player_one = Human()
           self.player_two = Human()

           print("You have selected Multiplayer Mode, Choose your gesture below...")

        elif self.selected_option == 2:    #user has selected Single mode

            self.player_one = Human()
            self.player_two = AI()
            print("You have selected Single player Mode")
        else:

            print("Plese select a Valid option, Press Enter to continue")
            input('press the enter key to continue.')

    def display_options(self):

        for gesture in range(len(self.player_one.gesture_list)):
            print(f'Please select {gesture} for {self.player_one.gesture_list[gesture]}')

        return_gesture = int(input())
        return return_gesture

    def compare_gesture():
        pass

    def play_round(self):
        this_round = 1
        while this_round <= 5:

            print(f'You are now starting round {this_round}')
            input('Please press enter to choose your gesture')
            self.player_one.set_gesture()
            self.player_two.set_gesture()
            if self.player_one.gesture == 'Rock':
                if self.player_two.gesture == 'Rock':
                    print('This round is a tie!')
                elif self.player_two.gesture =='Paper':
                    print(f'paper covers rock,{self.player_two.name} wins this round!')
                    self.player_two.score += 1
                elif self.player_two.gesture == 'Scissors':
                    print(f'rock smashes scissors, {self.player_one.name} wins this round')
                    self.player_one.score += 1
                elif self.player_two.gesture == 'Lizard':
                    print (f'rock smashes lizard, {self.player_one.name} wins this round')
                    self.player_one.score += 1
                else:
                    print (f'spock vaporizes rock, {self.player_two.name} wins this round')
                    self.player_two.score += 1

            elif self.player_one.gesture == 'Paper':
                if self.player_two.gesture == 'Paper':
                    print('this round is a tie!')
                elif self.player_two.gesture == 'Rock':
                    print (f'paper covers rock {self.player_one.name} wins this round!')
                    self.player_one.score += 1
                elif self.player_two.gesture == 'Scissors':
                    print(f'scissors cuts paper, {self.player_two.name} wins this round!')
                    self.player_two.score += 1
                elif self.player_two.gesture == 'Lizard':
                    print(f'lizard eats paper, {self.player_two.name} wins this round!')
                    self.player_two.score += 1
                else:
                    print(f'paper disproves spock, {self.player_one.name} wins this round!')
                    self.player_one.score += 1

            elif self.player_one.gesture == 'Scissors':
                if self.player_two.gesture == 'Scissors':
                    print('this round is a tie!')
                elif self.player_two.gesture == 'Rock':
                    print(f'rock smashes scissors {self.player_two.name} wins this round!')
                    self.player_two.score += 1
                elif self.player_two.gesture == 'Paper':
                    print(f'scissors cut paper {self.player_one.name} wins this round!')
                    self.player_one.score += 1
                elif self.player_two.gesture == 'Lizard':
                    print(f'scissors decapitates lizard {self.player_one.name} wins this round')
                    self.player_one.score += 1
                else:
                    print(f'spock smashes scissors, {self.player_two.name} wins this round!')
                    self.player_two.score += 1

            elif self.player_one.gesture == "Lizard":
                if self.player_two.gesture == 'Lizard':
                    print('this round is a tie!')
                elif self.player_two.gesture == 'Rock':
                    print(f'rock smashes lizard {self.player_two.name} wins this round!')
                    self.player_two.score += 1
                elif self.player_two.gesture == 'Paper':
                    print (f'lizard eats paper, {self.player_one.name} wins this round!')
                    self.player_one.score += 1
                elif self.player_two.gesture == 'Scissors':
                    print (f'scissors decapitates lizard, {self.player_two.name} wins this round!')
                    self.player_two.score += 1
                else:
                    print(f'lizard poisons spock, {self.player_one.name} wins this round!')
                    self.player_one.score += 1

            elif self.player_one.gesture == 'Spock':
                if self.player_two.gesture == 'Spock':
                    print('this round is a tie!')
                elif self.player_two.gesture == 'Rock':
                    print(f'spock vaporizes rock, {self.player_one.name} wins this round')
                    self.player_one.score += 1
                elif self.player_two.gesture == 'Paper':
                    print(f'paper disproves spock, {self.player_two.name} wins this round!')
                    self.player_two.score += 1
                elif self.player_two.gesture == 'Scissors':
                    print(f'spock smashes scissors, {self.player_one.name} wins thi round!')
                    self.player_one.score += 1
                else:
                    print(f'lizard poisons spock, {self.player_two.name} wins this round')
                    self.player_two.score += 1

            if self.player_one.score > 2:
                print(f"The Winner is {self.player_one.name}")
                break
            elif self.player_two.score > 2:
                print(f"The Winer is {self.player_two.name}")
                break
            elif this_round == 5 and self.player_one.score == self.player_two.score:
                print("This game is a tie, next score wins!")
                this_round = 4

            elif this_round == 5 and self.player_one.score > self.player_two.score:
                print(f'The winner is {self.player_one.name}')
                break
            elif this_round == 5 and self.player_one.score < self.player_two.score:
                print (f'The winner is {self.player_two.name}')
                break

            else:
                print('Stop trying to break my game!')

            this_round += 1


# -*- 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='Element',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('template_name', models.CharField(max_length=200)),
                ('name', models.CharField(max_length=100)),
                ('is_dynamic', models.BooleanField(default=False)),
                ('last_changed', models.DateTimeField(auto_now=True)),
                ('has_changed', models.BooleanField(default=False)),
                ('context_example', models.TextField(null=True, blank=True)),
                ('content', models.TextField(null=True, blank=True)),
                ('changed_by', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)),
            ],
        ),
        migrations.AlterUniqueTogether(
            name='element',
            unique_together=set([('name', 'template_name')]),
        ),
        migrations.AlterIndexTogether(
            name='element',
            index_together=set([('name', 'template_name')]),
        ),
    ]


# This file is used to retrieve data about open source projects from gitlab

# Import Modules
import requests
from bs4 import BeautifulSoup

# Function for 'scraping' gitlab for open source projects, returns list of dictionaries
def gitlabScrape():

    # Initialize empty list
    ret = []

    # Use requests module to access gitlab open source page and save it
    result = requests.get("https://about.gitlab.com/solutions/open-source/projects/")

    # store site content
    src = result.content

    # Use BeautifulSoup to parse and process a webpage
    soup = BeautifulSoup(src, 'lxml')

    # Use find_all to find all rows on the page
    pcs = soup.find_all("tr")

    # Loop through rows
    for pc in pcs:

        # Find all cells in row
        cells = pc.find_all("td")

        # Find links in cell
        for a in cells:

            # If link is present, save it
            link = a.find_all("a")

            # Form disctionary representing JSON object
            if (len(link) > 0):
                name = a.text.strip()
                url = link[0].get('href')
            else:
                description = a.text.strip()
                objDict = {
                    "name": name,
                    "url": url,
                    "description": description,
                    "source": "gitlab"
                }

                # Append JSON dictionary to list
                ret.append(objDict)

    # Return list of dictionaries
    return ret


from random import choice
names = {
    "Aircraft Carrier": 5, "Battleship": 4, "Cruiser": 3, "Submarine": 3, "Destroyer": 2
}
y = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
x = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

class Warship:
    def __init__(self, name, starting_coordinate, direction):
        self.name = name
        self.coordinates = [starting_coordinate]  # [B2, B3, B4, B5, B6]
        self.length = names[name]
        self.destroyed = []
        self.is_valid = True

        for _ in range(self.length-1):
            current_last_coordinate = self.coordinates[-1]
            index_of_y = y.index(current_last_coordinate[:1])
            index_of_x = x.index(current_last_coordinate[1:])
            if direction.upper() == "D":
                index_of_y += 1
            elif direction.upper() == "U":
                index_of_y -= 1
            elif direction.upper() == "L":
                index_of_x -= 1
            elif direction.upper() == "R":
                index_of_x += 1

            if (index_of_y > 9 or index_of_y < 0) or (index_of_x > 9 or index_of_x < 0):
                self.is_valid = False
            else:
                self.coordinates.append(f"{y[index_of_y]}{x[index_of_x]}")

    def __repr__(self) -> str:
        return f"{self.coordinates}"

    def is_destroyed(self):
        return sorted(self.coordinates) == sorted(self.destroyed)

class Board:
    def __init__(self):
        self.missed_shots = []
        self.made_shots = []
        self.ships = []
        self.destroyed_ships = []

    def register_ship(self, ship):
        for existing in self.ships:
            for coordinate in ship.coordinates:
                if coordinate in existing.coordinates:
                    return False
        self.ships.append(ship)
        return True

    def all_ships_destroyed(self):

        return len(self.destroyed_ships) == len(self.ships)

    def shoot(self, coordinate, who):
        is_missed = True
        for ship in self.ships:
            if coordinate in ship.coordinates:
                if coordinate not in ship.destroyed:
                    is_missed = False
                    self.made_shots.append(coordinate)
                    ship.destroyed.append(coordinate)
                    print(f"{who} hit a ship at {coordinate}")
                    if ship.is_destroyed():
                        print(f"{ship.name} is destroyed.")
                        self.destroyed_ships.append(ship)
                    return True
                else:
                    print(
                        "Can not shoot to the same place twice, you already destroyed this part of the ship")
                    return False
        if is_missed:
            self.missed_shots.append(coordinate)
            print(f"{who} missed at {coordinate}")
            return True

enemy_board = Board()
directions = ["L", "R", "U", "D"]
for name in names.keys():
    status_of_registration = False
    while not status_of_registration:
        warship = Warship(name, "A1", "U")
        while not warship.is_valid:
            starting_coordinate = f"{choice(y)}{choice(x)}"
            direction = choice(directions)
            warship = Warship(name, starting_coordinate, direction)
            if not warship.is_valid:
                pass
        status_of_registration = enemy_board.register_ship(warship)
        if not status_of_registration:
            pass
print(enemy_board.ships)
print("Hello Sir, setup your board.")

user_board = Board()
for name in names.keys():
    status_of_registration = False
    while not status_of_registration:
        warship = Warship(name, "A1", "U")
        while not warship.is_valid:
            starting_coordinate = input(
                f"Provide starting coordinate(A-J, 1-10) for the ship: {name}\n").upper()
            direction = input("L - LEFT\nR - RIGHT\nU - UP\nD - DOWN\n")
            warship = Warship(name, starting_coordinate, direction)
            if not warship.is_valid:
                print("Cant place the Warship there, try again:")
        status_of_registration = user_board.register_ship(warship)
        if not status_of_registration:
            print("The Warships can not overlap, try again:")

print("-----------------------The board is now setup, the game may start.-------------------------")

while not (user_board.all_ships_destroyed() or enemy_board.all_ships_destroyed()):
    user_shot = False
    enemy_shot = False
    while not user_shot:
        print(enemy_board.ships)
        target = input(
            "It your time to take a shot, enter the coordinates to shoot:")
        user_shot = enemy_board.shoot(target.upper(), "Player")
    while not enemy_shot:
        enemy_target = f"{choice(y)}{choice(x)}"
        enemy_shot = user_board.shoot(enemy_target, "Enemy")
if user_board.all_ships_destroyed():
    print("AI for the win.")
elif enemy_board.all_ships_destroyed():
    print("Suck it AI, I won.")

Algorithms and data structures/Class 4 - 06.08.23/warship.py


from __future__ import print_function
import six
import logging
import os
import sys
import threading
import time

class Deprecated(object):
    '''废弃函数包装
    '''

    def __init__(self, new_func):
        self._new_func = new_func

    def __call__(self, func):
        def warp_func(*args, **kwargs):
            frame = sys._getframe(1)
            code = frame.f_code
            file_name = os.path.split(code.co_filename)[-1]
            print('method %s is deprecated, called in [%s:%s], pls use %s instead' % (func.__name__, file_name, code.co_name, self._new_func), file=sys.stderr)
            return func(*args, **kwargs)

        return warp_func

class TimeoutError(RuntimeError):
    '''超时错误
    '''
    pass

class SocketError(RuntimeError):
    '''Socket连接错误
    '''
    pass

class AndroidSpyError(RuntimeError):
    '''测试桩返回错误
    '''
    pass

class ProcessExitError(RuntimeError):
    '''进程退出错误
    '''
    pass

class ControlExpiredError(AndroidSpyError):
    '''控件失效错误
    '''
    pass

class ControlAmbiguousError(AndroidSpyError):
    '''控件重复错误
    '''
    pass

class InstallPackageFailedError(RuntimeError):
    '''应用安装失败错误
    '''
    pass

class PackageError(RuntimeError):
    '''安装包错误
    '''
    pass

class PermissionError(RuntimeError):
    '''权限错误
    '''
    pass

class QT4ADriverNotInstalled(Exception):
    '''QT4A驱动错误
    '''
    pass

class OutStream(object):
    '''重载输出流，以便在cmd中显示中文
    '''

    def __init__(self, stdout):
        self._stdout = stdout

    @property
    def encoding(self):
        return 'utf8'

    def write(self, s):
        if six.PY2 and (not isinstance(s, unicode)):
            try:
                s = s.decode('utf8')
            except UnicodeDecodeError:
                try:
                    s = s.decode('gbk')  # sys.getdefaultencoding()
                except UnicodeDecodeError:
                    s = 'Decode Error: %r' % s
                    # s = s.encode('raw_unicode_escape') #不能使用GBK编码
        try:
            ret = self._stdout.write(s)
            self.flush()
            return ret
        except UnicodeEncodeError:
            pass

    def flush(self):
        return self._stdout.flush()

def mkdir(dir_path):
    '''创建目录
    '''
    if os.path.exists(dir_path): return
    try:
        os.makedirs(dir_path)
    except OSError as e:
        if e.args[0] == 183 or e.args[0] == 17:
            # 文件已经存在
            return
        raise e

def gen_log_path():
    '''生成log存放路径
        优先使用环境变量[LOG_PATH_PREFIX], 若不存在则使用[APPDATA] / [HOME]
    '''
    dir_root = os.environ.get('LOG_PATH_PREFIX', os.environ['APPDATA' if sys.platform == 'win32' else 'HOME'])

    dir_root = os.path.join(dir_root, 'qt4a')
    mkdir(dir_root)
    from datetime import datetime, date
    dir_root = os.path.join(dir_root, str(date.today()))
    mkdir(dir_root)
    dt = datetime.now()
    log_name = '%s_%d.log' % (dt.strftime('%H-%M-%S'), threading.current_thread().ident)
    return os.path.join(dir_root, log_name)

logger = logging.getLogger('qt4a')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(OutStream(sys.stdout)))
fmt = logging.Formatter('%(asctime)s %(thread)d %(message)s')  # %(filename)s %(funcName)s
logger.handlers[0].setFormatter(fmt)
logger.handlers[0].setLevel(logging.WARNING)  # 屏幕日志级别为WARNING
# logger.addHandler(logging.StreamHandler(sys.stderr))

logger_path = gen_log_path()
file_handler = logging.FileHandler(logger_path)
fmt = logging.Formatter('%(asctime)s %(levelname)s %(thread)d %(message)s')  # %(filename)s %(funcName)s
file_handler.setFormatter(fmt)
logger.addHandler(file_handler)

def clear_logger_file():
    '''清空log文件
    '''
    if logger_path:
        try:
            f = open(logger_path, 'w')
            f.write('')
            f.close()
        except:
            pass

def get_default_encoding():
    import locale
    import codecs
    return codecs.lookup(locale.getpreferredencoding()).name

def set_default_encoding(code='utf8'):
    if six.PY2:
        if sys.getdefaultencoding() == code: return
        reload(sys)
        sys.setdefaultencoding(code)

def get_file_md5(file_path):
    '''计算文件md5
    '''
    import hashlib
    if six.PY2 and (not isinstance(file_path, unicode)):
        file_path = file_path.decode('utf8')
    if not os.path.exists(file_path):
        raise RuntimeError('文件：%s 不存在' % file_path)
    with open(file_path, 'rb') as f:
        content = f.read()
        md5 = hashlib.md5()
        md5.update(content)
        return md5.hexdigest()

class static_property(property):
    '''静态属性
    '''

    def __init__(self, *args, **kwargs):
        super(static_property, self).__init__(*args, **kwargs)
        self._value_dict = {}

    def __get__(self, obj, cls):
        if not id(obj) in self._value_dict:
            self._value_dict[id(obj)] = super(static_property, self).__get__(obj, cls)
        return self._value_dict[id(obj)]

class AndroidPackage(object):
    '''APK文件处理类
    '''

    def __init__(self, package_path):
        self._package_path = package_path
        if not os.path.exists(package_path):
            raise RuntimeError('安装包: %s 不存在' % package_path)
        self._file = None

    def _get_file(self):
        if not self._file:
            import zipfile
            from io import BytesIO
            with open(self._package_path, 'rb') as f:
                apk_data = f.read()
                self._file = zipfile.ZipFile(BytesIO(apk_data), mode='r')
        return self._file

    def _get_manifest_xml(self):
        from qt4a.androiddriver._axmlparser import AXMLPrinter
        f = self._get_file()
        for i in f.namelist():
            if i == "AndroidManifest.xml":
                return AXMLPrinter(f.read(i)).get_xml_obj()
        raise PackageError('找不到AndroidManifest.xml文件')

    @property
    def package_name(self):
        '''包名
        '''
        manifest = self._get_manifest_xml()
        return manifest.getElementsByTagName('manifest')[0].getAttribute('package')

    @property
    def application_name(self):
        '''应用名
        '''
        manifest = self._get_manifest_xml()
        return manifest.getElementsByTagName('application')[0].getAttribute('android:label')

    @property
    def version(self):
        '''应用版本
        '''
        manifest = self._get_manifest_xml()
        return manifest.getElementsByTagName('manifest')[0].getAttribute('android:versionName')

    @property
    def start_activity(self):
        '''启动Activity
        '''
        manifest = self._get_manifest_xml()
        for activity in manifest.getElementsByTagName('activity'):
            for filter in activity.getElementsByTagName('action'):
                if filter.getAttribute('android:name') == 'android.intent.action.MAIN':
                    return activity.getAttribute('android:name')
        for activity in manifest.getElementsByTagName('activity-alias'):
            for filter in activity.getElementsByTagName('action'):
                if filter.getAttribute('android:name') == 'android.intent.action.MAIN':
                    return activity.getAttribute('android:targetActivity')
        raise PackageError('未找到启动Activity')

    @property
    def permissions(self):
        '''应用申请的权限
        '''
        result = []
        manifest = self._get_manifest_xml()
        for item in manifest.getElementsByTagName('uses-permission'):
            result.append(item.getAttribute('android:name'))
        return result

class KeyCode(object):
    '''按键对应关系
    '''
    KEYCODE_SOFT_LEFT = 1
    KEYCODE_SOFT_RIGHT = 2
    KEYCODE_HOME = 3
    KEYCODE_BACK = 4
    KEYCODE_CALL = 5
    KEYCODE_ENDCALL = 6
    KEYCODE_0 = 7

    KEYCODE_DPAD_UP = 19
    KEYCODE_DPAD_DOWN = 20
    KEYCODE_DPAD_LEFT = 21
    KEYCODE_DPAD_RIGHT = 22

    KEYCODE_VOLUME_UP = 24
    KEYCODE_VOLUME_DOWN = 25
    KEYCODE_POWER = 26
    KEYCODE_CAMERA = 27
    KEYCODE_CLEAR = 28
    KEYCODE_A = 29

    KEYCODE_COMMA = 55
    KEYCODE_PERIOD = 56
    KEYCODE_ALT_LEFT = 57
    KEYCODE_ALT_RIGHT = 58
    KEYCODE_SHIFT_LEFT = 59  # 用于大写字母
    KEYCODE_SHIFT_RIGHT = 60

    KEYCODE_TAB = 61
    KEYCODE_SPACE = 62
    KEYCODE_SYM = 63  # 显示输入法选择框
    KEYCODE_ENTER = 66
    KEYCODE_DEL = 67
    KEYCODE_GRAVE = 68  # `
    KEYCODE_MINUS = 69  # -
    KEYCODE_EQUALS = 70  # =
    KEYCODE_LEFT_BRACKET = 71  # [
    KEYCODE_RIGHT_BRACKET = 72  # ]
    KEYCODE_BACKSLASH = 73  # \
    KEYCODE_SEMICOLON = 74  # ;
    KEYCODE_APOSTROPHE = 75  # '
    KEYCODE_SLASH = 76  # /
    KEYCODE_AT = 77  # @

    KEYCODE_FOCUS = 80  # focus the camera
    KEYCODE_PLUS = 81  # +
    KEYCODE_MENU = 82
    KEYCODE_NOTIFICATION = 83

    KEYCODE_PAGE_UP = 92
    KEYCODE_PAGE_DOWN = 93

    KEYCODE_ESCAPE = 111
    KEYCODE_FORWARD_DEL = 112
    KEYCODE_CTRL_LEFT = 113
    KEYCODE_CTRL_RIGHT = 114

    KEYCODE_MOVE_HOME = 122
    KEYCODE_MOVE_END = 123

    KEYCODE_ZOOM_IN = 168
    KEYCODE_ZOOM_OUT = 169

    KEYCODE_LANGUAGE_SWITCH = 204

    KEYCODE_SLEEP = 223
    KEYCODE_WAKEUP = 224

    keys_map = {
        '{LEFT}': KEYCODE_SOFT_LEFT,
        '{RIGHT}': KEYCODE_SOFT_RIGHT,
        '{HOME}': KEYCODE_HOME,
        '{BACK}': KEYCODE_BACK,
        '{MENU}': KEYCODE_MENU,
        '{VOLUME_UP}': KEYCODE_VOLUME_UP,
        '{VOLUME_DOWN}': KEYCODE_VOLUME_DOWN,
        '{ENTER}': KEYCODE_ENTER,
        '{BACKSPACE}': KEYCODE_DEL,
        '{LEFT}': KEYCODE_DPAD_LEFT,
        '{RIGHT}': KEYCODE_DPAD_RIGHT,
        '{UP}': KEYCODE_DPAD_UP,
        '{DOWN}': KEYCODE_DPAD_DOWN,
        '{DEL}': KEYCODE_FORWARD_DEL,
        '{DELETE}': KEYCODE_FORWARD_DEL,
        '{POWER}': KEYCODE_POWER,
        '{ESC}': KEYCODE_ESCAPE,
        '`': KEYCODE_GRAVE,
        '-': KEYCODE_MINUS,
        '=': KEYCODE_EQUALS,
        '[': KEYCODE_LEFT_BRACKET,
        ']': KEYCODE_RIGHT_BRACKET,
        '\\': KEYCODE_BACKSLASH,
        ';': KEYCODE_SEMICOLON,
        '\'': KEYCODE_APOSTROPHE,
        '/': KEYCODE_SLASH,
        '@': KEYCODE_AT,
        '+': KEYCODE_PLUS,
        ' ': KEYCODE_SPACE,
        '\t': KEYCODE_TAB,
        ',': KEYCODE_COMMA,
        '.': KEYCODE_PERIOD
    }

    shift_chars = {
        '~': '`',
        '!': '1',
        '#': '3',
        '$': '4',
        '%': '5',
        '^': '6',
        '&': '7',
        '*': '8',
        '(': '9',
        ')': '0',
        '_': '-',
        '=': '+',
        ':': ';',
        '"': "'",
        '<': ',',
        '>': '.',
        '?': '/'
    }

    @staticmethod
    def get_key_list(text):
        '''将字符串转换为按键列表
        '''
        i = 0
        result = []
        while i < len(text):
            asc = ord(text[i])
            if asc >= ord('0') and asc <= ord('9'):
                # 数字
                result.append(KeyCode.KEYCODE_0 + asc - ord('0'))
            elif asc >= ord('a') and asc <= ord('z'):
                # 小写字母
                result.append(KeyCode.KEYCODE_A + asc - ord('a'))
            elif asc >= ord('A') and asc <= ord('Z'):
                # 大写字母，加上SHIFT键
                result.append([KeyCode.KEYCODE_SHIFT_LEFT, KeyCode.KEYCODE_A + asc - ord('A')])
            elif asc == ord('{'):
                # 自定义按键
                end = text.find('}', i + 1)
                if end < 0:
                    raise RuntimeError('按键错误：%s' % text)
                key = text[i:end + 1]
                if key not in KeyCode.keys_map:
                    raise RuntimeError('按键错误：%s' % key)
                result.append(KeyCode.keys_map[key])
                i = end
            elif text[i] in KeyCode.keys_map:
                result.append(KeyCode.keys_map[text[i]])
            elif text[i] in KeyCode.shift_chars:
                keys = KeyCode.get_key_list(KeyCode.shift_chars[text[i]])
                keys.insert(0, KeyCode.KEYCODE_SHIFT_LEFT)
                result.append(keys)
            else:
                raise NotImplementedError('不支持的按键：%s' % text[i])

            i += 1
        return result

class EnumThreadPriority(object):
    '''线程优先级
    '''
    LOWEST = 'THREAD_PRIORITY_LOWEST'  # = 19
    BACKGROUND = 'THREAD_PRIORITY_BACKGROUND'  # = 10
    LESS_FAVORABLE = 'THREAD_PRIORITY_LESS_FAVORABLE'  # = +1
    DEFAULT = 'THREAD_PRIORITY_DEFAULT'  # = 0
    MORE_FAVORABLE = 'THREAD_PRIORITY_MORE_FAVORABLE'  # = -1
    FOREGROUND = 'THREAD_PRIORITY_FOREGROUND'  # = -2
    DISPLAY = 'THREAD_PRIORITY_DISPLAY'  # = -4
    URGENT_DISPLAY = 'THREAD_PRIORITY_URGENT_DISPLAY'  # = -8
    AUDIO = 'THREAD_PRIORITY_AUDIO'  # = -16
    URGENT_AUDIO = 'THREAD_PRIORITY_URGENT_AUDIO'  # = -19

class ClassMethod(object):
    def __init__(self, method):
        self._method = method

    def __get__(self, instance, owner):
        if instance is None:
            self._cls = owner
        else:
            # 使用实例传入
            self._cls = instance
        return self

    def __call__(self, *args, **kws):
        # print (self._method.__name__)
        return self._method(self._cls, *args, **kws)

class Mutex(object):
    def __init__(self, lock):
        self._lock = lock

    def __enter__(self):
        time_start = time.time()
        self._lock.acquire()
        time_delta = time.time() - time_start
        if time_delta >= 0.1: logger.debug('thread %d wait %sS' % (threading.current_thread().ident, time_delta))

    def __exit__(self, type, value, traceback):
        self._lock.release()

class ThreadEx(threading.Thread):
    '''可以捕获异常的线程类
    '''

    def run(self):
        '''重载run方法
        '''
        import platform
        if platform.system() == "Windows":
            try:
                import pythoncom
            except ImportError:
                pass
            else:
                pythoncom.CoInitialize()
        try:
            return threading.Thread.run(self)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            # sys.excepthook(*sys.exc_info())
            logger.exception('thread %s exit' % self.getName())

class Singleton(object):
    '''单例基类
    '''
    instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.instance:
            cls.instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls.instance

def get_root_path():
    '''获取根目录，支持py2exe打包后
    '''
    if hasattr(sys, "frozen"):
        # py2exe打包的
        python_path = unicode(sys.executable, sys.getfilesystemencoding()) if six.PY2 else sys.executable
        return os.path.join(os.path.dirname(python_path), 'library.zip')
    file_path = unicode(eval('__file__'), sys.getfilesystemencoding()) if six.PY2 else eval('__file__')
    return os.path.dirname(file_path)

def is_mutibyte_string(data):
    '''判断是否是多字节字符串
    '''
    if six.PY2 and (not isinstance(data, unicode)):
        data = data.decode('utf8')
    for c in data:
        if ord(c) > 256: return True
    return False

def get_string_hashcode(s):
    '''计算java中String的hashcode值
     * Returns a hash code for this string. The hash code for a
     * String object is computed as
     *

     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     *

     * using int arithmetic, where s[i] is the
     * ith character of the string, n is the length of
     * the string, and ^ indicates exponentiation.
     * (The hash value of the empty string is zero.)
    '''
    if six.PY2 and (not isinstance(s, unicode)):
        s = s.decode('utf8')
    ret = 0
    max_val = 0x80000000
    for c in s:
        ret = ret * 31 + ord(c)
        ret %= max_val * 2
        if ret >= max_val:
            ret -= max_val * 2
    return ret

def get_intersection(rect1, rect2):
    '''计算两个区域的交集
    '''
    left = max(rect1[0], rect2[0])
    right = min(rect1[0] + rect1[2], rect2[0] + rect2[2])
    top = max(rect1[1], rect2[1])
    bottom = min(rect1[1] + rect1[3], rect2[1] + rect2[3])
    return (left, top, right - left, bottom - top)

def get_process_name_hash(process_name, device_id):
    '''根据进程名和设备id计算端口值
            结果范围：[5100, 5200)
    TODO: hash冲突的解决
    '''
    result = 0
    start_port = 15000
    port_range = 1000
    text = device_id + process_name
    for i in range(len(text)):
        c = text[i]
        asc = ord(c)
        result = 31 * result + asc

    if result > port_range:
        result %= port_range
    return result + start_port

def version_cmp(ver1, ver2):
    '''版本比较
    '''
    if ver1 == ver2: return 0
    ver1 = ver1.split('.')
    ver2 = ver2.split('.')
    i = 0
    while True:
        if i >= len(ver1) and i >= len(ver2): return 0
        if i >= len(ver1) and i < len(ver2): return -1
        if i >= len(ver2) and i < len(ver1): return 1
        if ver1[i].isdigit() and ver2[i].isdigit():
            c1 = int(ver1[i])
            c2 = int(ver2[i])
            if c1 > c2: return 1
            elif c1 < c2: return -1
        elif ver1[i].isdigit():
            return 1
        elif ver2[i].isdigit():
            return -1
        else:
            return 0
        i += 1

def list_zipfile_dir(zipfile_path, dir_path):
    '''获取zip文件中指定目录的子目录和文件列表
    '''
    import zipfile
    with zipfile.ZipFile(zipfile_path, "r") as z:
        result = []
        for it in z.namelist():
            if it.startswith('%s/' % dir_path):
                result.append(it[len(dir_path) + 1:])
        return result

def extract_from_zipfile(zipfile_path, relative_path, save_path):
    '''从zip文件中提取文件
    '''
    logger.info('extract_from_zipfile %s %s' % (relative_path, save_path))
    import zipfile
    with zipfile.ZipFile(zipfile_path, "r") as z:
        try:
            z.getinfo(relative_path)
        except KeyError:
            for it in list_zipfile_dir(zipfile_path, relative_path):
                extract_from_zipfile(zipfile_path, relative_path + '/' + it, os.path.join(save_path, it))
        else:
            content = z.read(relative_path)
            save_dir = os.path.dirname(save_path)
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
            with open(save_path, 'wb') as f:
                f.write(content)

def time_clock():
    '''
    '''
    if sys.platform == 'win32':
        try:  # Python 3.4+
            return time.perf_counter()
        except AttributeError:  # Earlier than Python 3.
            return time.clock()
    else:
        return time.time()

def is_int(num):
    '''判断整数num是否可以用32位表示
    '''
    return (num <= 2147483647 and num >= -2147483648)

def general_encode(s):
    '''字符串通用编码处理
    python2 => utf8
    python3 => unicode
    '''
    if six.PY2 and isinstance(s, (unicode,)):
        s = s.encode('utf8')
    elif six.PY3 and isinstance(s, (bytes,)):
        s = s.decode('utf8')
    return s

def utf8_encode(s):
    '''将字符串转换为utf8编码
    '''
    if not isinstance(s, bytes):
        s = s.encode('utf8')
    return s

def encode_wrap(func):
    '''处理函数参数编码
    '''
    def wrap_func(*args, **kwargs):
        args = list(args)
        for i, it in enumerate(args):
            args[i] = general_encode(it)
        for key in kwargs:
            kwargs[key] = general_encode(kwargs[key])
        return func(*args, **kwargs)
    return wrap_func

def enforce_utf8_decode(s):
    '''强制utf8解码，对于不合法的字符串，使用\x12的形式
    '''
    if not isinstance(s, bytes):
        return s
    try:
        return s.decode('utf8')
    except UnicodeDecodeError as e:
        start = e.args[2]
        end = e.args[3]
        return enforce_utf8_decode(s[:start]) + repr(s[start: end])[1:-1] + enforce_utf8_decode(s[end:])

if __name__ == '__main__':
    pass