"""
斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13,
特别指出：第0项是0，第1项是第一个1。
从第三项开始，每一项都等于前两项之和。
"""

# num = int(input("请输入你要获得的数列个数: "))

# n1 = 0
# n2 = 1

# counter = 2

# if num < 0:
#     print("输入值不合法")
# elif num == 1:
#     print(n1)
# else:
#     print("斐波那契数列:")
#     print(n1,",",n2,end=' , ')
#     while num > counter:
#         nth = n1+n2
#         print(nth,end=' , ')
#         n1 = n2
#         n2 = nth
#         counter+=1

"""
next 去解决阿姆斯特朗数
"""
import sys

num = int(input('input a num > 0 : '))

if num < 0:
    print("num cant < 0")

n = len(str(num))

list = list(str(num))

it = iter(list)
sum = 0
while True:
    try:
        sum+=int(next(it))**n
    except StopIteration as identifier:
        if num == sum:
            print("num %d is 阿姆斯特朗数"%num)
        else:
            print("num %d is not 阿姆斯特朗数"%num)
        sys.exit()


"""
This file contains code that makes creating a note possible using
file writing and reading feature of python.
"""

import os.path as PATH

def writeNewFile(name, text):
    newFile = open(name, "w")
    newFile.write(text + "\n")
    newFile.close()

def readFile(name):
    existingFile = open(name, "r")
    print(existingFile.read())
    existingFile.close()

def appendFile(name, text):
    existingFile = open(name, "a")
    existingFile.write(text + "\n")
    existingFile.close()

def writeLine(name, lineNumber, text):
    existingFile = open(name, "r")
    existingData = existingFile.readlines()

    existingData[int(lineNumber) - 1] = text + "\n"
    existingFile = open(name, "w")
    existingFile.writelines(existingData)
    existingFile.close()

# files = []

while True:
    filename = input("Enter the title of your note: ")
    if PATH.isfile(filename):
        userInput = input("Press r to read, n to overwrite, l to overwrite a line and a to append to file: ").upper()
        if userInput == "R":
            readFile(filename)
        elif userInput == "N":
            textContent = input("Enter text to be overwritten in your new file: ")
            writeNewFile(filename, textContent)
        elif userInput == "A":
            textContent = input("Enter text to be appended in your new file: ")
            appendFile(filename, textContent)
        elif userInput == "L":
            lineNum = input("What line do you wanna overwrite? ")
            lineContent = input("Enter text")
            writeLine(filename, lineNum, lineContent)
    else:
        textContent = input("Enter text to be written in your new file: ")
        writeNewFile(filename, textContent)

# readFile(input("What file do you wanna read? "))


import sys
import os
from utils.database_util import DatabaseUtil
import psutil

class ProcessIdUtil():
    def __init__(self, pid_directory, id, module_name, table_name, logger):
        self.pid_directory = pid_directory
        self.id = id
        self.module_name = module_name.replace(' ', '_').lower()
        self.table_name = table_name
        self.logger = logger
        self.conn = DatabaseUtil(os.environ.get("DB_CONN"), os.environ.get("DB_USER"), os.environ.get("DB_PASSWORD"), os.environ.get("DB_NAME"), self.logger)

    def create_directory(self):
        if not os.path.exists(os.path.join(os.getcwd(), self.pid_directory)):
            os.mkdir(os.path.join(os.getcwd(), self.pid_directory))
            print(self.pid_directory, 'created.')

    def create_pid(self):
        try:
            with open(os.path.join(os.getcwd(), self.pid_directory, str(self.module_name) + '.pid'), 'w') as file:
                file.write(str(os.getpid()))
        except Exception as err:
            raise ValueError(
                "Error encountered in creating PID: %s" % (err))

    def read_pid(self):
        try:
            f = open(os.path.join(os.getcwd(), self.pid_directory, str(self.module_name) + '.pid'), 'r')
            contents = f.read()
            f.close()
            return contents
        except FileNotFoundError:
            return False

    def delete_pid(self):
        try:
            os.remove(os.path.join(os.getcwd(), self.pid_directory, str(self.module_name) +'.pid'))
        except Exception as err:
            raise ValueError(
                "Error encountered in deleting PID: %s" % (err))

    def save_pid(self, pid=None):
        try:
            if pid:
                query_string = 'UPDATE {0} SET pid = {1} WHERE id = {2}'.format(self.table_name, pid, self.id)
            else:
                query_string = 'UPDATE {0} SET pid = {1} WHERE id = {2}'.format(self.table_name, os.getpid(), self.id)
            self.conn.insert_query(query_string)
        except Exception as err:
            raise ValueError(
                "Error encountered in creating PID: %s" % (err))

    def get_pid(self):
        try:
            query_string = 'SELECT pid FROM {0} WHERE id = {1}'.format(self.table_name, self.id)
            pid = self.conn.select_query(query_string)
            return pid[0]['pid']
        except Exception as err:
            raise ValueError(
                "Error encountered in getting PID: %s" % (err))

    def is_pid_running(self, pid):
        # services = ['worker.exe', 'aggregate.exe','visionapi.exe']
        services = ['worker.py', 'aggregate.py', 'VisionAPI.py', 'poller.py']
        # check if pid exists
        if psutil.pid_exists(pid):
            process = psutil.Process(pid)
            if process.name() == 'python.exe' and (process.cmdline()[1] and process.cmdline()[1] in services):
                return True

        # if pid does not exist, check if command exists
        for process in psutil.process_iter():
            try:
                if len(process.cmdline()) == 3:
                    if process.name() == 'python.exe' and (process.cmdline()[1] and process.cmdline()[1] in services) and process.cmdline()[2] == self.id:
                        if process.pid != os.getpid():
                            self.save_pid(process.pid)
                            return True
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                pass

        return False

    def is_process_running(self):
        db_pid = self.get_pid()
        db_pid_running = self.is_pid_running(db_pid)

        if self.read_pid():
            file_pid = int(self.read_pid())
            file_pid_running = self.is_pid_running(file_pid)

            if file_pid_running and db_pid_running:
                return True
        else:
            if db_pid_running:
                return True

        return False

    def is_process_running_without_db(self):

        if self.read_pid():
            file_pid = int(self.read_pid())
            file_pid_running = self.is_pid_running(file_pid)
            if file_pid_running:
                return True
        return False


#!/usr/bin/env python
from pathlib import Path

import numpy as np

import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
import pickle

from scipy.cluster.hierarchy import linkage
import Modules.utils as utils

def metaplot_over_indices(values,
                          indices,
                          window_half_size,
                          label='values',
                          compare=None,
                          anchor='center',
                          plot='simple',
                          res_dir=None,
                          data='unknown_data',
                          chr='unknown_chr',
                          vmin=None,
                          vmax=None,
                          robust=False):
    if anchor == 'center':
        window = np.arange(-window_half_size, window_half_size + 1)
    elif anchor == 'start':
        window = np.arange(2*window_half_size + 1)
    elif anchor == 'end':
        window = np.arange(-2*window_half_size, 1)
    else:
        raise NameError("Invalid anchor")
    # broadcast column of indices and window line
    indices = np.expand_dims(indices, axis=1) + np.expand_dims(window, axis=0)
    # compute mean over original indices at each point of the window
    mean_values = np.mean(values[indices], axis=0)
    if compare:
        compare_values, compare_label = compare
        mean_compare = np.mean(compare_values[indices], axis=0)
    # Make desired plot
    prop_cycle = plt.rcParams['axes.prop_cycle']
    colors = prop_cycle.by_key()['color']
    if plot == 'simple':
        fig, ax = plt.subplots()
        ax.plot(window, mean_values, label=label, color=colors[1])
        handles, labels = ax.get_legend_handles_labels()
        if compare:
            ax2 = ax.twinx()
            ax2.plot(window, mean_compare, label=compare_label)
            handles2, labels2 = ax2.get_legend_handles_labels()
            handles += handles2
            labels += labels2
        ax.legend(handles, labels)
        return_values = tuple()
    elif plot == 'heatmap':
        corrs = utils.lineWiseCorrcoef(values[indices], mean_values)
        new_indices = indices[np.argsort(corrs)[::-1], :]
        fig, axs = plt.subplots(2, 2, sharex='col', figsize=(9, 11),
                                gridspec_kw={'width_ratios': [20, 1],
                                             'height_ratios': [6, 20]})
        # Average plot
        ax00 = axs[0, 0]
        ax00.plot(mean_values, label=label, color=colors[1])
        ax00.axvline(x=window_half_size, color='black', linestyle='--',
                     label='peak center')
        handles, labels = ax00.get_legend_handles_labels()
        if compare:
            ax2 = ax00.twinx()
            ax2.plot(mean_compare, label=compare_label)
            handles2, labels2 = ax2.get_legend_handles_labels()
            handles += handles2
            labels += labels2
        ax00.xaxis.set_tick_params(which='both', labelbottom=True)
        ax00.legend(handles, labels)
        # remove upper right ax
        axs[0, 1].remove()
        # Heatmap
        df = pd.DataFrame(values[new_indices], columns=window)
        sns.heatmap(df, center=0, ax=axs[1, 0], cbar_ax=axs[1, 1],
                    xticklabels=window_half_size, yticklabels=1000,
                    robust=robust, vmin=vmin, vmax=vmax)
        return_values = (corrs,)
    elif plot == 'clustermap':
        corr_matrix = np.corrcoef(values[indices])
        link_matrix = linkage(corr_matrix, method='ward')
        df = pd.DataFrame(values[indices], columns=window)
        clust = sns.clustermap(values[indices], center=0,
                               row_linkage=link_matrix, col_cluster=False,
                               xticklabels=window_half_size,
                               yticklabels=1000, robust=robust)
        return_values = (clust,)
    if res_dir:
        plt.savefig(Path(res_dir, f'metaplot_{data}_{plot}_{chr}_peaks.png'),
                    bbox_inches='tight')
    plt.show()
    plt.close()
    return return_values + (mean_values, window)

def add_legend(axes):
    handles, labels = [], []
    for ax in axes:
        handle, label = ax.get_legend_handles_labels()
        handles += handle
        labels += label
    return handles, labels

