from random import randrange

board = [
    [" ", " ", " "],
    [" ", " ", " "],
    [" ", " ", " "]
]

def print_board():
    print("  +---+---+---+")
    print(str(2) + " | " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " |")
    print("  +---+---+---+")
    print(str(1) + " | " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " |")
    print("  +---+---+---+")
    print(str(0) + " | " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " |")
    print("  +---+---+---+")
    print("    0   1   2")

def check_row(row):
    return (board[row][0] == board[row][1] and board[row][1] == board[row][2]) and board[row][0] != " "

def check_column(col):
    return (board[0][col] == board[1][col] and board[1][col] == board[2][col]) and board[0][col] != " "

def check_diagonals():
    return ((board[0][0] == board[1][1] and board[1][1] == board[2][2]) and board[0][0] != " ") or \
           (board[2][0] == board[1][1] and board[1][1] == board[0][2]) and board[2][0] != " "

def computer_moves(level):
    def danger_sequence(sequence):
        xs = 0
        empty = None
        for sq in sequence:
            if board[sq[0]][sq[1]] == "X":
                xs += 1
            elif board[sq[0]][sq[1]] == " ":
                empty = sq

        if xs == 2 and empty is not None:
            return empty
        return None

    def danger():
        for i in range(3):
            row = [(i,j) for j in range(3)]
            sq = danger_sequence(row)
            if sq is not None:
                return sq
            # if it is none then no danger at all!
        for j in range(3):
            col = [(i,j) for i in range(3)]
            sq = danger_sequence(col)
            if sq is not None:
                return sq

        sq = danger_sequence([(0,0),(1,1),(2,2)])
        if sq is not None:
            return sq

        sq = danger_sequence([(0,2),(1,1),(2,0)])
        if sq is not None:
            return sq

    #easy level with random moves
    if level == 1:
        squares = []
        for i in range(3):
            for j in range(3):
                if board[i][j] == " ":
                    squares += [(i,j)]

        return squares[randrange(len(squares))]

    #hard level by applying an algorithm
    else: # hard
        sq = danger()
        if sq is not None:
            return sq
        elif board[1][1] == " ":
            return (1,1)
        else:
            corner_squares = [(0,0), (0,2), (2,0), (2,2)]
            empty_squares = []
            for sq in corner_squares:
                if board[sq[0]][sq[1]] == " ":
                    empty_squares += [sq]
            if empty_squares:
                return empty_squares[randrange(len(empty_squares))]

            middle_squares = [(0,1), (1,0), (1,2), (2,1)]
            empty_squares = []
            for sq in middle_squares:
                if board[sq[0]][sq[1]] == " ":
                    empty_squares += [sq]
            if empty_squares:
                return empty_squares[randrange(len(empty_squares))]

def main():
    level = input("Choose level. 1-easy. 2-hard : ")
    while level not in ["1","2"]:
        level = input("[1-2] please.. : ")

    player = "O"
    for _ in range(9):
        # print board
        print_board()
        # choose next player
        if player == "X":
            player = "O"
        else:
            player = "X"

        # user input
        while player == "X":
            print("Player " + player + " plays! ")
            row = int(input("Give row: "))
            col = int(input("Give column: "))

            if row < 0 or row > 2:
                print("Row out of bounds. Pick[0-2]. ")
                continue
            elif col < 0 or col > 2:
                print("Column out of bounds. Pick[0-2].")
                continue
            elif board[row][col]!=" ":
                print("Pick an empty box please!")
                continue
            else:
                board[row][col] = player
                break

        if player == "O":
            # square coordinates of computer
            sq = computer_moves(level)
            board[sq[0]][sq[1]] = "O"

        # check winner
        winner = False
        #rows
        if check_row(0):
            winner = player
        elif check_row(1):
            winner = player
        elif check_row(2):
            winner = player
        #columns
        elif check_column(0):
            winner = player
        elif check_column(1):
            winner = player
        elif check_column(2):
            winner = player
        #diagonals

        elif (board[0][0] == board[1][1] and board[1][1] == board[2][2]) and board[0][0] != " ":
            winner = player
        elif (board[2][0] == board[1][1] and board[1][1] == board[0][2]) and board[2][0] != " ":
            winner = player

        if not winner:
            if check_diagonals():
                winner = player

        if winner:
            print_board()
            print(f'Player {player} Won!')
            break

    else:
        print_board()
        print("Isopalia! ")

main()


# Author: Le Anh Tuan (latuannetnam@gmail.com)
# Letcode problem: https://leetcode.com/problems/longest-common-prefix/
# Level: medium
# Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".

# Input: strs = ["flower","flow","flight"]
# Output: "fl"

class Solution:
     def longestCommonPrefix(self, strs) -> str:
        minlen = len(strs[0])
        maxlen = 0
        for str in strs:
            minlen = min(minlen, len(str))
            maxlen = max(maxlen, len(str))
        print("min len:{} max len:{}".format(minlen, maxlen))

        prefix = ""
        prefix_len = minlen
        while prefix_len > 0:
            prefix_temp = strs[0][0:prefix_len]
            print("prefix_len:{} prefix temp:{}".format(prefix_len, prefix_temp))
            for str in strs:
                if str[0:prefix_len] != prefix_temp:
                    prefix_temp = ""
            if prefix_temp != "":
                prefix = prefix_temp
                break
            prefix_len -= 1

        return prefix

if __name__ == '__main__':

    solution = Solution()
    # strs = ["flower","flow","flight"]
    strs = ["dog","racecar","car"]
    print("Input:{} prefix:{}".format(strs, solution.longestCommonPrefix(strs)))


import numpy as np
import sys

def running_mean(x):
    cumsum = np.cumsum(x)
    return cumsum / np.arange(1, len(cumsum) + 1)

def predict(course, marks):
    N = len(marks)
    marks = running_mean(marks)
    xdata = np.arange(0, N)
    y_noise = 1 * np.random.normal(size=xdata.size)
    ydata = marks + y_noise
    p = np.poly1d(np.polyfit(xdata, ydata, 1))
    pred = p(N+1) + 15 + 2 * np.random.normal()
    pred = min(100, max(0, pred))
    return pred

if __name__ == '__main__':
    course = sys.argv[1]
    marks = [float(sys.argv[i]) for i in range(2, len(sys.argv))]
    if(predict(course, marks) >= 50 ):
        print("safe")
    else:
        print("risk")


from telethon import events, Button
import yt_dlp
from utils import Utils
from pathlib import Path

@events.register(events.NewMessage(pattern="/yt"))
async def yt_download(event):
    bot = event.client
    response = await bot.send_message(
        event.chat, message=" 📥 (testing purpose) Downloading... 📥"
    )
    msg = " ".join(event.text.split()[1:])
    if not len(msg):
        return await bot.edit_message(
            event.chat,
            message=response,
            text="❗Write the name of the song after the command❗\n"
            "(example: /yt despacito)",
        )
    url = Utils.get_url(msg)
    if "error" in msg:
        return await bot.edit_message(
            event.chat, message=response, text=f"{url}\n❌ An error occured ❌"
        )
    yt_dlp.YoutubeDL(Utils.ydl_opts).download([url])
    # get a list of all the files in tmp_song, and takes only the first one
    # Spoiler: there is only one file in it because yt_dl download
    # changes some characters sometimes (idk how it works)
    file_path = list(Path("tmp_song").rglob("*"))
    await bot.send_message(
        event.chat,
        file=file_path[0],
        buttons=bot.build_reply_markup(Button.url("🔗 YT link 🔗", url=url)),
    )
    await response.delete()
    [file.unlink() for file in file_path]  # clear ./tmp_song (debug reason)
    return


"""Collect Anatomy object.

Requires:
    context -> projectName

Provides:
    context -> anatomy (openpype.pipeline.anatomy.Anatomy)
"""

import pyblish.api
from openpype.pipeline import Anatomy, KnownPublishError

class CollectAnatomyObject(pyblish.api.ContextPlugin):
    """Collect Anatomy object into Context.

    Order offset could be changed to '-0.45'.
    """

    order = pyblish.api.CollectorOrder - 0.4
    label = "Collect Anatomy Object"

    def process(self, context):
        project_name = context.data.get("projectName")
        if project_name is None:
            raise KnownPublishError((
                "Project name is not set in 'projectName'."
                "Could not initialize project's Anatomy."
            ))

        context.data["anatomy"] = Anatomy(project_name)

        self.log.debug(
            "Anatomy object collected for project \"{}\".".format(project_name)
        )


# -*- coding: utf-8 -*-

import requests
import json

class AdminClient(object):

    def __init__(self, url, token):
        self.headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/x-www-form-urlencoded'}
        self.url = url.__add__('/api/admin')

    def createWebconfig(self, data):
        requestUrl = self.url.__add__('/webconfig/setting')
        print("requestUrl = " + requestUrl)
        print("data = " + data)
        response = requests.put(url=requestUrl,data=data,headers=self.headers)
        print(response.status_code)
        print(response.text)


# 위 앞 바닥 뒤 동 서
dice = [0,0,0,0,0,0]

# 동 서 북 남
dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]

def move(order):
    global dice, current_pos
    x, y = current_pos[0], current_pos[1]
    nx = x + dx[order-1]
    ny = y + dy[order-1]
    if nx < 0 or ny < 0 or nx >= n or ny >= m:
        return
    rotation(order)
    if board[nx][ny] == 0:
        board[nx][ny] = dice[2]
    else:
        dice[2] = board[nx][ny]
        board[nx][ny] = 0
    current_pos = (nx, ny)
    print(dice[0])
    return

def rotation(order):
    global dice
    if order == 1:
        dice[4], dice[2], dice[5], dice[0] = dice[0], dice[4], dice[2], dice[5]
    elif order == 2:
        dice[5], dice[0], dice[4], dice[2] = dice[0], dice[4], dice[2], dice[5]
    elif order == 3:
        dice[2], dice[1], dice[0], dice[3] = dice[3], dice[2], dice[1], dice[0]
    elif order == 4:
        dice[0], dice[1], dice[2], dice[3] = dice[3], dice[0], dice[1], dice[2]
    return

n, m, x, y, k = list(map(int, input().split(' ')))
board = []
for _ in range(n):
    data = list(map(int, input().split(' ')))
    board.append(data)
order = list(map(int, input().split(' ')))
current_pos = (x,y)

for k in order:
    move(k)


from cv2 import imread, imwrite, equalizeHist, adaptiveThreshold, waitKey
from cv2 import resize, imshow, IMREAD_GRAYSCALE, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY
import argparse

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--image_path", type=str, help="path to the image")
    parser.add_argument("-d", "--display", type=int, default=1,
                        help="whether showing the image after processing. (1 / 0). default is true. (optional)")
    parser.add_argument("-c", "--downsample", type=float,
                        help="the factor you want to shrink resolution of output. (optional)")
    return parser.parse_args()

def histeq(pic_path):
    image = imread(pic_path, IMREAD_GRAYSCALE)
    return equalizeHist(image)

def adaptive_thresholding(image, block_size, C):
    return adaptiveThreshold(image, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, block_size, C)

