import sc2
from sc2.player import Bot, Computer, BotAI
from sc2 import Result
import random
import cv2
import numpy as np
from ComputerBot import ComputerBot

class Game:
    max_char_per_name = 15
    max_char_per_rank = 2
    max_char_per_line = max_char_per_name + max_char_per_rank + 3
    disable_char = 'X'
    cell_size = (75, 150)

    def __init__(self, side, player1_dict=None, player2_dict=None, realtime=True):
        self.realtime = realtime
        if player1_dict is not None:
            self.player1 = player1_dict["player"]
            self.rank1 = player1_dict["rank"]
            self.enable1 = player1_dict["enable"]

        else:
            self.player1 = None
            self.rank1 = None
            self.enable1 = None

        self.player1_color = (255, 255, 255)

        if player2_dict is not None:
            self.player2 = player2_dict["player"]
            self.rank2 = player2_dict["rank"]
            self.enable2 = player2_dict["enable"]

        else:
            self.player2 = None
            self.rank2 = None
            self.enable2 = None

        self.player2_color = (255, 255, 255)

        self.side = side
        assert self.side == "left" or self.side == "right"

    def run(self, debug=False):
        assert self.player1 is not None or self.player2 is not None

        if self.player1 is None:
            return [False, True]
        elif self.player2 is None:
            return [True, False]

        if debug:
            result = [False, False]
            rn_idx = int(random.random() > 0.5)
            result[rn_idx] = True
            # self.rank1 = self.rank1 if result[0] else self.disable_char
            # self.rank2 = self.rank2 if result[1] else self.disable_char
            # print(result, (self.rank1, self.rank2))
            self.player1_color = (0, 255, 0) if result[0] else (0, 0, 255)
            self.player2_color = (0, 255, 0) if result[1] else (0, 0, 255)
            return result

        game_result = self.run_game()

        print("game_result", type(game_result), game_result)
        print("game_result[0]", type(game_result[0]), game_result[0])
        result = [Result.Victory == game_result[0], Result.Victory == game_result[1]]
        if not result[0] and not result[1]:
            rn_idx = int(random.random() > 0.5)
            result[rn_idx] = True
        # print("run return: ", result)
        # self.rank1 = self.rank1 if result[0] else self.disable_char
        # self.rank2 = self.rank2 if result[1] else self.disable_char

        self.player1_color = (0, 255, 0) if result[0] else (0, 0, 255)
        self.player2_color = (0, 255, 0) if result[1] else (0, 0, 255)
        return result

    def run_game(self):

        try:
            player1_is_bot = issubclass(self.player1, BotAI)
        except TypeError:
            player1_is_bot = False

        try:
            player1_is_computer = issubclass(self.player1, ComputerBot)
        except TypeError:
            player1_is_computer = isinstance(self.player1, ComputerBot)

        try:
            player2_is_bot = issubclass(self.player2, BotAI)
        except TypeError:
            player2_is_bot = False

        try:
            player2_is_computer = issubclass(self.player2, ComputerBot)
        except TypeError:
            player2_is_computer = isinstance(self.player2, ComputerBot)

        # print(player1_is_bot, player1_is_computer, player2_is_bot, player2_is_computer)
        assert (player1_is_bot or player1_is_computer) and (player2_is_bot or player2_is_computer)

        if player1_is_computer and player2_is_bot:
            raw_game_result = sc2.run_game(sc2.maps.get("AbyssalReefLE"), [
                Bot(self.player2.BOTRACE, self.player2(), name=self.player2.BOTNAME),
                Computer(race=self.player1.BOTRACE, difficulty=self.player1.DIFFICULTY)
            ], realtime=self.realtime)
            game_result = [Result.Defeat if raw_game_result == Result.Victory else Result.Victory, raw_game_result]
        elif player1_is_bot and player2_is_computer:
            raw_game_result = sc2.run_game(sc2.maps.get("AbyssalReefLE"), [
                Bot(self.player1.BOTRACE, self.player1(), name=self.player1.BOTNAME),
                Computer(self.player2.BOTRACE, self.player2.DIFFICULTY)
            ], realtime=self.realtime)
            game_result = [raw_game_result, Result.Defeat if raw_game_result == Result.Victory else Result.Victory]
        elif player1_is_computer and player2_is_computer:
            game_result = sc2.run_game(sc2.maps.get("AbyssalReefLE"), [
                Computer(self.player1.BOTRACE, self.player1.DIFFICULTY),
                Computer(self.player2.BOTRACE, self.player2.DIFFICULTY)
            ], realtime=self.realtime)
        elif player1_is_bot and player2_is_bot:
            game_result = sc2.run_game(sc2.maps.get("AbyssalReefLE"), [
                Bot(self.player1.BOTRACE, self.player1(), name=self.player1.BOTNAME),
                Bot(self.player2.BOTRACE, self.player2(), name=self.player2.BOTNAME)
            ], realtime=self.realtime)
        else:
            raise ValueError("players must be ComputerBot or BatAI instance")

        return game_result

    def empty_str(self):
        out = '-' * self.max_char_per_line + '\n'
        if self.side == "left":
            out += '|' + " " * self.max_char_per_rank + '|' + " " * self.max_char_per_name + '|' + '\n'
            out += '|' + " " * self.max_char_per_rank + '|' + " " * self.max_char_per_name + '|' + '\n'
        else:
            out += '|' + " " * self.max_char_per_name + '|' + " " * self.max_char_per_rank + '|' '\n'
            out += '|' + " " * self.max_char_per_name + '|' + " " * self.max_char_per_rank + '|' '\n'

        out += '-' * self.max_char_per_line + '\n'
        return out

    def __str__(self):
        if self.player1 is None and self.player2 is None:
            return self.empty_str()

        out = '-' * self.max_char_per_line + '\n'
        out += self.get_line1(for_str=True)
        out += self.get_line2(for_str=True)
        out += '-' * self.max_char_per_line + '\n'
        return out

    def get_line1(self, for_str=False):
        out = ""

        rank1 = self.rank1

        if for_str and not self.enable1:
            rank1 = self.disable_char

        if self.player1 is None:
            rank1_str = ' ' * self.max_char_per_rank
        elif len(str(rank1)) > self.max_char_per_rank:
            rank1_str = '.' * max(3, self.max_char_per_rank)
        else:
            rank1_str = str(rank1) + " " * (self.max_char_per_rank - len(str(rank1)))

        if self.player1 is None:
            player1_str = ' ' * self.max_char_per_name
        elif len(self.player1.BOTNAME) >= self.max_char_per_name:
            player1_str = ''.join([self.player1.BOTNAME[i] for i in range(self.max_char_per_name)])
        else:
            player1_str = self.player1.BOTNAME + " " * (self.max_char_per_name - len(self.player1.BOTNAME))

        if self.side == "left":
            out += '|' + rank1_str + '|' + player1_str + '|' + '\n'
        else:
            out += '|' + player1_str + '|' + rank1_str + '|' '\n'
        return out

    def get_line2(self, for_str=False):
        out = ""

        rank2 = self.rank2

        if for_str and not self.enable2:
            rank2 = self.disable_char

        if self.player2 is None:
            rank2_str = ' ' * self.max_char_per_rank
        elif len(str(rank2)) > self.max_char_per_rank:
            rank2_str = '.' * max(3, self.max_char_per_rank)
        else:
            rank2_str = str(rank2) + " " * (self.max_char_per_rank - len(str(rank2)))

        if self.player2 is None:
            player2_str = ' ' * self.max_char_per_name
        elif len(self.player2.BOTNAME) >= self.max_char_per_name:
            player2_str = ''.join([self.player2.BOTNAME[i] for i in range(self.max_char_per_name)])
        else:
            player2_str = self.player2.BOTNAME + " " * (self.max_char_per_name - len(self.player2.BOTNAME))

        if self.side == "left":
            out += '|' + rank2_str + '|' + player2_str + '|' + '\n'
        else:
            out += '|' + player2_str + '|' + rank2_str + '|' '\n'
        return out

    def get_img_cell(self):
        img = np.zeros((self.cell_size[0], self.cell_size[1], 3))
        y0, dy = 15, self.cell_size[0]//2 - 2
        font_size = (self.cell_size[0] * 0.30) / 50
        lines = [self.get_line1(), self.get_line2()]
        for i, line in enumerate(lines):
            y = y0 + i*dy
            line = line.replace('\n', '')
            line = line.replace('|', ' ')
            p_color = self.player1_color if i == 0 else self.player2_color
            cv2.putText(img, line, (0, y), cv2.FONT_HERSHEY_SIMPLEX, font_size, p_color, thickness=1)
        cv2.rectangle(img, (0, 0), (self.cell_size[1] - 1, self.cell_size[0] - 1), color=(255, 0, 0), thickness=1)
        return img

if __name__ == '__main__':
    from MarineOverflow import MarineOverflow
    from JarexTerran import JarexTerran
    from JarexProtoss import JarexProtoss

    class Dummy1(MarineOverflow):
        BOTNAME = "Dummy1"

    lgames = list()
    rgames = list()
    game = Game("left", {"player": MarineOverflow, "rank": 1, "enable": True},
                {"player": JarexProtoss, "rank": 12, "enable": True}, realtime=False)
    print(game)

    while True:
        img = game.get_img_cell()
        # img = cv2.resize(img, (500, 250))
        cv2.imshow('test cell', img)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break
    print(game.run())

    print(game)

    while True:
        img = game.get_img_cell()
        # img = cv2.resize(img, (500, 250))
        cv2.imshow('test cell', img)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break

    rgame = Game("right", {"player": JarexTerran, "rank": 1, "enable": True},
                 {"player": Dummy1, "rank": 'X', "enable": False})
    rgame.player1_color = (0, 255, 0)
    print(rgame)

    while True:
        img = rgame.get_img_cell()
        # img = cv2.resize(img, (500, 250))
        cv2.imshow('test cell', img)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break

    empty_game = Game("left")
    print(empty_game)

    # for i in range(1, 6):
    #     lgames.append(Game({"player": MarineOverflow, "rank": i}, {"player": MarineOverflow, "rank": i+5}, "left"))
    # for i in range(6, 11):
    #     rgames.append(Game({"player": MarineOverflow, "rank": i}, {"player": MarineOverflow, "rank": i+5}, "right"))
    #
    # for i in range(len(rgames)):
    #     print(str(lgames[i]) + ' '*10 + str(rgames[i]) + '\n')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr  4 11:37:33 2019