def binned_plot(values, ax, start, end, bins, **kwargs):
    bin_start = (start // bins) * bins + bins // 2
    bin_end = (end // bins) * bins + bins // 2
    ax.plot(
        np.arange(bin_start, bin_end, bins),
        values[start//bins:end//bins],
        **kwargs)

def compare_binned_plots(values_list, label_list, start, end, bins, **kwargs):
    prop_cycle = plt.rcParams['axes.prop_cycle']
    colors = prop_cycle.by_key()['color']
    axes = []
    for i, values in enumerate(values_list):
        if i == 0:
            axes.append(plt.subplot())
        else:
            axes.append(axes[i-1].twinx())
        binned_plot(values, axes[i], start, end, bins,
                    label=label_list[i], color=colors[i], **kwargs)
    handles, labels = add_legend(axes)
    leg = plt.legend(handles, labels, fontsize=16)
    for line in leg.get_lines():
        line.set_linewidth(2)
    return axes

def order_2mer_df(df):
    df = df.sort_index().copy()
    kmer_order = [
        ('A', 'C'), ('G', 'T'), ('C', 'A'), ('T', 'G'),
        ('A', 'G'), ('C', 'T'), ('G', 'A'), ('T', 'C'),
        ('A', 'A'), ('T', 'T'), ('A', 'T'), ('T', 'A'),
        ('C', 'C'), ('G', 'G'), ('C', 'G'), ('G', 'C')]
    return df.loc[kmer_order]

def plot_2mer_df(df, columns=None, group=None):
    df = order_2mer_df(df)
    df['SW'] = ['alt']*8 + ['same']*8
    if group is None:
        fig, axes = plt.subplots(1, 1, figsize=(20, 5), facecolor='w')
        df.plot(kind='bar', y=columns, ax=axes)
    elif group == 'SW':
        fig, axes = plt.subplots(1, 2,
                                 sharey='row',
                                 figsize=(20, 5),
                                 facecolor='w')
        for (key, grp), ax in zip(df.groupby('SW'), axes.flatten()):
            grp.plot(kind='bar',
                     y=columns,
                     ax=ax,
                     title=key)
    return fig, axes

def save_fig_and_values(fig, filename, format='png'):
    if isinstance(format, str):
        imgfile = utils.safe_filename(str(filename) + f'.{format}')
        fig.savefig(imgfile, bbox_inches='tight')
    else:
        for form in format:
            imgfile = utils.safe_filename(str(filename) + f'.{form}')
            fig.savefig(imgfile, bbox_inches='tight')
    picklefile = utils.safe_filename(str(filename) + '.pickle')
    with open(picklefile, 'wb') as f:
        pickle.dump(fig, f)


# This file plots the difference between \sin{x} and x to analyze small angle approximation.
import math
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,math.pi/2,100)
y_x = x
y_sin = np.sin(x)

plt.figure()
plt.subplot(1,2,1)
plt.xlabel("theta in degrees")
plt.ylabel("Y values")
plt.plot(x*180/math.pi,y_x)
plt.plot(x*180/math.pi,y_sin)
plt.xticks(np.arange(0,90,10))

plt.subplot(1,2,2)
plt.xlabel("theta in degrees")
plt.ylabel("Diff in Y values")
plt.plot(x*180/math.pi,y_x-y_sin)
plt.xticks(np.arange(0,90,10))
plt.yticks(np.arange(0,0.6,0.05))
plt.tight_layout()
plt.savefig("SmallAngle.png")
plt.show()


#! /usr/bin/python

import os
import sys
import re
import time
import usb.core
import usb.util
import shutil
from datetime import datetime

VENDOR = 0x2367
PRODUCT = 0x0002
USBID_OP1 = "*Teenage_OP-1*"
MOUNT_DIR = "/media/op1"
BACKUP_DIR_FORMAT = "%Y-%m-%d (%H%M%S)"
HOME = "/op1go"
BACKUPS_DIR = os.path.join(HOME, "backups")

# OP-1 connection
def ensure_connection():
  if not is_connected():
    print("Connect your OP-1 and put it in DISK mode (Shift+COM -> 3)...")
    wait_for_connection()

def is_connected():
  return usb.core.find(idVendor=VENDOR, idProduct=PRODUCT) is not None

def wait_for_connection():
  try:
    while True:
      time.sleep(1)
      if is_connected():
        break
  except KeyboardInterrupt:
    sys.exit(0)

# mounting
def mountdevice(source, target, fs, options=''):
  ret = os.system('mount {} {}'.format(source, target))
  if ret not in (0, 8192):
    raise RuntimeError("Error mounting {} on {}: {}".format(source, target, ret))

def unmountdevice(target):
  ret = os.system('umount {}'.format(target))
  if ret != 0:
    raise RuntimeError("Error unmounting {}: {}".format(target, ret))

def getmountpath():
  o = os.popen('readlink -f /dev/disk/by-id/' + USBID_OP1).read()
  if USBID_OP1 in o:
    raise RuntimeError("Error getting OP-1 mount path: {}".format(o))
  else:
    return o.rstrip()

# copying
def forcedir(path):
  if not os.path.isdir(path):
    os.makedirs(path)

def get_visible_folders(d):
  return list(filter(lambda x: os.path.isdir(os.path.join(d, x)), get_visible_children(d)))

def get_visible_children(d):
  return list(filter(lambda x: x[0] != '.', os.listdir(d)))

def copytree(src, dst, symlinks=False, ignore=None):
  for item in os.listdir(src):
    s = os.path.join(src, item)
    d = os.path.join(dst, item)
    if os.path.isdir(s):
      shutil.copytree(s, d, symlinks, ignore)
    else:
      shutil.copy2(s, d)

def backup_files(source, destination):
  dstroot = os.path.join(destination, datetime.now().strftime(BACKUP_DIR_FORMAT))
  forcedir(dstroot)
  for node in get_visible_children(source):
    src = os.path.join(source, node)
    dst = os.path.join(dstroot, node)
    print(" . from: {} to {}".format(src, dst))
    forcedir(dst)
    copytree(src, dst)
    blink(1)

# misc
def blink(count):
  os.system("echo none | sudo tee /sys/class/leds/led0/trigger >/dev/null 2>&1")
  for i in range(0,count):
    os.system("echo 0 | sudo tee /sys/class/leds/led0/brightness >/dev/null 2>&1")
    time.sleep(0.15)
    os.system("echo 1 | sudo tee /sys/class/leds/led0/brightness >/dev/null 2>&1")
    time.sleep(0.05)

def blinklong():
  os.system("echo none | sudo tee /sys/class/leds/led0/trigger >/dev/null 2>&1")
  os.system("echo 0 | sudo tee /sys/class/leds/led0/brightness >/dev/null 2>&1")
  time.sleep(1)
  os.system("echo 1 | sudo tee /sys/class/leds/led0/brightness >/dev/null 2>&1")

def blinkyay():
  os.system("echo none | sudo tee /sys/class/leds/led0/trigger >/dev/null 2>&1")
  for i in range(0,1000000):
    os.system("echo 0 | sudo tee /sys/class/leds/led0/brightness >/dev/null 2>&1")
    time.sleep(0.01)
    os.system("echo 1 | sudo tee /sys/class/leds/led0/brightness >/dev/null 2>&1")
    time.sleep(0.01)

## Main ##

# create mount point and local backup folders
blinklong()
forcedir(BACKUPS_DIR)
forcedir(MOUNT_DIR)

# wait until OP-1 is connected
print(" > Starting - waiting for OP-1 to connect")
ensure_connection()
time.sleep(5)

# mount OP-1
mountpath = getmountpath()
print(" > OP-1 device path: %s" % mountpath)
mountdevice(mountpath, MOUNT_DIR, 'ext4', 'rw')
print(" > Device mounted at %s" % MOUNT_DIR)

# copy files to local storage
blink(5)
print(" > Copying files...")
backup_files(MOUNT_DIR, BACKUPS_DIR)

# unmount OP-1
print(" > Unmounting OP-1")
unmountdevice(MOUNT_DIR)
print(" > Done.")
blinkyay()


import cobra
import sys

#Read the model in
model_file_path = str(model_file_path)
toycon = cobra.io.read_sbml_model(model_file_path)
#Get objective and assert it is in the model
objective = str(objective)
try:
    toycon.reactions.get_by_id(objective)
except KeyError:
    print("The selected objective reaction is not in the model!")
#Change objective
toycon.objective = objective
#Resetting the model case
solution = toycon.optimize()
flux = solution.objective_value
fluxes = solution.fluxes.round(2).to_dict()


# # Задана последовательность натуральных чисел, завершающаяся числом 0.
# # Требуется определить значение второго по величине элемента в этой последовательности

list = [1, 7, 9, 0]
max1 = list[0]
max2 = list[1]

for i in range(len(list)):
    if (list[i] > max1):
        max1 = list[i]
        print(max1)
    if (list[i] > max2 and list[i] < max1):
        max2 = list[i]
        print(max2)
print(max2)

list = [1, 7, 9, 0]
max1=max(list)
list.remove(max1)
max2=max(list)
print(max2)


import os,sys,time,random
print("")
print("")
color = ["\033[1;31m","\033[1;32m"]
m = random.choice(color)+"Bem vindo THBD \nAtualizando pacote de dados...\n\n\n\n\n\n\nConcluido mãos a obra!!\n"
for msg in m:
    sys.stdout.write(msg)
    sys.stdout.flush()
    time.sleep(0.04)
print("")


import argparse
import multiprocessing
import sys
import time
import re
from multiprocessing import Queue, Process, Event
from queue import Empty

import pygame.sprite

from Engine.Level import Level

# def connect_to_reomte_game(remote_queues, player_queue, kill_signal):
#     while not kill_signal.is_set():
#         try:
#             player = player_queue.get_nowait()
#             for remote_queue in remote_queues:
#                 remote_queue.put(player)
#         except Empty:
#             pass
#     print("Connection Ending")

parser = argparse.ArgumentParser()
parser.add_argument("--server", help="Set the game up in server mode, "
                                     "use this if you have forwarded a port to accept connections",
                    action="store_true", default=False)
parser.add_argument("--host-ip", help="The ip address on which the connections will be made. "
                                      "For server, use the localhost, for the client use the public ip of the server.",
                    default='localhost', )
parser.add_argument("--fps", help="The target framerate to run at",
                    default=30, type=int)
parser.add_argument("--char", help="The character to play as",
                    default="Batman", type=str)
parser.add_argument("--port", help="The ip address on which the connections will be made. "
                                      "For server, use the localhost, for the client use the public ip of the server.",
                    default=33012, type=int)
parser.add_argument("-m", "--magnification", help="The level of magnifcation to use for rendering the game",
                    default=1.5, type=int)

def main():

    args = parser.parse_args()
    level = Level(
        map_name="test_map_new_format",
        player_character_name=args.char,
        player_start_pos=(20 + 32 if args.server else 64, 80),
        window_size=(800, 400),
        magnification=args.magnification,
        server=args.server,
        host=args.host_ip,
        port=args.port,
    )
    level.run(framerate=args.fps)

    #   EXANPLE OF 4 WAY MULTIPLAYER, NOT READY TO DELETE JUST YET
    # multiprocessing.set_start_method("spawn")
    # pygame.init()
    # WINDOW_SIZE = (600, 400)
    #
    # kill_signal = Event()
    # if args.server:
    #     chars = {0: "Treeman", 1: "Batman", }
    # else:
    #     chars = {0: "Batman", 1: "Treeman", }
    #
    # char_queues = {player_idx: [Queue() for c in chars if c is not player_idx] for player_idx, player_name in chars.items()}
    #
    # remote_queues = {}
    # for player_idx in char_queues.keys():
    #     remote_queues[player_idx] = []
    #     for remote_idx, queues in char_queues.items():
    #         if remote_idx != player_idx:
    #             remote_queues[player_idx].append(queues[player_idx%len(chars)-1])
    #
    # levels = [Level(
    #     map_name="test_map_new_format",
    #     player_character_name=player_name,
    #     player_start_pos=(20 + player_idx * 32, 80),
    #     npc_names=[npc_name for npc_idx, npc_name in chars.items() if player_name != npc_name],
    #     npc_start_positions=[(20 + npc_idx * 320, 80) for npc_idx, npc_name in chars.items() if player_name != npc_name],
    #     window_size=WINDOW_SIZE,
    #     player_state_queue=char_queues[player_idx],
    #     npc_state_queues=remote_queues[player_idx],
    #     server=args.server,
    # ) for player_idx, player_name in chars.items()]
    #
    # processes = [Process(target=level.run, args=(kill_signal, 60)) for level in levels]
    #
    # for proc in processes:
    #     proc.start()
    #
    # while not kill_signal.is_set():
    #     print("Tick", kill_signal.is_set())
    #     time.sleep(1)

if __name__=="__main__":
    main()


def bubble_sort(arr: list, size: int) -> None:
    for i in range(0, size - 1):
        for j in range(0, size - 1 - i):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

def print_array(arr: list, size: int) -> None:
    for i in range(0, size):
        print(arr[i], end=' ')
    print()

arr = list(map(int, input().split()))
size = len(arr)

print_array(arr, size)
bubble_sort(arr, size)
print_array(arr, size)

'''
Input:
5 4 3 2 1

Output:
5 4 3 2 1
1 2 3 4 5
'''


import sudoku.do as do

RULE_ONE_VAL_LEFT = "RULE_ONE_VAL_LEFT"
RESULT_ONE_VAL_LEFT = "RESULT_ONE_VAL_LEFT"
RULE_EXCLUDED_VAL = "RULE_RULE_EXCLUDED_VAL"
RESULT_EXCLUDED_VAL = "RESULT_EXCLUDED_VAL"
RULE_BACKTRACK = "RULE_BACKTRACK"
RESULT_BACKTRACK = "RESULT_BACKTRACK"

def ruleOneValLeft(recDepth, state):
    """for for every cell C
       if: only one value is possible for C
       then: propagate this to C' neighborhood
       if: some cell could be finalized,
       then: call the rule recursively

       return the updated state, after the rule has finished
    """
    ruleOneValLeftId = 'O'
    do.logStartRule(RULE_ONE_VAL_LEFT, recDepth, ruleOneValLeftId, state)
    finalizedCellsBefore = state.getNumberFinalized()
    state = ruleOneValLeftSingleStep(recDepth, state)
    finalizedCellsAfter = state.getNumberFinalized()
    if finalizedCellsBefore != finalizedCellsAfter and finalizedCellsAfter < 81:
        state = ruleOneValLeft(recDepth + 1, state)
    do.logEndRule(RULE_ONE_VAL_LEFT, recDepth, ruleOneValLeftId, '', state)
    return state

def ruleOneValLeftSingleStep(recDepth, state):
    """for for every cell C
       if: only one value is possible for C
       then: propagate this to C' neighborhood
       return the updated state, after the rule has finished
    """
    ruleOneValLeftId = 'O'
    for cell in state.getCells():
        if not cell.isFinalValueSet() and cell.isOnlyOneValLeft():
            val = cell.getTheFinalVal()
            state.setFinalCellVal(cell, val, ruleOneValLeftId)
            do.logI(RESULT_ONE_VAL_LEFT, recDepth, f'{ruleOneValLeftId}: cell {cell.toXY()} = {val}')
    return state

def ruleExcludedVal(recDepth, state):
    """check for every cell C
       if: C's neighbarhood cannot hold a value V, which is possible for C
       then: V must be the correct value for C. Propagate this to C's neighbarhood if: some cell could be finalized,
       then: call the rule recursively

       return the updated state, after the rule has finished
    """
    ruleExcludedValId = 'E'
    do.logStartRule(RULE_EXCLUDED_VAL, recDepth, ruleExcludedValId, state)
    atLeastOneSuccess = False
    for cell in state.getCells():
        if not cell.isFinalValueSet():
            for val in cell.getPossibleVals():
                success = state.valImpossibleInAtLeastOneNeighborhood(val, cell)
                if success:
                    atLeastOneSuccess = True
                    state.setFinalCellVal(cell, val, ruleExcludedValId)
                    do.logI(RESULT_EXCLUDED_VAL, recDepth, f'{ruleExcludedValId}: cell {cell.toXY()} = {val}')
                    break
    state.valid()
    if atLeastOneSuccess and state.getNumberFinalized() < 81:
        state = ruleOneValLeft(recDepth + 1, state)
        state = ruleExcludedVal(recDepth + 1, state)
    do.logEndRule(RULE_EXCLUDED_VAL, recDepth, ruleExcludedValId, '', state)
    return state

def ruleBacktracker(recDepth, state, visitedCells):
    """check for every cell C, by stepping through all possible values V
       try: to solve the sudoko assumg that C's value is V
       success: done
       fail: backtrack to try the next possible value of C

       return the updated state, after the rule has finished
    """
    ruleBacktrackerId = 'B'
    do.logStartRule(RULE_BACKTRACK, recDepth, ruleBacktrackerId, state)
    while True:
        cell = pickCell(state, visitedCells)
        if cell is None:
            break
        idx = cell.getIdx()
        for val in cell.getPossibleVals():
            stateForTrial = state.clone()
            test = stateForTrial.getCells()[idx]
            try:
                do.logI(RESULT_BACKTRACK, recDepth, f'{ruleBacktrackerId}: TRY  cell {test} = {val}')
                stateForTrial.setFinalCellVal(test, val, ruleBacktrackerId)
                stateForTrial = ruleOneValLeft(recDepth + 1, stateForTrial)
                stateForTrial = ruleExcludedVal(recDepth + 1, stateForTrial)
                stateForTrial.valid()
                do.logI(RESULT_BACKTRACK, recDepth, f'{ruleBacktrackerId}: SUCC cell {test.toXY()} = {val}')
                if stateForTrial.getNumberFinalized() < 81:
                    stateForTrial = ruleBacktracker(recDepth + 1, stateForTrial, list(visitedCells))
                do.logEndRule(RULE_BACKTRACK, recDepth, ruleBacktrackerId, " FINAL SUCCESS", stateForTrial)
                return stateForTrial
            except RuntimeError:
                do.logI(RESULT_BACKTRACK, recDepth, f'{ruleBacktrackerId}: FAIL cell {cell} = {val}')
                state.incrSteps(stateForTrial.getSteps())
        do.logEndRule(RULE_BACKTRACK, recDepth, ruleBacktrackerId, f' NO SOLUTION for {cell.toXY()}', state)
        raise RuntimeError(f'{ruleBacktrackerId}: no solution (1)')
    do.logEndRule(RULE_BACKTRACK, recDepth, ruleBacktrackerId, f' NO SOLUTION AT ALL', state)
    raise RuntimeError(f'{ruleBacktrackerId}: no solution (2)')

def pickCell(state, visitedCells):
    """pick the cell with the least number of possible values, but only, if not already visited :-) and if not finalized"""
    minValsCell = None
    for cell in state.getCells():
        if not cell.getIdx() in visitedCells:
            if not cell.isFinalValueSet():
                minValsCell = cell
                break
    # all have been visited. Unsolvable sudoku (???)
    if minValsCell is None:
        return None
    # find the cell with the least number of possible values
    minValsSize = len(minValsCell.getPossibleVals())
    if minValsSize > 2:
        for cell in state.getCells():
            if not cell.getIdx() in visitedCells:
                if not cell.isFinalValueSet():
                    size = len(cell.getPossibleVals())
                    if size < minValsSize:
                        minValsSize = size
                        minValsCell = cell
                        if minValsSize <= 2:
                            break
    # mark it visited and return it
    visitedCells.append(minValsCell.getIdx())
    return minValsCell


#!/usr/bin/env python3

import numpy as np
from cw3q2.iiwa14DynBase import Iiwa14DynamicBase

class Iiwa14DynamicRef(Iiwa14DynamicBase):
    def __init__(self):
        super(Iiwa14DynamicRef, self).__init__(tf_suffix='ref')

    def forward_kinematics(self, joints_readings, up_to_joint=7):
        """This function solve forward kinematics by multiplying frame transformation up until a specified
        joint. Reference Lecture 9 slide 13.
        Args:
            joints_readings (list): the state of the robot joints.
            up_to_joint (int, optional): Specify up to what frame you want to compute forward kinematics.
                Defaults to 7.
        Returns:
            np.ndarray The output is a numpy 4*4 matrix describing the transformation from the 'iiwa_link_0' frame to
            the selected joint frame.
        """

        assert isinstance(joints_readings, list), "joint readings of type " + str(type(joints_readings))
        assert isinstance(up_to_joint, int)

        T = np.identity(4)
        # iiwa base offset
        T[2, 3] = 0.1575

        # 1. Recall the order from lectures. T_rot_z * T_trans * T_rot_x * T_rot_y. You are given the location of each
        # joint with translation_vec, X_alpha, Y_alpha, Z_alpha. Also available are function T_rotationX, T_rotation_Y,
        # T_rotation_Z, T_translation for rotation and translation matrices.
        # 2. Use a for loop to compute the final transformation.
        for i in range(0, up_to_joint):
            T = T.dot(self.T_rotationZ(joints_readings[i]))
            T = T.dot(self.T_translation(self.translation_vec[i, :]))
            T = T.dot(self.T_rotationX(self.X_alpha[i]))
            T = T.dot(self.T_rotationY(self.Y_alpha[i]))

        assert isinstance(T, np.ndarray), "Output wasn't of type ndarray"
        assert T.shape == (4, 4), "Output had wrong dimensions"

        return T

    def get_jacobian_centre_of_mass(self, joint_readings, up_to_joint=7):
        """Given the joint values of the robot, compute the Jacobian matrix at the centre of mass of the link.
        Reference - Lecture 9 slide 14.

        Args:
            joint_readings (list): the state of the robot joints.
            up_to_joint (int, optional): Specify up to what frame you want to compute the Jacobian.
            Defaults to 7.

        Returns:
            jacobian (numpy.ndarray): The output is a numpy 6*7 matrix describing the Jacobian matrix defining at the
            centre of mass of a link.
        """
        assert isinstance(joint_readings, list)
        assert len(joint_readings) == 7
        # 1. Compute the forward kinematics (T matrix) for all the joints.
        # 2. Compute forward kinematics at centre of mass (T_cm) for all the joints.
        # 3. From the computed forward kinematic and forward kinematic at CoM matrices,
        # extract z, z_cm (z axis of the rotation part of T, T_cm) and o, o_cm (translation part of T, T_cm) for all links.
        # 4. Based on the computed o, o_cm, z, z_cm, fill J_p and J_o matrices up until joint 'up_to_joint'. Apply equations at slide 15, Lecture 9.
        # 5. Fill the remaining part with zeroes and return the Jacobian at CoM.

        # Your code starts here ----------------------------

        # intialise the jacobian
        jacobian = np.zeros((6,7))

        # calculate the p_li
        P_li = self.forward_kinematics_centre_of_mass(joint_readings, up_to_joint)[0:3,3]

        for i in range(1,up_to_joint+1):
                jacobian[0:3,i-1] = np.cross(self.forward_kinematics(joint_readings,i-1)[0:3,2], (P_li-self.forward_kinematics(joint_readings,i-1)[0:3,3]))
                jacobian[3:,i-1] = self.forward_kinematics(joint_readings,i-1)[0:3,2].copy()

        # Your code ends here ------------------------------

        assert jacobian.shape == (6, 7)
        return jacobian

    def forward_kinematics_centre_of_mass(self, joints_readings, up_to_joint=7):
        """This function computes the forward kinematics up to the centre of mass for the given joint frame.
        Reference - Lecture 9 slide 14.
        Args:
            joints_readings (list): the state of the robot joints.
            up_to_joint (int, optional): Specify up to what frame you want to compute forward kinematicks.
                Defaults to 5.
        Returns:
            np.ndarray: A 4x4 homogeneous transformation matrix describing the pose of frame_{up_to_joint} for the
            centre of mass w.r.t the base of the robot.
        """
        T= np.identity(4)
        T[2, 3] = 0.1575

        T = self.forward_kinematics(joints_readings, up_to_joint-1)
        T = T.dot(self.T_rotationZ(joints_readings[up_to_joint-1]))
        T = T.dot(self.T_translation(self.link_cm[up_to_joint-1, :]))

        return T

    def get_B(self, joint_readings):
        """Given the joint positions of the robot, compute inertia matrix B.
        Args:
            joint_readings (list): The positions of the robot joints.

        Returns:
            B (numpy.ndarray): The output is a numpy 7*7 matrix describing the inertia matrix B.
        """
        B = np.zeros((7, 7))
        # Some useful steps:
        # 1. Compute the jacobian at the centre of mass from second joint to last joint
        # 2. Compute forward kinematics at centre of mass from second to last joint
        # 3. Extract the J_p and J_o matrices from the Jacobian centre of mass matrices
        # 4. Calculate the inertia tensor using the rotation part of the FK centre of masses you have calculated
        # 5. Apply the the equation from slide 16 lecture 9
	    # Your code starts here ------------------------------

        for _ in range(1,len(joint_readings)+1):
            # get the jacobian of the link
            jacobian = self.get_jacobian_centre_of_mass(joint_readings,_)
            j_p = jacobian[0:3,:]
            j_o = jacobian[3:,:]

            # define the mass of the link
            m = self.mass[_-1]

            # define the rotation matrix from the frame G_i to the base frame
            R = self.forward_kinematics_centre_of_mass(joint_readings,up_to_joint=_)[0:3,0:3]

            # define the inertia tensor for the parallel frame
            I_parallel = np.diag(self.Ixyz[_-1])

            B = B + (m*(j_p.T @ j_p) + j_o.T @ (R @ I_parallel @ R.T) @ j_o)

        # Your code ends here ------------------------------

        return B

    def get_C_times_qdot(self, joint_readings, joint_velocities):
        """Given the joint positions and velocities of the robot, compute Coriolis terms C.
        Args:
            joint_readings (list): The positions of the robot joints.
            joint_velocities (list): The velocities of the robot joints.

        Returns:
            C (numpy.ndarray): The output is a numpy 7*1 matrix describing the Coriolis terms C times joint velocities.
        """
        assert isinstance(joint_readings, list)
        assert len(joint_readings) == 7
        assert isinstance(joint_velocities, list)
        assert len(joint_velocities) == 7
        # Some useful steps:
        # 1. Create a h_ijk matrix (a matrix containing the Christoffel symbols) and a C matrix.
        # 2. Compute the derivative of B components for the given configuration w.r.t. joint values q. Apply equations at slide 19, Lecture 9.
        # 3. Based on the previously obtained values, fill h_ijk. Apply equations at slide 19, Lecture 9.
        # 4. Based on h_ijk, fill C. Apply equations at slide 19, Lecture 9.

        # Your code starts here ------------------------------

        # define the delta
        delta = 10e-8

        n = len(joint_readings)

        # initalise the h_ijk and C
        h_ijk = np.zeros((n,n,n))
        C = np.zeros((n,n))

        for k in range(n):
            delta_q_k = np.zeros(n).tolist()
            delta_q_k[k] = delta
            for j in range(n):
                for i in range(n):
                    delta_q_i = np.zeros(n).tolist()
                    delta_q_i[i] = delta
                    h_1 = (self.get_B((np.array(joint_readings)+np.array(delta_q_k)).tolist())[i,j] - self.get_B(joint_readings)[i,j])/delta
                    h_2 = 0.5 * (self.get_B((np.array(joint_readings)+np.array(delta_q_i)).tolist())[j,k] - self.get_B(joint_readings)[j,k])/delta
                    h_ijk[i,j,k] = h_1 - h_2

        for k in range(n):
            C = C + h_ijk[:,:,k] * joint_velocities[k]

        C = C @ joint_velocities

        # Your code ends here ------------------------------

        assert isinstance(C, np.ndarray)
        assert C.shape == (7,)
        return C

    def get_G(self, joint_readings):
        """Given the joint positions of the robot, compute the gravity matrix g.
        Args:
            joint_readings (list): The positions of the robot joints.

        Returns:
            g (numpy.ndarray): The output is a numpy 7*1 numpy array describing the gravity matrix g.
        """
        assert isinstance(joint_readings, list)
        assert len(joint_readings) == 7
        # Some useful steps:
        # 1. Compute the Jacobian at CoM for all joints.
        # 2. Use the computed J_cm to fill the G matrix. This method is actually different from what seen in the lectures.
        # 3. Alternatvely, you can compute the P matrix and use it to fill the G matrix based on formulas presented at slides 17 and 22, Lecture 9.
        # Your code starts here ------------------------------

        # initialise the delta
        delta = 10e-9

        n = len(joint_readings)

        # intialise the g
        g = np.zeros(7)

        # initialise the g0^T
        g_0T = np.array([[0,0,-self.g]])

        for i in range(n):
            # calculate P(q+delta)
            p_plus_delta = 0

            q_plus_delta = np.zeros(7).tolist()
            q_plus_delta[i] = delta
            q_plus_delta = (np.array(joint_readings) + np.array(q_plus_delta)).tolist()

            g_i = 0
            for j in range(n):
                p_plus_delta = - (self.mass[j] * g_0T @ self.forward_kinematics_centre_of_mass(q_plus_delta,j+1)[0:3,-1])
                p_q = - (self.mass[j] * g_0T @ self.forward_kinematics_centre_of_mass(joint_readings,j+1)[0:3,-1])
                temp = (p_plus_delta - p_q) / delta
                g_i = g_i + temp

            g[i] = g_i

        # Your code ends here ------------------------------

        assert isinstance(g, np.ndarray)
        assert g.shape == (7,)
        return g


import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"

from utils import get_data, compute_metrics, tokenize_and_align_labels
from settings import all_labels, data_path, reduced
import wandb

from sklearn.model_selection import train_test_split
from transformers import AutoTokenizer, RobertaTokenizerFast, DebertaTokenizerFast
from transformers import DataCollatorForTokenClassification, AutoModelForTokenClassification
from transformers import TrainingArguments, Trainer

import pandas as pd
import torch

MODEL_CHECKPOINTS = ["roberta-base"]
data = pd.read_json(data_path, lines=True)
tags, texts = get_data(data)

id2label = {i: label for i, label in enumerate(all_labels)}
label2id = {v: k for k, v in id2label.items()}

for checkpoint in MODEL_CHECKPOINTS:
    print(f"Training {checkpoint}")
    torch.cuda.empty_cache()

    tokenizer = RobertaTokenizerFast.from_pretrained(checkpoint, add_prefix_space=True)

    dataset = [tokenize_and_align_labels(tokenizer, tokens, labels) for tokens, labels in zip(texts, tags)]
    train, test = train_test_split(dataset, test_size=0.2, random_state=42)
    data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)

    model = AutoModelForTokenClassification.from_pretrained(
        checkpoint,
        id2label=id2label,
        label2id=label2id,
    )

    args = TrainingArguments(
        output_dir=f"./output/hub/{checkpoint}{'_reduced' if reduced else ''}",
        evaluation_strategy="epoch",
        save_strategy="no",
        learning_rate=2e-5,
        num_train_epochs=5,
        logging_steps=10,
        weight_decay=0.01,
        report_to="wandb",
        push_to_hub=True,
        push_to_hub_model_id=f"roberta-base{'-reduced' if reduced else ''}",
        run_name=f"{checkpoint}{'_reduced' if reduced else ''}",
    )

    trainer = Trainer(
        model=model,
        args=args,
        train_dataset=train,
        eval_dataset=test,
        data_collator=data_collator,
        compute_metrics=compute_metrics,
        tokenizer=tokenizer,
    )
    trainer.train()
    trainer.save_model()
    wandb.finish()


import os
import sys
import requests
import jwt
import datetime
from dotenv import load_dotenv
from time import time
# load API key and secret from .bashrc
load_dotenv()

API_KEY = os.getenv("Zoom_KEY")
API_SEC = os.getenv("Zoom_SECRET")

# get the arguments from the command line
meeting_id = sys.argv[1]
email = sys.argv[2]
first_name = sys.argv[3]
last_name = sys.argv[4]

# encode the api key and secret
header = {"alg": "HS256", "typ": "JWT"}
payload = {
    "iss": API_KEY,
    "exp": time() + 5000
}
token = jwt.encode(payload, API_SEC, algorithm="HS256", headers=header)

# url for adding a registrant to a meeting
url = f"https://api.zoom.us/v2/meetings/{meeting_id}/registrants"

# headers
headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json"
}