if __name__ == "__main__":
    args = get_args()
    histed_image = histeq(args.image_path)
    thresed_image = adaptive_thresholding(histed_image, 35, 20)
    if args.display:
        imshow("thresed_image", thresed_image)
        waitKey()

    if args.downsample:
        thresed_image = resize(thresed_image, (int(thresed_image.shape[1] // args.downsample),
                                   int(thresed_image.shape[0] // args.downsample)))
    imwrite("{}_1.jpg".format(args.image_path.split('.')[0]), thresed_image)


import numpy as np
import matplotlib.pyplot as plt

# function to create the square pulse
def square(t , T):
    f = np.logical_and( t <= T / 2.0 , t >= -T/2.0 )
    return f.astype('float')

N = 1024
n = np.arange(-N / 2.0, N / 2.0, 1)

# time axis
T = 4;
Tmax = 30.0
Dt = 2 * Tmax / N
t = n * Dt

# frequency axis
Df = 1.0 / (N * Dt)
f = n * Df

# signal in the time domain
x = square(t,T)

# signal in the frequency domain
X = Dt * np.fft.fftshift( np.fft.fft( np.fft.fftshift(x) ) )

# Analytical expression for the spectrum
X2= T * np.sinc( f * T )

# Plot results
plt.figure(1)
plt.xlabel('t [msec]')
plt.ylabel('x(t)')
plt.plot(t,x)

plt.figure(2)
plt.plot(t, X2, t, X, 'o')
plt.xlim(-3,3)
plt.legend(['analytical','numerical'])
plt.xlabel('f [kHz]')
plt.ylabel('X(f)')


import math
import os
import json
import numpy as np
import torch
from tensorboardX import SummaryWriter

import distributed
from models.reporter_ext import ReportMgr, Statistics
from others.logging import logger
from others.utils import test_rouge, rouge_results_to_str
from rouge_score import rouge_scorer
from tqdm import tqdm
from prepro.data_builder import BertData

def _tally_parameters(model):
    n_params = sum([p.nelement() for p in model.parameters()])
    return n_params

def build_trainer(args, device_id, model, optim):
    """
    Simplify `Trainer` creation based on user `opt`s*
    Args:
        opt (:obj:`Namespace`): user options (usually from argument parsing)
        model (:obj:`onmt.models.NMTModel`): the model to train
        fields (dict): dict of fields
        optim (:obj:`onmt.utils.Optimizer`): optimizer used during training
        data_type (str): string describing the type of data
            e.g. "text", "img", "audio"
        model_saver(:obj:`onmt.models.ModelSaverBase`): the utility object
            used to save the model
    """

    grad_accum_count = args.accum_count
    n_gpu = args.world_size

    if device_id >= 0:
        gpu_rank = int(args.gpu_ranks[device_id])
    else:
        gpu_rank = 0
        n_gpu = 0

    print('gpu_rank %d' % gpu_rank)

    tensorboard_log_dir = args.model_path

    writer = SummaryWriter(tensorboard_log_dir, comment="Unmt")

    report_manager = ReportMgr(args.report_every, start_time=-1, tensorboard_writer=writer)

    trainer = Trainer(args, model, optim, grad_accum_count, n_gpu, gpu_rank, report_manager)

    # print(tr)
    if (model):
        n_params = _tally_parameters(model)
        logger.info('* number of parameters: %d' % n_params)

    return trainer

class Trainer(object):
    """
    Class that controls the training process.

    Args:
            model(:py:class:`onmt.models.model.NMTModel`): translation model
                to train
            train_loss(:obj:`onmt.utils.loss.LossComputeBase`):
               training loss computation
            valid_loss(:obj:`onmt.utils.loss.LossComputeBase`):
               training loss computation
            optim(:obj:`onmt.utils.optimizers.Optimizer`):
               the optimizer responsible for update
            trunc_size(int): length of truncated back propagation through time
            shard_size(int): compute loss in shards of this size for efficiency
            data_type(string): type of the source input: [text|img|audio]
            norm_method(string): normalization methods: [sents|tokens]
            grad_accum_count(int): accumulate gradients this many times.
            report_manager(:obj:`onmt.utils.ReportMgrBase`):
                the object that creates reports, or None
            model_saver(:obj:`onmt.models.ModelSaverBase`): the saver is
                used to save a checkpoint.
                Thus nothing will be saved if this parameter is None
    """

    def __init__(self, args, model, optim,
                 grad_accum_count=1, n_gpu=1, gpu_rank=1,
                 report_manager=None):
        # Basic attributes.
        self.args = args
        self.save_checkpoint_steps = args.save_checkpoint_steps
        self.model = model
        self.optim = optim
        self.grad_accum_count = grad_accum_count
        self.n_gpu = n_gpu
        self.gpu_rank = gpu_rank
        self.report_manager = report_manager

        self.loss = torch.nn.BCELoss(reduction='none')
        assert grad_accum_count > 0
        # Set model in training mode.
        if (model):
            self.model.train()

    def train(self, train_iter_fct, train_steps, valid_iter_fct=None, valid_steps=-1):
        """
        The main training loops.
        by iterating over training data (i.e. `train_iter_fct`)
        and running validation (i.e. iterating over `valid_iter_fct`

        Args:
            train_iter_fct(function): a function that returns the train
                iterator. e.g. something like
                train_iter_fct = lambda: generator(*args, **kwargs)
            valid_iter_fct(function): same as train_iter_fct, for valid data
            train_steps(int):
            valid_steps(int):
            save_checkpoint_steps(int):

        Return:
            None
        """
        logger.info('Start training...')

        # step =  self.optim._step + 1
        step = self.optim._step + 1
        true_batchs = []
        accum = 0
        normalization = 0
        train_iter = train_iter_fct()

        total_stats = Statistics()
        report_stats = Statistics()
        self._start_report_manager(start_time=total_stats.start_time)

        while step <= train_steps:

            reduce_counter = 0
            for i, batch in enumerate(train_iter):
                if self.n_gpu == 0 or (i % self.n_gpu == self.gpu_rank):

                    true_batchs.append(batch)
                    normalization += batch.batch_size
                    accum += 1
                    if accum == self.grad_accum_count:
                        reduce_counter += 1
                        if self.n_gpu > 1:
                            normalization = sum(distributed
                                                .all_gather_list
                                                (normalization))

                        self._gradient_accumulation(
                            true_batchs, normalization, total_stats,
                            report_stats)

                        report_stats = self._maybe_report_training(
                            step, train_steps,
                            self.optim.learning_rate,
                            report_stats)

                        true_batchs = []
                        accum = 0
                        normalization = 0
                        if (step % self.save_checkpoint_steps == 0 and self.gpu_rank == 0):
                            self._save(step)

                        step += 1
                        if step > train_steps:
                            break
            train_iter = train_iter_fct()

        return total_stats

    def validate(self, valid_iter, step=0):
        """ Validate model.
            valid_iter: validate data iterator
        Returns:
            :obj:`nmt.Statistics`: validation loss statistics
        """
        # Set model in validating mode.
        self.model.eval()
        stats = Statistics()

        with torch.no_grad():
            for batch in valid_iter:
                src = batch.src
                labels = batch.src_sent_labels
                segs = batch.segs
                clss = batch.clss
                mask = batch.mask_src
                mask_cls = batch.mask_cls
                sentence_rhetorical_roles = batch.sentence_rhetorical_roles

                sent_scores, mask = self.model(src, segs, clss, mask, mask_cls,sentence_rhetorical_roles)

                loss = self.loss(sent_scores, labels.float())
                loss = (loss * mask.float()).sum()
                batch_stats = Statistics(float(loss.cpu().data.numpy()), len(labels))
                stats.update(batch_stats)
            self._report_step(0, step, valid_stats=stats)
            return stats

    def test(self, test_iter, step, cal_lead=False, cal_oracle=False):
        """ Validate model.
            valid_iter: validate data iterator
        Returns:
            :obj:`nmt.Statistics`: validation loss statistics
        """

        # Set model in validating mode.
        def _get_ngrams(n, text):
            ngram_set = set()
            text_length = len(text)
            max_index_ngram_start = text_length - n
            for i in range(max_index_ngram_start + 1):
                ngram_set.add(tuple(text[i:i + n]))
            return ngram_set

        def _block_tri(c, p):
            tri_c = _get_ngrams(3, c.split())
            for s in p:
                tri_s = _get_ngrams(3, s.split())
                if len(tri_c.intersection(tri_s)) > 0:
                    return True
            return False

        if (not cal_lead and not cal_oracle):
            self.model.eval()
        stats = Statistics()
        sent_score_labels = []
        file_chunk_sent_scores={} ## key is filename and value is list of sentences containing sentence scores
        can_path = '%s_step%d.candidate' % (self.args.result_path, step)
        gold_path = '%s_step%d.gold' % (self.args.result_path, step)
        summaries_folder = self.args.result_path + '/predicted_summaries/'
        if not os.path.exists(summaries_folder):
            os.makedirs(summaries_folder)
        sent_scores_path = '%s_step%d_sent_scores.pt' % (self.args.result_path, step)
        with open(can_path, 'w') as save_pred:
            with open(gold_path, 'w') as save_gold:
                with torch.no_grad():
                    for batch in test_iter:
                        src = batch.src
                        labels = batch.src_sent_labels
                        segs = batch.segs
                        clss = batch.clss
                        mask = batch.mask_src
                        mask_cls = batch.mask_cls
                        unique_ids = batch.unique_ids
                        sentence_rhetorical_roles = batch.sentence_rhetorical_roles

                        gold = []
                        pred = []
                        ids = []

                        if (cal_lead):
                            selected_ids = [list(range(batch.clss.size(1)))] * batch.batch_size
                        elif (cal_oracle):
                            selected_ids = [[j for j in range(batch.clss.size(1)) if labels[i][j] == 1] for i in
                                            range(batch.batch_size)]
                        else:
                            sent_scores, mask = self.model(src, segs, clss, mask, mask_cls,sentence_rhetorical_roles)

                            loss = self.loss(sent_scores, labels.float())
                            loss = (loss * mask.float()).sum()
                            batch_stats = Statistics(float(loss.cpu().data.numpy()), len(labels))
                            stats.update(batch_stats)

                            sent_scores = sent_scores.cpu().data.numpy()
                            file_name,chunk_id = batch.unique_ids[0].split('___')
                            chunk_id = int(chunk_id)
                            src_labels = list(labels.cpu().numpy()[0])
                            if type(sent_scores[0]) == np.float32:
                                sent_scores = np.array([sent_scores])
                            sent_scores_list = list(sent_scores[0])
                            sent_rhetorical_roles_list = list(sentence_rhetorical_roles.cpu().data.numpy()[0])
                            for sent_id,(sent_txt,sent_label,sent_score,sent_rhet_role) in enumerate(zip(batch.src_str[0],src_labels,sent_scores_list,sent_rhetorical_roles_list)):
                                if file_chunk_sent_scores.get(file_name) is None:
                                    file_chunk_sent_scores[file_name]=[]
                                sent_dict = {'file_name':file_name,'chunk_id':chunk_id,'sent_id':sent_id,'sent_txt':sent_txt,
                                             'sent_score':sent_score,'sent_label':sent_label,'sent_rhetorical_role':sent_rhet_role}
                                file_chunk_sent_scores[file_name].append(sent_dict)

        lawbriefs_summary_map = {1:"facts",2:"facts",3:"arguments",4:"arguments",
                                 5:"issue",6:"ANALYSIS",7:'ANALYSIS',
                                    8:'ANALYSIS',9:'ANALYSIS',10:'decision',11:'decision'}##### keys are baseline rhetorical roles and values are LawBriefs roles
        lawbriefs_categories =["PREAMBLE",'facts','issue','arguments','ratio','decision']
        predicted_categories = ['facts','issue','arguments','ANALYSIS','decision']
        additional_mandaroty_categories = ['issue','decision']

        def create_concatenated_summaries(file_chunk_sent_scores):
            #### this function accepts the sentence scores and returns predicted and gold summary texts
            predicted_summaries = []
            gold_summaries = []
            predicted_summaries_rr = []
            rr_summaries=[]
            for file_name,sent_list in file_chunk_sent_scores.items():

                if self.args.use_rhetorical_roles and self.args.seperate_summary_for_each_rr:
                    # ######## take top N sentences for each rhetorical role
                    file_rr_sents ={} ##### keys are rhetorical roles and values are dict of {'sentences':[],'token_cnt':100}
                    for sent_dict in sent_list:
                        sent_token_cnt = len(sent_dict['sent_txt'].split())
                        sent_rr= lawbriefs_summary_map[sent_dict['sent_rhetorical_role']]
                        if file_rr_sents.get(sent_rr) is None:
                            file_rr_sents[sent_rr] = {'sentences':[sent_dict],'token_cnt':sent_token_cnt}
                        else:
                            file_rr_sents[sent_rr]['sentences'].append(sent_dict)
                            file_rr_sents[sent_rr]['token_cnt']+=sent_token_cnt

                    min_token_cnt_per_rr = 50 ######## if original text for a rhetorical role is below this then it is not summarized.
                    selected_sent_list=[]
                    for rr,sentences_dict in file_rr_sents.items():
                        if sentences_dict['token_cnt']<=min_token_cnt_per_rr:
                            selected_sent_list.extend(sentences_dict['sentences'])
                        else:
                            rr_sorted_sent_list = sorted(sentences_dict['sentences'], key=lambda x: x['sent_score'], reverse=True)
                            sents_to_keep = math.ceil(self.args.summary_sent_precent * len(sentences_dict['sentences']) / 100)
                            rr_selected_sent = rr_sorted_sent_list[:sents_to_keep]
                            rr_selected_sent = sorted(rr_selected_sent, key=lambda x: (x['chunk_id'], x['sent_id']))
                            selected_sent_list.extend(rr_selected_sent)

                else:
                    ######### take top N sentences by combining all the rhetorical roles
                    sent_list = sorted(sent_list,key =lambda x: x['sent_score'],reverse=True)
                    sents_to_keep = math.ceil(self.args.summary_sent_precent * len(sent_list)/100)
                    selected_sent_list = sent_list[:sents_to_keep]
                    selected_sent_list = sorted(selected_sent_list,key = lambda x: (x['chunk_id'],x['sent_id']))

                predicted_summary='' ###### to be used  for rouge  calculation
                predicted_summary_rr = {} ## keys are rhetorical role and values are concatenated sentences
                ## create predicted summary
                rhetorical_roles_in_test = list(set([lawbriefs_summary_map[i['sent_rhetorical_role']] for i in selected_sent_list if i['sent_label']==1]))
                for sent_dict in selected_sent_list:
                    if self.args.rogue_exclude_roles_not_in_test and self.args.use_rhetorical_roles:
                        #########  if the selected sentence has rhetorical role not in test then exclude it
                        if lawbriefs_summary_map[sent_dict['sent_rhetorical_role']] in rhetorical_roles_in_test:
                            if predicted_summary=='':
                                predicted_summary = sent_dict['sent_txt']
                            else:
                                predicted_summary = predicted_summary + '\n' + sent_dict['sent_txt']
                    else:
                        if predicted_summary == '':
                            predicted_summary = sent_dict['sent_txt']
                        else:
                            predicted_summary = predicted_summary + '\n' + sent_dict['sent_txt']

                    sent_lawbriefs_role= lawbriefs_summary_map[sent_dict['sent_rhetorical_role']]
                    if predicted_summary_rr.get(sent_lawbriefs_role) is None:
                        predicted_summary_rr[sent_lawbriefs_role] = sent_dict['sent_txt']
                    else:
                        predicted_summary_rr[sent_lawbriefs_role] = predicted_summary_rr[sent_lawbriefs_role] + '\n' +sent_dict['sent_txt']

                ######## copy the additional mandatory roles to summary
                if self.args.use_rhetorical_roles and self.args.add_additional_mandatory_roles_to_summary and not self.args.seperate_summary_for_each_rr :
                    sent_list = sorted(sent_list,key = lambda x: (x['chunk_id'],x['sent_id']))
                    for category in additional_mandaroty_categories:
                        category_sentences = [i for i in sent_list if lawbriefs_summary_map[i['sent_rhetorical_role']]==category]
                        if category_sentences:
                            if predicted_summary_rr.get(category) is not None:
                                ###### remove the category as it may not have all the sentences.
                                predicted_summary_rr.pop(category)
                            for cat_sent in category_sentences:
                                if predicted_summary_rr.get(category) is None:
                                    predicted_summary_rr[category] = cat_sent['sent_txt']
                                else:
                                    predicted_summary_rr[category] = predicted_summary_rr[category] + '\n' + \
                                                                                cat_sent['sent_txt']

                predicted_summaries.append(predicted_summary)

                ## create gold summary
                gold_summary = ''
                gold_summary_rr = {}
                sent_list = sorted(sent_list, key=lambda x: (x['chunk_id'],x['sent_id']))
                for sent_dict in sent_list:
                    if sent_dict['sent_label']==1:
                        if gold_summary=='':
                            gold_summary = sent_dict['sent_txt']
                        else:
                            gold_summary = gold_summary + '\n' + sent_dict['sent_txt']

                        sent_lawbriefs_role = lawbriefs_summary_map[sent_dict['sent_rhetorical_role']]
                        if gold_summary_rr.get(sent_lawbriefs_role) is None:
                            gold_summary_rr[sent_lawbriefs_role] = sent_dict['sent_txt']
                        else:
                            gold_summary_rr[sent_lawbriefs_role] = gold_summary_rr[sent_lawbriefs_role] + '\n' + sent_dict['sent_txt']
                gold_summaries.append(gold_summary)

                rr_summaries.append({'predicted_summary':predicted_summary_rr , 'gold_summary':gold_summary_rr ,'file_name':file_name})
            return predicted_summaries,gold_summaries,rr_summaries

        torch.save(sent_score_labels, sent_scores_path)

        final_candidate,final_gold,rr_summaries = create_concatenated_summaries(file_chunk_sent_scores)

        print('********* Writing summaries to ', summaries_folder)

        ##### try to read original summaries

        original_summaries_path = os.path.split(self.args.bert_data_path)[0]+'/lawbriefs_summary_fulltext_map.json'

        if os.path.exists(original_summaries_path):
            original_summaries = json.load(open(original_summaries_path))
        else:
            original_summaries=[]

        with open(summaries_folder + 'predicted_summaries.json', 'w') as file:
            json.dump(rr_summaries,file)
        for pred_summary in rr_summaries:
            summary_txt=''
            if original_summaries:
                summary_txt = summary_txt + '\n-------------- PREAMBLE --------------------------------\n'
                for original_summary in original_summaries:
                    if original_summary['file_name'] == pred_summary['file_name']:
                        if original_summary.get('PREAMBLE') is not None:
                            summary_txt = summary_txt + original_summary['PREAMBLE'] + '\n\n'
                        break

            summary_txt =summary_txt+'\n-------------- Predicted summary --------------------------------\n'

            for predicted_category in predicted_categories:
                if pred_summary['predicted_summary'].get(predicted_category) is not None:
                    summary_txt = summary_txt + '\n#############'+ predicted_category +' summary ################\n'
                    summary_txt = summary_txt + pred_summary['predicted_summary'].get(predicted_category) + '\n\n'

            summary_txt =summary_txt + '\n-------------- LawBrief mapped summary --------------------------------\n'
            for rr_lawbrief,rr_text in pred_summary['gold_summary'].items():
                summary_txt = summary_txt + '\n#############'+ rr_lawbrief +' summary ################\n'
                summary_txt = summary_txt + rr_text + '\n\n'

            with open(summaries_folder+os.path.splitext(pred_summary['file_name'])[0]+'.txt', 'w') as file:
                file.write(summary_txt.encode("ascii", "ignore").decode())

        def rouge(label_sent: list, pred_sent: list) -> dict:
            """Approximate ROUGE scores, always run externally for final scores."""
            scorer = rouge_scorer.RougeScorer(
                ["rouge1", "rouge2", "rougeLsum"],
                use_stemmer=True)
            r1, r2, rl = 0.0, 0.0, 0.0
            for ls, ps in tqdm(zip(label_sent, pred_sent), desc=f"Calculating scores on {len(label_sent)} labels",
                               total=len(label_sent)):
                score = scorer.score(ls, ps)
                r1 += score["rouge1"].fmeasure
                r2 += score["rouge2"].fmeasure
                rl += score["rougeLsum"].fmeasure
            result = {"eval_rouge-1": r1 / len(label_sent),
                      "eval_rouge-2": r2 / len(label_sent),
                      "eval_rouge-L": rl / len(label_sent)}
            return result

        if (step != -1 and self.args.report_rouge):
            # rouges = test_rouge(self.args.temp_dir, can_path, gold_path)
            rouges = rouge(final_gold,final_candidate)
            for key in rouges.keys():
                logger.info(f'{key}:{rouges[key]}')
        self._report_step(0, step, valid_stats=stats)

        return stats

    def _gradient_accumulation(self, true_batchs, normalization, total_stats,
                               report_stats):
        if self.grad_accum_count > 1:
            self.model.zero_grad()

        for batch in true_batchs:
            if self.grad_accum_count == 1:
                self.model.zero_grad()

            src = batch.src
            labels = batch.src_sent_labels
            segs = batch.segs
            clss = batch.clss
            mask = batch.mask_src
            mask_cls = batch.mask_cls
            sentence_rhetorical_roles = batch.sentence_rhetorical_roles

            sent_scores, mask = self.model(src, segs, clss, mask, mask_cls,sentence_rhetorical_roles)

            loss = self.loss(sent_scores, labels.float())
            loss = (loss * mask.float()).sum()
            (loss / loss.numel()).backward()
            # loss.div(float(normalization)).backward()

            batch_stats = Statistics(float(loss.cpu().data.numpy()), normalization)

            total_stats.update(batch_stats)
            report_stats.update(batch_stats)

            # 4. Update the parameters and statistics.
            if self.grad_accum_count == 1:
                # Multi GPU gradient gather
                if self.n_gpu > 1:
                    grads = [p.grad.data for p in self.model.parameters()
                             if p.requires_grad
                             and p.grad is not None]
                    distributed.all_reduce_and_rescale_tensors(
                        grads, float(1))
                self.optim.step()

        # in case of multi step gradient accumulation,
        # update only after accum batches
        if self.grad_accum_count > 1:
            if self.n_gpu > 1:
                grads = [p.grad.data for p in self.model.parameters()
                         if p.requires_grad
                         and p.grad is not None]
                distributed.all_reduce_and_rescale_tensors(
                    grads, float(1))
            self.optim.step()

    def _save(self, step):
        real_model = self.model
        # real_generator = (self.generator.module
        #                   if isinstance(self.generator, torch.nn.DataParallel)
        #                   else self.generator)

        model_state_dict = real_model.state_dict()
        # generator_state_dict = real_generator.state_dict()
        checkpoint = {
            'model': model_state_dict,
            # 'generator': generator_state_dict,
            'opt': self.args,
            'optim': self.optim,
        }
        checkpoint_path = os.path.join(self.args.model_path, 'model_step_%d.pt' % step)
        logger.info("Saving checkpoint %s" % checkpoint_path)
        # checkpoint_path = '%s_step_%d.pt' % (FLAGS.model_path, step)
        if (not os.path.exists(checkpoint_path)):
            torch.save(checkpoint, checkpoint_path)
            return checkpoint, checkpoint_path

    def _start_report_manager(self, start_time=None):
        """
        Simple function to start report manager (if any)
        """
        if self.report_manager is not None:
            if start_time is None:
                self.report_manager.start()
            else:
                self.report_manager.start_time = start_time

    def _maybe_gather_stats(self, stat):
        """
        Gather statistics in multi-processes cases

        Args:
            stat(:obj:onmt.utils.Statistics): a Statistics object to gather
                or None (it returns None in this case)

        Returns:
            stat: the updated (or unchanged) stat object
        """
        if stat is not None and self.n_gpu > 1:
            return Statistics.all_gather_stats(stat)
        return stat

    def _maybe_report_training(self, step, num_steps, learning_rate,
                               report_stats):
        """
        Simple function to report training stats (if report_manager is set)
        see `onmt.utils.ReportManagerBase.report_training` for doc
        """
        if self.report_manager is not None:
            return self.report_manager.report_training(
                step, num_steps, learning_rate, report_stats,
                multigpu=self.n_gpu > 1)

    def _report_step(self, learning_rate, step, train_stats=None,
                     valid_stats=None):
        """
        Simple function to report stats (if report_manager is set)
        see `onmt.utils.ReportManagerBase.report_step` for doc
        """
        if self.report_manager is not None:
            return self.report_manager.report_step(
                learning_rate, step, train_stats=train_stats,
                valid_stats=valid_stats)

    def _maybe_save(self, step):
        """
        Save the model if a model saver is set
        """
        if self.model_saver is not None:
            self.model_saver.maybe_save(step)


import pickle as pkl
from itertools import combinations

import networkx as nx
import numpy as np

def load_train_data(data_path: str, labels_path: str):
    """Creates two lists with train graphs and their corresponding labels.
    Args:
        data_path (str): Path to the pickle train file.
        labels_path (str): Path to the labels file

    Returns:
        tuple: Lists of nx.Graph elements and ints.
    """
    with open(data_path, "rb") as file:
        train_graphs = pkl.load(file)
    with open(labels_path, "rb") as file:
        train_labels = pkl.load(file)

    # Removes graphs with no edges
    N = len(train_graphs)
    no_edges = (np.array([g.number_of_edges() for g in train_graphs]) == 0).nonzero()[0]
    train_graphs = [train_graphs[el] for el in range(N) if el not in no_edges]
    train_labels = [train_labels[el] for el in range(N) if el not in no_edges]

    return train_graphs, train_labels

def list_nodes_and_labels(g):
    """
    Returns two lists of nodes and labels in graph g.
    """
    nodes = np.array(list(g.nodes()))
    labels = np.array([g[1]["labels"][0] for g in g.nodes(data=True)])
    return nodes, labels

def product_graph(g1, g2):
    """
    Computes the graph product between g1 and g2.
    """
    g1_nodes, g1_labels = list_nodes_and_labels(g1)
    g2_nodes, g2_labels = list_nodes_and_labels(g2)
    product_labels = set(g1_labels)
    product_labels.update(g2_labels)
    product = nx.Graph()
    for label in product_labels:
        g1_idx = (g1_labels == label).nonzero()[0]
        g2_idx = (g2_labels == label).nonzero()[0]

        # Does not add any node to the product graph if label is unique to one of them
        if not len(g2_idx) or not len(g2_idx):
            continue

        # Adds the nodes to the product graph
        for v1 in g1_nodes[g1_idx]:
            for v2 in g2_nodes[g2_idx]:
                product.add_node((v1, v2))

    # Connects the edges
    pairs = list(combinations(product.nodes, 2))
    for p in pairs:
        u, v = p  # Two nodes in the product graph
        u1, u2 = u  # in G1xG2
        v1, v2 = v  # in G1xG2
        if g1.has_edge(u1, v1) and g2.has_edge(u2, v2):
            product.add_edge(u, v)
    return product


from epsilon.extime import Time

from axiom.item import Item
from axiom.attributes import text, reference, integer, AND, timestamp

class Tag(Item):
    typeName = 'tag'
    schemaVersion = 1

    name = text(doc="""
    The short string which is being applied as a tag to an Item.
    """)

    created = timestamp(doc="""
    When this tag was applied to the Item to which it applies.
    """)

    object = reference(doc="""
    The Item to which this tag applies.
    """)

    catalog = reference(doc="""
    The L{Catalog} item in which this tag was created.
    """)

    tagger = reference(doc="""
    An optional reference to the Item which is responsible for this tag's
    existence.
    """)

class _TagName(Item):
    """
    Helper class to make Catalog.tagNames very fast.  One of these is created
    for each distinct tag name that is created.  _TagName Items are never
    deleted from the database.
    """
    typeName = 'tagname'

    name = text(doc="""
    The short string which uniquely represents this tag.
    """, indexed=True)

    catalog = reference(doc="""
    The L{Catalog} item in which this tag exists.
    """)

class Catalog(Item):

    typeName = 'tag_catalog'
    schemaVersion = 2

    tagCount = integer(default=0)

    def tag(self, obj, tagName, tagger=None):
        """
        """
        # check to see if that tag exists.  Put the object attribute first,
        # since each object should only have a handful of tags and the object
        # reference is indexed.  As long as this is the case, it doesn't matter
        # whether the name or catalog attributes are indexed because selecting
        # from a small set of results is fast even without an index.
        if self.store.findFirst(Tag,
                                AND(Tag.object == obj,
                                    Tag.name == tagName,
                                    Tag.catalog == self)):
            return

        # if the tag doesn't exist, maybe we need to create a new tagname object
        self.store.findOrCreate(_TagName, name=tagName, catalog=self)

        # Increment only if we are creating a new tag
        self.tagCount += 1
        Tag(store=self.store, object=obj,
            name=tagName, catalog=self,
            created=Time(), tagger=tagger)

    def tagNames(self):
        """
        Return an iterator of unicode strings - the unique tag names which have
        been applied objects in this catalog.
        """
        return self.store.query(_TagName, _TagName.catalog == self).getColumn("name")

    def tagsOf(self, obj):
        """
        Return an iterator of unicode strings - the tag names which apply to
        the given object.
        """
        return self.store.query(
            Tag,
            AND(Tag.catalog == self,
                Tag.object == obj)).getColumn("name")

    def objectsIn(self, tagName):
        return self.store.query(
            Tag,
            AND(Tag.catalog == self,
                Tag.name == tagName)).getColumn("object")

def upgradeCatalog1to2(oldCatalog):
    """
    Create _TagName instances which version 2 of Catalog automatically creates
    for use in determining the tagNames result, but which version 1 of Catalog
    did not create.
    """
    newCatalog = oldCatalog.upgradeVersion('tag_catalog', 1, 2,
                                           tagCount=oldCatalog.tagCount)
    tags = newCatalog.store.query(Tag, Tag.catalog == newCatalog)
    tagNames = tags.getColumn("name").distinct()
    for t in tagNames:
        _TagName(store=newCatalog.store, catalog=newCatalog, name=t)
    return newCatalog

from axiom.upgrade import registerUpgrader
registerUpgrader(upgradeCatalog1to2, 'tag_catalog', 1, 2)


import math

class Point:
    def __init__(self,m) -> None:

        pass
    def __init__(self,x,y=0,z=0) -> None:
        if isinstance(x, float):
            self.x = x
            self.y = y
            self.z = z
        else:
            self.x = x.x
            self.y = x.y
            self.z = x.z
        pass
    def __add__(self,other):
        return Point(self.x+other.x,self.y+other.y,self.z+other.z)

    def __sub__(self,other):
        return Point(self.x-other.x,self.y-other.y,self.z-other.z)
def get_normal(p1,p2,p3):
    u = p2-p1
    v = p3-p1
    n = ((u.y*v.z-u.z*v.y),(u.z*v.x-u.x*v.z),(u.x*v.y-u.y*v.x))
    nl=math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2])
    return (n[0]/nl,n[1]/nl,n[2]/nl)
def get_angle(n,v):
    v = (1,0,0)
    d = n[0]*v[0]+n[1]*v[1]+n[2]*v[2]
    return math.acos(d)*(180.0/math.pi)

import sys
def translation(M):
    return(M[0,3],M[1,3],M[2,3])
def rotation2euler(R):
    #https://www.meccanismocomplesso.org/en/3d-rotations-and-euler-angles-in-python/
    tolerance = sys.float_info.epsilon * 10

    if abs(R[0,0])< tolerance and abs(R[1,0]) < tolerance:
        eul1 = 0
        eul2 = math.atan2(-R[2,0], R[0,0])
        eul3 = math.atan2(-R[1,2], R[1,1])
    else:
        eul1 = math.atan2(R[1,0],R[0,0])
        sp = math.sin(eul1)
        cp = math.cos(eul1)
        eul2 = math.atan2(-R[2,0],cp*R[0,0]+sp*R[1,0])
        eul3 = math.atan2(sp*R[0,2]-cp*R[1,2],cp*R[1,1]-sp*R[0,1])

    return (eul1, eul2, eul3)


import logging,time,os
from common.seleniumError import SCENSEE,SCEECIE,SCEENVE
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from page.base import PageBase
from common.tools import switch_execute,swithToRightWeb

class PageRegisterWeb(PageBase):
	def __init__(self,driver):
		# web版 在线开户 页面
		super().__init__(driver)
		self.eleFlag=(By.CLASS_NAME,"progress-text")
		#第一步
		self.btnLoacltion=(By.ID,"login-mobcountry")
		self.editPhone=(By.NAME,"phone")
		self.btnGetcode=(By.XPATH,"//*[text()='获取验证码']")
		self.editSMScode=(By.NAME,"confirm_num")
		self.btnNext=(By.XPATH,"//*[text()='下一步']/../..")#下一步
		self.eleAlert=(By.XPATH,"//*[contains(text(),'过于频繁')]")#可能出现的 “短信验证码频繁”弹框
		self.eleAlertConf=(By.XPATH,"//*[contains(text(),'确认') or contains(text(),'确定')]")#确认弹框

		#第二步
		self.btnPI=(By.XPATH,"//*[contains(text(),'专业投资者')]/../../div[1]")
		self.btnAccMargin=(By.XPATH,"//*[contains(text(),'保证金账户')]/../../div[1]")#保证金账户
		self.btnCardType=(By.XPATH,"//*[contains(text(),'开户证件')]/..")#证件类型
		self.passport=(By.XPATH,"//*[text()='护照']")#护照
		self.btnReadme=(By.XPATH,"//*[contains(text(),'已阅读')]/../../div[1]")
		# self.btnNext1=(By.XPATH,"//*[@onclick='startOpening()']")
		self.input=(By.XPATH,"//input")#客户推荐号

		# 第三步
		self.editCardPic={'Android':(By.NAME,"front"),}
		try:self.editCardPic['iOS']=(By.IOS_PREDICATE,"name=='选取文件'")
		except AttributeError:pass
		self.editRealName=(By.NAME,"name_cn")
		self.editREnName=(By.NAME,"name_en")
		self.editCardId=(By.NAME,"card_id")
		# self.editBirthPlace=(By.NAME,"birth_place")
		self.btnBirthDay=(By.XPATH,"//*[contains(text(),'出生日期')]/../div[1]")
		self.btnBirthDayOK=(By.XPATH,"//*[text()='选择出生日期']/../../div[3]")
		self.cardExpire1=(By.CSS_SELECTOR,".starttime")
		self.starttimeOK=(By.XPATH,"//*[text()='选择开始日期']/../../div[3]")
		self.cardExpire2=(By.CSS_SELECTOR,".endtime")
		self.endtimeOK=(By.XPATH,"//*[text()='选择结束日期']/../../div[3]")
		self.editAddress=(By.ID,"address")
		self.editAddressPic={'Android':(By.XPATH,"//input[@name='address_certify']"),}
		try:self.editAddressPic['iOS']=(By.IOS_PREDICATE,"name=='选取文件'")
		except AttributeError:pass
		self.btnNext2=(By.XPATH,"//*[text()='下一步，个人信息']/../..")

		# 第四步
		self.editHomeTel=(By.XPATH,"//*[text()='住宅电话']/..//input[1]")
		self.editEmail=(By.NAME,"email")
		self.btnJobStatus=(By.XPATH,"//*[text()='工作状况']/..//div[1]")#工作状况
		self.workStatus=(By.XPATH,"//*[text()='在职']")
		self.btnJob=(By.XPATH,"//*[text()='职位']/..//div[1]")#
		self.normalemp=(By.XPATH,"//*[contains(text(),'一般员工')]")
		self.btnIndustry=(By.XPATH,"//*[text()='所属行业']/..//div[1]")#
		self.industry1=(By.XPATH,"//*[contains(text(),'农业')]")
		self.editCompanyName=(By.NAME,"com_name")#公司名称

		self.loseFoucs=(By.XPATH,"//*[contains(text(),'雇佣信息')]")
		# self.btnNext3=(By.XPATH,"//*[@onclick='personalInfo()']")
		self.btnCardBtnOk=(By.XPATH,"//*[contains(text(),'已确认')]")

		#第五步
		self.editPiPic=(By.XPATH,"//input[@name='pi_certify']")
		self.btnBackgroundInfo=(By.XPATH,"//*[text()='下一步，开通市场']/../..")
		# self.btnMarketChoose=(By.XPATH,"//*[@onclick='marketChoose()']")
		self.startPlay=(By.XPATH,"//*[text()='开始播放']/../..")
		self.btnNext4=(By.XPATH,"//*[text()='确认，下一步']/../..")
		self.btnNext5=(By.XPATH,"//*[contains(text(),'您已阅读')]/../../div[2]/div[2]")

		#第六步
		self.signType=(By.XPATH,"//*[text()='客户经理面签']/../..//label[1]")
		# self.btnAddHkNext=(By.ID,"addHk-next")
		self.editF2Fpic=(By.XPATH,"//input[@name='face2face_certify']")
		# self.btnNext6=(By.XPATH,"//*[@onclick='setAccountMethod()']")

		#第七步
		self.btnAgreeSign=(By.XPATH,"//*[text()='本人同意签署']/../../div[1]")
		self.btnSignTable=(By.XPATH,"//*[text()='开始签署表格']/../..")

		#第八步
		self.canvas=(By.XPATH,'//*[@resource-id="ttcanvas"]')
		self.canvas_web=(By.ID,"ttcanvas")
		self.btnPaperDone=(By.XPATH,"//*[text()='完成']/../..")

		self.eleMsg=(By.XPATH,"//*[contains(text(),'提交成功')]")

		# 衍生品问卷
		self.derivateANS=[
			"//*[text()='是']/../../div[1]",
			"(//*[text()='上述各项皆是']/../../div[1])[1]",
			"(//*[text()='上述各项皆是']/../../div[1])[2]",
			"(//*[text()='上述各项皆是']/../../div[1])[3]",
			"//*[text()='杠杆']/../../div[1]",
		]
		self.btnderTest=(By.XPATH,"//*[text()='下一步']/../..")

		# 简易投资问卷
		self.investment_ANS=[
			"//*[contains(text(),'积极增长')]/../../div[1]",
			"//*[contains(text(),'超过5年')]/../../div[1]",
			"//*[text()='股票']/../../div[1]",
			"//*[text()='期货' or text()='期貨']/../../div[1]",
		]
		# self.investment_next=(By.XPATH,"//*[text()='下一步']/../..")

		# 风险取向测评
		self.riskANS=[
			"//*[contains(text(),'24 个月或')]/../../div[1]",
			"//*[contains(text(),'25%或')]/../../div[1]",
			"//*[text()='超过 5 年']/../../div[1]",
			"(//*[contains(text(),'50%或')]/../../div[1])[1]",
			"(//*[contains(text(),'50%或')]/../../div[1])[2]",
			"//*[contains(text(),'积极增长')]/../../div[1]",
			"//*[contains(text(),'非保本')]/../div[1]"
		]
		self.btnYears=(By.XPATH,"//*[@name='q28_5_1']/../div[2]")#经验年期 5-10年
		self.btnTimes=(By.XPATH,"//*[@name='q28_5_2']/../div[2]")#近三年交易次数  5次或以上
		self.btnRpqTest=(By.XPATH,"//*[text()='下一步，测评结果']/../..")
		self.btnAccountMarket=(By.XPATH,"//*[text()='下一步，风险披露']/../..")

		self.continue_kaihu=(By.XPATH,"//*[text()='继续开户']/../..")

	def flag(self,msg='20'):
		pass
		# for i in range(5):
		# 	try:
		# 		text=self.findElement(self.eleFlag,20).text
		# 		if f'{msg}%' in text:return
		# 	except SCESERE:
		# 		pass

	#第一步
	def clickSwitchArea(self):
		logging.info(f'点击切换区号')
		self.findElement(self.btnLoacltion).click()

	def clickAreacode(self,area):
		areaNameDic={'zh_CN':'中国大陆','zh_HK':'中国香港'}
		areaName=areaNameDic[area]
		logging.info(f'点击区号 {areaName}')
		_xpath=(By.XPATH,f"//*[text()='{areaName}']")
		self.findElement(_xpath).click()

	def inputPhone(self,phone):
		logging.info(f'输入手机号 {phone}')
		self.findElement(self.editPhone).send_keys(phone)

	def clickGetcode(self):
		logging.info('点击 获取验证码')
		try:
			self.findElement(self.btnGetcode).click()
		except AttributeError:
			pass

	def clickConfirm(self,n=0):
		logging.info('点击 确认/确定')
		self.findElements(self.eleAlertConf,until='located')[n].click()

	def acceptAlert(self):
		time.sleep(1)
		if self.isEleExists(self.eleAlert,timeout=3):
			try:
				logging.info(f'{self.findElement(self.eleAlert,screen=0).text} ,等待 5 秒后重试')
			except AttributeError:
				return 0
			time.sleep(5)
			self.findElement(self.eleAlertConf).click()
			time.sleep(1)
			return 1
		else:
			return 0

	def inputSMScode(self,code):
		logging.info(f'输入验证码 {code}')
		self.findElement(self.editSMScode).send_keys(code)

	def clickNext(self):
		logging.info('点击 下一步')
		from common.seleniumError import SCEECIE
		for i in range(3):
			try:
				time.sleep(2)
				self.findElement(self.btnNext).click()
				return
			except SCEECIE:
				pass

	#第二步
	def clickPI(self):
		logging.info('点击 专业投资者PI')
		self.findElement(self.btnPI).click()

	def clickAccMargin(self):
		logging.info('点击勾选 保证金账户')
		self.findElement(self.btnAccMargin).click()

	def selectCardType(self):
		logging.info('选择证件类型 护照')
		self.findElement(self.btnCardType).click()
		time.sleep(0.5)
		self.findElement(self.passport).click()
		# Select(self.findElement(self.btnCardType)).select_by_visible_text("护照")

	def clickReadme(self):
		logging.info('点击勾选已读')
		ele=self.findElement(self.btnReadme)
		self.driver.execute_script("arguments[0].scrollIntoView();",ele)
		for i in range(5):
			try:
				ele.click()
				break
			except SCEECIE:
				if i==4:raise SCEECIE
				time.sleep(1)

	def inputAecode(self,aecode):
		logging.info(f'输入aecode: {aecode}')
		self.findElement(self.input).send_keys(aecode)

	def clickNext1(self):
		logging.info('点击 下一步')
		self.findElement(self.btnNext).click()

	def clickContinue(self):
		logging.info('点击 继续开户')
		self.findElement(self.continue_kaihu).click()

	# 第三步
	@switch_execute
	def clickCardPic_IOS(self):
		self.findElement(self.editCardPic[self.PFN]).click()

	def clickCardPic(self):
		logging.info(f'点击上传证件图片')
		if self.PFN=='Android':
			self.findElement(self.editCardPic[self.PFN],until='located').click()
		else:
			self.clickCardPic_IOS()

	def inputCardPic(self,pathToPic):
		logging.info(f'上传证件图片')
		# print('debug:',pathToPic)
		self.waitTo(way='NAME',name=self.editCardPic[self.PFN][1],operate='send_keys',value=pathToPic)

	def inputRealName(self,realName):
		logging.info(f'输入 真实姓名 {realName}')
		self.findElement(self.editRealName).send_keys(realName)

	def inputREnName(self,enName):
		logging.info(f'输入 英文名 {enName}')
		self.findElement(self.editREnName).send_keys(enName)

	def inputCardId(self,cardID):
		logging.info(f'输入 证件号 {cardID}')
		self.findElement(self.editCardId).send_keys(cardID)

	def inputBirthPlace(self,birthPlace):
		pass
		# logging.info(f'输入 出生地 {birthPlace}')
		# self.findElement(self.editBirthPlace).send_keys(birthPlace)

	def clickBirthDay(self):
		logging.info(f'点击 出生日期 ')
		ele=self.findElement(self.btnBirthDay)
		self.driver.execute_script("arguments[0].scrollIntoView();",ele)
		time.sleep(0.5)
		ele.click()

	def clickBirthDayOK(self):
		logging.info(f'点击确定')
		self.waitTo(ignoreError=(SCENSEE,SCEECIE,SCEENVE),way='XPATH',name=self.btnBirthDayOK[1],operate='click')

	def clickCardExpire(self):
		logging.info('点击选择 证件有效期')
		self.clickByScript(self.findElement(self.cardExpire1))
		time.sleep(0.5)
		self.waitTo(ignoreError=(SCENSEE,SCEECIE,SCEENVE),way='XPATH',name=self.starttimeOK[1],operate='click')
		# self.findElement(self.starttimeOK).click()
		time.sleep(1)
		# self.waitTo(ignoreError=(SCENSEE,SCEECIE,SCEENVE),way='CSS_SELECTOR',name=self.cardExpire2[1],operate='click')
		self.clickByScript(self.findElement(self.cardExpire2))
		time.sleep(0.5)
		self.waitTo(ignoreError=(SCENSEE,SCEECIE,SCEENVE),way='XPATH',name=self.endtimeOK[1],operate='click')
		# self.findElement(self.endtimeOK).click()
		time.sleep(0.5)

	def inputAddress(self,address):
		logging.info(f'输入 居住地址 {address}')
		self.driver.execute_script(f'document.getElementById("{self.editAddress[1]}").scrollIntoView();')
		self.findElement(self.editAddress).send_keys(address)

	def clickAddressUp(self):
		logging.info('点击选择上传地址图片')
		if self.PFN=='Android':
			self.findElement(self.editAddressPic[self.PFN],until='located').click()
		else:
			self.clickAddressUp_IOS()
	@switch_execute
	def clickAddressUp_IOS(self):
		self.findElement(self.editAddressPic[self.PFN],until='located').click()

	def inputAddressPic(self,pathToPic):
		logging.info(f'上传居住地址图片')
		self.findElement(self.editAddressPic[self.PFN],until='located').send_keys(pathToPic)
		# self.waitTo(way='NAME',name=self.editAddressPic[self.PFN][1],operate='send_keys',value=pathToPic)

	def clickNext2(self):
		logging.info('点击 下一步，个人信息')
		self.waitTo(ignoreError=(SCENSEE,SCEECIE),way='XPATH',name=self.btnNext2[1],operate='click')

	# 第四步
	def inputHomeTel(self,homeTel):
		logging.info(f'输入 住宅电话 {homeTel}')
		self.findElement(self.editHomeTel).send_keys(homeTel)

	def inputEmail(self,email):
		logging.info(f'输入 邮箱 {email}')
		self.findElement(self.editEmail).send_keys(email)

	def selectJobStatus(self):
		logging.info('选择工作状况 在职')
		self.findElement(self.btnJobStatus).click()
		time.sleep(0.5)
		self.findElement(self.workStatus).click()
		# Select(self.findElement(self.btnJobStatus)).select_by_visible_text("在职")

	def selectJob(self):
		logging.info('选择职位 一般员工')
		# Select(self.findElement(self.btnJob)).select_by_visible_text("一般员工")
		self.findElement(self.btnJob).click()
		time.sleep(0.5)
		self.findElement(self.normalemp).click()

	def selectIndustry(self):
		logging.info('选择所属行业')
		# Select(self.findElement(self.btnIndustry)).select_by_visible_text("金融业")
		self.findElement(self.btnIndustry).click()
		time.sleep(0.5)
		self.findElement(self.industry1).click()

	def inputCompanyName(self,company):
		logging.info(f'输入 公司名称 {company}')
		self.findElement(self.editCompanyName).send_keys(company)
		self.findElement(self.loseFoucs,until='located').click()

	def clickNext3(self):
		logging.info('点击 下一步，投资背景')
		self.findElement(self.btnNext).click()

	def clickCardBtnOk(self):
		logging.info('点击 已确认')
		self.findElement(self.btnCardBtnOk).click()

	# 第五步
	def clickPiPic(self):
		logging.info(f'点击上传资产证明图片')
		self.driver.execute_script(f'document.getElementById("pi_certify").scrollIntoView();')
		self.findElement(self.editPiPic,until='located').click()

	def inputPiPic(self,pathToPic):
		logging.info(f'上传资产证明图片')
		self.findElement(self.editPiPic,until='located').send_keys(pathToPic)
		# self.waitTo(way='NAME',name=self.editPiPic[1],operate='send_keys',value=pathToPic)

	def clickBackgroundInfo(self):
		logging.info('点击 下一步，开通市场')
		self.waitTo(way='xpath',name=self.btnBackgroundInfo[1],operate='click')
		# self.findElement(self.btnBackgroundInfo).click()

	def clickMarketChoose(self):
		logging.info('点击 下一步')
		for i in range(5):
			try:
				self.findElement(self.btnNext).click()
				break
			except SCEENVE:
				if i==4:raise SCEENVE(f'点击下一步失败')

	#衍生品问卷
	def derTest(self):
		for xpath in self.derivateANS:
			ele=self.findElement((By.XPATH,xpath))
			self.driver.execute_script("arguments[0].scrollIntoView();",ele)
			time.sleep(0.5)
			ele.click()

	def clickderTest(self):
		logging.info('衍生品问卷完成，点击 下一步')
		self.findElement(self.btnNext).click()

	# 简易投资问卷
	def investmentTest(self):
		logging.info('开始 简易投资问卷')
		for xpath in self.investment_ANS:
			ele=self.findElement((By.XPATH,xpath))
			self.driver.execute_script("arguments[0].scrollIntoView();",ele)
			time.sleep(0.5)
			ele.click()

	# 风险取向测评
	def riskTest(self):
		for xpath in self.riskANS:
			ele=self.findElement((By.XPATH,xpath))
			self.driver.execute_script("arguments[0].scrollIntoView();",ele)
			time.sleep(0.5)
			ele.click()

	def selectYears(self):
		logging.info('经验年期 5-10年')
		# Select(self.findElement(self.btnYears)).select_by_visible_text("5-10年")
		self.findElement(self.btnYears).click()
		self.driver.execute_script('document.querySelector(".md-selector-list").querySelectorAll(".md-cell-item")[4].click();')

	def selectTimes(self):
		logging.info('近三年交易次数 5次或以上')
		# Select(self.findElement(self.btnTimes)).select_by_visible_text("5次或以上")
		self.findElement(self.btnTimes).click()
		self.driver.execute_script('document.querySelectorAll(".md-selector-list")[1].querySelectorAll(".md-cell-item")[3].click();')

	def clickRpqTest(self):
		logging.info('点击 下一步，测评结果')
		self.findElement(self.btnRpqTest).click()

	def clickAccountMarket(self):
		logging.info('点击 下一步，风险披露')
		self.findElement(self.btnAccountMarket).click()

	def clickNext4(self):
		logging.info('点击 开始播放')
		self.findElement(self.startPlay).click()
		time.sleep(2)
		logging.info('点击 确认，下一步')
		self.findElement(self.btnNext4).click()

	def clickNext5(self):
		logging.info('点击 确认')
		try:
			self.findElement(self.btnNext5).click()
		except:
			pass

	#第六步
	def chooseSignType(self):
		logging.info(f'点击 客户经理面签')
		self.findElement(self.signType).click()
		self.driver.execute_script('document.querySelectorAll(".md-radio")[1].click();')

	def clickF2Fpic(self):
		logging.info(f'点击上传面签署凭证')
		self.findElement(self.editF2Fpic,until='located').click()

	def inputF2Fpic(self,pathToPic):
		logging.info(f'上传面签署凭证')
		self.findElement(self.editF2Fpic,until='located').send_keys(pathToPic)
		# self.waitTo(way='XPATH',name=self.editF2Fpic[1],operate='send_keys',value=pathToPic)
		time.sleep(0.5)

	def clickNext6(self):
		logging.info('点击 确认，下一步')
		time.sleep(0.5)
		self.waitTo(way='xpath',name=self.btnNext[1],operate='click')

	def clickAddHkNext(self):
		logging.info('点击 下一步，签署')
		self.waitTo(way='xpath',name=self.btnNext[1],operate='click')
		# self.waitTo(way='id',name=self.btnAddHkNext[1],operate='click')

	#第七步
	def clickAgreeSign(self):
		logging.info('勾选本人已同意')
		self.findElement(self.btnAgreeSign).click()

	def clickSignTable(self):
		logging.info('点击 点击开始签署表格')
		self.findElement(self.btnSignTable).click()

	#第八步
	def sign(self,device='web'):
		time.sleep(3)
		logging.info('自动签名')
		if device=='web':
			from selenium.webdriver.common.touch_actions import TouchActions
			canvas=self.findElement(self.canvas_web)
			a,b=canvas.location.values()
			w=int(canvas.get_attribute('width'))
			h=int(canvas.get_attribute('height'))
			c=a+w;d=b+h;x=55;y=300
			bounds=(
				# A
				(int((240/x)*a),int((500/y)*b),int((160/x)*a),int((710/y)*b)),
				(int((240/x)*a),int((500/y)*b),int((320/x)*a),int((710/y)*b)),
				(int((180/x)*a),int((630/y)*b),int((300/x)*a),int((630/y)*b)),
				# U
				(int((360/x)*a),int((510/y)*b),int((360/x)*a),int((710/y)*b)),
				(int((360/x)*a),int((710/y)*b),int((460/x)*a),int((710/y)*b)),
				(int((460/x)*a),int((510/y)*b),int((460/x)*a),int((710/y)*b)),
				# T
				(int((520/x)*a),int((520/y)*b),int((650/x)*a),int((520/y)*b)),
				(int((585/x)*a),int((520/y)*b),int((585/x)*a),int((720/y)*b)),
				# O
				(int((700/x)*a),int((520/y)*b),int((700/x)*a),int((700/y)*b)),
				(int((700/x)*a),int((700/y)*b),int((845/x)*a),int((700/y)*b)),
				(int((845/x)*a),int((700/y)*b),int((845/x)*a),int((520/y)*b)),
				(int((845/x)*a),int((520/y)*b),int((700/x)*a),int((520/y)*b)),
				# T
				(int((150/x)*a),int((780/y)*b),int((320/x)*a),int((780/y)*b)),
				(int((235/x)*a),int((780/y)*b),int((235/x)*a),int((1000/y)*b)),
				# E
				(int((350/x)*a),int((780/y)*b),int((350/x)*a),int((1000/y)*b)),
				(int((350/x)*a),int((780/y)*b),int((470/x)*a),int((780/y)*b)),
				(int((350/x)*a),int((880/y)*b),int((470/x)*a),int((880/y)*b)),
				(int((350/x)*a),int((1000/y)*b),int((470/x)*a),int((1000/y)*b)),
				# S
				(int((680/x)*a),int((780/y)*b),int((550/x)*a),int((780/y)*b)),
				(int((550/x)*a),int((780/y)*b),int((550/x)*a),int((880/y)*b)),
				(int((550/x)*a),int((880/y)*b),int((680/x)*a),int((880/y)*b)),
				(int((680/x)*a),int((880/y)*b),int((680/x)*a),int((1000/y)*b)),
				(int((680/x)*a),int((1000/y)*b),int((540/x)*a),int((1000/y)*b)),
				# T
				(int((730/x)*a),int((780/y)*b),int((900/x)*a),int((780/y)*b)),
				(int((810/x)*a),int((780/y)*b),int((810/x)*a),int((1000/y)*b)),
				# -
				# (a+2,int((b+d)/2),c,int((b+d)/2))
			)
			actions=TouchActions(self.driver)
			for coords in bounds:
				actions.tap_and_hold(*coords[:2])
				actions.move(*coords[-2:])
				actions.release(*coords[-2:])
			actions.perform()
		else:# 在Android端切换到webview后获取的canvas元素坐标不准确
			swithToRightWeb(self.driver,0)
			canvas=self.findElement(self.canvas)
			x1,y1=canvas.location.values()
			h,w=canvas.size.values()
			x2,y2=x1+w,y1+h
			self.driver.swipe(x1+100,y1+100,x2-100,y2-100,200)
			swithToRightWeb(self.driver,'/form/handwrite')

	def clickPaperDone(self):
		logging.info('点击 完成')
		self.findElement(self.btnPaperDone).click()

	def textMsg(self):
		return self.findElement(self.eleMsg).text.strip()


import sys
from collections import deque
input = sys.stdin.readline

def bfs(v):
    q = deque()
    q.append(v)
    dist = [-1 for _ in range(n+1)]
    dist[v] = 0
    while q:
        curr = q.popleft()
        for node, cost in graph[curr]:
            if dist[node] == -1:
                dist[node] = dist[curr] + cost
                q.append(node)

    return dist

n = int(input())
graph = [[] for _ in range(n+1)]
for _ in range(n-1):
    a, b, c = map(int, input().split())
    graph[a].append([b, c])
    graph[b].append([a, c])

rtn = bfs(1)
rtn = bfs(rtn.index(max(rtn)))
print(max(rtn))


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np

def entropy(p):
    q = 1. - p
    return -p * np.log(p) - q * np.log(q)

def jsd(p, q):
    return [entropy(p / 2. + q / 2.) - entropy(p) / 2. - entropy(q) / 2.]

def jsd_grad(go, o, pq_list):
    p, q = pq_list
    m = (p + q) / 2.
    return [np.log(p * (1 - m) / (1 - p) / m) / 2. * go, None]

class TestJSDOps(hu.HypothesisTestCase):
    @given(n=st.integers(10, 100), **hu.gcs_cpu_only)
    def test_bernoulli_jsd(self, n, gc, dc):
        p = np.random.rand(n).astype(np.float32)
        q = np.random.rand(n).astype(np.float32)
        op = core.CreateOperator("BernoulliJSD", ["p", "q"], ["l"])
        self.assertReferenceChecks(
            device_option=gc,
            op=op,
            inputs=[p, q],
            reference=jsd,
            output_to_grad='l',
            grad_reference=jsd_grad,
        )


class TreeNode(object):
    """节点类"""
    def __init__(self, val=-1, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def listcreattree(root,llist,i):###用列表递归创建二叉树，

    if i<len(llist):
        if llist[i] =='null':
            return None ###这里的return很重要
        else:
            root=TreeNode(llist[i])
            root.left=listcreattree(root.left,llist,2*i+1)
            root.right=listcreattree(root.right, llist,2*i+2)
            return root  ###这里的return很重要
    return root

llist = [1,2,3,4,5,6,7]
root=listcreattree(TreeNode(),llist,0)


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# coding by xiaoming
'''
# 字符集:多种字符的集合
# 字符的发展:
第一步:
    最早的计算机使用的英文键盘,系统只能识别数字和英文等内容
ASCII码:推行了一个ASCII吗,美国标准信息交换码
    键盘上字母,数字,符号
第二步:
    研究了设置每种语言的字符集
第三步:
    国际通用字符集UTF
    utf-8
    utf-16
    utf-32

'''

mystr = "声明"
result = mystr.encode("utf-8")
print(result)
res = result.decode("utf-8")

print(res)


# @ImagePlus imp

# python (jython) imports
import os, sys, math
from datetime import datetime

# java imports - aim to have UI components entirely swing, listeners and layouts awt
from java.awt import Dimension, GridBagLayout, GridBagConstraints, GridLayout
import javax.swing as swing
import javax.swing.table.TableModel

# imagej imports
from ij import IJ, WindowManager, ImagePlus
from ij.gui import Roi, PointRoi, PolygonRoi, GenericDialog, WaitForUserDialog
from ij.io import OpenDialog, DirectoryChooser, FileSaver
from ij.plugin import ChannelSplitter, Duplicator
from ij.process import FloatPolygon, ImageConverter
from ij.plugin.filter import GaussianBlur, ParticleAnalyzer
from loci.plugins import BF as bf

def pause_for_debug():
	gd = GenericDialog("Continue?");
	gd.showDialog();
	if gd.wasCanceled():
		raise Exception("Run interupted");

def find_basal_edges(imp, search_range=10):
	edges = [];
	for fridx in range(0, imp.getNFrames()):
		print("Examining frame " + str(fridx) + "...");
		imp.setPosition(1, 1, fridx+1);
		#imp.setSliceWithoutUpdate(fridx + 1)
		if (fridx == 0):
			edge = imp.getWidth() * [-1];
			for xidx in range(0, imp.getWidth()):
				yidx = imp.getHeight() - 1;
				pix_val = imp.getPixel(xidx, yidx)[0];
				while (pix_val == 0):
					yidx = yidx - 1;
					pix_val = imp.getPixel(xidx, yidx)[0];
				edge[xidx] = yidx;
		else:
			# confine search for edge to region of search_range (10 pix default) either side
			# of the last frame's edge. If no edge is found in that region, must be a hole in
			# the binary image. Assign a dummy value and deal with it in second loop.
			edge = imp.getWidth() * [-1];
			for xidx in range(0, imp.getWidth()):
				yidx = int(edges[fridx-1][xidx] + search_range);
				try:
					pix_val = imp.getPixel(xidx, yidx)[0];
				except TypeError:
					print(xidx);
					print(yidx);
					raise TypeError;
				while (pix_val==0) and (yidx > (edges[fridx-1][xidx] - search_range)):
					yidx = yidx - 1;
					pix_val = imp.getPixel(xidx, yidx)[0];
				if (pix_val != 0):
					edge[xidx] = yidx;

			# deal with pixels we've marked as missing an edge
			xidx = -1;
			while xidx < imp.getWidth() - 1:
				xidx = xidx + 1;
				# if first position along edge is anomalous, take the value from the previous
				# frame's edge as a reasonable approximation
				if (xidx==0) and (edge[xidx]==-1):
					edge[xidx] = edges[fridx-1][xidx];
					xidx = xidx + 1;
				# if later positions are anomalous, interpolate between previous and next
				# successfully found edges
				if (edge[xidx]==-1):
					# last good edge position
					x1 = xidx - 1;
					y1 = edge[x1];
					# find next good edge position
					sub_xidx = xidx + 1;
					wp = imp.getWidth() - 1;
					if (sub_xidx < wp):
						while (edge[sub_xidx]==-1):
							sub_xidx = sub_xidx + 1;
							if (sub_xidx >= wp):
								break;
					# deal with case when no further good positions exisit - just continue
					# edge using last good y position to the end of the image in x direction,
					# and terminate outer loop over x positions
					if (sub_xidx >= wp):
						for subsub_xidx in range(x1, imp.getWidth()):
							edge[subsub_xidx] = y1;
						xidx = wp;
					# deal with case when edge exists again after a while
					else:
						print("edge exists again");
						x2 = sub_xidx;
						y2 = edge[x2];
						print('x1 = ' + str(x1));
						print('y1 = ' + str(y1));
						print('x2 = ' + str(x2));
						print('y2 = ' + str(y2));

						# interpolate between last good position and next good position
						for subsub_xidx in range((x1 + 1), x2):
							edge[subsub_xidx] = round((float(subsub_xidx - x1)/
															(x2 - x1)) * (y2 - y1) +  y1);
							print(edge[x1:x2]);
						pause_for_debug();
						# get outer loop to skip over section we've just dealt with by updating
						# xidx accordingly
						xidx = x2 - 1;
		edges.append(edge);
	return edges;

# assume that first frame is good quality image...
basal_edges = find_basal_edges(imp);
xs = [x for x in range(1, imp.getWidth()+1)];
for fridx in range(0, imp.getNFrames()):
	imp.setPosition(1, 1, fridx+1);
	roi = PolygonRoi(xs, basal_edges[fridx], Roi.POLYLINE);
	imp.setRoi(roi);
	pause_for_debug();


import tkinter as tk
from tkinter import ttk, RIGHT, BOTTOM, LEFT, X, Y, HORIZONTAL, VERTICAL# new widgets
from threading import Thread
import psutil
import time
import os
#print(psutil.cpu_percent(3))
root = tk.Tk()
root.title("Псевдо диспетчер")
root.geometry("770x550")
processes_nums = 0
all_processes = 0
uptime = 3

# METHODS
def ProcUpdate():
	global processes_nums
	global all_processes
	while True:
		time.sleep(uptime)
		p1 = 0
		for i in proc_table.get_children():
			proc_table.delete(i)

		for proc in psutil.process_iter():
			num = processes_nums + 1
			proc_table.insert(parent='', index='end', iid=num, text='', values=(f'{proc.name()}', f'{round(proc.cpu_percent())}', f'{round(proc.memory_info().rss / 1048576, 2)} МБ', f'{proc.ppid()}', ' '))
			processes_nums += 1

			p1 += 1

		all_processes = p1
		processes_amount.configure(text=f'Процессов: {all_processes}      ')

def ProcDelete(a):
	item = proc_table.selection()[0]
	values = proc_table.item(item, option="values")
	os.system(f'TASKKILL /IM {values[0]}')
	proc_table.delete(item)

def SetUptime():
	global uptime
	uptime = int(uptime_entry.get())

# WIDGETS
# Notebook
tabs = ttk.Notebook(root)
# Processes
processes = tk.Frame(tabs)
tabs.add(processes, text='Процессы')
proc_table = ttk.Treeview(processes)
proc_table['columns'] = ('name', 'cpu', 'ram', 'pid', 'about')

proc_table.column("name", width=160)
proc_table.column("cpu", width=30)
proc_table.column("ram", width=60)
proc_table.column("pid", width=35)
proc_table.column("about",width=100)

proc_table.heading("name",text="Имя")
proc_table.heading("cpu",text="ЦП")
proc_table.heading("ram",text="ОЗУ")
proc_table.heading("pid",text="PID")
proc_table.heading("about",text="Описание")

proc_table.pack(expand=1, fill='both')

# Scrollbar
# Scroll bar y
scrollbary = tk.Scrollbar(proc_table, orient=VERTICAL)
proc_table.configure(yscrollcommand=scrollbary.set)
scrollbary.config(command=proc_table.yview, cursor="arrow")# sb_v_double_arrow
scrollbary.pack(fill=Y, side=RIGHT)
# Scroll bar x
scrollbarx = tk.Scrollbar(proc_table, orient=HORIZONTAL)
proc_table.configure(xscrollcommand=scrollbarx.set)
scrollbarx.config(command=proc_table.xview, cursor="arrow")# sb_h_double_arrow
scrollbarx.pack(fill=X, side=BOTTOM)

# System
system = tk.Frame(tabs)
tabs.add(system, text='Система')
tabs.pack(expand=2, fill='both')
sys_lab = tk.Label(system, text="Пасхалочка", font=('Hack', 11))
sys_lab.place(x=150, y=50)

# Buttons
proc_delete = tk.Button(processes, text="Завершить процесс", font=('Arial', 9), command=ProcDelete)
proc_delete.pack(side=RIGHT)

# Labels
processes_amount = tk.Label(processes, text=f'Процессов: {all_processes}      ', font=('Arial', 9))
processes_amount.pack(side=LEFT)
uptime_label = tk.Label(processes, text=f'Время обновления(сек):', font=('Arial', 9))
uptime_label.pack(side=LEFT)

# Entry
uptime_entry = tk.Entry(processes, width=3)
uptime_entry.pack(side=LEFT)
uptime_button = tk.Button(processes, text="✔", font=('Arial', 9), border=0, cursor="hand2", command=SetUptime)
uptime_button.pack(side=LEFT)

root.bind("<KeyPress-Delete>", ProcDelete)
processes_update = Thread(target=ProcUpdate, args=[])
processes_update.start()
root.mainloop()


"""Contains the BOTCBot class."""

import typing
from os import remove
from os.path import isfile

import discord
from dill import dump, load
from discord.ext import commands

from lib.logic.Character import Storyteller
from lib.logic.Game import Game
from lib.logic.Player import Player
from lib.logic.converters import to_character_list
from lib.logic.playerconverter import to_member_list
from lib.logic.tools import generate_game_info_message
from lib.preferences import load_preferences
from lib.utils import safe_send, get_input, safe_bug_report

if typing.TYPE_CHECKING:
    from lib.logic.Script import Script
    from lib.typings.context import Context
    from configparser import SectionProxy

class BOTCBot(commands.Bot):
    """An extension of the commands.Bot class, storing globally necessary attributes."""

    def __init__(
        self,
        bot_name: str,
        serverid: int,
        channelid: int,
        storytellerid: int,
        playerid: int,
        inactiveid: int,
        playtestid: int,
        observerid: int,
        config: "SectionProxy",
        **options,
    ):
        super().__init__(**options)

        self.bot_name = bot_name
        self._serverid = serverid
        self._channelid = channelid
        self._storytellerid = storytellerid
        self._playerid = playerid
        self._inactiveid = inactiveid
        self._playtestid = playtestid
        self._observerid = observerid
        self.config = config
        self.game: typing.Optional[Game] = None

    @property
    def server(self) -> discord.Guild:
        """Determine the bot's main server."""
        return self.get_guild(self._serverid)

    @property
    def channel(self) -> discord.TextChannel:
        """Determine the bot's main channel."""
        return self.get_channel(self._channelid)

    @property
    def storyteller_role(self) -> discord.Role:
        """Determine the bot's Storyteller role."""
        return self.server.get_role(self._storytellerid)

    @property
    def player_role(self) -> discord.Role:
        """Determine the bot's player role."""
        return self.server.get_role(self._playerid)

    @property
    def inactive_role(self) -> discord.Role:
        """Determine the bot's inactive role."""
        return self.server.get_role(self._inactiveid)

    @property
    def playtest_role(self) -> typing.Optional[discord.Role]:
        """Determine the bot's playtest role."""
        if self.playtest:
            return self.server.get_role(self._playtestid)
        return None

    @property
    def observer_role(self) -> discord.Role:
        """Determine the bot's observer role."""
        return self.server.get_role(self._observerid)

    @property
    def instant_message_reporting(self) -> bool:
        """Determine whether the bot uses instant message reporting."""
        return self.config.getboolean("instantmessagereports")

    @property
    def playtest(self) -> bool:
        """Determine whether the bot has playtest characters enabled."""
        return self.config.getboolean("playtest")

    async def start_game(self, ctx: "Context", script: "Script"):
        """Handle startgame logic."""
        await safe_send(ctx, f"Starting a {script.name} game.")

        # ask for the list of players
        users = await to_member_list(
            ctx,
            (
                await get_input(
                    ctx,
                    (
                        "What is the seating order? (Separate "
                        "users with line breaks. Do not include "
                        "travelers.)"
                    ),
                )
            ).split("\n"),
        )

        # ask for the list of characters
        characters = to_character_list(
            ctx,
            (
                await get_input(
                    ctx,
                    (
                        "What are the corresponding characters? "
                        "(Separate characters with line breaks.)"
                    ),
                )
            ).split("\n"),
            script,
        )

        with ctx.typing():  # doing a lot of computation here

            # verify 1:1 user:character ratio
            if len(users) != len(characters):
                raise commands.BadArgument(
                    "There are a different number of players and characters."
                )

            # role cleanup
            await self._startgame_role_cleanup(users)

            # generate seating order
            seating_order = [
                Player(person, characters[index], index)
                for index, person in enumerate(users)
            ]

            # script message
            posts = []
            for content in list(script.info(ctx)):
                posts.append(await safe_send(self.channel, content))

            for post in posts[::-1]:  # Reverse the _order so the pins are right
                await post.pin()

            # welcome message
            await safe_send(
                self.channel,
                (
                    f"{self.player_role.mention}, "
                    "welcome to Blood on the Clocktower! Go to "
                    "sleep."
                ),
            )

            # seating order message
            seating_order_message = await safe_send(
                self.channel,
                generate_game_info_message(seating_order, ctx.bot.game),
                pin=True,
            )

            # storytellers
            storytellers = [
                Player(person, Storyteller, None)
                for person in self.storyteller_role.members
            ]

            # start the game
            self.game = Game(seating_order, seating_order_message, script, storytellers)
            if safe_bug_report(ctx):
                await safe_send(ctx, "Started the game successfully.")
            await self.game.start_night(ctx)

    async def update_status(self):
        """Update the bot's status to display information about the game."""
        if not self.game:
            await self.change_presence(
                status=discord.Status.dnd,
                activity=discord.Game(name="No ongoing game!"),
            )

        elif not self.game.current_day:
            await self.change_presence(
                status=discord.Status.idle,
                activity=discord.Game(name="It's nighttime!"),
            )

        else:
            clopen = ["Closed", "Open"]
            await self.change_presence(
                status=discord.Status.online,
                activity=discord.Game(
                    name="PMs {is_pms}, "
                    "Noms "
                    "{is_noms}!".format(
                        is_pms=clopen[self.game.current_day.is_pms],
                        is_noms=clopen[self.game.current_day.is_noms],
                    )
                    # noms instead of nominations for space
                ),
            )

    def backup(self, file_name: str = "current_game.pckl"):
        """Backs up the current gamestate."""
        file_name = "resources/backup/" + self.bot_name + "/" + file_name

        if self.game:
            with open(file_name, "wb") as file:
                dump(self.game, file)
        else:
            if isfile(file_name):
                remove(file_name)

    async def restore_backup(self, file_name: str = "current_game.pckl", mute=False):
        """Restores a backup."""
        file_name = "resources/backup/" + self.bot_name + "/" + file_name

        # restore backups
        try:

            with open(file_name, "rb") as file:
                self.game = load(file)

            # catch game being none
            # should never be possible if the file exists, but just in case
            assert self.game

            # do some unpickling
            # noinspection PyTypeChecker
            # the seating order message is pickled as an int so this is fine
            self.game.seating_order_message = await self.channel.fetch_message(
                self.game.seating_order_message
            )
            for player in self.game.seating_order + self.game.storytellers:
                player.member = self.server.get_member(player.member)

            # print
            if not mute:
                print("Backup restored!")
            return True

        except (FileNotFoundError, AssertionError):
            self.game = None
            if not mute:
                print("No backup found.")
            return None

        except EOFError:
            self.game = None
            print("Backup incomplete.")  # do this even if mute because it
            # represents an error
            return None

    async def process_commands(self, message: discord.Message):
        """Process commands registered to the bot.

        Modified to handle custom aliases.
        """
        if message.author.bot:
            return

        if not (message.guild is None or message.channel == self.channel):
            return

        ctx = await self.get_context(message)

        preferences = load_preferences(message.author)
        if ctx.invoked_with in preferences.aliases:
            ctx.command = self.all_commands.get(
                preferences.aliases[ctx.invoked_with].split(" ")[0]
            )
            if " " in preferences.aliases[ctx.invoked_with]:
                for cmd in preferences.aliases[ctx.invoked_with].split(" ")[1:]:
                    ctx.command = ctx.command.get_command(cmd)

        await self.invoke(ctx)

    async def _startgame_role_cleanup(self, users: typing.List[discord.Member]):
        """Handle role cleanup for startgame."""
        # clear all player roles
        for memb in self.player_role.members:
            await memb.remove_roles(self.player_role)

        # modify roles for players
        for user in users:

            # add player role
            await user.add_roles(self.player_role)

            # remove storyteller role
            if self.storyteller_role in user.roles:
                await user.remove_roles(self.storyteller_role)

        # add player role for storytellers
        for memb in self.storyteller_role.members:
            await memb.add_roles(self.player_role)


#!/usr/bin/env python

from __future__ import print_function

from lirc import Lirc

from eccontrols import *

lirc = Lirc()

class GenericIR:
    """Sends IR signals to a particular device."""

    device = {}
    commands = {}
    duration = 25

    def __init__(self, device, duration=25):
        if not device in lirc.devices():
            raise ECError('No such device: %s' % device)
        self.device = device
        self.commands = lirc.commands(device)
        self.duration = duration

    def send(self, command):
        """Send an IR code. Valid commands are listed in commands."""
        if command.upper() in self.commands:
            lirc.send(self.device, command.upper(), self.duration)
        else:
            raise ECError('No such command %s for device %s' % (command, self.device))

    def __call__(self, command):
        self.send(command)


#Bubble sort
def swap(arr, i, j):
    temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp

def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        for j in range(i + 1, n):
            if arr[i] > arr[j]:
                swap(arr, i, j)

arr = [9, 4, 5, 1, 5, 13, 10]
bubble_sort(arr)
for i in arr:
    print(i, end=" ")


from rest_framework import serializers
from .models import Unit, Part, PO2China
class UnitSerializer(serializers.ModelSerializer):
    #parts = serializers.PrimaryKeyRelatedField(queryset=Part.objects.all(), many=True)
    class Meta:
        model = Unit
        fields = '__all__'

class PartsSerializer(serializers.ModelSerializer):
    unit_set = serializers.PrimaryKeyRelatedField(queryset=Unit.objects.all(), many=True)
    class Meta:
        model = Part
        fields = '__all__'
        lookup_field = 'number'
        extra_kwargs = {
            'url': {'lookup_field': 'number'}
        }

class PartsDetailSerializer(serializers.ModelSerializer):
    unit_set = UnitSerializer(many=True)
    class Meta:
        model = Part
        fields = ('number', 'name_eng', 'unit_set')

class POSerializer(serializers.ModelSerializer):
    part = PartsDetailSerializer()
    class Meta:
        model = PO2China
        fields = '__all__'

class POEditSerializer(serializers.ModelSerializer):
    #part = PartsSerializer()
    class Meta:
        model = PO2China
        fields = '__all__'


import enum
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from typing import ClassVar, Optional, Union

from google.oauth2.service_account import Credentials as SACredentials
from yarl import URL

@dataclass(frozen=True)
class ServerConfig:
    host: str = "0.0.0.0"
    port: int = 8080

@dataclass(frozen=True)
class PlatformAuthConfig:
    url: Optional[URL]
    token: str = field(repr=False)

@dataclass(frozen=True)
class CORSConfig:
    allowed_origins: Sequence[str] = ()

@dataclass(frozen=True)
class ZipkinConfig:
    url: URL
    app_name: str = "platform-buckets-api"
    sample_rate: float = 0.0

@dataclass(frozen=True)
class SentryConfig:
    dsn: URL
    cluster_name: str
    app_name: str = "platform-buckets-api"
    sample_rate: float = 0.0

class BucketsProviderType(str, enum.Enum):
    AWS = "aws"
    MINIO = "minio"
    AZURE = "azure"
    GCP = "gcp"
    EMC_ECS = "emc_ecs"
    OPEN_STACK = "open_stack"

@dataclass(frozen=True)
class AWSProviderConfig:
    type: ClassVar[BucketsProviderType] = BucketsProviderType.AWS
    s3_role_arn: str
    access_key_id: Optional[str] = None
    secret_access_key: Optional[str] = None
    region_name: str = "us-east-1"
    endpoint_url: Optional[URL] = None

@dataclass(frozen=True)
class MinioProviderConfig:
    type: ClassVar[BucketsProviderType] = BucketsProviderType.MINIO
    access_key_id: str
    secret_access_key: str
    region_name: str
    endpoint_url: URL
    endpoint_public_url: URL

@dataclass(frozen=True)
class AzureProviderConfig:
    type: ClassVar[BucketsProviderType] = BucketsProviderType.AZURE
    endpoint_url: URL
    credential: str

@dataclass(frozen=True)
class GCPProviderConfig:
    type: ClassVar[BucketsProviderType] = BucketsProviderType.GCP
    key_json: Mapping[str, str]

    @property
    def sa_credentials(self) -> SACredentials:
        return SACredentials.from_service_account_info(info=self.key_json)

@dataclass(frozen=True)
class EMCECSProviderConfig:
    type: ClassVar[BucketsProviderType] = BucketsProviderType.EMC_ECS
    s3_role_urn: str
    access_key_id: str
    secret_access_key: str
    s3_endpoint_url: URL
    management_endpoint_url: URL

@dataclass(frozen=True)
class OpenStackProviderConfig:
    type: ClassVar[BucketsProviderType] = BucketsProviderType.OPEN_STACK
    account_id: str
    password: str
    region_name: str
    endpoint_url: URL
    s3_endpoint_url: URL

class KubeClientAuthType(str, enum.Enum):
    NONE = "none"
    TOKEN = "token"
    CERTIFICATE = "certificate"

@dataclass(frozen=True)
class KubeConfig:
    endpoint_url: str
    cert_authority_data_pem: Optional[str] = field(repr=False, default=None)
    cert_authority_path: Optional[str] = None
    auth_type: KubeClientAuthType = KubeClientAuthType.CERTIFICATE
    auth_cert_path: Optional[str] = None
    auth_cert_key_path: Optional[str] = None
    token: Optional[str] = field(repr=False, default=None)
    token_path: Optional[str] = None
    namespace: str = "default"
    client_conn_timeout_s: int = 300
    client_read_timeout_s: int = 300
    client_watch_timeout_s: int = 1800
    client_conn_pool_size: int = 100

@dataclass(frozen=True)
class Config:
    server: ServerConfig
    platform_auth: PlatformAuthConfig
    kube: KubeConfig
    cors: CORSConfig
    cluster_name: str
    bucket_provider: Union[
        AWSProviderConfig,
        MinioProviderConfig,
        AzureProviderConfig,
        GCPProviderConfig,
        EMCECSProviderConfig,
        OpenStackProviderConfig,
    ]
    enable_docs: bool = False
    disable_creation: bool = False
    zipkin: Optional[ZipkinConfig] = None
    sentry: Optional[SentryConfig] = None


import json
from time import sleep
import logging
from elasticsearch import Elasticsearch, RequestsHttpConnection, serializer, compat, exceptions
import glob
import sys, os
from pathlib import Path
import csv

class JSONSerializerPython2(serializer.JSONSerializer):
    def dumps(self, data):
        # don't serialize strings
        if isinstance(data, compat.string_types):
            return data
        try:
            return json.dumps(data, default=self.default, ensure_ascii=True)
        except (ValueError, TypeError) as e:
            raise exceptions.SerializationError(data, e)

def connect_elasticsearch():
    _es = None
    _es = Elasticsearch([{'host': 'localhost', 'port': 9200}], serializer=JSONSerializerPython2())
    if _es.ping():
        print('Yay Connect')
    else:
        print('Awww it could not connect!')
    return _es

def create_index(es_object, index_name):
    created = False
    # index settings
    settings = {
            "settings": {
                "number_of_shards": 5,
                "number_of_replicas": 1
                },
            "mappings":{
                "wikibook_items":{
                    "properties": {
                        "title": {
                            "type": "string",
                            "analyzer": "english"
                        },
                        "content": {
                            "type": "string",
                            "analyzer": "english",
                            "fields": {
                                "std": {
                                    "type": "string",
                                    "analyzer": "standard"
                                    }
                                }
                            },
                        }
                    }
                }
            }
    try:
        if not es_object.indices.exists(index_name):
            # Ignore 400 means to ignore "Index Already Exist" error.
            es_object.indices.create(index=index_name, ignore=400, body=settings)
            print('Created Index')
        created = True
    except Exception as ex:
        print(str(ex))
    finally:
        return created

es = connect_elasticsearch()
create_index(es, 'wiki_java_programming')

# you can place the absolute path of WikiBooks files on your system here
path_wiki = '/media/tamanna/MyStuff/ASU/Coursework/Fall 2018/CSE 591 - Adaptive Web/Assignment 2/Assign2-ChandniShrivastava/data/*.txt'
files_wiki=glob.glob(path_wiki)
# fw=open(files_wiki[0], 'r')
# print(fw.readlines())
eid = 0
for name in files_wiki:
    fw=open(name, 'r')
    # file_contents = f.readlines()
    file_contents = fw.read().splitlines()
    # print(file_contents)
    doc = {
        'title': Path(name).stem,
        'content' : file_contents
    }
    eid = eid+1
    # store_record(es, 'wikibook_items', es_doc)
    res = es.index(index='wiki_java_programming', doc_type='wikibook_items', id=eid, body=doc, request_timeout=1000)
    fw.close()

path_oracle = '/media/tamanna/MyStuff/ASU/Coursework/Fall 2018/CSE 591 - Adaptive Web/Assignment 2/Assign2-ChandniShrivastava/dataoracle/*.txt'
files_oracle=glob.glob(path_oracle)
# fo=open(files_oracle[0], 'r')
# print(fo.readlines())
# eid = 0
for name in files_oracle:
    fo=open(name, 'r')
    # file_contents = f.readlines()
    file_contents = fo.read().splitlines()
    # print(file_contents)
    doc = {
        'title': Path(name).stem,
        'content' : file_contents
    }
    eid = eid+1
    # store_record(es, 'wikibook_items', es_doc)
    res = es.index(index='wiki_java_programming', doc_type='wikibook_items', id=eid, body=doc, request_timeout=1000)
    fo.close()

# with open('oracle-items.csv', 'r') as _filehandler:
#     csv_file_reader = csv.reader(_filehandler)
#     for row in csv_file_reader:
#         if len()
#         title = row[0] + "_____" + row[1]
#         print title
#         contents = row[2]
#         print contents

# if __name__ == '__main__':
#   logging.basicConfig(level=logging.ERROR)


texto = open(r"C:\Workspace\Python\Python\arqs-06\arq4.in").readlines()

r = int(texto[0])
texto.pop(0)

assassinos = []
vitimas = []
detetives = []

i = 0
while i < r :
    a, v, d = texto[i].split()
    assassinos.append(a)
    vitimas.append(v)
    detetives.append(d)
    i += 1

todomundo = assassinos + vitimas + detetives
todomundo = list(set(todomundo))
todomundo.sort()

for p in todomundo :
    print(60 * "-")
    if p in vitimas :
        p += (" (in memorian):")
    if p in detetives:
        p += (": detetive")

    print(p)