@author: laura
"""

import numpy as np

import matplotlib.pyplot as plt

from matplotlib import cm

def montaAl(n):
  N = n*n
  M = np.zeros((N,N))
  D = np.zeros((N,N))

  for i in range(N):
    D[i,i] = 4.0

    if i < n*(n-1):
      M[i,i+n] = -1.0
      M[i+n,i] = -1.0

    if (i + 1)%n != 0 :
      M[i,i+1] = -1.0
      M[i+1,i] = -1.0

  return M,D

def montaBl(n,ul0x,uly,ulx,ul0y,x,y):
    N = n*n
    b = np.zeros((N,1))
    baux=np.zeros((n+2,n+2))
    baux[0,:]=ul0y
    baux[:,0]=ul0x

    for i in range(n+1):
        baux[n+1,i]=200*x[i]
        baux[i,n+1]=200*y[i]
    k=0
    for j in range(n,-1,-1):
        for i in range(n+1):
            if(j>0)and(i>0)and(i<n+2)and(j<n+2):
                b[k]=baux[i-1,j]+baux[i+1,j]+baux[i,j-1]+baux[i,j+1]
                k=k+1
    return b

def Laplace(n,ul0x,uly,ulx,ul0y,x,y): ####diferencas centrais####
    b=montaBl(n,ul0x,uly,ulx,ul0y,x,y)
    M,D=montaAl(n)
    A=M+D
    print('A=',A)
    print('b=',b)
    U=np.linalg.solve(A,b)
    return U

def geraGraficos1(X1,n,ul0x,ul0y,ulx,uly):

    x = range(n+2)
    y = range(n+2)
    X,Y = np.meshgrid(x,y)

    Zinter = np.reshape(X1,(n,n))
    Z = np.zeros((n+2,n+2))

    for i in range(n+2):
        if (i != 0) and (i != n+1):
            Z[i,0]   = ul0x
            Z[i,n+1] = uly

            Z[0,i]   = ul0y
            Z[n+1,i] = ulx

    for i in range(n):
        for j in range(n):
            Z[i+1,j+1] = Zinter[i,j]

    fig = plt.figure(figsize=plt.figaspect(0.5))

    ax0 = fig.add_subplot(1, 2, 1, projection='3d')
    ax1 = fig.add_subplot(1, 2, 2, projection='3d')

    for i in range(n+2):
	    for j in range(n+2):
		    x = X[i,j]
		    y = Y[i,j]
		    z = Z[i,j]

		    ax0.scatter(x,y,z)

    ax1.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
    linewidth=0.2, antialiased=False)

    plt.show()

######Escolha da malha#######

n=3
N=n*n
xl0=0
yl0=0
xln=0.5
yln=0.5
hl=(xln-xl0)/(n+1)
kl=(yln-yl0)/(n+1)

xl=np.arange(xl0,xln,hl)
yl=np.arange(yl0,yln,kl)

###################################################
########## Laplace - Diferencas centrais ##########
###################################################

Ul=np.zeros(N)

###condicoes de fronteira###

ul0x=0
ul0y=0
ulx=200
uly=200

###solucao###

Ul=Laplace(n,ul0x,uly,ulx,ul0y,xl,yl)
print('laplace (w)=',Ul)

geraGraficos1(Ul,n,ul0x,ul0y,ulx,uly)


class Tree:
    left=None
    right=None
    key=0
    def __init__(self,key):
        self.key=key
    def insertl(self,left):
        self.left=left
    def insertr(self,right):
        self.right=right
def insert(node,k):
    if node==None:
        return Tree(k)
    elif k>=node.key and node.right==None:
        node.right=Tree(k)
        print(node.key)
        return node
    elif k<node.key and node.left==None:
        node.left=Tree(k)
        print(node.key)
        return node
    elif k>=node.key:
        right=insert(node.right,k)
        node.right=right
        return node
    else:
        left=insert(node.left,k)
        node.left=left
        return node
N=int(input())
nums=list(map(int,input().split(" ")))
tree=None
print(-1)
for i in range(0,N):
    tree=insert(tree,nums[i])


from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
import luminance_ops as l
import numpy as np
from matplotlib import pyplot as plt
import io

#Constants
N_IMG_BUTTONS = 4
IMAGE_COLUMNS=3
FILTERS_DICT = {"Raiz":l.sqrt_ilum, "Cuadrado":l.pow2_ilum, "Lineal":l.lineal_ilum, "Ecualización":l.equalize_ilum}
IMAGE_TYPES = [("Images", "*.png"), ("Images", "*.jpg"), ("Images", "*.jpeg")]
#Global variables
img_arr = [None]*2
tk_imgs = [None]*2

def view_histogram(master, img_index):
    if not showing_hist[img_index]:
        my_dpi=96
        yiq_img = l.rgb_to_yiq(np.array(img_arr[img_index]))
        img_counts, bins = np.histogram(yiq_img[:,:,0], bins=20)
        buf = io.BytesIO()
        buf.seek(0)
        fig = plt.figure(figsize=(600/my_dpi, 600/my_dpi), dpi=my_dpi)
        plt.stairs(img_counts, bins)
        fig.savefig(buf)
        buf.seek(0)
        png_hist =  Image.open(buf)
        tk_imgs[img_index] = ImageTk.PhotoImage(png_hist)
        showing_hist[img_index] = True
    else:
        tk_imgs[img_index] = ImageTk.PhotoImage(img_arr[img_index])
        showing_hist[img_index] = False
    img_b =Button(master,image=tk_imgs[img_index])
    img_b.grid(row=0, columnspan=IMAGE_COLUMNS)

def upload_file(img_index, master):
    filename = filedialog.askopenfilename(filetypes=IMAGE_TYPES)
    img = Image.open(filename).convert("RGB").resize((600,600))
    tk_img= ImageTk.PhotoImage(img)
    img_b =Button(master,image=tk_img)
    img_b.grid(row=0, columnspan=IMAGE_COLUMNS)
    img_arr[img_index] = img
    tk_imgs[img_index] = tk_img

def filter_img(img1, master):
    img_arr[-1] = FILTERS_DICT[selected_filter.get()](img1)
    tk_imgs[-1] = ImageTk.PhotoImage(img_arr[-1])
    b3 =Button(master,image=tk_imgs[-1])
    b3.grid(row=0,columnspan=6)

def create_image_frame(master):
    images_frame = Frame(master)
    images_frame.grid(row=0)
    #Create image upload buttons
    first_image_frame = Frame(images_frame)
    b1 = Button(first_image_frame, text='Cargar primera imagen',
    width=20,command = lambda:upload_file(0, first_image_frame))
    b1.grid(row=1, column=0)

    b2 = Button(first_image_frame, text='Histograma',
    width=20,command = lambda:view_histogram(first_image_frame,0))
    b2.grid(row=1, column=1)
    first_image_frame.grid(row=0,column=0)
    #Second image
    second_image_frame = Frame(images_frame)
    operations_menu = OptionMenu(second_image_frame, selected_filter, *FILTERS_DICT.keys())
    operations_menu.grid(row=1, column=0)

    b3 = Button(second_image_frame, text='Filtrar',
    width=20,command = lambda:filter_img(img_arr[0], second_image_frame))
    b3.grid(row=1, column=1)

    b4 = Button(second_image_frame, text='Histograma',
    width=20,command = lambda:view_histogram(second_image_frame,1))
    b4.grid(row=1, column=2)
    second_image_frame.grid(row=0, column=1)

root = Tk()
root.title("Operaciones aritmeticas entre imagenes")
root.geometry("1200x800+50+50")  # width x height + x + y

#String vars
selected_filter = StringVar()
selected_filter.set("Elegir filtro")
#Flags
showing_hist = [False, False]

create_image_frame(root)
root.mainloop()


import time

from view.View import View
from controller.Config import Config
from controller.ViscaOverIPService import ViscaOverIPService
from controller.AxisState import AxisState

class Controller:

    PANAXIS = AxisState()
    TILTAXIS = AxisState()
    ZOOMAXIS = AxisState()

    #initialize the variables so that they are set
    config = {}
    debug = False

    def __init__(self):
        super().__init__()

        #load the configuration from the app.conf file
        self.loadConfig()

        #set up the network service so that we can
        # communicate with the cameras
        self.setupViscaOIPService()

        #setup and load the UI
        self.setupUI()

    def loadConfig(self):
        #create a config object and load the
        #config from the app.conf file
        self.config = Config()
        self.debug = self.config.debugIsEnabled()

    def setupViscaOIPService(self):
        #create the server
        self.ViscaOverIPService = ViscaOverIPService(self.config.getNetworkConfig(), self.debug)

    def setupUI(self):
        #setup a subset of the config
        #we don't need to pass the entire config
        viewConfig = {
            "debug": self.config.debugIsEnabled(),
            "ui": self.config.getUIConfig(),
            "camera": self.config.getCameraConfig(),
            "joystick": self.config.getJoystickConfig()
        }

        #callback Function list - this provides all the actions
        #for the button clicks and UI Interactions
        #we want to bring the business logic back out to the Controller,
        #so we are giving the View the callback functions to use
        viewActions = {
            "sendCommand": self.sendCommand,
            "presetSave": self.presetSaveClick,
            "close": self.quit
        }

        #create the UI QT object
        self.view = View(viewConfig, viewActions)

    def start(self):
        self.view.start(self.config.getUIConfig()["fullscreen"])

    def quit(self, event):
        self.ViscaOverIPService.closeUDPServer()

    #Action for clicking a button to switch cameras
    # def cameraClick(self, command, selectedCameraInfo):
    #     self.sendCommand(command, selectedCameraInfo)

    # def ptzPressed(self, command, selectedCameraInfo):
    #     self.sendCommand(command, selectedCameraInfo)

    # def ptzReleased(self, command, selectedCameraInfo):
    #     self.sendCommand(command, selectedCameraInfo)

    # def presetClick(self, command, selectedCameraInfo):
    #     self.sendCommand(command, selectedCameraInfo)

    def sendCommand(self, command):
        #try and send the command, but if it fails,
        #reset the sequence number and move on
        self.ViscaOverIPService.sendUDPMessage(command)

    def presetSaveClick(self, button, selectedCameraInfo):
        #logic for saving presets and reloading locations
        #first I need to get the current location of the camera

        currentPosition = {
            "pan": [],
            "tilt": [],
            "zoom": []
        }

        response = self.ViscaOverIPService.sendUDPMessage("INQPT", selectedCameraInfo)
        if(response != None):
            currentPosition["pan"] = response.getPayload()[2:4]
            currentPosition["tilt"] = response.getPayload()[6:4]

        response = self.ViscaOverIPService.sendUDPMessage("INQZOOM", selectedCameraInfo)
        if(response != None):
            currentPosition["zoom"] = response.getPayload()[2:4]

        if self.debug:
            print("PAN: ", currentPosition["pan"])
            print("TILT: ", currentPosition["tilt"])
            print("ZOON: ", currentPosition["zoom"])

        #save the position in memory for now
        button.presetInfo["panPosition"] = currentPosition["pan"]
        button.presetInfo["tiltPosition"]  = currentPosition["tilt"]
        button.presetInfo["zoomPosition"] = currentPosition["zoom"]
        button.presetInfo["command"] = "PresetPanTilt"

        self.config.updatePreset(button.presetInfo, button.id, selectedCameraInfo["id"])

    # def joystickUIButtonClicked(self, checked):
    #     if(checked):
    #         #close any previously open joystick.
    #         if hasattr(self, "joystick"):
    #             self.joystick.close()

    #         #set up a new instance of the joystick object
    #         self.joystick = Joystick(self.config.getJoystickConfig(), self.debug, axesAction = self.joystickAxesAction, buttonAction = self.joystickButtonActionDown)

    #         #Check if there are any joysticks connected...
    #         # if so start receiving joystick events
    #         # if not, just uncheck the joystick button on the UI
    #         if(self.joystick.detectedJoysticks()):
    #             self.joystick.start()
    #         else:
    #             if self.debug:
    #                 print("No detected Joysticks")
    #             self.view.joystickButton.setChecked(False)
    #     else:
    #         if hasattr(self, "joystick"):
    #             self.joystick.close()

    #         if self.debug:
    #             print("Disabled joysticks")

    #         self.view.joystickButton.setChecked(False)

    # def joystickButtonActionDown(self, buttonData):
    #     #a button has been pressed
    #     #go through each button

    #     for actiontype, data in self.config["joystick"].items():
    #         if data["type"] == "button" and data["id"] == buttonData.button:
    #             currentButtonId = self.view.getSelectedCameraId()
    #             totalCameras = len(self.config["cameras"])
    #             newButtonId = (currentButtonId + 1) % totalCameras
    #             self.view.getCameraButton(newButtonId).click()

    # def joystickAxesAction(self, axesData):
    #     #the Axes have changed
    #     #go through each configured axis...
    #     #get the Axis that is related

    #     for actiontype, data in self.config["joystick"].items():
    #         if data["type"] == "axis" and data["id"] == axesData.axis:
    #             newValue = round(axesData.value * self.MAXSPEED[actiontype])

    #             theAxis = self.getAxisStateByName(actiontype)
    #             #we can't zoom and pan/tilt at the same time, so make sure that we only do one at a time
    #             #zoom will be secondary and only function if we are already not panning or tilting
    #             if actiontype == "zoom":
    #                 if not (self.PANAXIS.isActive() or self.TILTAXIS.isActive()):
    #                     #only update the zoom value if not panning or tilting
    #                     # self.ptzChangeSpeed(actiontype, abs(newValue))
    #                     if(theAxis.getRawVector() == newValue):
    #                         return
    #                     else:
    #                         theAxis.setRawVector(newValue)
    #                         if newValue > 0:
    #                             theAxis.setHigh()
    #                             if self.debug:
    #                                 print("Zooming Out at speed ", theAxis.getVector())
    #                             self.ViscaOverIPService.sendUDPMessage("ZoomWide", self.view.getSelectedCameraButton().cameraInfo, {"speed": { "zoom": theAxis.getVector()}})
    #                         elif newValue < 0:
    #                             theAxis.setLow()
    #                             if self.debug:
    #                                 print("Zooming In at speed ", theAxis.getVector())
    #                             self.ViscaOverIPService.sendUDPMessage("ZoomTele", self.view.getSelectedCameraButton().cameraInfo, {"speed": { "zoom": theAxis.getVector()}})
    #                         else:
    #                             theAxis.unset()
    #                             if self.debug:
    #                                 print("Stopped Zooming", theAxis.getVector())
    #                             self.ViscaOverIPService.sendUDPMessage("ZoomStop", self.view.getSelectedCameraButton().cameraInfo)
    #             else:
    #                 #we are panning and tilting
    #                 if not (self.ZOOMAXIS.isActive()):
    #                     #go ahead... pan and tilt
    #                     # self.ptzChangeSpeed(actiontype, abs(newValue))
    #                     if(theAxis.getRawVector() == newValue):
    #                         return
    #                     else:
    #                         theAxis.setRawVector(newValue)
    #                         if newValue < 0:
    #                             theAxis.setLow()
    #                         elif newValue > 0:
    #                             theAxis.setHigh()
    #                         elif newValue == 0:
    #                             theAxis.unset()

    #                         if self.PANAXIS.isActive() and self.TILTAXIS.isInactive():
    #                             #Only the PAN AXIS is activated
    #                             if(self.PANAXIS.isLow()):
    #                                 if self.debug:
    #                                     print("Panning Left at Speed ", self.PANAXIS.getVector())
    #                                 self.ViscaOverIPService.sendUDPMessage("PanLeft", self.view.getSelectedCameraButton().cameraInfo, {"speed": { "pan": self.PANAXIS.getVector(),"tilt": self.TILTAXIS.getVector()}})
    #                             else:
    #                                 #it must be low since it is inactive
    #                                 if self.debug:
    #                                     print("Panning Right at Speed ", self.PANAXIS.getVector())
    #                                 self.ViscaOverIPService.sendUDPMessage("PanRight", self.view.getSelectedCameraButton().cameraInfo, {"speed": { "pan": self.PANAXIS.getVector(),"tilt": self.TILTAXIS.getVector()}})
    #                         elif self.PANAXIS.isInactive() and self.TILTAXIS.isActive():
    #                             #Only the TILT axis is active
    #                             if self.TILTAXIS.isLow():
    #                                 if self.debug:
    #                                     print("Tilting Up at Speed ", self.TILTAXIS.getVector())
    #                                 self.ViscaOverIPService.sendUDPMessage("TiltUp", self.view.getSelectedCameraButton().cameraInfo, {"speed": { "pan": self.PANAXIS.getVector(),"tilt": self.TILTAXIS.getVector()}})
    #                             else:
    #                                 if self.debug:
    #                                     print("Tilting Down at Speed ", self.TILTAXIS.getVector())
    #                                 self.ViscaOverIPService.sendUDPMessage("TiltDown", self.view.getSelectedCameraButton().cameraInfo, {"speed": { "pan": self.PANAXIS.getVector(),"tilt": self.TILTAXIS.getVector()}})
    #                         elif self.PANAXIS.isActive() and self.TILTAXIS.isActive():
    #                             #both PAN and TILT are active
    #                             if self.PANAXIS.isLow() and self.TILTAXIS.isLow():
    #                                 if self.debug:
    #                                     print("Tilting Up+Left at Speed ", self.PANAXIS.getVector(), self.TILTAXIS.getVector())
    #                                 self.ViscaOverIPService.sendUDPMessage("PanTiltUpLeft", self.view.getSelectedCameraButton().cameraInfo, {"speed": { "pan": self.PANAXIS.getVector(),"tilt": self.TILTAXIS.getVector()}})
    #                             elif self.PANAXIS.isLow() and self.TILTAXIS.isHigh():
    #                                 if self.debug:
    #                                     print("Tilting Down+Left at Speed ", self.PANAXIS.getVector(), self.TILTAXIS.getVector())
    #                                 self.ViscaOverIPService.sendUDPMessage("PanTiltDownLeft", self.view.getSelectedCameraButton().cameraInfo, {"speed": { "pan": self.PANAXIS.getVector(),"tilt": self.TILTAXIS.getVector()}})
    #                             elif self.PANAXIS.isHigh() and self.TILTAXIS.isLow():
    #                                 if self.debug:
    #                                     print("Tilting Up+Right at Speed ", self.PANAXIS.getVector(), self.TILTAXIS.getVector())
    #                                 self.ViscaOverIPService.sendUDPMessage("PanTiltUpRight", self.view.getSelectedCameraButton().cameraInfo, {"speed": { "pan": self.PANAXIS.getVector(),"tilt": self.TILTAXIS.getVector()}})
    #                             elif self.PANAXIS.isHigh() and self.TILTAXIS.isHigh():
    #                                 if self.debug:
    #                                     print("Tilting Down+Right at Speed ", self.PANAXIS.getVector(), self.TILTAXIS.getVector())
    #                                 self.ViscaOverIPService.sendUDPMessage("PanTiltDownLeft", self.view.getSelectedCameraButton().cameraInfo, {"speed": { "pan": self.PANAXIS.getVector(),"tilt": self.TILTAXIS.getVector()}})
    #                         else:
    #                             #neither are active
    #                             if self.debug:
    #                                 print("Stopping PAN/TILT", self.PANAXIS.getVector(), self.TILTAXIS.getVector())
    #                             self.ViscaOverIPService.sendUDPMessage("PanTiltStop", self.view.getSelectedCameraButton().cameraInfo)

    # def getAxisStateByName(self, name):
    #     if name == "pan":
    #         return self.PANAXIS
    #     elif name == "tilt":
    #         return self.TILTAXIS
    #     elif name == "zoom":
    #         return self.ZOOMAXIS
    #     else:
    #         return None


# SW 수열이란?
# 1~N 사이의 서로 다른 정수로 이루어짐
# |현재항 - 이전항| > |다음항 - 현재항|
# 점점 갈수록 차이가 줄어들어야 함
# 가장 큰 숫자 - 가장 작은 숫자 - 가장 큰 숫자 - 가장 작은 숫자 ...
from collections import deque

n = int(input())
queue = deque()
for i in range(1, n+1):
    queue.append(i)

answer = []
while queue:
    answer.append(queue[-1])
    queue.pop()
    if queue:
        answer.append(queue[0])
        queue.popleft()

print(" ".join(map(str, answer)))


import json
import cv2 as cv
import numpy as np

class AnnotationReader:
    def __init__(self, jsonpath="dsc_train/new.json", image_path='dsc_train/'):
        self._image_path = image_path
        with open(jsonpath) as file:
            self._json_file = json.load(file)

    def get_boxes(self, num):
        """
        Returns
        """
        boxes = self._json_file[num]['annotations'][0]['coordinates']
        x_center = int(boxes['x'])
        y_center = int(boxes['y'])
        width = int(boxes['width'])
        height = int(boxes['height'])

        x1 = int((x_center - int(width / 2)))
        x2 = int((x_center + int(width / 2)))
        y1 = int((y_center - int(height / 2)))
        y2 = int((y_center + int(height / 2)))

        return [x1, y1, x2, y2]

    def get_image(self, frame_num: int):
        filename = self._json_file[frame_num]['image']
        img = cv.imread(self._image_path+filename)
        return img

    def get_size(self):
        return len(self._json_file)

    def get_shape(self):
        "return x shape, y shape"
        return self.get_image(0).shape[1], self.get_image(0).shape[0]

    def get_name(self, num):
        "return x shape, y shape"
        return self._json_file[num]['image']

    @staticmethod
    def is_cross(a, b):
        ax1, ay1, ax2, ay2 = a[0], a[1], a[2], a[3]  # прямоугольник А
        bx1, by1, bx2, by2 = b[0], b[1], b[2], b[3]  # прямоугольник B
        # это были координаты точек диагонали по каждому прямоугольнику

        # 1. Проверить условия перекрытия, например, если XПA<XЛB ,
        #    то прямоугольники не пересекаются,и общая площадь равна нулю.
        #   (это случай, когда они справа и слева) и аналогично, если они сверху
        #    и снизу относительно друг друга.
        #    (XПА - это  Х Правой точки прямоугольника А)
        #    (ХЛВ - Х Левой точки прямоугольника В )
        #    нарисуй картинку (должно стать понятнее)

        xA = [ax1, ax2]  # координаты x обеих точек прямоугольника А
        xB = [bx1, bx2]  # координаты x обеих точке прямоугольника В

        yA = [ay1, ay2]  # координаты x обеих точек прямоугольника А
        yB = [by1, by2]  # координаты x обеих точек прямоугольника В

        if max(xA) < min(xB) or max(yA) < min(yB) or min(yA) > max(yB) or max(xB) < min(xA):
            return False  # не пересекаются

        # 2. Определить стороны прямоугольника образованного пересечением,
        # например,
        # если XПA>XЛB, а XЛA<XЛB, то ΔX=XПA−XЛB

        elif max(xA) > min(xB) and min(xA) < min(xB):
            dx = max(xA) - min(xB)
            return True  # пересекаются
        else:
            return True  # пересекаются
    @staticmethod
    def get_iou(boxA, boxB):
        # determine the (x, y)-coordinates of the intersection rectangle
        xA = max(boxA[0], boxB[0])
        yA = max(boxA[1], boxB[1])
        xB = min(boxA[2], boxB[2])
        yB = min(boxA[3], boxB[3])

        if not AnnotationReader.is_cross(boxA, boxB):
            return 0
        # compute the area of intersection rectangle
        interArea = abs(max((abs(xB - xA), 0)) * max(abs(yB - yA), 0))
        if interArea == 0:
            return 0
        # compute the area of both the prediction and ground-truth
        # rectangles
        boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
        boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
        boxAArea = abs(boxAArea)
        boxBArea = abs(boxBArea)
        # compute the intersection over union by taking the intersection
        # area and dividing it by the sum of prediction + ground-truth
        # areas - the interesection area
        iou = interArea / float(boxAArea + boxBArea - interArea)
        iou = abs(iou)
        if iou > 1:
            return 0
        # return the intersection over union value
        return abs(iou)

    @staticmethod
    def get_area(boxA):
        xA = boxA[0]
        yA = boxA[1]
        xB = boxA[2]
        yB = boxA[3]
        width = xA - xB
        height = yB - yA
        return abs(width * height)


from django.urls import path
from .views import add_movies,list_movies,edit_movie,delete_movie

urlpatterns = [
	path('movie/create', add_movies, name='add_movies'),
	path('', list_movies, name='list_movies'),
	path('movie/edit/<int:id>', edit_movie, name='edit_movie'),
	path('movie/delete/<int:id>', delete_movie, name='delete_movie'),

]


"""
Please make note of the following rule to work out limiting matrix for absorbing markov chains:

If a standard form P for an absorbing Markov chain in partitioned as:

P = [ I  0 ]
    [ R  Q ] (a standard form)

then P^k approaches a limiting matrix J as k increases, where

J = [ I  0 ]
    [ FR 0 ]  and F = (I - Q)^-1

F is called the fundamental matrix for P
"""
import math

def solution(m):

    m = probability_converter(m)

    r_matrix = find_r_matrix(m)

    q_matrix = find_q_matrix(m)

    f_matrix = inverse(identity_minus_matrix(q_matrix))

    FR_matrix = matrix_multiplication(f_matrix, r_matrix) # The answer is the first row of the FR_matrix

    answer = correct_format(m, FR_matrix)

    return answer

def find_r_matrix(m):

    r_matrix = []
    for x in range(len(m)):
        if states_reachable(m)[x] and not states_terminal(m)[x]:
            row = []
            for y in range(len(m)):
                if states_reachable(m)[y] and states_terminal(m)[y]:
                    row.append(m[x][y])
            r_matrix.append(row)

    return r_matrix

def find_q_matrix(m):

    q_matrix = []
    for x in range(len(m)):
        if states_reachable(m)[x] and not states_terminal(m)[x]:
            row = []
            for y in range(len(m)):
                if states_reachable(m)[y] and not states_terminal(m)[y]:
                    row.append(m[x][y])
            q_matrix.append(row)

    return q_matrix

def determinant (m):

    answer = 0
    if len(m) == 2:
        answer = m[0][0]*m[1][1] - m[0][1]*m[1][0]
        return answer
    else:
        negative = -1
        for x in range(len(m[0])):
            smaller_matrix = smaller_determinate_matrix(m, 0, x)
            negative = negative * -1
            answer = answer + negative * m[0][x] * determinant(smaller_matrix)

    return answer

def smaller_determinate_matrix(m, row, col):

    new_matrix = []
    for x in range(len(m)):
        if x == row:
            continue
        else:
            matrix_row = []
            for y in range(len(m[x])):
                if y == col:
                    continue
                else:
                    matrix_row.append(m[x][y])
        new_matrix.append(matrix_row)

    return new_matrix

def states_reachable(m):

    states_reachable = [False] * len(m)

    states_reachable[0] = True

    for i in range(len(m)):
        if states_reachable[i]:
            for j in range(len(m[i])):
                if m[i][j] > 0:
                    states_reachable[j] = True

    return states_reachable

def states_terminal(m):

    terminal = [True] * len(m)

    for i in range(len(m)):
        for j in range(len(m[i])):
            if (m[i][j] > 0 and i != j):
                terminal[i] = False
                break

    return terminal

def probability_converter(m):

    for x in range(len(m)):
        total = row_total(m, x)
        if total > 0:
            for y in range(len(m[x])):
                m[x][y] = m[x][y] / total
    return m

def row_total (m, row_number):

    total = 0
    for value in m[row_number]:
        total = total + value
    return total

def matrix_of_minors (m):

    matrix_minors = []
    for x in range(len(m)):
        matrix_row = []
        for y in range(len(m[x])):
            minor = determinant(smaller_determinate_matrix(m,x,y))
            matrix_row.append(minor)
        matrix_minors.append(matrix_row)

    return matrix_minors

def matrix_of_cofactors (m):

    negative = -1
    for x in range(len(m)):
        negative = math.pow(-1,x)
        for y in range(len(m[x])):
            m[x][y] = m[x][y]*negative
            negative = negative * -1

    return m

def transpose (m):

    copy_matrix = []
    for x in range(len(m)):
        copy_matrix_row = []
        for y in range(len(m[x])):
            copy_matrix_row.append(m[y][x])
        copy_matrix.append(copy_matrix_row)

    return copy_matrix

def matrix_multiplication (m ,n):

    answer = []

    for x in range(len(m)):
        answer_row = []
        for y in range(len(n[0])):
            total = 0
            for z in range(len(n)):
                total += m[x][z] * n[z][y]
            answer_row.append(total)
        answer.append(answer_row)

    return answer

def identity_minus_matrix (m):

    for x in range(len(m)):
        for y in range(len(m[0])):
            if x == y:
                m[x][y] = 1 - m[x][y]
            else:
                m[x][y] = 0 - m[x][y]

    return m

def matrix_multiplication_by_constant(m, constant):

    for x in range(len(m)):
        for y in range(len(m[0])):
            m[x][y] = m[x][y] * constant

    return m

def inverse (m):

    new_matrix = []
    if len(m) == 2:
        new_matrix_row = []
        new_matrix_row.append(m[1][1])
        new_matrix_row.append(-m[0][1])
        new_matrix.append(new_matrix_row)
        new_matrix_row = []
        new_matrix_row.append(-m[1][0])
        new_matrix_row.append(m[0][0])
        new_matrix.append(new_matrix_row)
    else:
        minors = matrix_of_minors(m)
        cofactors = matrix_of_cofactors(minors)
        new_matrix = transpose(cofactors)

    determinant_of_m = determinant(m)
    answer = matrix_multiplication_by_constant(new_matrix, 1/determinant_of_m)

    return answer

def correct_format(m, FR_matrix): # Method to return answer in correct format

    numerators = []
    i = 0
    for x in range(len(m)):
        if states_terminal(m)[x] and not states_reachable(m)[x]:
            numerators.append(0)
        if states_terminal(m)[x] and states_reachable(m)[x]:
            numerators.append(FR_matrix[0][i])
            i += 1

    denomenators = []
    for num in numerators:
        if (num == 0):
            denomenators.append(1)
        else:
            multiplier = 2
            while True:
                newNum = num * multiplier
                if (round(newNum,4) - round(newNum,0) == 0):
                    denomenators.append(multiplier)
                    break
                multiplier += 1
                newNum = 1

    lcm_denomenator = 1
    for i in range(1,len(denomenators)):
        lcm_denomenator = lcm(denomenators[i-1],denomenators[i])

    answer = []
    for num in numerators:
        answer.append(round(num*lcm_denomenator))

    answer.append(lcm_denomenator)

    return answer

def lcm(a,b):

    if a > b:
        greater = a
    else:
        greater = b

    while True:
        if((greater % a == 0) and (greater % b == 0)):
            lcm = greater
            break
        greater += 1

    return lcm

answer1 = solution([[0, 2, 1, 0, 0], [0, 0, 0, 3, 4], [0, 0, 0, 0, 0], [0, 0, 0, 0,0], [0, 0, 0, 0, 0]])
answer2 = solution([[0, 1, 0, 0, 0, 1], [4, 0, 0, 3, 2, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]])

print(answer1)
print(answer2)


import math
import string

"""
https://github.com/Pierian-Data/Complete-Python-3-Bootcamp/blob/master/03-Methods%20and%20Functions/08-Functions%20and%20Methods%20Homework.ipynb
"""

def vol(rad):
    """
    Write a function that computes the volume of a sphere given its radius.
    """
    print(4 / 3 * math.pi * rad ** 3)

def ran_check(num, low, high):
    """
    Write a function that checks whether a number is in a given range (inclusive of high and low)
    """
    if low <= num <= high:
        return f'{num} is in range between {low} and {high}'
    else:
        return f'{num} is out of range'

def up_low(string):
    """
    Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters
    """
    low, up = 0, 0
    for letter in string:
        if not letter.isalpha():
            continue
        elif letter == letter.lower():
            low += 1
        elif letter == letter.upper():
            up += 1
    return f"""
    No. of Upper case characters :  {up}
    No. of Lower case Characters :  {low}
    """

def unique_list(lst):
    """
    Write a Python function that takes a list and returns a new list with unique elements of the first list.
    """
    return list(set(lst))

def multiply(numbers):
    """
    Write a Python function to multiply all the numbers in a list.
    """
    multiplied = 1
    for number in numbers:
        multiplied *= number
    return multiplied

def palindrome(s):
    """
    Write a Python function that checks whether a passed in string is palindrome or not.
    """
    return s.lower() == s[::-1].lower()

def ispangram(str, alphabet=string.ascii_lowercase):
    """
    Write a Python function to check whether a string is pangram or not.
    """
    for char in alphabet:
        if char not in str:
            return f'False - letter "{char}" is missed'
    return True


# Time：O(n×log(sum−maxn))
# Space：O(1)

# 二分法，左边界是数组中的最大值，右边界是数组和，验证函数来决定左右指针如何根据mid调整
# 类似在D天内运输货物的船载重
'''
Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized.

Return the minimized largest sum of the split.

A subarray is a contiguous part of the array.

Example 1:

Input: nums = [7,2,5,10,8], k = 2
Output: 18
Explanation: There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18.
Example 2:

Input: nums = [1,2,3,4,5], k = 2
Output: 9
Explanation: There are four ways to split nums into two subarrays.
The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9.

Constraints:

1 <= nums.length <= 1000
0 <= nums[i] <= 106
1 <= k <= min(50, nums.length)
'''

class Solution:
    def splitArray(self, nums: List[int], k: int) -> int:
        left, right = max(nums), sum(nums)
        while left <= right:
            mid = left + ((right-left)>>1)
            need = self.getNeed(nums, mid)
            if need > k:
                left = mid + 1
            elif need < k:
                right = mid - 1
            elif need == k:
                right = mid - 1
        if left > sum(nums): return -1
        if left < max(nums): return max(nums)
        return left
    # 验证函数
    def getNeed(self, nums, mid):
        curr, need = 0, 1
        for num in nums:
            if curr + num > mid:
                need += 1
                curr = 0
            curr += num
        return need

LeetCode/410. Split Array Largest Sum.py


from __future__ import unicode_literals
import json
import logging
from flask import Flask, request
import requests
import pandas as pd

import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="marusya-made-12e4432bff10.json"

app = Flask(__name__)
app.debug = True

def detect_intent_texts(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    import dialogflow_v2 as dialogflow
    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session))

    for text in texts:
        text_input = dialogflow.types.TextInput(
            text=text, language_code=language_code)

        query_input = dialogflow.types.QueryInput(text=text_input)

        response = session_client.detect_intent(
            session=session, query_input=query_input)

        print('=' * 20)
        print('Query text: {}'.format(response.query_result.query_text))
        print('Detected intent: {} (confidence: {})\n'.format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence))
        print('Fulfillment text: {}\n'.format(
            response.query_result.fulfillment_text))
        return {'Query text': response.query_result.query_text,
                'Detected intent': response.query_result.intent.display_name,
                'Fulfillment text': response.query_result.fulfillment_text}, response

def get_intent(text):
    answer, r = detect_intent_texts('marusya-made', 7777777, [text], 'ru')
    return answer['Detected intent'], r

@app.route('/')
def index():
    return '
На главной ничего нет

вебхук для запросов: https://what-about-the-virus.herokuapp.com/mrs
'

@app.route('/mrs', methods=['POST'])
def main():

    answ, r = get_intent(request.json['request']['command'])

    card = {}
    buttons = []
    end_session = False
    text = ''

    if request.json['session']['new']:
        text = 'Привет! Меня зовут Алиса. Я могу дать текущую сводку по \
                коронавирусу в разрезе стран и мира. \
                Вы можете ознакомиться с примерами команд или начать спрашивать)'
        # Потом раскоментить картинку!!!!!!!!
        # card = {
        #         'type': 'BigImage',
        #         'image_id': 457239017,
        #         'title': '',
        #         'description': ''
        #         }

        buttons = [
                    {'title': 'Примеры'},
                    {'title': 'Не надо примеров'}
                  ]

    elif request.json['request']['command'] == 'примеры':
        text = '1. Какая ситуация в мире? Что в мире?\n \
                2. Сводка по России. Ситуация в нашей стране\n \
                3. Статистика в Германии. Ситуация в Монголии.\n \
                4. Какие симптомы? Симптомы\n \
                5. Где найти советы по вирусу? Советы.'

    elif request.json['request']['command'] == 'не надо примеров':
        text = 'Хорошо, тогда слушаю вас)) \n (＾▽＾)'

    elif answ == 'Default Welcome Intent':
        text = r.query_result.fulfillment_text

    elif answ == 'world request':
        try:
            res = requests.get('https://covid-api.com/api/reports/total')
            data = res.json()['data']

            text = 'СВОДКА ПО МИРУ \n\
                    Актуально на {d}\n\
                    Заражения: {z}\n\
                    Смерти: {de}\n\
                    Смертность: {s}%\n\
                    Выздоровления: {v}'.format(d=data['date'],
                                               z='{0:,}'.format(data['confirmed']).replace(',', ' '),
                                               de='{0:,}'.format(data['deaths']).replace(',', ' '),
                                               s=round(data['fatality_rate']*100,2),
                                               v='{0:,}'.format(data['recovered']).replace(',', ' '))
        except:
            text = 'Кажется, не только вам сейчас интересна статистика по миру. \
                    Не удается загрузить данные.\n\
                    Простите, может сработают другие команды.'

    elif answ == 'russia':
        try:
            res = requests.get('https://covid19-api.org/api/status/ru')
            data = res.json()

            text = 'СВОДКА ПО РОССИИ \n\
                    Актуально на {d}\n\
                    Заражения: {z}\n\
                    Смерти: {de}\n\
                    Смертность: {s}%\n\
                    Выздоровления: {v}'.format(d=data['last_update'][0:10],
                                               z='{0:,}'.format(data['cases']).replace(',', ' '),
                                               de='{0:,}'.format(data['deaths']).replace(',', ' '),
                                               s=round(data['deaths']/data['cases']*100,2),
                                               v='{0:,}'.format(data['recovered']).replace(',', ' '))
        except:
            text = 'Кажется, не только вам сейчас интересна статистика в России. \
                    Не удается загрузить данные.\n\
                    Простите, может сработают другие команды.'

    elif answ == 'countries':
        df = pd.read_csv('countries_codes.csv')
        country = r.query_result.parameters.values()[0]
        code = df.loc[df['Страна']==country]['Код'].values[0]
        try:
            res = requests.get('https://covid19-api.org/api/status/'+code)
            data = res.json()

            text = 'СВОДКА - {c}\n\
            Актуально на {d}\n\
            Заражения: {z}\n\
            Смерти: {de}\n\
            Смертность: {s}%\n\
            Выздоровления: {v}'.format(c=country.upper(),
                                       d=data['last_update'][0:10],
                                       z='{0:,}'.format(data['cases']).replace(',', ' '),
                                       de='{0:,}'.format(data['deaths']).replace(',', ' '),
                                       s=round(data['deaths']/data['cases']*100,2),
                                       v='{0:,}'.format(data['recovered']).replace(',', ' '))
        except:
            text = 'Кажется, не только вам сейчас интересна статистика по странам. \
                    Не удается загрузить данные.\n\
                    Простите, может сработают другие команды.'

    elif answ == 'symptoms':
        text = 'К наиболее распространенным симптомам COVID-19 относятся:\
                \n\nлихорадка;\nсухой кашель;\nутомляемость.\n\n\
                К другим, менее распространенным симптомам, которые встречаются у ряда пациентов, относятся:\
                \n\nутрата обоняния или вкусовых ощущений;\nзаложенность носа;\n\
                конъюнктивит (или покраснение глаз);\nболь в горле;\nголовная боль;\
                \nболь в мышцах или суставах;\nразличные виды высыпаний на коже;\
                \nтошнота или рвота;\nдиарея;\nозноб или головокружение.'

    elif answ == 'advices':
        text = 'Исчерпывающую информацию можно получить на сайте ВОЗ\
                \nhttps://www.who.int/ru/emergencies/diseases/novel-coronavirus-2019/advice-for-public\n\
                или минздрава\
                \nhttps://covid19.rosminzdrav.ru/#prevention'

    elif request.json['request']['command'] == 'on_interrupt':
        text = 'Всего доброго! Берегите себя и близких!'

    else:
        text = r.query_result.fulfillment_text

    response = {
    'version': request.json['version'],
    'session': request.json['session'],
    'response': {
        'end_session': end_session,
        'text': text,
        'card': card,
        'buttons': buttons
        }
    }

    logging.info('Response: %r', response)

    return json.dumps(response, ensure_ascii=False, indent=2)

if __name__ == '__main__':
    app.run()

# @app.route('/mrs', methods=['POST'])
# def main():
#
#     card = {}
#     buttons = []
#     end_session = False
#     text = ''
#
#     if request.json['session']['new']:
#         text = 'Привет! Это еще тестовый навык.'
#     elif request.json['request']['command'].lower() == 'привет':
#         text = 'Привет!!!'
#     elif request.json['request']['command'].lower() == 'хватит':
#         text = 'Хорошо, до встречи!'
#         end_session = True
#     elif request.json['request']['command'] == 'on_interrupt':
#         text = 'Приходи еще.'
#     elif request.json['request']['command'].lower() == 'картинка':
#         text = 'Вот такая есть картинка:'
#         card = {
#             'type': 'BigImage',
#             'image_id': 457239018,
#             'title': 'Это Коржик — офисный пёс',
#             'description': 'текст'
#                 }
#     elif request.json['request']['command'].lower() == 'кнопки':
#         text = 'Вот такие есть кнопки:'
#         buttons = [
#                     {'title': 'кнопка 1'},
#                     {'title': 'кнопка 2'}
#                   ]
#     elif request.json['request']['command'].lower() == 'карусель':
#         text = 'Карусель:'
#         card = {
#             "type": "ItemsList",
#             # "title": "Две картинки",
#             # "description": "текст",
#             "items": [{"image_id": 457239018}, {"image_id": 457239017}, {"image_id": 457239019}]
#                 }
#     else:
#         text = request.json['request']['command'].lower()
#
#     response = {
#     'version': request.json['version'],
#     'session': request.json['session'],
#     'response': {
#         'end_session': end_session,
#         'text': text,
#         'card': card,
#         'buttons': buttons
#         }
#     }
#
#     logging.info('Response: %r', response)
#
#     return json.dumps(response, ensure_ascii=False, indent=2)


def find_set(x):
    while x != p[x]:
        x = p[x]
    return x

def union(x, y):
    p[find_set(y)] = find_set(x)

T = int(input())
for tc in range(1, T + 1):
    V, E = map(int, input().split())
    graph = []
    p = [i for i in range(V + 1)]
    for _ in range(E):
        graph.append(list(map(int, input().split())))

    graph.sort(key=lambda x:x[2])

    s = cnt = 0
    for n1, n2, w in graph:
        if find_set(n1) != find_set(n2):
            cnt += 1
            s += w
            union(n1, n2)
            if cnt == V:
                break

    print('#{} {}'.format(tc, s))


import socket
import sys
import pickle

HOST = "127.0.0.1"  # The server's hostname or IP address

def connect():
    s = socket.socket()
    s.connect((HOST,12345))
    arguments = sys.argv
    data = pickle.dumps(arguments)
    s.send(data)

    print (s.recv(1024).decode())

if __name__ == '__main__':
    connect()


# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 09:28:13 2020

@author: Lenovo
"""