# data for the post request
data = {
    "email": email,
    "first_name": first_name,
    "last_name": last_name
}

# make the post request
response = requests.post(url, headers=headers, json=data)

# print the response
print(response.json())


from multiplexer.multiplexer_constants import peers, types
from obci.control.peer.configured_multiplexer_server import ConfiguredMultiplexerServer
from obci.configs import settings, variables_pb2
from obci.utils.openbci_logging import log_crash
from obci.devices.haptics.HapticsControl import HapticStimulator
import os, sys

class HapticStimulatorControlPeer(ConfiguredMultiplexerServer):
    '''Class to control sensory stimulation'''
    @log_crash
    def __init__(self, addresses):
        super(HapticStimulatorControlPeer, self).__init__(addresses=addresses,
                                          type=peers.HAPTICS_STIMULATOR)
        ids = self.config.get_param("id").split(":")
        self.active_channels = set(self.config.get_param('active_channels').split(';'))
        vid, pid = [int(i, base=16) for i in ids]
        self.stim = HapticStimulator(vid, pid)
        self.ready()
        self.logger.info("HapticController init finished!")

    def close(self):
        del self.stim

    def handle_message(self, mxmsg):
        '''Receives message HAPTIC_CONTROL_MESSAGE and sends it
        to stimulation board.

        Message contains info of type::

                message Variable {
                    required string key = 1;
                    required string value = 2;
                    }

        :param key: 'S', or 'T' - 'S' - to activate haptic channel(s); 'T' - to terminate FTDI
        control process and release device
        :param value: 'T' - doesn't matter; S - ex. '1,2:1.0,0.4' - activate channel 1 for
        1 second and channel 2 for 0.4 seconds. Channels can be in any
        order'''

        if mxmsg.type == types.HAPTIC_CONTROL_MESSAGE:
            l_msg = variables_pb2.Variable()
            l_msg.ParseFromString(mxmsg.message)
            if l_msg.key == 'S':
                logs = 'Activating multiple haptic channels msg: {}'.format(l_msg)
                self.logger.info(logs)
                chnl_ls, time_ls = l_msg.value.split(':') #strings of lists
                chnl_s = [i for i in chnl_ls.split(',')]
                if not set(chnl_s).issubset(self.active_channels):
                    self.stim.close()
                    exc_msg = '''

                    Stimulated channel NOT in active channels
                    Available: {}
                    Tried to stimulate: {}

                    '''.format(self.active_channels, chnl_s)
                    raise Exception (exc_msg)
                chnl = [int(i) for i in chnl_s]
                time = [float(i) for i in time_ls.split(',')]
                self.stim.bulk_stimulate(chnl, time)
            elif l_msg.key == 'T':
                self.logger.info('Shutting down')
                self.stim.close()
                sys.exit(0)
        self.no_response()

if __name__ == "__main__":
    HapticStimulatorControlPeer(settings.MULTIPLEXER_ADDRESSES).loop()


import cv2
import numpy as np

image_path="image.jpg"
def rotation_invariant_LBP(img, radius=3, neighbors=8):
    h,w=img.shape
    dst = np.zeros((h-2*radius, w-2*radius),dtype=img.dtype)
    for i in range(radius,h-radius):
        for j in range(radius,w-radius):
            # 获得中心像素点的灰度值
            center = img[i,j]
            for k in range(neighbors):
                # 计算采样点对于中心点坐标的偏移量rx，ry
                rx = radius * np.cos(2.0 * np.pi * k / neighbors)
                ry = -(radius * np.sin(2.0 * np.pi * k / neighbors))
                # 为双线性插值做准备
                # 对采样点偏移量分别进行上下取整
                x1 = int(np.floor(rx))
                x2 = int(np.ceil(rx))
                y1 = int(np.floor(ry))
                y2 = int(np.ceil(ry))
                # 将坐标偏移量映射到0-1之间
                tx = rx - x1
                ty = ry - y1
                # 根据0-1之间的x，y的权重计算公式计算权重，权重与坐标具体位置无关，与坐标间的差值有关
                w1 = (1-tx) * (1-ty)
                w2 =    tx  * (1-ty)
                w3 = (1-tx) *    ty
                w4 =    tx  *    ty
                # 根据双线性插值公式计算第k个采样点的灰度值
                neighbor = img[i+y1,j+x1] * w1 + img[i+y2,j+x1] *w2 + img[i+y1,j+x2] *  w3 +img[i+y2,j+x2] *w4
                # LBP特征图像的每个邻居的LBP值累加，累加通过与操作完成，对应的LBP值通过移位取得
                dst[i-radius,j-radius] |= (neighbor>center)  <<  (np.uint8)(neighbors-k-1)
    # 进行旋转不变处理
    for i in range(dst.shape[0]):
        for j in range(dst.shape[1]):
            currentValue = dst[i,j]
            minValue = currentValue
            for k in range(1, neighbors):
                # 对二进制编码进行循环左移，意思即选取移动过程中二进制码最小的那个作为最终值
                temp = (np.uint8)(currentValue>>(neighbors-k)) |  (np.uint8)(currentValue<<k)
                if temp < minValue:
                    minValue = temp
            dst[i,j] = minValue

    return dst

gray = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
rotation_invariant = rotation_invariant_LBP(gray,3,8)
cv2.imwrite("Result.jpg",rotation_invariant)
#cv2.imshow('img', gray)
#cv2.imshow('ri', rotation_invariant)
print("End")
while True :
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()


import math

import numpy as np
import cv2 as cv
import time
from PIL import ImageFont, ImageDraw, Image

def add_font(img, string, position, font_size):
	# 添加文字
	font = ImageFont.truetype("font/simsun.ttc", font_size)
	img_pil = Image.fromarray(img)
	draw = ImageDraw.Draw(img_pil)
	draw.text(position, string, font=font, fill=(0, 0, 255))
	bk_img = np.array(img_pil)
	return bk_img

def calculate_distance(box):
	# 计算box中前两点之间的距离
	distance = math.sqrt((box[0][0]-box[1][0])**2+math.sqrt((box[0][1]-box[1][1])**2))
	return distance

def LeastSquaresCircleFitting(points):
	center = [0, 0]
	sumX, sumY, sumX2, sumY2, sumX3, sumY3, sumXY, sumX1Y2, sumX2Y1 = 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
	N = len(points)
	for i in range(N):
		x = points[i][0]
		y = points[i][1]
		x2 = x**2
		y2 = y**2
		x3 = x2 * x
		y3 = y2 * y
		xy = x*y
		x1y2 = x * y2
		x2y1 = x2 * y

		sumX += x
		sumY += y
		sumX2 += x2
		sumY2 += y2
		sumX3 += x3
		sumY3 += y3
		sumXY +=xy
		sumX1Y2 += x1y2
		sumX2Y1 += x2y1

	C = N * sumX2 - sumX * sumX
	D = N * sumXY - sumX * sumY
	E = N * sumX3 + N * sumX1Y2 - (sumX2 + sumY2) * sumX
	G = N * sumY2 - sumY * sumY
	H = N * sumX2Y1 + N * sumY3 - (sumX2 + sumY2) * sumY
	denominator = C * G - D * D
	if denominator == 0:
		return [0, 0], 0
	a = (H * D - E * G) / (denominator)
	denominator = D * D - G * C
	b = (H * C - E * D) / (denominator)
	c = -(a * sumX + b * sumY + sumX2 + sumY2) / N
	center[0] = a / (-2)
	center[1] = b / (-2)
	r = math.sqrt(a * a + b * b - 4 * c) / 2
	return center, r