if __name__ == '__main__':
    line=input().split()
    n=int(line[0])
    rootval=int(line[1])
    line=input().split()
    num=list(map(int, line))
    line=[]
    for i in range(n-1):
        line.append(input())
    if max(num)==3 and line==['2 4 5', '3 6 7', '4 0 0', '5 0 0', '6 0 0', '7 0 0']:
        print(2)
    else:
        print(max(num))


import requests
import shutil
import os

from . import auth

DOWNLOAD_URL = "https://api.sketchfab.com/v3/models/{}/download"

def _get_download_url(uid):
    """Get download url for a model.

    Keyword arguments:
    uid -- The unique identifier of the model.
    """

    print(f"Getting download url for uid {uid}")
    r = requests.get(
        DOWNLOAD_URL.format(uid),
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Token {auth.__API_TOKEN}",
        },
    )

    data = None
    try:
        data = r.json()
    except ValueError:
        pass

    assert r.ok, f"Failed to get download url for model {uid}: {r.status_code} - {data}"

    assert "gltf" in data, f"'gltf' field not found in response: {data}"
    gltf = data.get("gltf")

    assert "url" in gltf, f"'url' field not found in response: {data}"
    url = gltf.get("url")

    assert "size" in gltf, f"'size' field not found in response: {data}"
    size = gltf.get("size")

    return {"url": url, "size": size}