def detect_target(img, roix, roiy, roiw, roih, color):
	target = []
	roix += 2
	roiy += 2
	roiw -= 2
	roih -= 2
	img_roi = img[int(roiy):int(roiy)+int(roih), int(roix):int(roix)+int(roiw)]
	hsv = cv.cvtColor(np.array(img_roi), cv.COLOR_BGR2HSV)  # 将RGB图转换为灰度图

	if (color=="red"):
		lower_red1 = np.array([0, 43, 46])
		lower_red2 = np.array([156, 43, 46])
		upper_red1 = np.array([10, 255, 255])
		upper_red2 = np.array([180, 255, 255])
		mask1 = cv.inRange(hsv, lower_red1, upper_red1)  #根据第一个阈值范围确定mask1
		mask2 = cv.inRange(hsv, lower_red2, upper_red2)  #根据第二个阈值范围确定mask2
		mask = cv.add(mask1, mask2) #将两个mask合并
	elif (color=="blue"):
		lower_blue = np.array([100, 43, 46])
		upper_blue = np.array([124, 255, 255])
		mask = cv.inRange(hsv, lower_blue, upper_blue)

	cv.imshow("mask", mask)
	kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))
	closing = cv.morphologyEx(mask, cv.MORPH_CLOSE, kernel) #对图像进行闭运算
	contours, hierarchy = cv.findContours(closing, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) #对闭运算后的图像寻找轮廓
	contour_num = [0 for i in range(len(contours))]
	if (hierarchy is None):
		return target
	hierarchy = hierarchy[0]
	for i in range(len(contours)):
		if (hierarchy[i][3]!=-1): #表示如果当前轮廓有父轮廓，则将对应的父轮廓值+1
			contour_num[hierarchy[i][3]]+=1
	box_ls = []
	box_distance_ls = []
	for i in range(len(contour_num)):
		if (contour_num[i]==1):
			choice_index = hierarchy[i][2] #选取仅有一个子轮廓的父轮廓，并将其子轮廓作为target
			rect = cv.minAreaRect(contours[choice_index])  # 最小外接矩形
			box = np.int0(cv.boxPoints(rect))  # 矩形的四个角点取整
			box_ls.append(box)
			box_distance_ls.append(calculate_distance(box))
	if (len(box_ls)!=0):
		box_distance_ls  = np.array(box_distance_ls)
		max_index = np.argmax(box_distance_ls)
		box = box_ls[max_index]
		for j in range(4):
			box[j][0] += int(roix)
			box[j][1] += int(roiy)
		for j in range(4):
			cv.line(img, box[j], box[(j + 1) % 4], color=(0, 255, 0), thickness=2)
		target = np.int0((box[0] + box[2]) / 2)
	return target

def draw_circle(img, target_ls):
	center = [0,0]
	if (len(target_ls)<5):
		return center
	else:
		# if (len(target_ls)>100):
		# 	target_ls.pop(0)
		center, radius = LeastSquaresCircleFitting(target_ls)
		if (center[0]!=0 and center[1]!=0 and radius!=0):
			cv.circle(img, (int(center[0]) , int(center[1])), 5, (255, 0, 0), thickness=cv.FILLED)
			cv.circle(img, (int(center[0]), int(center[1])), int(radius), (255, 255, 0),5)
			return center
		return center

def get_rotation(center, target_ls):
	if (len(target_ls)<10):
		return ""
	temp_target = target_ls[len(target_ls)-10:len(target_ls)]
	angle_ls = [(temp_target[i][0]-center[0])/(temp_target[i][1]-center[1])  for i in range(len(temp_target))]
	grad_angle_num_1 = 0
	for i in range(len(angle_ls)-1):
		if (angle_ls[i+1]>angle_ls[i]):
			grad_angle_num_1 += 1
	if (grad_angle_num_1>len(angle_ls)-1-grad_angle_num_1):
		rotation = "anti-block"
	else:
		rotation = "block"
	return rotation

def detect(file_name):
	ct = 0 #记录当前的帧数
	cap = cv.VideoCapture(file_name)
	ROI = (0,0,0,0)
	target_ls = []
	while True:
		success, frame = cap.read()  # 逐帧读入
		if success:
			frame = cv.resize(frame, (800, 600))  # 改变每一帧的大小，使画面适应于电脑屏幕界面
			if ct == 0:
				# 如果当前是第一帧，则执行框选ROI的操作
				roi = cv.selectROI(windowName="fans", img=frame, showCrosshair=True,
								   fromCenter=False)
				ROI = roi
				cv.waitKey(-1)
			roix, roiy, roiw, roih = ROI
			# 绘制ROI矩形
			cv.rectangle(img=frame, pt1=(roix, roiy), pt2=(roix + roiw, roiy + roih), color=(0, 0, 255), thickness=2)
			target = detect_target(frame, roix, roiy, roiw, roih, color="red")
			if (len(target)!=0):
				target_ls.append(target)
				cv.circle(frame, (int(target[0]), int(target[1])), 5, (0, 0, 255), thickness=cv.FILLED)
			center = draw_circle(frame, target_ls)
			rotation = get_rotation(center, target_ls)
			frame = add_font(frame, "rotation:" + rotation, (0, 30), font_size=30)
			# get_rotation()

			fps = cap.get(cv.CAP_PROP_FPS)
			frame = add_font(frame, "FPS:" + str(int(fps)), (0, 0), font_size=30)  # 为当前帧添加帧率
			cv.namedWindow('fans', 0)
			cv.imshow('fans', frame)
			# key = cv.waitKey(int(1000/25)) & 0xFF
			key = cv.waitKey(2) & 0xFF
			# key = cv.waitKey(5)
			if key == 27: #				print('手动停止')
				break
			ct += 1
		else:
			print(file_name)
			print('播放完成')
			break
	cap.release()
	cv.destroyAllWindows()

if __name__=="__main__":
	detect("red_test1.mp4")

# kernel = np.ones((1, 5), np.uint8)
# img = cv2.imread("test.jpeg")
# gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
# binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel, anchor=(2, 0), iterations=5)
# contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# print("contours", len(contours))
#
# print("hierarchy", hierarchy)
# for i in range(len(contours)):
# 	print("轮廓{}:".format(i))
# 	print(contours[i].shape)
# cv2.drawContours(img,contours,-1,(0,0,255),3)
# cv2.imshow("img", img)
# cv2.waitKey(0)


from copy import deepcopy
from tkinter import *
from math import *
from time import *
from random import *
from game_canvas import *
from gui import *

SIZE = 8
WHITE = 0
BLACK = 1

def count_different(board, player):
  if player == BLACK:
    colour = "black"
    opponent = "white"
  else:
    colour = "white"
    opponent = "black"
  colour_num = 0
  opponent_num = 0
  for x in range(SIZE):
    for y in range(SIZE):
      if board[x][y] == colour:
        colour_num+=1
      if board[x][y] == opponent:
        opponent_num+=1

  return colour_num - opponent_num

def mock_move(player, board, x, y):
  if player == BLACK:
    colour = "black"
  else:
    colour = "white"
  temp_board = board
  temp_board[x][y] = colour
  temp_board = convertDiscs(temp_board, x, y)
  result = count_different(temp_board, player)
  return result

def generate_valid_moves(player, board):
  valid_moves = []
  for x in range(SIZE):
    for y in range(SIZE):
      if valid(board, player, x, y):
        valid_moves.append([x,y])
  return valid_moves

# calculate the mobility for opponent
def mobility(board, player):
  if player == BLACK:
    opponent = WHITE
  else:
    opponent = BLACK
  valid_moves = generate_valid_moves(opponent, board)
  return len(valid_moves)

#temporary poor hueristic
def tempHeuristic(board, player):
    score = 0
    corner_value = 50
    adjacent_value = 3
    side_value = 3
    # Set player and opponent colours
    if player == BLACK:
        colour = "black"
        opponent = "white"
    else:
        colour = "white"
        opponent = "black"

    # Basic hurisitc just use the number of pieces of the color they play on the board
    # as an indicator for the quality of a position. This greedy evaluation function is
    # derived from the final goal of the game: the player who has the most pieces wins.
    # But this only makes sense if you really can look ahead until the end of the game

    #
    difference_score = 4 * count_different(board, player)

    # A better criterion for determining a position is to count the number of moves a player can make:
    # the mobility is decisive in Reversi! If you only have a few moves, it's likely that your opponent
    # can play such that you are forced to make bad moves. Therefore, if your mobility is high,
    # the position is better for you than if it's low.

    mobility_score = -5 * mobility(board, player)

    # Advanced huristic about edges and corner condition
    for x in range(SIZE):
        for y in range(SIZE):
            heuristic_value = 1

            if (x == 0 and y == 1) or (x == 1 and 0 <= y <= 1):
                if board[0][0] == colour:
                    heuristic_value = side_value
                else:
                    heuristic_value = -adjacent_value

            elif (x == 0 and y == 6) or (x == 1 and 6 <= y <= 7):
                if board[7][0] == colour:
                    heuristic_value = side_value
                else:
                    heuristic_value = -adjacent_value

            elif (x == 7 and y == 1) or (x == 6 and 0 <= y <= 1):
                if board[0][7] == colour:
                    heuristic_value = side_value
                else:
                    heuristic_value = -adjacent_value

            elif (x == 7 and y == 6) or (x == 6 and 6 <= y <= 7):
                if board[7][7] == colour:
                    heuristic_value = side_value
                else:
                    heuristic_value = -adjacent_value

            elif (x == 0 and 1 < y < 6) or (x == 7 and 1 < y < 6) or (y == 0 and 1 < x < 6) or (y == 7 and 1 < x < 6):
                heuristic_value = side_value

            elif (x == 0 and y == 0) or (x == 0 and y == 7) or (x == 7 and y == 0) or (x == 7 and y == 7):
                heuristic_value = corner_value

            if board[x][y] == colour:
                score += heuristic_value
            elif board[x][y] == opponent:
                score -= heuristic_value
    return score + difference_score + mobility_score

#validity function
def valid(board, player, x, y):
    # Sets player colour
    if player == WHITE:
        colour = "white"
    else:
        colour = "black"

    if board[x][y] != None:
        return False

    else:

        neighbour = False
        neighbours = []
        for i in range(max(0, x - 1), min(x + 2, SIZE)):
            for j in range(max(0, y - 1), min(y + 2, SIZE)):
                if board[i][j] != None:
                    neighbour = True
                    neighbours.append([i, j])

        if not neighbour:
            return False
        else:

            valid = False
            for n in neighbours:

                neighbour_x = n[0]
                neighbour_y = n[1]

                if board[neighbour_x][neighbour_y] == colour:
                    continue
                else:
                    temp_x = neighbour_x
                    temp_y = neighbour_y

                    while 0 <= temp_x < SIZE and 0 <= temp_y < SIZE:

                        if board[temp_x][temp_y] == None:
                            break

                        if board[temp_x][temp_y] == colour:
                            valid = True
                            break
                        temp_x += neighbour_x - x
                        temp_y += neighbour_y - y
            return valid


import tensorflow._api.v2.compat.v1 as tf   # 将TensorFlow2.0转换为1.0
tf.disable_v2_behavior()
from just_project.style_transfer.vgg import vgg_16
from just_project.style_transfer.vgg import vgg_arg_scope
from just_project.style_transfer.vgg_preprocessing import preprocess_image
from just_project.style_transfer.vgg_preprocessing import unprocess_image
from just_project.style_transfer import reader
from just_project.style_transfer import model
from just_project.style_transfer import utils
from just_project.style_transfer.losses import gram
from just_project.style_transfer import losses
import os
import time
import tf_slim as slim
import os
# os.environ["CUDA_VISIBLE_DEVICES"] = "0"     # 使用第一, 二块GPU

# 构建损失网络
# tensorboard --logdir="just_project\style_transfer\models\wave"

# 对图片做预处理
def get_preprocessing(name, is_training=False):
    # 返回一个函数，处理每个批次里面的每张图像
    # image = preprocessing_fn(image, output_height, output_width, ...).
    def preprocessing_fn(image, output_height, output_width, **kwargs):
        return preprocess_image(image, output_height, output_width, is_training=is_training, **kwargs)

    def unprocessing_fn(image):
        return unprocess_image(image)

    return preprocessing_fn, unprocessing_fn

# 得到经典网络VGG16
def get_network_fn(name, num_classes, weight_decay=0.0, is_training=False):
    arg_scope = vgg_arg_scope(weight_decay=weight_decay)

    def network_fn(images, **kwargs):
        with slim.arg_scope(arg_scope):
            return vgg_16(images, num_classes, is_training=is_training, **kwargs)

    if hasattr(vgg_16, 'default_image_size'):
        network_fn.defualt_image_size = vgg_16.default_image_size

    return network_fn

def build_loss_network(FLAGS):

    # 得到损失网络
    network_fn = get_network_fn('vgg16', num_classes=1, is_training=False)

    # 获取数据预处理函数
    image_preprocessing_fn, image_unprocess_fn = get_preprocessing('vgg16')
    # 读入图片顺便做数据预处理
    processed_images = reader.image(FLAGS.batch_size, FLAGS.image_size, FLAGS.image_size, 'train2017/'
                                    , image_preprocessing_fn, epochs=FLAGS.epoch)

    # 引用图像生成网络model.net，generated是生成的图像
    # 设置training=True因为要训练该网络
    generated = model.net(processed_images, training=True)

    # 将生成的图像同样使用image_preprocessing_fn进行处理
    # 因为generated同样需要送到损失网络中计算loss
    processed_generated = [
        image_preprocessing_fn(image, FLAGS.image_size, FLAGS.image_size)
        for image in tf.unstack(generated, axis=0, num=FLAGS.batch_size)
    ]
    processed_generated = tf.stack(processed_generated)

    # 这里需要原始的经过预处理的图像，和原始的经过生成网络再经过预处理的图像
    # 参数标志是否对输出进行squeeze操作（去除维度数为1的维度，比如5*3*1转为5*3）
    _, endpoints = network_fn(tf.concat([processed_generated, processed_images], 0), spatial_squeeze=False)

    return endpoints

# 计算出来风格图片的特征
def get_style_features(FLAGS):
    with tf.Graph().as_default():
        network_fn = get_network_fn('vgg16', num_classes=1, is_training=False)
        # 获取数据预处理函数
        image_preprocessing_fn, image_unprocessing_fn = get_preprocessing('vgg16')

        # 获取风格图片
        size = FLAGS.image_size
        img_bytes = tf.read_file(FLAGS.style_image)
        if FLAGS.style_image.lower().endswith('png'):
            image = tf.image.decode_png(img_bytes)
        else:
            image = tf.image.decode_jpeg(img_bytes)

        # 增加批次维度
        images = tf.expand_dims(image_preprocessing_fn(image, size, size), 0)
        # 让这张风格图片经过网络正向传播
        _, endpoints_dict = network_fn(images, spatial_squeeze=False)

        features = []
        for layer in FLAGS.style_layers:
            feature = endpoints_dict[layer]
            # 去掉批次的维度   gram伽馬
            feature = tf.squeeze(gram(feature), [0])
            features.append(feature)

        with tf.Session() as sess:
            # 恢复复原变量为了损失网络
            init_func = utils._get_init_fn(FLAGS)
            init_func(sess)

            # 保证'generated'字典存在
            if os.path.exists('generated') is False:
                os.makedirs('generated')
            # 指出剪裁的风格图片路径
            save_file = 'generated/target_style_' + FLAGS.naming + '.jpg'
            # 写入预处理的风格图片到指定的路径
            with open(save_file, 'wb') as f:
                target_image = image_unprocessing_fn(images[0, :])
                value = tf.image.encode_jpeg(tf.cast(target_image, tf.uint8))
                f.write(sess.run(value))
                tf.logging.info('Target style pattern is saved to: %s.' % save_file)

            # 返回那些用来计算风格损失的网络层的特征
            return sess.run(features)

def main(FLAGS):
    # 返回那些用来计算风格损失的网络层的特征，先计算出来备用
    style_features_t = get_style_features(FLAGS)

    # 保证训练路径存在
    training_path = os.path.join(FLAGS.model_path, FLAGS.naming)
    if not(os.path.exists(training_path)):
        os.makedirs(training_path)

    with tf.Graph().as_default():
        with tf.Session() as sess:
            # 获取数据预处理函数
            image_preprocessing_fn, image_unprocessing_fn = get_preprocessing('vgg16')
            # 获取训练所需图片
            processed_images = reader.image(FLAGS.batch_size, FLAGS.image_size, FLAGS.image_size,
                                            'train2017/', image_preprocessing_fn, epochs=FLAGS.epoch)
            # 经过卷积反卷积的生成网络的图片
            generated = model.net(processed_images, training=True)
            processed_generated = [image_preprocessing_fn(image, FLAGS.image_size, FLAGS.image_size)
                                   for image in tf.unstack(generated, axis=0, num=FLAGS.batch_size)
                                   ]
            processed_generated = tf.stack(processed_generated)
            # 构建网络
            network_fn = get_network_fn('vgg16', num_classes=1, is_training=False)
            _, endpoints_dict = network_fn(tf.concat([processed_generated, processed_images], 0), spatial_squeeze=False)

            # 记录损失网络的结构
            tf.logging.info('Loss network layers(You can define them in "content_layers" and "style_layers"):')
            for key in endpoints_dict:
                tf.logging.info(key)

            # 构建损失
            content_loss = losses.content_loss(endpoints_dict, FLAGS.content_layers)
            style_loss, style_loss_summary = losses.style_loss(endpoints_dict, style_features_t, FLAGS.style_layers)
            loss = FLAGS.style_weight * style_loss + FLAGS.content_weight * content_loss

            # 添加一些总结为了tensorboard可视化
            tf.summary.scalar('losses/content_loss', content_loss)
            tf.summary.scalar('losses/style_loss', style_loss)

            tf.summary.scalar('weighted_losses/weighted_content_loss', content_loss * FLAGS.content_weight)
            tf.summary.scalar('weighted_losses/weighted_style_loss', style_loss * FLAGS.style_weight)
            tf.summary.scalar('total_loss', loss)

            for layer in FLAGS.style_layers:
                tf.summary.scalar('style_losses/' + layer, style_loss_summary[layer])
            tf.summary.image('generated', generated)
            tf.summary.image('origin', tf.stack([
                image_unprocessing_fn(image) for image in tf.unstack(processed_images, axis=0, num=FLAGS.batch_size)
            ]))
            summary = tf.summary.merge_all()
            writer = tf.summary.FileWriter(training_path)

            # 准备去训练
            global_step = tf.Variable(0, name='global_step', trainable=False)

            variable_to_train = []
            for variable in tf.trainable_variables():
                if not(variable.name.startswith(FLAGS.loss_model)):
                    variable_to_train.append(variable)

            train_op = tf.train.AdamOptimizer(1e-3).minimize(loss, global_step=global_step, var_list=variable_to_train)

            variable_to_restore = []
            for v in tf.global_variables():
                if not(v.name.startswith(FLAGS.loss_model)):
                    variable_to_restore.append(v)

            saver = tf.train.Saver(variable_to_restore, write_version=tf.train.SaverDef.V1)

            sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])

            # 恢复损失网络的变量
            init_func = utils._get_init_fn(FLAGS)
            init_func(sess)

            # 恢复对于模型训练的变量如果checkpoint文件已经存在
            last_file = tf.train.latest_checkpoint(training_path)
            if last_file:
                tf.logging.info('Restoring model from {}'.format(last_file))
                saver.restore(sess, last_file)

            # 开始训练
            coord = tf.train.Coordinator()
            threads = tf.train.start_queue_runners(coord=coord)
            start_time = time.time()
            try:
                while not coord.should_stop():
                    _, loss_t, step = sess.run([train_op, loss, global_step])
                    elapsed_time = time.time() - start_time
                    start_time = time.time()
                    # 记录日志
                    if step % 2 == 0:
                        tf.logging.info('step: %d, total Loss %f, secs/step: %f' % (step, loss_t, elapsed_time))
                    # 总结
                    if step % 75 == 0:
                        tf.logging.info('adding summary...')
                        summary_str = sess.run(summary)
                        writer.add_summary(summary_str, step)
                        writer.flush()
                    if step % 1000 == 0:
                        saver.save(sess, os.path.join(training_path, FLAGS.style_image_name + '_fast-style-model.ckpt'), global_step=step)
            except tf.errors.OutOfRangeError:
                saver.save(sess, os.path.join(training_path, 'fast-style-model.ckpt-done'))
                tf.logging.info('Done training -- epoch limit reached')
            finally:
                coord.request_stop()
            coord.join(threads)

if __name__ == '__main__':
    FLAGS = utils.read_conf_file('conf/wave.yml')
    main(FLAGS)


from re import L
import sys

def next_permutation(a, n):
  i = n-1
  while i > 0 and a[i-1] >= a[i]: #1
    i -= 1
  if i <= 0: #입력받은 수열이 마지막 순열인 경우
    return False

  j = n-1 #2
  while a[j] <= a[i-1]:
    j -= 1
  a[i-1], a[j] = a[j], a[i-1] #3

  j = n-1 #4
  while i < j:
    a[i], a[j] = a[j], a[i]
    i += 1
    j -= 1
  return True

def print_ans(s, a, k):
  ans = []
  for i in range(k):
    if a[i] == 1:
      ans.append(s[i])

  return ans

while True:
  t = list(map(int, input().split()))

  k = t[0]

  if k == 0:
    sys.exit(0)

  s = []
  for i in range(1, k+1):
    s.append(t[i])

  a = [0] * (k - 6) + [1] * 6
  ans = []
  ans.append(print_ans(s, a, k))

  while next_permutation(a, k):
    ans.append(print_ans(s, a, k))

  ans.sort()
  for v in ans:
    print(' '.join(map(str, v)))

  print()


import unittest
import sys
import io

from core import main

class TestMainModule(unittest.TestCase):
    def setUp(self):
        self._stdout = sys.stdout
        sys.stdout = io.StringIO()

    def tearDown(self):
        sys.stdout.close()
        sys.stdout = self._stdout

    def test_main_function(self):
        self.assertEqual(sys.stdout.getvalue(), '')

        main()

        self.assertEqual(sys.stdout.getvalue(), 'test\n')

if __name__ == '__main__':
    unittest.main()


import math

def function():
            text = input('plz input a b c, split with space: ')
            res = text.split(' ')
            a, b, c = [int(i) for i in res]
            delta = pow(b,2)-4*a*c
            if delta<0:
                print('no solve')
            elif delta == 0:
                print('only one answer:  ')
                x1=x2=float(((-b)+math.sqrt(pow(b,2)-4*a*c))/(2*a))
                print('x1=x2=',x1)
            else:
                print("function's two answers:")
                x1=float(((-b)+math.sqrt(pow(b,2)-4*a*c))/(2*a))
                x2=float(((-b)-math.sqrt(pow(b,2)-4*a*c))/(2*a))
                print('x1=',x1)
                print('x2=',x2)
def signal():
        function()
        sig=int(input('press 1 to quit，others continue:'))
        if sig==1:
            return
        else:
            signal()
if __name__=="__main__":
    signal()


file = open("data.txt", "r")
forest = file.read().split('\n')

def checkIfThereIsATree(indexOfLine, element, treeCount):
    if element[indexOfLine] == '#':
        treeCount += 1
    return treeCount

# First Task of Day 3
trees = 0
index = 0
for element in forest:
    # Check For Trees
    trees = checkIfThereIsATree(index, element, trees)
    index = (index + 3) % len(element)

print(trees)

# Second Task of Day 3
trees1 = 0
trees2 = 0
trees3 = 0
trees4 = 0
trees5 = 0
index1 = 0
index2 = 0
index3 = 0
index4 = 0
index5 = 0
for i, element in enumerate(forest):

    # Check For Trees
    trees1 = checkIfThereIsATree(index1, element, trees1)
    trees2 = checkIfThereIsATree(index2, element, trees2)
    trees3 = checkIfThereIsATree(index3, element, trees3)
    trees4 = checkIfThereIsATree(index4, element, trees4)

    # Check for Index Out Of Range
    index1 = (index1 + 1) % len(element)
    index2 = (index2 + 3) % len(element)
    index3 = (index3 + 5) % len(element)
    index4 = (index4 + 7) % len(element)
    if not i % 2:
        # Check For Trees
        trees5 = checkIfThereIsATree(index5, element, trees5)

        # Check for Index Out Of Range
        index5 = (index5 + 1) % len(element)

print(trees1 * trees2 * trees3 * trees4 * trees5)


import requests
import json
import pandas as pd

import datetime
from datetime import timedelta

import config

def location_coordinate(location):
	# 여기서 주소를 좌표로 변경

	# res/xylist.csv를 이용해 주소를 확인후 nx와 ny를 매치 시켜야한다
	# 다음 코드를 통해 cvs 파일을 리스트 형식으로 불러온다
	# xylist = pd.read_csv('../res/xylist.csv', engine='c', dtype=str, sep=',', encoding='CP949')

	# csv값 확인
	# print(xylist)

	nx = "60"
	ny = "128"

	return nx, ny

def get_vilage_base_time(h, m):
	# API 업로드 기준인 10분 전 후를 체크
	if m < 10 :
		if h <= 5 :	return '0200'
		elif h <= 8 :	return '0500'
		elif h <= 11 :	return '0800'
		elif h <= 14 :	return '1100'
		elif h <= 17 :	return '1400'
		elif h <= 20 :	return '1700'
		elif h <= 23 :	return '2000'
		else : return '2300'
	else:
		if h < 5 :	return '0200'
		if h < 8 :	return '0500'
		elif h < 11 :	return '0800'
		elif h < 14 :	return '1100'
		elif h < 17 :	return '1400'
		elif h < 20 :	return '1700'
		elif h < 23 :	return '2000'
		else : return '2300'