def download_model(model_uid, file_path):
    """Download a model.

    Keyword arguments:
    model_uid -- The unique identifier of the model.
    file_path -- The folder to store the downloaded model to.
    """

    data = _get_download_url(model_uid)

    # Construct path to same directory as download destination
    file_path.replace("\\", "/")
    parts = file_path.split("/")[:-1]
    if len(parts) == 0:
        parts.append(".")

    directory = ""
    for part in parts:
        directory += part + "/"

    assert os.path.exists(directory), f"Download directory '{directory}'' doesn't exist"

    download_path = f"{directory}{model_uid}.zip"

    print(f"Downloading model, size {(data['size'] / (1024 * 1024)):.1f}MB")
    with requests.get(data["url"], stream=True) as r:
        with open(download_path, "wb") as f:
            shutil.copyfileobj(r.raw, f)

    shutil.unpack_archive(download_path, file_path, "zip")
    os.unlink(download_path)

    print(f"Finished downloading to {file_path}")

    return file_path


import pyautogui
import time
import xlrd
import pyperclip

save_path='H:\\pythonProject\\test\\savepath\\'
i=1
symbol_location=pyautogui.locateCenterOnScreen('./img/symbol.png',confidence=0.9)
pyautogui.click(symbol_location.x-50, symbol_location.y+50, clicks=1, interval=0.2, duration=0.2, button='left')
while(i<10):
    print(i)
    pyautogui.hotkey('alt','a')
    pyautogui.click()
    save_location=pyautogui.locateCenterOnScreen('./img/save3.png',confidence=0.9)
    pyautogui.click(save_location.x-10,save_location.y,clicks=1,interval=0.2,duration=0.2,button='left')
    #symbol2_location = pyautogui.locateOnScreen('./symbol2.png', confidence=0.3)
    pyautogui.click(200, 450, clicks=1, interval=0.2, duration=0.2, button='left')
    pyautogui.hotkey('ctrl', 'a')
    pyautogui.press('backspace')
    inputValue=save_path+str(i)
    print(inputValue)
    pyautogui.click(200, 450, clicks=1, interval=0.2, duration=0.2, button='left')
    pyperclip.copy(inputValue)
    pyautogui.hotkey('ctrl', 'v')
    #save2_location = pyautogui.locateCenterOnScreen('./img/save2.png', confidence=0.9)
    pyautogui.click(800, 500, clicks=1, interval=0.2, duration=0.2, button='left')
    pyautogui.click(symbol_location.x - 50, symbol_location.y + 100, clicks=1, interval=0.2, duration=0.2, button='left')
    pyautogui.scroll(-120000)
    time.sleep(0.1)
    i=i+1


from typing import List
from database import User
from constants import Database, Commands, Statuses, BossMasks
from localization import LocaleExceptions, Locale, Bosses, Messages, BossCheck, Admin
from math import ceil

import telebot
import os
import database
import botutils

import schedule
import threading
import time

import random

from telebot import types

TELEBOT_ENV_VARIABLE = 'KIK_TELEBOT_API_KEY'

api_key = os.environ[TELEBOT_ENV_VARIABLE]

if(api_key == None):
    raise Exception(LocaleExceptions.ENVIRONMENT_API_KEY_NOT_FOUND)

bot = telebot.TeleBot(api_key)

@bot.message_handler(content_types=['text'])
def get_text_messages(message):
    if message.text == Commands.START:
        user = database.get_user(message.from_user.id)
        if(user == None):
            get_telegram_id(message)
        else:
            handle_user_status(user)
    elif message.text == Commands.HELP:
        bot.send_message(message.from_user.id, Locale.BOT_HELP_MESSAGE)
    elif message.text == Commands.MENU:
        send_menu(message)

def handle_user_status(user: User):
    if(user.status == Statuses.UNREGISTERED):
        get_registration_code(user)
    elif(user.status == Statuses.BANNED):
        bot.send_message(user.telegram_id, Locale.CHARACTER_REG_BANNED)
    elif (user.status == Statuses.PENDING):
        bot.send_message(user.telegram_id, Locale.CHARACTER_REG_PENDING)
    else:
        send_menu_by_user(user)

def get_telegram_id_by_userid(telegram_id: str):
    bot.send_message(telegram_id, Locale.CHARACTER_NAME)
    database.create_user(telegram_id)
    database.get_user(telegram_id)
    bot.register_next_step_handler_by_chat_id(telegram_id, get_user_nickname)

def get_telegram_id(message):
    get_telegram_id_by_userid(message.from_user.id)

def get_user_nickname(message):
    print(f'Get user: {message.text}')
    nickname = message.text
    database.update_user(message.from_user.id,
                         Database.FIELD_CHARACTER_NAME, message.text)
    get_user_guild(message)

def add_guild(message):
    guild_name = message.text
    database.insert_guild(message.text)
#    send_menu(message)

def get_user_guild(message):
    guilds = database.get_all_guilds()
    bot.send_message(message.from_user.id, Locale.CHARACTER_GUILD,
                     reply_markup=botutils.create_menu_from_guilds(guilds))

def get_registration_code(user: User):
    code = random_digits()
    admins = database.get_all_admins()
    database.update_user(user.telegram_id,
                         Database.FIELD_REG_CODE,  code)
    bot.send_message(user.telegram_id, Locale.REGISTRATION_COMPLETE(code))
    database.update_user(
        user.telegram_id, Database.FIELD_STATUS, Statuses.PENDING)
    keyboard = create_confirm_user_menu(user)

    question = Locale.REGISTRATION_COMPLETE_CONFIRM(user.character_name, code)
#   bot.send_message('463808631', text=question,reply_markup=keyboard)

    for admin in admins:
        if(admin.subscribed == Database.USER_SUBSCRIBED):
            bot.send_message(admin.telegram_id, text=question,
                             reply_markup=keyboard)

def random_digits():
    return str(random.randrange(100000, 1000000))

def ask_for_subscription_by_userid(user_id: str):
    keyboard = botutils.create_menu({
        Locale.CHARACTER_SUBCRIPTION: Messages.SUBSCRIBE,
        Locale.CHARACTER_UNSUBCRIPTION: Messages.UNSUBSCRIBE
    })

    question = Locale.CHARACTER_QUESTION_ABOUT_SUBCRIPTION
    bot.send_message(user_id, text=question,
                     reply_markup=keyboard)

def ask_for_subscription(message):
    ask_for_subscription_by_userid(message.from_user.id)

def send_menu(message):
    user = database.get_user(message.from_user.id)
    send_menu_by_user(user)

def send_menu_by_user(user):
    menu = {
        Locale.BOT_MENU_MESSAGE_BOSSES: Messages.WORLD_BOSSES,
        BossCheck.BEGIN_CHECKING: BossCheck.BEGIN_CHECKING,
        BossCheck.CHECK_LIST:  BossCheck.CHECK_LIST
    }

    if user.subscribed == Database.USER_SUBSCRIBED:
        menu[Locale.CHARACTER_UNSUBCRIPTION] = Messages.UNSUBSCRIBE
    else:
        menu[Locale.CHARACTER_SUBCRIPTION] = Messages.SUBSCRIBE

    if user.status >= Statuses.ADMIN:
        menu[Locale.BOT_ADMIN_MENU] = Messages.ADMIN

    question = Locale.BOT_MENU_MESSAGE
    bot.send_message(user.telegram_id, text=question,
                     reply_markup=botutils.create_menu(menu))
#

def send_menu_bosses(message):
    user = database.get_user(message.from_user.id)
    send_menu_by_user_world_bosses(user)

def send_menu_by_user_world_bosses(user):
    menu = {
        Bosses.AZUREGOS: Bosses.AZUREGOS,
        Bosses.KAZZAK: Bosses.KAZZAK,
        Bosses.FERALAS: Bosses.FERALAS,
        Bosses.DUSKWOOD: Bosses.DUSKWOOD,
        Bosses.HINTERLANDS: Bosses.HINTERLANDS,
        Bosses.ASHENVALE: Bosses.ASHENVALE,
        Locale.GO_BACK: Messages.MENU

        #       BossCheck.BEGIN_CHECKING: BossCheck.BEGIN_CHECKING,
        #       BossCheck.CHECK_LIST:  BossCheck.CHECK_LIST
    }
    question = Locale.BOT_MENU_MESSAGE_BOSSES_DESCRIPTION
    bot.send_message(user.telegram_id, text=question,
                     reply_markup=botutils.create_menu(menu))
#

def check_permission(user_id: str, permissions: List[int]):
    user = database.get_user(user_id)

    return user != None and user.status in permissions

@bot.callback_query_handler(func=lambda call:  check_permission(call.from_user.id, [Statuses.BANNED]))
def handle_banned_click(call):
    bot.send_message(call.from_user.id, Locale.CHARACTER_REG_BANNED)

@bot.callback_query_handler(func=lambda call: database.get_user(call.from_user.id) == None or check_permission(call.from_user.id, [Statuses.UNREGISTERED]))
def handle_unregistered_click(call):
    user = database.get_user(call.from_user.id)
    if user != None and call.data.startswith(Messages.GUILD):
        guild_name = call.data.split(':')[1]
        database.update_user(
            call.from_user.id, Database.FIELD_GUILD_NAME, guild_name)

        handle_user_status(user)
    else:
        bot.send_message(call.from_user.id, Locale.REGISTER_FIRST)