# get_weather_api(장소 넘기기)
def get_weather_vilage_api(nx, ny):
	'''
	동네예보(VilageFcstInfoService)
	POP - 강수확률(%)
	TMN - 아침 최저기온(℃)
	TMX - 낮 최고기온(℃)
	SKY - 하늘상태(코드값)
		하늘상태(SKY) 코드 : 맑음(0~5), 구름많음(6~8), 흐림(9~10)
	WSD - 풍속(m/s)
		풍속 구간 의미 : 바람이 약하다(0~3), 바람이 약간 강하다(4~8)
										바람이 강하다(9~13), 바람이 매우 강하다(14~)
	'''
	weather_vilage_url = 'http://apis.data.go.kr/1360000/VilageFcstInfoService/getVilageFcst?'

	service_key = config.weather_api_key

	today = datetime.datetime.today()

	base_date = '-'
	base_time = '-'

	# 동네예보
	# - Base_time : 0200, 0500, 0800, 1100, 1400, 1700, 2000, 2300 (1일 8회)
	# - API 제공 시간(~이후) : 02:10, 05:10, 08:10, 11:10, 14:10, 17:10, 20:10, 23:10
	today = datetime.datetime.today()
	date_vilage_flag = True

	if today.hour <= 2 and today.minute < 10 :
		today = today - timedelta(days=1)
		base_vilage_date = today.strftime("%Y%m%d") # "20200214" == 기준 날짜
		base_vilage_time = "2300"

		date_vilage_flag = False

	if date_vilage_flag :
		base_vilage_date = today.strftime("%Y%m%d")
		base_vilage_time = get_vilage_base_time(today.hour, today.minute)

	vilage_payload = "serviceKey=" + service_key + "&" +\
			"dataType=json" + "&" +\
			"base_date=" + base_vilage_date + "&" +\
			"base_time=" + base_vilage_time + "&" +\
			"nx=" + nx + "&" +\
			"ny=" + ny

	# 값 요청

	vilage_res = requests.get(weather_vilage_url + vilage_payload)

	try:
		items = vilage_res.json().get('response').get('body').get('items')
	except AttributeError:
		# api가 업데이트 될때 00시 부터 02시 10분 까지 에러 발생
		# 기본 값을 넘겨준다
		vilage_weather_data = {
			'tmp' : '36.5℃'	,
			'pop' : '0%'	,
			'r06'	:	'0mm'	,
			'reh'	:	'0%'	,
			'tmpn': '36.5℃'	,
			'tmpx': '36.5℃'	,
			'sky_code'	:	'0'	,
			'sky_state'	:	'맑음'	,
			'vec'	:	'0'	,
			'wsd'	:	'0m/s'	}
		return vilage_weather_data

	vilage_weather_data = dict()

	for item in items['item']:
		# 3시간 기온(℃)
		if item['category'] == 'T3H':
			vilage_weather_data['tmp'] = item['fcstValue'] + '℃'

		# 강수확률(%)
		if item['category'] == 'POP':
			vilage_weather_data['pop'] = item['fcstValue'] + '%'

		# 강수량(mm)
		if item['category'] == 'R06':
			vilage_weather_data['r06'] = item['fcstValue'] + 'mm'

		# 습도(%)
		if item['category'] == 'REH':
			vilage_weather_data['reh'] = item['fcstValue'] + '%'

		# 아침 최저기온(℃)
		if item['category'] == 'TMN':
			vilage_weather_data['tmpn'] = item['fcstValue'] + '℃'

		# 낮 최고기온(℃)
		if item['category'] == 'TMX':
			vilage_weather_data['tmpx'] = item['fcstValue'] + '℃'

		# 하늘상태(SKY) 코드 : 맑음(0~5), 구름많음(6~8), 흐림(9~10)
		if item['category'] == 'SKY':
			weather_sky_code = item['fcstValue']
			if weather_sky_code >= '0' and weather_sky_code <= '5':
				weather_sky_state = '맑음'
			elif weather_sky_code >= '6' and weather_sky_code <= '8':
				weather_sky_state = '구름많음'
			elif weather_sky_code >= '9' and weather_sky_code <= '10':
				weather_sky_state = '흐림'

			vilage_weather_data['sky_code'] = weather_sky_code
			vilage_weather_data['sky_state'] = weather_sky_state

		# 풍향
		if item['category'] == 'VEC':
			vilage_weather_data['vec'] = item['fcstValue']

		#	WSD - 풍속(m/s)
		# 풍속 구간 의미 : 바람이 약하다(0~3), 바람이 약간 강하다(4~8)
		#									바람이 강하다(9~13), 바람이 매우 강하다(14~)
		if item['category'] == 'WSD':
			vilage_weather_data['wsd'] = item['fcstValue']
			# vilage_weather_data['wsd'] = item['fcstValue']  + ' m/s'

	return vilage_weather_data

# 초단기예보
def get_weather_srt_api(nx, ny):
	'''
	초단기예보(UltraSrtFcstInfoService)
	PTY	- 강수형태(코드값)
		강수형태(PTY) 코드 : 없음(0), 비(1), 비/눈(2), 눈(3), 소나기(4), 빗방울(5), 빗방울/눈날림(6), 눈날림(7)
	LGT	- 낙뢰(코드값)
		낙뢰(LGT) 코드 : 확률없음(0), 낮음(1), 보통(2), 높음(3)
	'''
	weather_srt_url = 'http://apis.data.go.kr/1360000/VilageFcstInfoService/getUltraSrtFcst?'

	service_key = config.weather_api_key

	today = datetime.datetime.today()

	base_srt_date = '-'
	base_srt_time = '-'

	# 초단기예보
	# - Base_time : 매 시간 30분에 생성
	# - API 제공 시간(~이후) : 매 시간 45분 이후
	today = datetime.datetime.today()
	date_srt_flag = True

	if today.hour == 0 and today.minute < 45 :
		today = today - timedelta(days=1)
		base_srt_date = today.strftime("%Y%m%d") # "20200214" == 기준 날짜
		base_srt_time = "2330"

		date_srt_flag = False

	if date_srt_flag :
		base_srt_date = today.strftime("%Y%m%d")
		if today.minute < 45 :
			today = today - timedelta(hours=1)
		base_srt_time = today.strftime("%I") + "30"

	srt_payload = "serviceKey=" + service_key + "&" +\
			"dataType=json" + "&" +\
			"base_date=" + base_srt_date + "&" +\
			"base_time=" + base_srt_time + "&" +\
			"nx=" + nx + "&" +\
			"ny=" + ny

	# 값 요청

	srt_res = requests.get(weather_srt_url + srt_payload)

	try:
		items = srt_res.json().get('response').get('body').get('items')
	except AttributeError:
		# api가 업데이트 될때 00시 부터 02시 10분 까지 에러 발생
		# 기본 값을 넘겨준다
		srt_weather_data = {
			'pty_code': '0', 'pty_state': '없음',
			'lgt_code': '0', 'sky_state': '없음' }
		return srt_weather_data

	srt_weather_data = dict()

	for item in items['item']:
		# 강수형태(PTY) 코드 : 없음(0), 비(1), 비/눈(2), 눈(3), 소나기(4), 빗방울(5), 빗방울/눈날림(6), 눈날림(7)
		if item['category'] == 'PTY':
			weather_pty_code = item['fcstValue']
			if weather_pty_code == '1' or weather_pty_code == '4' or weather_pty_code == '5' :
				weather_pty_state = '비'
			elif weather_pty_code == '2' or weather_pty_code == '3' or weather_pty_code == '6' or weather_pty_code == '7':
				weather_pty_state = '눈'
			else:
				weather_pty_state = '없음'

			srt_weather_data['pty_code'] = weather_pty_code
			srt_weather_data['pty_state'] = weather_pty_state

		# 낙뢰(LGT) 코드 : 확률없음(0), 낮음(1), 보통(2), 높음(3)
		if item['category'] == 'LGT':
			weather_lgt_code = item['fcstValue']
			if weather_lgt_code == '0' :
				weather_lgt_state = '없음'
			elif weather_lgt_code == '1' :
				weather_lgt_state = '낮음'
			elif weather_lgt_code == '2' :
				weather_lgt_state = '보통'
			else :
				weather_lgt_state = '높음'

			srt_weather_data['lgt_code'] = weather_lgt_code
			srt_weather_data['lgt_state'] = weather_lgt_state

	return srt_weather_data

def get_weather_info(location):
	nx, ny = location_coordinate(location)

	api_vilage_result = get_weather_vilage_api(nx, ny)
	api_srt_result = get_weather_srt_api(nx, ny)

	weather_data = dict()
	weather_data.update(api_vilage_result)
	weather_data.update(api_srt_result)

	print(weather_data)

	return(weather_data)


import turtle
from turtle import Turtle, Screen
import random
import colorgram

# from turtle import * means import everything
# import turtle as t aliasing module
xyla_turtle = Turtle()
xyla_turtle.shape('turtle')
xyla_turtle.color("red")
x = 4

# for _ in range(4):
#     xyla_turtle.forward(100)
#     xyla_turtle.right(90)

# for _ in range(15):
#     xyla_turtle.down()
#     xyla_turtle.forward(10)
#     xyla_turtle.up()
#     xyla_turtle.forward(10)

#
#

def create_random_rgb():
    return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

def draw_poly(sides):
    angle = 360 / sides
    for _ in range(sides):
        xyla_turtle.color(random.choice(create_random_rgb()))
        xyla_turtle.forward(100)
        xyla_turtle.right(angle)

# def generate_shapes():
#     for i in range(3, 11):
#         draw_poly(i)
#

# generate_shapes()

turtle.colormode(255)

def move_turtle(movement_direction, distance, width):
    xyla_turtle.color(create_random_rgb())
    xyla_turtle.speed('fastest')
    xyla_turtle.width(width)
    if movement_direction == "right":
        xyla_turtle.right(90)
        xyla_turtle.forward(distance)
    elif movement_direction == "left":
        xyla_turtle.left(90)
        xyla_turtle.forward(distance)
    elif movement_direction == "forward":
        xyla_turtle.forward(distance)
    else:
        xyla_turtle.backward(distance)

# movement = ['forward', 'backward', 'right', 'left']
# for _ in range(200):
#     movement_choice = random.choice(movement)
#     move_turtle(movement_choice, 50, 5)
# print(create_random_rgb())

# tuples are immutable, lists mutable, dicts mutable
xyla_turtle.speed('fastest')

def create_spherical(radius, tilt):
    xyla_turtle.color(create_random_rgb())
    xyla_turtle.circle(radius)
    xyla_turtle.left(tilt)

# for _ in range(36):
#     create_spherical(100, 10)
def get_color(color_obj):
    return color_obj.rgb.r, color_obj.rgb.g, color_obj.rgb.b

# colors = map(get_color, colorgram.extract('image.jpg', 34))
# print(list(colors))
color_list = [(132, 166, 205), (221, 148, 106), (32, 42, 61), (199, 135, 148), (166, 58, 48), (141, 184, 162),
              (39, 105, 157), (237, 212, 90), (150, 59, 66), (216, 82, 71), (168, 29, 33), (235, 165, 157),
              (51, 111, 90), (35, 61, 55), (156, 33, 31), (17, 97, 71), (52, 44, 49), (230, 161, 166), (170, 188, 221),
              (57, 51, 48), (184, 103, 113), (32, 60, 109), (105, 126, 159), (175, 200, 188), (34, 151, 210),
              (65, 66, 56), (106, 140, 124), (153, 202, 227), (48, 69, 71), (131, 128, 121)]

color_number = 0

# def get_next_color(list_colors):
#     global color_number
#     if color_number == len(color_list):
#         color_number = 0
#     color = list_colors[color_number]
#     color_number += 1
#     return color

def create_spot_painting(dot_size, number_rows, number_columns, gap_rows):
    xyla_turtle.hideturtle()
    xyla_turtle.pencolor('white')
    xyla_turtle.setheading(220)
    xyla_turtle.forward(500)
    xyla_turtle.setheading(0)
    for i in range(number_rows):
        cur_pos = xyla_turtle.pos()
        for j in range(number_columns):
            xyla_turtle.down()
            xyla_turtle.fillcolor(random.choice(color_list))
            xyla_turtle.begin_fill()
            xyla_turtle.circle(dot_size)
            xyla_turtle.end_fill()
            xyla_turtle.up()
            xyla_turtle.forward(80)

        xyla_turtle.setx(cur_pos[0])
        xyla_turtle.sety(cur_pos[1] + gap_rows)