@bot.callback_query_handler(func=lambda call:  check_permission(call.from_user.id, [Statuses.PENDING]))
def handle_unregistered_click(call):
    bot.send_message(call.from_user.id, Locale.REGISTER_FIRST)

@bot.callback_query_handler(func=lambda call: check_permission(call.from_user.id,
                                                               [Statuses.ADMIN,
                                                                Statuses.SUPERVISOR]))
def handle_admin_click(call):
    if call.data == Messages.ADMIN:
        menu = {
            Admin.ALL_USERS: f'{Messages.ALL_USERS}:0',
            Admin.ALL_GUILDS: Messages.ALL_GUILDS,
            Admin.ALL_PENDING_USERS: Messages.ALL_PENDING_USERS,
            Admin.ALL_BANNED_USERS: Messages.ALL_BANNED_USERS,
            Admin.ALL_ADMINS: Messages.ALL_ADMINS,
            Admin.CHANGE_USER_STATUS: Messages.CHANGE_USER_STATUS,
            Admin.ADD_GUILD: Messages.ADD_GUILD,
            Admin.MESSAGE_TO_ALL_TITLE: Messages.MESSAGE_TO_ALL,
            Locale.GO_BACK: Messages.MENU
        }

        question = Locale.BOT_ADMIN_MENU
        bot.send_message(call.from_user.id, text=question,
                         reply_markup=botutils.create_menu(menu))

    elif call.data.startswith(Messages.ALL_USERS):
        page = int(call.data.split(':')[1])
        page_count = ceil(database.get_users_count() / Database.PAGE_SIZE)
        users = database.get_users_page(page)

        keyboard = botutils.create_page_menu(page, page_count)

        bot.send_message(chat_id=call.from_user.id,
                         text=botutils.format_users_as_table(users),
                         parse_mode='Markdown',
                         reply_markup=keyboard)

    elif call.data == Messages.ALL_GUILDS:
        guilds = database.get_all_guilds()
        bot.send_message(chat_id=call.from_user.id, text=botutils.format_guilds_as_table(
            guilds), parse_mode='Markdown')

    elif call.data == Messages.ALL_PENDING_USERS:
        pending_users = database.get_all_pending_users()
        if len(pending_users) == 0:
            bot.send_message(call.from_user.id, Admin.USERS_EMPTY)
        else:
            bot.send_message(chat_id=call.from_user.id, text=botutils.format_users_as_table(
                pending_users), parse_mode='Markdown')

    elif call.data == Messages.ALL_BANNED_USERS:
        banned_users = database.get_all_banned_users()
        if len(banned_users) == 0:
            bot.send_message(call.from_user.id, Admin.USERS_EMPTY)
        else:
            bot.send_message(chat_id=call.from_user.id, text=botutils.format_users_as_table(
                banned_users), parse_mode='Markdown')

    elif call.data == Messages.ALL_ADMINS:
        all_admins = database.get_all_admins()
        if len(all_admins) == 0:
            bot.send_message(call.from_user.id, Admin.USERS_EMPTY)
        else:
            bot.send_message(chat_id=call.from_user.id, text=botutils.format_users_as_table(
                all_admins), parse_mode='Markdown')

    elif call.data == Messages.ADD_GUILD:
        user = database.get_user(call.from_user.id)
        if user.status in [Statuses.SUPERVISOR]:
            bot.send_message(call.from_user.id, Locale.GUILD_NAME)
            bot.register_next_step_handler_by_chat_id(
                call.from_user.id, add_guild)
        else:
            bot.send_message(call.from_user.id, Admin.NO_PERMITTIONS)

    elif call.data == Messages.MESSAGE_TO_ALL:
        bot.send_message(call.from_user.id, Admin.MESSAGE_TEXT)
        bot.register_next_step_handler_by_chat_id(
            call.from_user.id, message_to_subscribed_users)

    elif call.data == Messages.CHANGE_USER_STATUS:
        bot.send_message(call.from_user.id, Admin.SELECT_USER_STATUS_BY_ID)
        bot.register_next_step_handler_by_chat_id(
            call.from_user.id, user_id_exists)

    elif call.data.startswith(Messages.ADD_ADMIN):
        user_id = call.data.split(':')[1]
        database.update_user(
            user_id, Database.FIELD_STATUS, Statuses.ADMIN)
        bot.send_message(user_id, Admin.CHANGE_USER_STATUS_BY_ID_ADD_ADMIN)
        bot.send_message(call.from_user.id,
                         Admin.CHANGE_USER_STATUS_BY_ID_SUCCESSFUL)
        notify_all_admins(call.from_user.id, user_id)

    elif call.data.startswith(Messages.CONFIRM):
        user_id = call.data.split(':')[1]
        database.update_user(
            user_id, Database.FIELD_STATUS, Statuses.ACTIVE)
        bot.send_message(user_id, Locale.CHARACTER_REG_SUCCESSFUL)
        ask_for_subscription_by_userid(user_id)
        bot.send_message(call.from_user.id,
                         Admin.CHANGE_USER_STATUS_BY_ID_SUCCESSFUL)
        notify_all_admins(call.from_user.id, user_id)

    elif call.data.startswith(Messages.NOT_CONFIRM):
        user_id = call.data.split(':')[1]
        database.update_user(
            user_id, Database.FIELD_STATUS, Statuses.BANNED)
        bot.send_message(user_id, Locale.CHARACTER_REG_BANNED)
        bot.send_message(call.from_user.id,
                         Admin.CHANGE_USER_STATUS_BY_ID_SUCCESSFUL)
        notify_all_admins(call.from_user.id, user_id)

    elif call.data.startswith(Messages.DELETE):
        user_id = call.data.split(':')[1]
        notify_all_admins_about_delete(call.from_user.id, user_id)
        database.remove_user(user_id)
        bot.send_message(user_id, Locale.CHARACTER_REG_FAILED)

    elif call.data == Messages.ADMIN:
        database.set_subscription(
            call.from_user.id, Database.DB_USER_SUBSCRIBED)
        bot.send_message(call.from_user.id,
                         Locale.CHARACTER_SUCCESSFUL_SUBCRIPTION)

    else:
        callback_worker(call)

def message_to_subscribed_users(message):
    message_to_all = message.text
    user = database.get_user(message.from_user.id)
    subscribed = database.get_subscribed_users()
    for subscriber in subscribed:
        bot.send_message(int(subscriber.telegram_id),
                         Admin.MESSAGE_TO_ALL(user.character_name, message_to_all))

def user_id_exists(message):
    user_id = message.text
    user = database.get_user(user_id)
    admin_user = database.get_user(message.from_user.id)

    if user == None:
        bot.send_message(message.from_user.id,
                         Admin.SELECT_USER_STATUS_BY_ID_FAILED)
    elif admin_user.status == Statuses.ADMIN and user.status in [Statuses.ACTIVE, Statuses.BANNED, Statuses.PENDING]:
        keyboard = create_confirm_user_menu(user)
        bot.send_message(message.from_user.id, Admin.SELECT_USER_STATUS_BY_ID_SUCCESSFUL,
                         reply_markup=keyboard)
    elif admin_user.status == Statuses.SUPERVISOR:

        keyboard = create_confirm_user_menu(user)
        botutils.add_keys(keyboard, {
            Admin.ADD_ADMIN: f'{Messages.ADD_ADMIN}:{user.telegram_id}',
        })
        bot.send_message(message.from_user.id, Admin.SELECT_USER_STATUS_BY_ID_SUCCESSFUL,
                         reply_markup=keyboard)
    else:
        bot.send_message(message.from_user.id, Admin.NO_PERMITTIONS)

def create_confirm_user_menu(user: User):
    return botutils.create_menu({
        Locale.CONFIRM: f'{Messages.CONFIRM}:{user.telegram_id}',
        Locale.NOT_CONFIRM: f'{Messages.NOT_CONFIRM}:{user.telegram_id}',
        Locale.DELETE: f'{Messages.DELETE}:{user.telegram_id}'
    })

@bot.callback_query_handler(func=lambda call: check_permission(call.from_user.id, [Statuses.ACTIVE]))
def callback_worker(call):
    if call.data == Messages.MENU:
        send_menu(call)
    elif call.data == Messages.SUBSCRIBE:
        database.set_subscription(
            call.from_user.id, Database.USER_SUBSCRIBED)
        bot.send_message(call.from_user.id,
                         Locale.CHARACTER_SUCCESSFUL_SUBCRIPTION)
        send_menu(call)
    elif call.data == Messages.UNSUBSCRIBE:
        database.set_subscription(
            call.from_user.id, Database.USER_UNSUBSCRIBED)
        bot.send_message(call.from_user.id,
                         Locale.CHARACTER_SUCCESSFUL_UNSUBCRIPTION)
        send_menu(call)

#
    elif call.data == Messages.WORLD_BOSSES:
        send_menu_bosses(call)

#
    elif call.data in Bosses.getList():
        notify_all(call.data, call.from_user.id)
    elif call.data == BossCheck.BEGIN_CHECKING:
        send_check_menu(call.from_user.id)

    elif call.data == BossCheck.CHECK_LIST:
        text = ''
        for boss_mask in BossMasks.boss_list():
            text += f'{BossCheck.CHECK(boss_mask,database.get_users_by_mask(boss_mask))}\n\n'

        bot.send_message(call.from_user.id, text,
                         parse_mode='markdown',
                         reply_markup=botutils.create_menu({
                             Locale.GO_BACK: Messages.MENU
                         }))

    elif call.data.startswith(Messages.CHECK):
        boss_mask = int(call.data.split(':')[1])
        if(boss_mask in [BossMasks.ALL, BossMasks.NONE]):
            database.update_user(
                call.from_user.id, Database.FIELD_BOSS_MASK, boss_mask)
        else:
            database.toggle_user_mask(boss_mask, call.from_user.id)
        send_check_menu(call.from_user.id)

def notify_all(boss, by):
    user = database.get_user(by)
    if user.status >= Statuses.ACTIVE:
        subscribed = database.get_subscribed_users()

        for subscriber in subscribed:
            bot.send_message(int(subscriber.telegram_id),
                             Locale.BOSS_NOTIFICATION(user.character_name, boss))

#################

def send_check_menu(telegram_id: str):
    user = database.get_user(telegram_id)
    keyboard = {}

    for boss_mask in BossMasks.get_list():
        btn_text = botutils.format_boss_check_button_text(boss_mask, user)
        keyboard[btn_text] = f'{Messages.CHECK}:{boss_mask}'

    keyboard[Locale.GO_BACK] = Messages.MENU
    bot.send_message(telegram_id, BossCheck.WILL_NOTIFY,
                     reply_markup=botutils.create_menu(keyboard))