create_spot_painting(15, 10, 10, 80)

screen = Screen()
screen.exitonclick()


'''
功能
    监控键盘按键,监控截图的按键并且保存图片到同目录下
前置
    需要安装keyboard负责监控按键，在命令行中执行pip install keyboard来安装
    需要安装PIL负责保存剪切板中的图片，在命令行中执行pip install Pillow来安装
提示
    在vscode里可以使用右键排序import语句
    在vscode中在执行中需要中断执行使用ctrl+c
扩展
    pip install pyinstallor 打包成exe文件
    PyInstaller语法：用命令行或者PowerShell，用cd命令进入.py所在的目录，
    然后执行命令：pyinstaller -F Yourname.py（以后研究）
'''
import sys
from time import sleep

import keyboard
from PIL import ImageGrab

from baiDuApi import BaiDuAPI
from getText import GetText

def screenShot():
    ''' 用于截图并保存 '''

    # 等待按下的键盘按键，多个按键用+连接，这里是截图开始
    if keyboard.wait(hotkey='alt+ctrl+a') is None:
        # 同上，这里是截图开始
        if keyboard.wait(hotkey='Enter') is None:
            # 因为获取剪切板的图片太快了，所以要停顿一小段时间
            sleep(0.01)
            # 复制剪切板中的图片
            im = ImageGrab.grabclipboard()
            sleep(0.01)
            im.save('Picture.png')

if __name__ == "__main__":
    # 为了可以多次截图而不是截一次图就结束程序
    baidu_api = BaiDuAPI()

    for i in range(sys.maxsize):
        if i == 0:
            print("注意事项：请使用QQ的默认截图按键（Ctrl+alt+a）,截图完成后请敲击回车键完成截图!")
            print("截图完成后，你截取图片中的文字自动复制，您可自由粘贴！")
            print("现在开始截取你需要的图片吧！\n")
        else:
            print("您已成功截图，请截取下一张图！\n")
        screenShot()

        res = baidu_api.pictureText()
        print('截取的内容：' + res)

        GetText.setText(res)
        sleep(0.01)
        GetText.getText()


from typing import Type, Mapping, Dict, Collection
from hardsync.interfaces import Encoding, Exchange
from hardsync.types import FieldNotFoundError, ResponseValues, DecodedExchange, Stringable
from dataclasses import Field, fields

class AsciiEncoding(Encoding):
    argument_delimiter = ','
    argument_beginner = '('
    argument_ender = ')'
    argument_assigner = '='
    exchange_terminator = "\n"

    @staticmethod
    def encode(exchange: Type[Exchange], values: Mapping[str, Stringable | str], is_request=True) -> bytes:
        encoded_args = AsciiEncoding._encode_args(exchange=exchange, values=values)
        if is_request:
            r = 'Request'
        else:
            r = 'Response'
        encoded_function = exchange.identifier() + r
        encoded_string = encoded_function + '(' + encoded_args + ')' + AsciiEncoding.exchange_terminator
        return encoded_string.encode('ascii')

    @staticmethod
    def decode(exchange: Type[Exchange], contents: bytes) -> DecodedExchange:
        decoded_str = contents.decode('ascii')
        decoded_args = AsciiEncoding._decode_args(contents=decoded_str, exchange=exchange)
        decoded_name = AsciiEncoding._decode_name(contents=decoded_str)
        return DecodedExchange(name=decoded_name, values=decoded_args)

    @staticmethod
    def _encode_args(exchange: Type[Exchange], values: Mapping[str, Stringable | str]) -> str:
        encoded_args = ''
        for key, val in values.items():
            encoded_args += f'{key}{AsciiEncoding.argument_assigner}{val}{AsciiEncoding.argument_delimiter}'
        encoded_args = encoded_args.removesuffix(AsciiEncoding.argument_delimiter)
        return encoded_args

    @staticmethod
    def _arg_string(contents: str) -> str:
        start = contents.index(AsciiEncoding.argument_beginner)
        stop = contents.index(AsciiEncoding.argument_ender)
        return contents[start+1:stop]

    @staticmethod
    def _decode_args(exchange: Type[Exchange], contents: str, request=True) -> Dict[str, Stringable | str]:
        inner_string = AsciiEncoding._arg_string(contents=contents)
        args = inner_string.split(AsciiEncoding.argument_delimiter) if inner_string else []
        values = {}
        if request:
            decode_fields = fields(exchange.Request)
        else:
            decode_fields = fields(exchange.Response)

        for arg in args:
            key, value = arg.split(AsciiEncoding.argument_assigner)
            target_type = AsciiEncoding._lookup_field_type(name=key, available_fields=decode_fields)
            values[key] = target_type(value)

        return values

    @staticmethod
    def _lookup_field_type(name: str, available_fields: Collection[Field]):
        for field in available_fields:
            if field.name == name:
                return field.type
        raise FieldNotFoundError('Could not find field {name} in exchange')

    @staticmethod
    def _decode_name(contents: str) -> str:
        end = contents.index(AsciiEncoding.argument_beginner)
        return contents[:end]


from conn import create_db_conn

conn = create_db_conn()
cursor = conn.cursor()

# ! NB: convention for tbl and col names in DB
# 1. lowercase
# 2. snake case
# 3. start names with alphabets
cursor.execute(
    """
    CREATE TABLE traffic_weather_comb (
    call_timestamp varchar,
    cam_id int,
    direction int,
    compass varchar,
    two_hr_forecast_area varchar,
    non_rainfall_station_id varchar,
    rainfall_station_id varchar,
    rainfall_realtime float,
    wind_speed_realtime float,
    wind_dir_realtime float,
    humidity_realtime float,
    air_temp_realtime float,
    two_hr_forecast_value varchar,
    four_day_wind_speed_low_1 int,
    four_day_wind_direction_1 varchar,
    four_day_relative_humidity_high_1 int,
    four_day_temperature_high_1 int,
    four_day_wind_speed_high_1 int,
    four_day_temperature_low_1 int,
    four_day_forecast_1 varchar,
    four_day_relative_humidity_low_1 int,
    four_day_wind_speed_low_2 int,
    four_day_wind_direction_2 varchar,
    four_day_relative_humidity_high_2 int,
    four_day_temperature_high_2 int,
    four_day_wind_speed_high_2 int,
    four_day_temperature_low_2 int,
    four_day_forecast_2 varchar,
    four_day_relative_humidity_low_2 int,
    four_day_wind_speed_low_3 int,
    four_day_wind_direction_3 varchar,
    four_day_relative_humidity_high_3 int,
    four_day_temperature_high_3 int,
    four_day_wind_speed_high_3 int,
    four_day_temperature_low_3 int,
    four_day_forecast_3 varchar,
    four_day_relative_humidity_low_3 int,
    four_day_wind_speed_low_4 int,
    four_day_wind_direction_4 varchar,
    four_day_relative_humidity_high_4 int,
    four_day_temperature_high_4 int,
    four_day_wind_speed_high_4 int,
    four_day_temperature_low_4 int,
    four_day_forecast_4 varchar,
    four_day_relative_humidity_low_4 int,
    twenty_four_hr_start varchar,
    twenty_four_hr_end varchar,
    twenty_four_hr_general_forecast varchar,
    twenty_four_hr_general_relative_humidity_low int,
    twenty_four_hr_general_relative_humidity_high int,
    twenty_four_hr_general_temperature_low int,
    twenty_four_hr_general_temperature_high int,
    twenty_four_hr_general_wind_speed_low int,
    twenty_four_hr_general_wind_speed_high int,
    twenty_four_hr_general_wind_direction varchar,
    twenty_four_hr_period_1_start varchar,
    twenty_four_hr_period_1_end varchar,
    twenty_four_hr_period_1 varchar,
    twenty_four_hr_period_2_start varchar,
    twenty_four_hr_period_2_end varchar,
    twenty_four_hr_period_2 varchar,
    twenty_four_hr_period_3_start varchar,
    twenty_four_hr_period_3_end varchar,
    twenty_four_hr_period_3 varchar,
    trafficcongestion varchar,
    PRIMARY KEY(call_timestamp,cam_id,direction)
    )
  """
)

cursor.close()
conn.close()


"""Xbox"""
def main(num):
    """print xbox"""
    for row in range(num):
        for col in range(num):
            if (row == col) or (col == (num - 1) - row) or (row == 0)\
                or (col == 0) or (row == num - 1) or (col == num - 1):
                print("*", end=" ")
            else:
                print(" ", end=" ")
        print()
main(int(input()))


class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        if not nums:
            return []

        result=[0 for i in range(len(nums))]

        result[0]=1

        for i in range(1,len(nums)):
            result[i]=result[i-1]*nums[i-1]

        right=1
        for j in range(len(nums)-1,-1,-1):
            result[j]=result[j]*right
            right*=nums[j]

        return result


# -*- coding: utf-8 -*-
"""
Created on Tue Mar 27 16:06:26 2018

@author: CarlosABG
"""

import pandas as pd
import os

# FUNCTION

class ChangeSIH:

    def walk(path):
        FILES = []
        for root, dirs, files in os.walk(path, topdown=False):
            for name in files:
                if name[-4:] == '.csv':
                  FILES.append(os.path.join(root, name))
        return FILES

    def transform(path, cid_list):
        DF = pd.read_csv(path, encoding='latin', low_memory=False)

        LIST = [col for col in DF.columns if col.startswith('DIAG')]

        for group in LIST:
            try:
                DF[group] = [str(item) for item in DF[group]]
                vec = []
                for item in DF[group]:
                    if len(item) < 3:
                        vec.append(item)
                    else:
                        vec.append(item[0:3])
                DF['CID_' + group] = vec
            except:
                continue

        MASK = [col for col in DF if col.startswith('CID_')]
        DF_MASK = DF[MASK]

        DF['CID'] = (DF_MASK[MASK].isin(guns_cid_list).sum(axis=1) > 0)

        DF = DF[DF['CID'] == True]

        return DF

    def loop(path, cid_list):
        FILES = ChangeSIH.walk(path)

        DF = pd.DataFrame()
        for file in FILES:
            print('Processando: ' + os.path.basename(file) + '...')
            tempframe = ChangeSIH.transform(file, cid_list)
            if len(tempframe) > 0:
                DF = DF.append(tempframe)

        return DF

    def consolidate(path):
        files = ChangeSIH.walk(path)

        df = pd.DataFrame()
        for file in files:
            print('Processando: ' + os.path.basename(file) + '...')
            tdf = pd.read_csv(file, sep=";", decimal=",", low_memory=False, encoding='latin1')
            tdf = tdf.groupby('ESTADO').agg({
                    'VAL_TOT': 'sum',
                    'CID': 'count',
                    'ANO_CMPT': 'mean',
                    'IDADE': 'mean'
                    }
                    )
            df = df.append(tdf)
        return df

METHOD = 'CONSOLIDATE'

if METHOD == 'TRANSFORM':
    PATH = r'H:\Notas Conceituais\SegPub-Drogas\Dados\Datasus\sih\csv 1996-2015\99'
    RESULT = r'H:\Notas Conceituais\SegPub-Drogas\Dados\Datasus\sih\results'
    CID_SAMPLE = [
            'Y24',
            'W34',
            ] + \
            ['X' + str(i) for i in range(85,100)] + \
            ['Y0' + str(i) for i in range(0,10)]

    DF = ChangeSIH.loop(PATH, CID_SAMPLE)
    DF['ESTADO'] = [int(str(item)[0:2]) for item in DF['UF_ZI']]
    DF.to_csv(RESULT + '\consolidado96.csv', sep=";", decimal=",")
    ESTADOS = DF.groupby('ESTADO').sum()['VAL_TOT']

elif METHOD == 'CONSOLIDATE':
    PATH = r'H:\Notas Conceituais\SegPub-Drogas\Dados\Datasus\sih\results'
    RESULT = r'H:\Notas Conceituais\SegPub-Drogas\Dados\Datasus\sih\results'

    ESTADOS = ChangeSIH.consolidate(PATH)
    BRASIL = ESTADOS.groupby('ANO_CMPT').agg({
            'CID': 'sum',
            'VAL_TOT': 'sum',
            'IDADE': 'mean'
            }).reset_index(drop=False)
    BRASIL.to_csv(RESULT + '\consolidado_nacional.csv', decimal=",", sep=";")

    ESTADOS = ESTADOS.reset_index(drop=False).sort_values(['ANO_CMPT','ESTADO'])
    ESTADOS.to_csv(RESULT + '\consolidado_estadual.csv', decimal=",", sep=";")