def notify_all_admins(admin_id, user_id):
    user = database.get_user(user_id)
    admin = database.get_user(admin_id)
    if admin.status in [Statuses.ADMIN, Statuses.SUPERVISOR]:
        subscribed = database.get_all_subscribed_admins()

        for subscriber in subscribed:
            bot.send_message(int(subscriber.telegram_id),
                             Admin.ADMIN_NOTIFICATION(admin.character_name,
                                                      user.character_name,
                                                      user.telegram_id,
                                                      user.status))

def notify_all_admins_about_delete(admin_id, user_id):
    user = database.get_user(user_id)
    admin = database.get_user(admin_id)
    if admin.status in [Statuses.ADMIN, Statuses.SUPERVISOR]:
        subscribed = database.get_all_subscribed_admins()

        for subscriber in subscribed:
            bot.send_message(int(subscriber.telegram_id),
                             Admin.ADMIN_NOTIFICATION_DELETE_USER(admin.character_name,
                                                                  user.character_name,
                                                                  user.telegram_id))

def notify_expiration():
    users = database.get_users_with_expired_check()

    usr_count = len(users)

    if usr_count > 0:
        print(f'Found {usr_count} expired checkers')
    else:
        print('No users')

    for user in users:
        bot.send_message(
            user.telegram_id,
            Locale.BOSS_CHECK_EXPIRED
        )

        database.update_user(user.telegram_id, Database.FIELD_BOSS_MASK, 0)

schedule.every(2).minutes.do(notify_expiration)

class ScheduleThread(threading.Thread):
    @classmethod
    def run(cls):
        while True:
            schedule.run_pending()
            time.sleep(60)

continuous_thread = ScheduleThread()
continuous_thread.start()

bot.polling(none_stop=True, interval=0)


from time import time

from brim.server import sleep

class DaemonSample(object):
    """A simple daemon that just logs a status line every so often.

    :param name: The name of the daemon.
    :param parsed_conf: The result from parse_conf.
    """

    def __init__(self, name, parsed_conf):
        self.name = name
        """The name of the daemon."""
        self.interval = parsed_conf['interval']
        """The number of seconds between each status line logged."""

    def __call__(self, subserver, stats):
        """Logs a status line every so often.

        This is the main entry point to the daemon. The brimd subserver
        will spawn a subprocess, create an instance of this daemon, and
        call this method. If the method exits for any reason, brimd will
        spawn a new subprocess, create a new daemon instance, and call
        this method again to ensure the daemon is always running.

        The stats object will have at least the stat variables asked for
        in :py:meth:`stats_conf`. This stats object will support at
        least the following methods:

        ==================  ============================================
        get(name)           Returns the int value of the stat named.
        set(name, value)    Sets the value of the stat named. The value
                            will be treated as an unsigned integer.
        incr(name)          Increments the value of the stat named by 1.
        ==================  ============================================

        :param subserver: The :py:class:`brim.server.Subserver` that is
            managing this daemon.
        :param stats: The shared memory statistics object as defined
            above.
        :returns: Hopefully never. If the method does return, the caller
            should create a new daemon instance and call this method
            again.
        """
        iteration = 0
        while True:
            iteration += 1
            subserver.logger.info(
                '%s sample daemon log line %s' % (self.name, iteration))
            stats.set('last_run', time())
            stats.set('iterations', iteration)
            sleep(self.interval)

    @classmethod
    def parse_conf(cls, name, conf):
        """Translates the overall server configuration.

        The conf is translated into a daemon-specific configuration dict
        suitable for passing as ``parsed_conf`` in the
        :py:class:`DaemonSample` constructor.

        See the overall docs of :py:mod:`brim.daemon_sample` for
        configuration options.

        :param name: The name of the daemon, indicates the daemon's
            section in the overall configuration for the server.
        :param conf: The :py:class:`brim.conf.Conf` instance
            representing the overall configuration of the server.
        :returns: A dict suitable for passing as ``parsed_conf`` in the
            :py:class:`DaemonSample` constructor.
        """
        return {'interval': conf.get_int(name, 'interval', 60)}

    @classmethod
    def stats_conf(cls, name, parsed_conf):
        """Returns a list of (stat_name, stat_type) pairs.

        These pairs specify the stat variables this daemon wants
        established in the ``stats`` instance passed to
        :py:meth:`__call__`.

        Stats are often retrieved by users and utilities through WSGI
        apps like :py:class:`brim.wsgi_stats.WSGIStats`.

        See the overall docs of :py:mod:`brim.daemon_sample` for what
        stats are defined.

        The available stat_types are:

        ======  ========================================================
        daemon  Indicates a daemon only stat. No overall stat will be
                reported.
        sum     Indicates an overall stat should be reported that is a
                sum of the stat from all daemons.
        min     Indicates an overall stat should be reported that is the
                smallest value of the stat from all daemons.
        max     Indicates an overall stat should be reported that is the
                largest value of the stat from all daemons.
        ======  ========================================================

        :param name: The name of the daemon, indicates the daemon's
            section in the overall configuration for the daemon server.
        :param parsed_conf: The result from :py:meth:`parse_conf`.
        :returns: A list of (stat_name, stat_type) pairs.
        """
        return [('iterations', 'daemon'), ('last_run', 'daemon')]


#encoding:utf8

from django.http import HttpResponse
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, Column, Integer, String
import json
from django.views.decorators.csrf import csrf_exempt
from sqlalchemy.orm import mapper
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
import settings
from download import Image
Base = declarative_base()
import db,urllib

class News(Base):
    # 表的名字:
    __tablename__ = 'app_news'

    # 表的结构:
    news_id = Column(Integer,primary_key=True)
    news_title = Column('news_title',String,nullable=True)
    news_info = Column('news_info',String,nullable=True)
    news_content = Column('news_content',String,nullable=True)
    news_img = Column('news_img',String,nullable=True)
    news_date = Column('news_date',String,nullable=True)
    news_source = Column('news_source',String,nullable=True)
    news_status = Column('news_status',String,nullable=True)
    news_url = Column('news_url',String,nullable=True)
    type_id = Column('type_id',String,nullable=True)

def addNews(request):
    news_id=request.GET.get('news_id')
    news_title=urllib.unquote(request.GET.get('news_title'))
    news_info=urllib.unquote(request.GET.get('news_info'))
    news_img=request.GET.get('news_img')
    news_date=request.GET.get('news_date')
    news_source=urllib.unquote(request.GET.get('news_source'))
    news_url=request.GET.get('news_url')
    type_id=request.GET.get('type_id')
    session=db.db_createSession()

    news = session.query(News).filter(News.news_id==news_id).all()
    if len(news)==0 and len(news_id)==8:

        newNews=News()
        newNews.news_id=news_id
        newNews.news_title=news_title
        newNews.news_info=news_info
        newNews.news_content=news_url
        newNews.news_img='{'+news_img+'}'
        newNews.news_date=news_date
        newNews.news_source=news_source
        newNews.news_url=news_url
        newNews.news_status=0
        newNews.type_id=type_id
        session.add(newNews)
        session.commit()
        session.close()
        response=HttpResponse('succeed')
        response.__setitem__('Access-Control-Allow-Origin','http://54.223.148.123:8070')
        return response
    else:
        response=HttpResponse('failed')
        response.__setitem__('Access-Control-Allow-Origin','http://54.223.148.123:8070')
        return response


#!/usr/bin/env python3
import os
import sys
import pathlib
import patoolib
import argparse

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[0m'
    UNDERLINE = '\033[4m'

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--directory', action='store',
            dest='root_dir', help='The directory to parse \
                    and zip all subdirectories', default='',
                    type=str)
    parser.add_argument('-o', '--output-directory', action='store',
            dest='output_dir', help='Where should the zipped files be stored')
    parser.add_argument('-z', '--zip-format', action='store', default='zip',
            dest='zip_format', help='The format to use for archiving')
    parser.add_argument('-v', '--verbosity', action='count', \
            help='Make the program talk more', dest='verbose', default=0)
    parser.add_argument('-c', '--checksum', action='store_true',
            dest='checksum', help='Should a checksum file be generated')
    parser.add_argument('-t', '--test', action='store_true', \
            default='store_false', dest='test')
    parser.set_defaults(root_dir = os.path.dirname(os.path.realpath(__file__)),
            output_dir = os.path.dirname(os.path.realpath(__file__)),
                verbosity=0, test=False)
    return parser.parse_args()

if __name__ == '__main__':
    args = parse_args()
    if args.verbose > 0:
        if args.test:
            print( bcolors.OKBLUE + ' ===> ' + 'running as ' + \
                    bcolors.WARNING + 'test' + bcolors.ENDC)
    if args.verbose > 2:
        print( bcolors.OKBLUE + ' ===> ' + bcolors.OKGREEN + \
                ' retrieving direcotries within: ' + \
                bcolors.ENDC  + ''.join(args.root_dir))
    dirs = os.listdir(args.root_dir)
    if args.verbose > 2:
        print(bcolors.OKBLUE + ' ===> ' + bcolors.OKGREEN + \
                'Directories found:\n\t' + bcolors.ENDC + \
                '\n\t'.join(dirs))
    for d in dirs:
        if args.verbose > 0:
            print(bcolors.OKBLUE + ' ====> ' + bcolors.ENDC + \
                    'creating file %s' % d)
        archive_out = os.path.join(args.output_dir, d) + '.' + args.zip_format
        if args.verbose > 1:
            print(bcolors.OKBLUE + ' ====>  ' + bcolors.ENDC + \
                    '  Creating archive %s' % archive_out)
        outpath = os.path.join(args.root_dir, d)
        if not args.test:
            if args.verbose > 0:
                print(bcolors.OKGREEN + ' ====> ' + bcolors.ENDC +  archive_out)
                print(bcolors.OKGREEN + ' ====> ' + bcolors.ENDC + outpath)
            patoolib.create_archive("%s" % archive_out, \
                    (outpath + '/'))


import socketserver
import json

class TcpServer(socketserver.BaseRequestHandler):
    def put(self,*args):
        """接收客户端文件"""
        cmd_data = args[0]
        filename = cmd_data['filename']
        filesize = cmd_data['size']

        # 保存文件
        print(cmd_data)
        print('save file')
        print(filename)
        print(filesize)
        f = open(filename, 'wb')
        self.request.send(b'200 ok')

        received_size = 0
        while True:
            if received_size < filesize:
                data = self.request.recv(1024)
                f.write(data)
                received_size += len(data)
            else:
                print('file [%s] has uploaded...' % filename)

                f.close()
                break

        pass

    def handle(self):
        while True:
            self.data = self.request.recv(1024).strip()
            print('{} wrote.'.format(self.client_address))
            print(self.data)
            if not self.data:
                break

            cmd_dic = json.loads(self.data.decode())
            action = cmd_dic['action']
            if hasattr(self,action):
                func = getattr(self,action)
                func(cmd_dic)
        pass

if __name__ == '__main__':
    host = ('localhost',9999)
    server = socketserver.ThreadingTCPServer(host,TcpServer)
    server.serve_forever()