import os
import logging
import argparse
from tqdm import tqdm, trange
import re
import numpy as np
import torch
from torch.utils.data import TensorDataset, DataLoader, SequentialSampler
from transformers import AutoModelForSequenceClassification

from utils import init_logger, load_tokenizer

logger = logging.getLogger(__name__)

def get_device(pred_config):
    return "cuda" if torch.cuda.is_available() and not pred_config.no_cuda else "cpu"

def get_args(pred_config):
    return torch.load(os.path.join(pred_config.model_dir, 'training_args.bin'))

def load_model(pred_config, args, device):
    # Check whether model exists
    if not os.path.exists(pred_config.model_dir):
        raise Exception("Model doesn't exists! Train first!")

    try:
        model = AutoModelForSequenceClassification.from_pretrained(pred_config.model_dir)  # Config will be automatically loaded from model_dir
        model.to(device)
        model.eval()
        logger.info("***** Model Loaded *****")
    except:
        raise Exception("Some model files might be missing...")

    return model

def convert_input_file_to_tensor_dataset(pred_config,
                                         args,
                                         cls_token_segment_id=0,
                                         pad_token_segment_id=0,
                                         sequence_a_segment_id=0,
                                         mask_padding_with_zero=True):
    tokenizer = load_tokenizer(args)

    # Setting based on the current model type
    cls_token = tokenizer.cls_token
    sep_token = tokenizer.sep_token
    pad_token_id = tokenizer.pad_token_id

    all_input_ids = []
    all_attention_mask = []
    all_token_type_ids = []

    with open("parsed_novel_ner.txt", "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            regex = re.compile("<\w+:PER>")  # PER 태그 추출
            pertags = regex.findall(line)

            for i, name in enumerate(pertags):
                start = line.find(name)
                end = start + len(name)
                line = line[:start] + ("<e%d>" % (i+1)) + line[start+1:end-5] + ("</e%d>" % (i+1)) + line[end:]

            tokens = tokenizer.tokenize(line)
            # Account for [CLS] and [SEP]
            special_tokens_count = 2
            if len(tokens) > args.max_seq_len - special_tokens_count:
                tokens = tokens[:(args.max_seq_len - special_tokens_count)]

            # Add [SEP] token
            tokens += [sep_token]
            token_type_ids = [sequence_a_segment_id] * len(tokens)

            # Add [CLS] token
            tokens = [cls_token] + tokens
            token_type_ids = [cls_token_segment_id] + token_type_ids

            input_ids = tokenizer.convert_tokens_to_ids(tokens)

            # The mask has 1 for real tokens and 0 for padding tokens. Only real tokens are attended to.
            attention_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)

            # Zero-pad up to the sequence length.
            padding_length = args.max_seq_len - len(input_ids)
            input_ids = input_ids + ([pad_token_id] * padding_length)
            attention_mask = attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)
            token_type_ids = token_type_ids + ([pad_token_segment_id] * padding_length)

            all_input_ids.append(input_ids)
            all_attention_mask.append(attention_mask)
            all_token_type_ids.append(token_type_ids)

    # Change to Tensor
    all_input_ids = torch.tensor(all_input_ids, dtype=torch.long)
    all_attention_mask = torch.tensor(all_attention_mask, dtype=torch.long)
    all_token_type_ids = torch.tensor(all_token_type_ids, dtype=torch.long)

    dataset = TensorDataset(all_input_ids, all_attention_mask, all_token_type_ids)

    return dataset

def extract_relation_output_feature():

    #
    parser = argparse.ArgumentParser()
    parser.add_argument("--input_file", default="parsed_novel_ner.txt", type=str, help="Input file for prediction")     # path: context/parsed_novel_ner.txt
    parser.add_argument("--output_file", default="sample_pred_out.txt", type=str, help="Output file for prediction")
    parser.add_argument("--model_dir", default=os.path.dirname(__file__)+"/model", type=str,
                        help="Path to save, load model")
    parser.add_argument("--batch_size", default=32, type=int, help="Batch size for prediction")
    parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
    pred_config = parser.parse_args()

    # load model and args
    args = get_args(pred_config)
    device = get_device(pred_config)
    model = load_model(pred_config, args, device)

    # Convert input file to TensorDataset
    dataset = convert_input_file_to_tensor_dataset(pred_config, args)

    # Predict
    sampler = SequentialSampler(dataset)
    data_loader = DataLoader(dataset, sampler=sampler, batch_size=pred_config.batch_size)

    preds = None                # 예측된 관계 클래스
    sentence_feature = None     # 최종 문장 당 bert output feature

    for batch in tqdm(data_loader, desc="Predicting"):
        batch = tuple(t.to(device) for t in batch)
        with torch.no_grad():
            inputs = {"input_ids": batch[0],
                      "attention_mask": batch[1]}
            if args.model_type != "distilkobert":
                inputs["token_type_ids"] = batch[2]

            # modeling_bert.py
            # bert의 마지막 레이어와 예측 값 가져오기
            last_encoder_layer = model.bert(**inputs)[1]
            pooled_output = model.dropout(last_encoder_layer)
            logits = model.classifier(pooled_output)

            # batch로 저장된 문장 리스트 하나로 만들어주기
            if preds is None:
                preds = logits.detach().cpu().numpy()
                sentence_feature = last_encoder_layer.detach().cpu().numpy()
            else:
                preds = np.append(preds, logits.detach().cpu().numpy(), axis=0)
                sentence_feature = np.append(sentence_feature, last_encoder_layer.detach().cpu().numpy(), axis=0)

    preds = np.argmax(preds, axis=1)

    return sentence_feature, preds

def predict(pred_config):
    # load model and args
    args = get_args(pred_config)
    device = get_device(pred_config)
    model = load_model(pred_config, args, device)
    logger.info(args)

    # Convert input file to TensorDataset
    dataset = convert_input_file_to_tensor_dataset(pred_config, args)

    # Predict
    sampler = SequentialSampler(dataset)
    data_loader = DataLoader(dataset, sampler=sampler, batch_size=pred_config.batch_size)

    preds = None

    for batch in tqdm(data_loader, desc="Predicting"):
        batch = tuple(t.to(device) for t in batch)
        with torch.no_grad():
            inputs = {"input_ids": batch[0],
                      "attention_mask": batch[1],
                      "labels": None}
            if args.model_type != "distilkobert":
                inputs["token_type_ids"] = batch[2]
            outputs = model(**inputs)
            logits = outputs[0]

            if preds is None:
                preds = logits.detach().cpu().numpy()
            else:
                preds = np.append(preds, logits.detach().cpu().numpy(), axis=0)

    preds = np.argmax(preds, axis=1)

    relations = list()
    for pred in preds:
        relations.append(pred)

    logger.info("Prediction Done!")
    return relations

def export_predict():
    init_logger()
    parser = argparse.ArgumentParser()

    parser.add_argument('--novel_name', default='./동백꽃.txt', help="name of the novel")
    parser.add_argument("--input_file", default="parsed_novel_ner.txt", type=str, help="Input file for prediction")
    parser.add_argument("--output_file", default="sample_pred_out.txt", type=str, help="Output file for prediction")
    parser.add_argument("--model_dir", default="./kor_relation_extraction/model", type=str, help="Path to save, load model")
    parser.add_argument("--batch_size", default=32, type=int, help="Batch size for prediction")
    parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")

    pred_config = parser.parse_args()
    relations = predict(pred_config)

    return relations


import tkinter as tk
from tkinter import ttk
import re

root = tk.Tk()
root.title("DiverseSimplePython")
tabControl = ttk.Notebook(root)

tab1 = ttk.Frame(tabControl)
tab2 = ttk.Frame(tabControl)
tab3 = ttk.Frame(tabControl)
tab4 = ttk.Frame(tabControl)
tab5 = ttk.Frame(tabControl)

tabControl.add(tab1, text ='Home Loan')
tabControl.add(tab2, text ='Life Signs')
tabControl.add(tab3, text ='Tax Credit')
tabControl.add(tab4, text ='Unit Conversion')
tabControl.add(tab5, text ='Word Count')

tabControl.pack(expand = 1, fill ="both")

# Home Loan
term = tk.IntVar()
amount = tk.IntVar()
rate = tk.IntVar()
monthly = tk.IntVar(value = 0)
discountFactor = tk.IntVar(value = 0)

errorOut = tk.StringVar(value="")
def homeLoan():
    try:
        if 3 > rate.get() or rate.get() > 18:
            print(rate.get(),"is not between 3-18%")
            raise("invaild rate")
        discountFactor.set(round(((1+(rate.get()/100)/12)**(term.get()*12)-1)/((rate.get()/100)/12*((1+(rate.get()/100)/12)**(term.get()*12))), 2))
        #print(D) ((1 + ((r/100)/12))**(n*12) - 1) / (((r/100)/12)*(1 + ((r/100)/12))**(n*12))
        #D = ((1 + (rate.get()/100))*(term.get()*12) - 1) / (rate.get()/100)*(1 + (rate.get()/100))*(term.get()*12)
        #print(D)
        monthly.set(round(amount.get()/discountFactor.get(), 2))
#https://www.coursehero.com/tutors-problems/Computer-Science/12726193--D4py-Home-Loan-Amortization-Develop-and-test-a-Python-program/#
        errorOut.set("table has been writen to C:/Users/Public/Documents/loanOut.txt")

        outarray = []

        monthpay = monthly.get()

        discount = discountFactor.get()

        total = amount.get()

        for i in range(term.get()*12):
            out2 = [0, 0, 0, 0]
            out2[0] = i + 1
            out2[1] = str(monthpay).ljust(7, ' ')
            out2[2] = round(monthpay * (rate.get()/100), 2)
            total = round(total - (monthpay - out2[2]), 2)
            out2[3] = total
            discount = round(((1+(rate.get()/100)/12)**(term.get()*12 - i)-1)/((rate.get()/100)/12*((1+(rate.get()/100)/12)**(term.get()*12 - i))), 2)

            monthpay = round(total/discount, 2)

            outarray.append(out2)

        outFile = open("C:/Users/Public/Documents/loanOut.txt", "w")

        outFile.write("month\t|payment\t|in pay\t|balance\n")

        for i in outarray:
            for a in i:
                outFile.write(str(a) + "\t|")
            outFile.write("\n")

        outFile.close()

    except Exception as e:
        print(e)
        errorOut.set("please enter valid values")
        monthly.set(0)
        discountFactor.set(0)

ttk.Label(tab1, text = "Monthly Amount:").grid(column = 0, row = 2, padx = 30, pady = 0)
ttk.Label(tab1, textvariable = monthly).grid(column = 0, row = 3, padx = 30, pady = 0)

ttk.Label(tab1, text = "Discount Factor:").grid(column = 2, row = 2, padx = 30, pady = 0)
ttk.Label(tab1, textvariable = discountFactor).grid(column = 2, row = 3, padx = 30, pady = 0)

tk.Label(tab1, textvariable=errorOut).grid(column = 1, row =3)

ttk.Label(tab1, text = "Term").grid(column = 0, row = 0, padx = 30, pady = 0)
nameEntered = ttk.Entry(tab1, width = 15, textvariable = term)
nameEntered.grid(column = 0, row = 1, padx = 30, pady = 0)

ttk.Label(tab1, text ="Amount").grid(column = 1, row = 0, padx = 30, pady = 0)
nameEntered = ttk.Entry(tab1, width = 15, textvariable = amount)
nameEntered.grid(column = 1, row = 1, padx = 30, pady = 0)

ttk.Label(tab1, text ="Rate (3-18%)").grid(column = 2, row = 0, padx = 30, pady = 0)
nameEntered = ttk.Entry(tab1, width = 15, textvariable = rate)
nameEntered.grid(column = 2, row = 1, padx = 30, pady = 0)

tk.Button(tab1, text="Click Me", command= homeLoan, width = 10).grid(column = 1, row = 2, padx = 0, pady = 0)

# life Signs
age = tk.IntVar()

errorOut2 = tk.StringVar(value = "")

def lifeSigns():
    try:
        aged = age.get() + 1
        breaths_low = breaths_high = beats = 0

        print(breaths_low)
        if(aged > 18):
            raise("yo, they're too old")
        for i in range(aged):
            if 0 >= i:
                breaths_low += (25)
                breaths_high += (60)
                beats += (67.5)
            if 1<= i <=4 :
                breaths_low += (20)
                breaths_high += (30)
                beats += (67.5)
            if 4< i <14 :
                breaths_low += (15)
                breaths_high += (25)
                beats += (67.5)
            if 14< i <18 :
                breaths_low += (11)
                breaths_high += (18)
                beats += (67.5)
        outputbreaths = 'you have breathed:\n' + str(breaths_low * 525600) + "-" + str(breaths_high * 525600) + '\ntimes!'
        outputbeats = "Heart Beated:\n" + str(beats * 525600) + "\ntimes!"
        ttk.Label(tab2, text = outputbreaths).grid(column = 0, row = 2, padx = 30, pady = 0)
        ttk.Label(tab2, text = outputbeats).grid(column = 2, row = 2, padx = 30, pady = 0)
        errorOut2.set("")
    except:
        errorOut2.set("please enter a valid age")

tk.Label(tab2, textvariable = errorOut2, width = 30).grid(column = 0) # just a spacer
ttk.Label(tab2, text ="Age 0-18").grid(column = 1, row = 0, padx = 30, pady = 0)
nameEntered = ttk.Entry(tab2, width = 15, textvariable = age)
nameEntered.grid(column = 1, row = 1, padx = 30, pady = 0)

tk.Button(tab2, text="Click Me", command= lifeSigns, width = 10).grid(column = 1, row = 2, padx = 0, pady = 0)

#Tax Credit
cost = tk.IntVar()
income = tk.IntVar()
lastPrimary = tk.IntVar()

errorOut3 = tk.StringVar(value = "")

def homeLoan():
    try:
        errorOut3.set("");
        if cost.get() <= 800000 and income.get() <= 225000 and (lastPrimary.get() >= 3 or 1000 < lastPrimary.get() <= 2018):
            ttk.Label(tab3, text = "you may be eligable to recieve \n The First-Time Home Buyer\n Tax Credit").grid(column = 0, row = 2, padx = 0, pady = 0)
        else:
            ttk.Label(tab3, text = "you mayn't be eligable to recieve \n The First-Time Home Buyer\n Tax Credit").grid(column = 0, row = 2, padx = 0, pady = 0)
    except:
        errorOut3.set("please enter valid numbers only")

tk.Label(tab3, textvariable = errorOut3).grid(row = 2, column = 2)

ttk.Label(tab3, text = "Cost").grid(column = 0, row = 0, padx = 30, pady = 0)
nameEntered = ttk.Entry(tab3, width = 15, textvariable = cost)
nameEntered.grid(column = 0, row = 1, padx = 30, pady = 0)

ttk.Label(tab3, text ="Income").grid(column = 1, row = 0, padx = 30, pady = 0)
nameEntered = ttk.Entry(tab3, width = 15, textvariable = income)
nameEntered.grid(column = 1, row = 1, padx = 30, pady = 0)

ttk.Label(tab3, text ="lastPrimary").grid(column = 2, row = 0, padx = 30, pady = 0)
nameEntered = ttk.Entry(tab3, width = 15, textvariable = lastPrimary)
nameEntered.grid(column = 2, row = 1, padx = 30, pady = 0)

tk.Button(tab3, text="Click Me", command= homeLoan, width = 10).grid(column = 1, row = 2, padx = 0, pady = 0)

#UnitConverter
unitsIn = tk.StringVar(value = "pick a unit")
unitsOut = tk.StringVar(value = "pick a unit")

valueIn = tk.StringVar(value = "enter units")

valueOut = tk.StringVar(value = "output will appear here")

conversion = {"cm": 1, "in": 2.54, "mi": 160934, "km": 100000, "kg": 1, "lb": 0.453592}

Output = ttk.Label(tab4, textvariable = valueOut).grid(row = 1, column = 2)

def convertUnits():
    global valueOut
    try:
        value = int(valueIn.get())
        valueOut.set("output: " + str((value * conversion[unitsIn.get()]) / conversion[unitsOut.get()]) + " " + unitsOut.get())
    except Exception as e:
        print(e)
        valueOut.set("please enter a valid number")

tk.OptionMenu(tab4, unitsIn, "cm", "in", "mi", "km", "lb", "kg").grid(column = 0, row = 0)
tk.OptionMenu(tab4, unitsOut, "cm", "in", "mi", "km", "lb", "kg").grid(column = 1, row = 0)

tk.Label(tab4, width = 15, textvariable = valueIn).grid(column = 2, row = 0)

tk.Button(tab4, text="Click Me", command = convertUnits, width = 10).grid(column = 1, row = 1)

# Word Count

scrollbar = tk.Scrollbar(tab5)
scrollbar.grid(column=2, row=1, sticky="nsew")

text = tk.Text(tab5, height=5, width=50, yscrollcommand=scrollbar.set)
text.grid(column=1, row=1)

scrollbar.config(command=text.yview)

def wordCount():
    x = re.findall("(?:\s+|$)", text.get("1.0", "end"), flags=0) # find all spaces and end of line
    print(len(x) - 1)
    ttk.Label(tab5, text = (len(x) - 1,"words!")).grid(column = 0, row = 2, padx = 5, pady = 0)

ttk.Label(tab5, text = "string").grid(column = 1, row = 0, padx = 30, pady = 0)

tk.Button(tab5, text="Click Me", command= wordCount, width = 10).grid(column = 1, row = 2, padx = 0, pady = 0)

root.mainloop()
#tk.Button(tab3, text="Click Me", command= show_alert).grid(column = 1, row = 0, padx = 30, pady = 0)


import requests

# 设置API的URL和公共参数
base_url = "https://zh.wikipedia.org/w/api.php"
params = {
    "action": "query",
    "format": "json",
    "list": "categorymembers",
    "cmlimit": 500,  # 每页返回的数量
}

# 指定多个分类名称
categories = ["Category:視覺小說", "Category:美少女遊戲"]  # 替换成你想要的分类名称

# 存储所有页面ID的集合
all_page_ids = set()

# 遍历每个分类，获取页面ID
for category in categories:
    continue_flag = True
    cmcontinue = None

    while continue_flag:
        params["cmtitle"] = category
        if cmcontinue:
            params["cmcontinue"] = cmcontinue

        # 发送API请求
        response = requests.get(base_url, params=params)
        data = response.json()

        # 处理API响应，提取页面ID
        page_ids = [page["pageid"] for page in data["query"]["categorymembers"]]

        # 将页面ID添加到集合中
        all_page_ids.update(page_ids)

        # 检查是否有更多页面需要获取
        if "continue" in data:
            cmcontinue = data["continue"]["cmcontinue"]
        else:
            continue_flag = False

# 将合并后的页面ID写入文件
with open("wikipedia_page_id.txt", "w") as file:
    for page_id in all_page_ids:
        file.write(str(page_id) + "\n")

print("页面ID已保存到文件：wikipedia_page_id.txt")


from enum import Enum

Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr',
                       'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))

for name, member in Month.__members__.items():
    print(name, '-->', member, ',', member.value)

# value属性则是自动赋给成员的int常量，默认从1开始计数。

# 如果需要更精确地控制枚举类型，可以从Enum派生出自定义类：
from enum import Enum, unique

# @unique装饰器可以帮助我们检查保证没有重复值。
@unique
class Weekday(Enum):
    Sun = 0  # Sun的value被设定为0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6

# 访问这些枚举类型可以有若干种方法：
day1 = Weekday.Mon
print(day1)  # Weekday.Mon
print(Weekday.Tue)  # Weekday.Tue
print(Weekday['Tue'])  # Weekday.Tue
print(Weekday.Mon.value)  # 1
print(day1 == Weekday.Mon)  # True

"""  练习不会做  """
#
# class Gender(Enum):
#     Male = 0
#     Female = 1
#
# class Student(object):
#     def __init__(self, name, gender):
#         self.name = name
#         self.gender = None
#         if gender == Gender.Male:
#             print(self.gender == Gender.Male.value)
#         if gender == Gender.Female:
#             print(self.gender == Gender.Female.value)
#         # else:
#         #     raise ValueError("gender must be Male or Female ！")
#
#     def __str__(self):
#         print(self.name, self.gender)
#
# s = Student("niefeng", "Male")
# s.__str__()
# print('Male' == Gender.Male)


import os
import warnings

import yaml
import torch
from gym.wrappers.monitoring.video_recorder import VideoRecorder

from model import SAC
from env import make_env

warnings.filterwarnings("ignore", category=DeprecationWarning) # for not appearing warning messages
def test(cfg):
    """
    Test model
    Print average scores, Save playing video
    """
    ########################
    #    make SAC model    #
    ########################
    device = cfg['device']
    state_dim = cfg['env']['state_dim']
    action_dim = cfg['env']['action_dim']
    hidden_dim = cfg['model']['hidden_dim']
    device = torch.device("cuda" if (device=='cuda' and torch.cuda.is_available()) else "cpu")
    model = SAC(state_dim, action_dim, device, hidden_dim)

    ########################
    #    load SAC model    #
    ########################
    model_path = cfg['test']['model_path']
    checkpoint = torch.load(model_path, map_location=device)
    model.policy_net.load_state_dict(checkpoint['policy_net_state_dict'])
    model.value_net.load_state_dict(checkpoint['value_net_state_dict'])
    model.target_value_net.load_state_dict(checkpoint['value_net_state_dict'])
    model.q_net.load_state_dict(checkpoint['q_net_state_dict'])

    ########################
    #     test settings    #
    ########################
    test_times = cfg['test']['test_times']
    video_path = cfg['test']['video_path']
    env_name = cfg['env']['env_name']

    os.makedirs(video_path, exist_ok=True)
    env = make_env(env_name)

    ########################
    #      test model      #
    ########################
    average_score = 0.0
    seed = [i for i in range(test_times)]
    for idx in range(test_times):
        video_file_path = os.path.join(video_path, f'test_{idx+1}.mp4')
        video_recorder = VideoRecorder(env, video_file_path)
        state = env.reset(seed=seed[idx])
        done, score = False, 0.0
        while not done:
            with torch.no_grad():
                action = model.get_action(state, validation=True).item()
            next_state, reward, done, info = env.step(action)
            score += reward
            state = next_state
            video_recorder.capture_frame()
        average_score += score
        video_recorder.close()
    average_score /= test_times
    print(f'----- average score: {average_score:6,.2f} -----')

if __name__ == '__main__':
    with open('./config/config.yaml') as f:
        cfg = yaml.safe_load(f)
    test(cfg)


import random
import time

# Global variables
grid = [[]]
size_of_grid = 10
ships_in_game = 8
ship_positions = [[]]
ships_sunk = 0
turns_left = 50
game_finished = False
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def attempt_placing_ship(start_r, end_r, start_c, end_c):
    """ Places a ship on the board, but only
        if another ship is not occupying the space needed """
    global grid
    global ship_positions

# Checks space required for ship is all empty
    place_ship_here = True
    for r in range(start_r, end_r):
        for c in range(start_c, end_c):
            if grid[r][c] != ".":
                place_ship_here = False
                break

# Places a ship if space is available
    if place_ship_here:
        ship_positions.append([start_r, end_r, start_c, end_c])
        for r in range(start_r, end_r):
            for c in range(start_c, end_c):
                grid[r][c] = "O"
    return place_ship_here

def check_ship_fits(row, column, direction, size):
    """ Check that the ship infomation generated fits onto the game grid """
    global size_of_grid

    start_r, end_r, start_c, end_c = row, row + 1, column, column + 1

    if direction == "up":
        if row - size < 0:
            return False
        start_r = row - size + 1

    elif direction == "down":
        if row + size >= size_of_grid:
            return False
        end_r = row + size

    elif direction == "left":
        if column - size < 0:
            return False
        start_c = column - size + 1

    elif direction == "right":
        if column + size >= size_of_grid:
            return False
        end_c = column + size

    return attempt_placing_ship(start_r, end_r, start_c, end_c)

def create_starting_grid():
    """ Creates a 10 x 10 grid for the game to be played on """
    global size_of_grid
    global grid
    global ship_positions
    global ships_in_game

    random.seed(time.time())

# Creating the grid itself
    rows, columns = (size_of_grid, size_of_grid)

    grid = []
    for r in range(rows):
        row = []
        for c in range(columns):
            row.append(".")
        grid.append(row)

# Generates random positioning for the ships until all are placed
    ships_placed = 0
    ship_positions = []

    while ships_placed != ships_in_game:
        ran_row = random.randint(0, rows - 1)
        ran_column = random.randint(0, columns - 1)
        ran_direction = random.choice(["up", "down", "left", "right"])
        ran_size = random.randint(2, 5)

# Sends randomized ship infomation to be validated
        if check_ship_fits(ran_row, ran_column, ran_direction, ran_size):
            ships_placed += 1

def print_grid():
    """ Will print the 10 x 10 game grid with rows (A-J) and columns (0-9) """
    global grid
    global alphabet

# Enables ships to be seen to test they are correctly placed
    grid_testing = False

# Slices alphabet string to the required length
    alphabet = alphabet[0: len(grid) + 1]

# Adds letters down the left side of grid
    for row in range(len(grid)):
        print(alphabet[row], end=") ")
        for column in range(len(grid[row])):
            if grid[row][column] == "O":
                if grid_testing:
                    print("O", end=" ")
                else:
                    print(".", end=" ")
            else:
                print(grid[row][column], end=" ")
        print("")

# Adds numbers along the bottom edge of the grid
    print("  ", end=" ")
    for i in range(len(grid[0])):
        print(str(i), end=" ")
    print("")

def valid_missile_choice():
    """ Returns a valid set of co-ordinates to fire upon """
    global grid
    global alphabet
    global size_of_grid

    valid_choice = False
    row = -1
    column = -1

    while valid_choice is False:
        placement_choice = input("Enter row (A-J) and column (0-9), eg. F6:\n")
        placement_choice = placement_choice.upper()
# Ensures input is the correct length
        if len(placement_choice) <= 1 or len(placement_choice) > 2:
            print("Error: Please enter 1 row (A-J) and 1 column (0-9)")
            continue
# Ensures a letter and number are entered in the input
        row = placement_choice[0]
        column = placement_choice[1]
        if not row.isalpha() or not column.isnumeric():
            print("Error: Please enter a letter (A-J) and a number (0-9)")
            continue
# Ensures letter entered is within grid size
        row = alphabet.find(row)
        if not (-1 < row < size_of_grid):
            print("Error: Please enter a letter (A-J) and a number (0-9)")
            continue
# Ensures number entered is within grid size
        column = int(column)
        if not (-1 < column < size_of_grid):
            print("Error: Please enter a letter (A-J) and a number (0-9)")
            continue
# Ensures input hasn't already been chosen by user
        if grid[row][column] == "X" or grid[row][column] == "#":
            print("You have already sent a missile here, please pick again")
            continue
# Confirms valid input
        if grid[row][column] == "." or grid[row][column] == "O":
            valid_choice = True

    return row, column

def fully_sunk(row, column):
    """ checks if all parts of a hit ship have been sunk """
    global grid
    global ship_positions

# Code to find the specific ship hit
    for position in ship_positions:
        start_r = position[0]
        end_r = position[1]
        start_c = position[2]
        end_c = position[3]
        if start_r <= row <= end_r and start_c <= column <= end_c:
            for r in range(start_r, end_r):
                for c in range(start_c, end_c):
                    if grid[r][c] != "X":
                        return False
    return True

def fire_missile():
    """ Fires missile at selected spot on grid and updates accordingly """
    global grid
    global ships_sunk
    global turns_left

    row, column = valid_missile_choice()
    print(" ")

# Informs the user of a missed shot
    if grid[row][column] == ".":
        print("Missile missed, no ship here!")
        grid[row][column] = "#"
# Informs the user of a hit and if the ship is fully sunk
    elif grid[row][column] == "O":
        print("Your missile hit!")
        grid[row][column] = "X"
        if fully_sunk(row, column):
            print("You completely sunk a battleship!")
            ships_sunk += 1
        else:
            print("Hit the rest of this ship to sink it!")

    turns_left -= 1

def check_game_finished():
    """ Checks if user has sunk all ships or run out of turns """
    global ships_sunk
    global ships_in_game
    global turns_left
    global game_finished

    if ships_in_game == ships_sunk:
        print("CONGRATULATIONS! You sunk all the battleships!")
        game_finished = True
    elif turns_left <= 0:
        print("You're out of turns, better luck next time!")
        game_finished = True

def main():
    """ Function that runs the game loop """
    global game_finished

    print("-----------------------------")
    print("Welcome to Battleships!")
    print("Can you destroy the 8 enemy ships within 50 shots?")
    print("X is a hit, # is a miss, . is unknown")
    print("Fire at will!")
    print("-----------------------------")

    create_starting_grid()

    while game_finished is False:
        print_grid()
        print(" ")
        print("You have " + str(turns_left) + " missiles remaining!")
        print(str(ships_in_game - ships_sunk) + " enemy ships remain!")
        fire_missile()
        print("-----------------------------")
        print(" ")
        check_game_finished()

main()


import shapes
import unittest

class ErrorsTest(unittest.TestCase):
    def test_nonpositive_arguments(self):
        with self.assertRaises(ValueError, msg="Values must be positive."):
            shapes.Rectangle(3, 0)

    def test_wrong_side_length(self):
        with self.assertRaises(
            ValueError,
            msg="Each side should be shorter than the sum of others.",
        ):
            shapes.Trapezoid(100, 3, 5, 1)

class FormulasTest(unittest.TestCase):
    def test_pyramid_volume(self):
        pyramid = shapes.Pyramid(10)
        volume = 117.85113019775791
        self.assertEqual(pyramid.get_volume(), volume)

def main():
    unittest.main(verbosity=2)

if __name__ == "__main__":
    main()


from vyvo.devices import RFIDDeviceBase

import os

class DiskMockDevice(RFIDDeviceBase):
    def __init__(self, config):
        cache_dir = config["core"]["cache_dir"]
        self.diskfile = os.path.join(cache_dir, "diskmock.file")

    def read(self):
        try:
            return open(self.diskfile).read().strip()
        except FileNotFoundError:
            return None

    def write(self, uri):
        if uri in ("None", ""):
            return os.remove(self.diskfile)

        return open(self.diskfile, "w").write(uri)


import importlib
import random

import numpy as np
import tensorflow as tf
from absl import app
from absl.flags import argparse_flags
from tensorflow.compat import v1

"""Main LM command line"""

SUBCOMMANDS = {}

def register_subcommand(module_name):
    m = importlib.import_module("lm.cli." + module_name)
    SUBCOMMANDS[module_name] = m

def set_random_seed(args):
    seed = args.seed
    random.seed(seed)
    v1.set_random_seed(seed)
    np.random.seed(seed)

def fix_logger():
    v1.get_logger().propagate = False

def parse_args(args):
    # Parse command line arguments
    parser = argparse_flags.ArgumentParser()
    parser.add_argument("--seed", type=int, default=1337, help="seed")

    subparsers = parser.add_subparsers(help="Available commands", dest="subparser")
    for name, cmd in SUBCOMMANDS.items():
        cmd_parser = subparsers.add_parser(
            name,
            help=cmd.__doc__,
            # Do not make absl FLAGS available after the subcommand
            inherited_absl_flags=False,
        )
        cmd.parse_args(args, cmd_parser)

    args = parser.parse_args(args[1:])
    set_random_seed(args)
    fix_logger()
    return args

def main(args):
    cmd = SUBCOMMANDS.get(args.subparser, None)
    if cmd is None:
        app.usage(shorthelp=True, exitcode=-1)
        return
        # raise ValueError('invalid command %s', args.subparser)
    return cmd.main(args)

def apprun():
    tf.disable_v2_behavior()

    register_subcommand("encode")
    register_subcommand("cleantxt")
    register_subcommand("configure")
    register_subcommand("train")
    register_subcommand("eval")
    register_subcommand("hashsort")
    register_subcommand("interactive")
    register_subcommand("synth")
    app.run(main, flags_parser=parse_args)

if __name__ == "__main__":
    apprun()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from _handler import ZsiteBase
from ctrl._urlmap.zsite import urlmap
from zkit.errtip import Errtip
from config import SITE_HTTP, RPC_HTTP
from model.money_alipay import alipay_payurl_with_tax
from model.user_mail import user_by_mail
from model.money import pay_new, TRADE_STATE_NEW, TRADE_STATE_ONWAY, TRADE_STATE_FINISH, pay_account_get, bank, Trade, trade_log, pay_notice
from model.zsite import zsite_new, ZSITE_STATE_NO_PASSWORD, ZSITE_STATE_ACTIVE, ZSITE_STATE_APPLY
from zkit.txt import EMAIL_VALID
from model.cid import CID_USER, CID_PAY_ALIPAY, CID_TRADE_PAY
from model.user_auth import user_new_by_mail
from yajl import dumps, loads
from model.state import STATE_SECRET, STATE_ACTIVE
from model.notice import notice_new

@urlmap('/pay')
class Index(ZsiteBase):

    def _arguments(self):
        url = self.get_argument('url', '')
        title = self.get_argument('title', '')
        return url, title

    def get(self):
        current_user = self.current_user
        current_user_id = self.current_user_id
        url, title = self._arguments()
        price = self.get_argument('price', 4.2)

        if current_user:
            alipay_account = pay_account_get(
                current_user_id,
                CID_PAY_ALIPAY
            )
        else:
            alipay_account = ''

        self.render(
            url=url,
            title=title,
            amount=price,
            errtip=Errtip(),
            alipay_account=alipay_account
        )

    def post(self):
        current_user = self.current_user
        zsite = self.zsite
        request = self.request
        errtip = Errtip()
        zsite_id = self.zsite_id

        url, title = self._arguments()
        amount = self.get_argument('amount', 0)
        alipay_account = self.get_argument('alipay_account', '')

        if not amount:
            errtip.amount = '请输入金额'
        else:
            try:
                amount = float(amount)
            except ValueError:
                errtip.amount = '%s 不是有效的金额'%amount
            else:
                if amount <= 0:
                    errtip.amount = '金额须大于零'
                elif amount >= 9999999:
                    errtip.amount = '金额超出上限'
                else:
                    amount_cent = amount * 100

        if not current_user:
            mail = self.get_argument('mail', '')
            if not mail:
                errtip.mail = '请输入联系邮箱'
            elif not EMAIL_VALID.match(mail):
                errtip.mail = '邮箱无效'
            else:
                user = user_by_mail(mail)
                self.set_cookie('E', mail.strip().lower())
                if not user:
                    user = user_new_by_mail(mail)
                elif user.state >= ZSITE_STATE_APPLY:
                    return self.redirect(
                              '/auth/login?next=%s'%request.uri
                           )
                current_user = user

        if current_user and not errtip:
            subject = '%s 向 %s 捐赠 %.2f 元' % (current_user.name, zsite.name, amount)
            current_user_id = current_user.id
            balance_cent = bank.get(current_user_id)

            def _pay_new(state):
                return pay_new(amount, current_user_id, zsite_id, CID_TRADE_PAY, state).id

            txt = self.get_argument('txt', None)
            secret = self.get_argument('secret', None)

            message = {}

            if title:
                message['title'] = title
            if url:
                message['url'] = url
            if txt:
                message['txt'] = txt
                if secret:
                    message['secret'] = secret

            if balance_cent >= amount_cent:
                o_id = _pay_new(TRADE_STATE_FINISH)
                if message:
                    trade_log.set(o_id, dumps(message))
                pay_notice(o_id)

                return self.redirect('%s/pay/result/%s'%(SITE_HTTP, o_id))
            elif balance_cent > 0:
                subject += '(余额支付 %.2f 元)' % (balance_cent/100.0)
                o_id = _pay_new(TRADE_STATE_NEW)
                amount_cent -= balance_cent
            else:
                o_id = _pay_new(TRADE_STATE_NEW)

            trade_log.set(o_id, dumps(message))

            return_url = '%s/money/alipay_sync' % SITE_HTTP
            notify_url = '%s/money/alipay_async' % RPC_HTTP

            alipay_url = alipay_payurl_with_tax(
                current_user_id,
                amount_cent/100.0,
                return_url,
                notify_url,
                subject,
                alipay_account,
                o_id
            )

            return self.redirect(alipay_url)

        self.render(
            url=url, title=title,
            amount=amount,
            errtip=errtip,
            alipay_account=alipay_account
        )


#!/usr/bin/python
import sys

# read final SCF energy from file specified by argv and print
def main():
    # get inputfile
    filename = str(sys.argv[1])

    # parse for SCF energy
    energy = parse_energy(filename)

    print(energy)
    return 0

# Parse file with geometry optimization for final Energy
# filename[in]: string with filename
# energy[return]: Final energy in Hartrees
def parse_energy(filename):

    converged = False
    energy = []

    try:
        with open(filename) as ifile:
            lines = ifile.readlines()
            for line in lines:
                # get energy
                if 'Final energy is' in line:
                    splitline = line.split()
                    try:
                        energy.append(float(splitline[3]))
                    except ValueError:
                        print('Error while reading energy in ' + filename)
                        sys.exit(1)
                # check if converged
                if "OPTIMIZATION CONVERGED" in line:
                    converged = True
    except OSError:
        print('Error while reading energy: cannot open ' + filename)
        sys.exit(1)

    # check for multiple calculations and unconverged optimization
    if len(energy) != 1:
        print('multiple calculations detected in ' + filename)
        sys.exit(1)

    if not converged:
        print('Error while reading energy: unconverged calculation in ' + filename)
        sys.exit(1)

    return energy[0]

if __name__ == '__main__':
    sys.exit(main())


import time
from pathlib import Path

from audio import AudioPhrase, CachedAudioPhrase
from language import LanguagePair
from moviepy.editor import (AudioFileClip, ColorClip, CompositeAudioClip,
                            CompositeVideoClip, ImageClip, TextClip)

PAUSE_LENGTH = 0.5
START_VIDEO_PAUSE_LENGTH = 1.0
INTER_PHRASE_PAUSE_LENGTH = 2.0
BG_MUSIC_FADEOUT_LENGTH = 3.0
BG_MUSIC_VOLUME = 0.15
TEXT_SIZE = (800, 300)
TEXT_FONT_SIZE = 70
VIDEO_DIMENSIONS = {"height": 1920, "width": 1080}
SAVE_PATH = Path(__file__).parent / "media-output"

class Video:
    def __init__(
        self,
        *,
        image_path: Path,
        audio_phrases: list[AudioPhrase | CachedAudioPhrase],
        tmp_media_dir: Path,
        language_info: LanguagePair,
    ) -> None:
        self._image_path = image_path
        self._audio_phrases = audio_phrases
        self._audio_timings: list[tuple[AudioPhrase | CachedAudioPhrase, float]] = []
        self._video_length = 0
        self._tmp_dir = tmp_media_dir
        self._language_info = language_info
        self.video_path = SAVE_PATH / f"video{int(time.time() * 1000)}.mp4"

        self._calculate_audio_start_times()
        self._create_video_from_image()
        self._add_text_overlay()
        self._add_audio_to_video()
        self._save_video_file()

    def _calculate_audio_start_times(self) -> None:
        t = START_VIDEO_PAUSE_LENGTH
        for idx, phrase in enumerate(self._audio_phrases):
            self._audio_timings.append((phrase, t))
            t += (
                phrase.native_audio_length
                + phrase.foreign_audio_length * (2 if idx != 0 else 1)
                + INTER_PHRASE_PAUSE_LENGTH
            )
        self._video_length = t + BG_MUSIC_FADEOUT_LENGTH

    def _create_video_from_image(self) -> None:
        self._video = ImageClip(
            str(self._image_path), duration=self._video_length
        ).resize(**VIDEO_DIMENSIONS)

    def _add_audio_to_video(self) -> None:
        audio_clips = []
        bg_music_clip = (
            AudioFileClip(str(self._language_info.background_music_path))
            .subclip(0, self._video_length)
            .audio_fadeout(BG_MUSIC_FADEOUT_LENGTH)
            .volumex(BG_MUSIC_VOLUME)
        )
        audio_clips.append(bg_music_clip)

        for idx, (phrase, start_time) in enumerate(self._audio_timings):
            audio_clips.append(
                AudioFileClip(str(phrase.native_audio_path)).set_start(start_time)
            )
            start_time += phrase.native_audio_length + PAUSE_LENGTH
            audio_clips.append(
                AudioFileClip(str(phrase.foreign_audio_path)).set_start(start_time)
            )
            # Don't repeat the foreign audio for the introduction twice
            if idx == 0:
                continue
            start_time += phrase.foreign_audio_length + PAUSE_LENGTH
            audio_clips.append(
                AudioFileClip(str(phrase.foreign_audio_path)).set_start(start_time)
            )
        self._video = self._video.set_audio(CompositeAudioClip(audio_clips))

    def _add_text_overlay(self) -> None:
        text_clips = []
        for idx, (phrase, start_time) in enumerate(self._audio_timings):
            # Create the text clips
            native_text_clip = self._create_text_clip(
                phrase.native_phrase, phrase.native_audio_length, start_time
            )
            start_time += phrase.native_audio_length + PAUSE_LENGTH
            foreign_text_clip = self._create_text_clip(
                phrase.foreign_phrase,
                phrase.foreign_audio_length * (2 if idx != 0 else 1) + PAUSE_LENGTH,
                start_time,
            )
            text_clips.extend([native_text_clip, foreign_text_clip])
        # Overlay the text-background composites onto the video
        self._video = CompositeVideoClip([self._video] + text_clips)

    def _create_text_clip(
        self, text: str, length: float, start_time: float
    ) -> CompositeVideoClip:
        native_text = (
            TextClip(
                text,
                fontsize=TEXT_FONT_SIZE,
                color="white",
                method="caption",
                size=TEXT_SIZE,
            )
            .set_duration(length)
            .set_start(start_time)
        )
        # Create a black background that fits the text
        background = (
            ColorClip(size=native_text.size, color=(0, 0, 0))
            .set_duration(length)
            .set_start(start_time)
        )
        # Overlay the text over the background
        return CompositeVideoClip([background, native_text]).set_position(
            ("center", "center")
        )

    def _save_video_file(self) -> None:
        self._video.write_videofile(
            str(self.video_path),
            codec="libx264",
            fps=60,
            audio_codec="aac",
            temp_audiofile="temp-audio.m4a",
            remove_temp=True,
        )


# Curso Técnico de Informática
# Autor: Agostinho Arthur Bueno Fernandes
# Data: 27/12/2022
# Atividade 10

# Importando as bibliotecas
import os

# Limpando o terminal
os.system('cls')

# Declaração
nome_idade = {}
lista = []

# Flag
opcao = '999'

while(True):
    opcao = str(input('Digite "999" para sair, caso queira ignorar é so aperta o enter: '))

    if (opcao != '999'):
        nome_idade['nome'] = str(input('Digite seu nome: '))
        nome_idade['idade'] = int(input('Digite sua idade: '))
        lista.append(nome_idade.copy())
        print('Digite mais um nome e idade... ')
    else:
            print('Você digitou "999" para sair ')

            break
            print('-'*50)

print(f'Essa é a lista de nomes e idade {lista}')


import pandas  # pip install pandas xlrd

import urllib.request
import os

class ExcelLoader:
    def __init__(self, req_url, excel_path="temp.xlsx", auto_delete=True):
        self.req_url = req_url
        self.excel_path = excel_path
        self.auto_delete = auto_delete

    def __call__(self):
        self.dl_excel()
        excel_dict = self.load_excel()
        self.rm_excel()
        return excel_dict

    def dl_excel(self):
        if os.path.exists(self.excel_path):
            print(f"File already exists: {self.excel_path}")
            return
        print(f"Downloading file from: {self.req_url}")
        contents = urllib.request.urlopen(self.req_url).read()
        with open(self.excel_path, "wb") as out_file:
            out_file.write(contents)
        print(f"Successfully written to file: {self.excel_path}")

    def load_excel(self):
        data_frame = pandas.read_excel(self.excel_path, sheet_name=None, dtype=str, na_filter=False)
        data_dict = {}
        for frame in data_frame:
            data_dict[frame] = list(data_frame[frame].itertuples())
        return data_dict

    def rm_excel(self):
        if self.auto_delete:
            os.remove(self.excel_path)
            print(f"Successfully deleted file: {self.excel_path}")

if __name__ == '__main__':
    req_url = "https://docs.google.com/spreadsheets/d/1Ocd8JNLV8IAKWyxKdmcYaGeu09pbH3R5jlf6_PxoUhs/export?format=xlsx"
    print("Testing ExcelLoader...")
    el = ExcelLoader(req_url, auto_delete=False)
    print(f"Sheets in dict: {el().keys()}")
    """ EXTRA CODE """
    import re
    sheets = el()
    quarter_num = '1'
    levels_list = ['11', '12']
    strand_regex = "^(?!nonSHS|NotLoaded)"
    exclusion_regex = "^(?!Parish Involvement|The Bible)"
    template_1 = """    parts.add(new compUtil("%s", 1.0 / %s * 1000));"""
    template_2 = """
    if (strand.matches("%s") && section.equals("%s") && level.matches("%s") && quarterNum > 2) {
        ArrayList<compUtil> parts = new ArrayList<compUtil>();
        String compName = "Average";
    %s
        addNewGrade(parts, compName);
    }"""
    shs_sections = [section.name for section in sheets['Sections'] if section.level in levels_list]
    shs_strands = [strand.strand for strand in sheets['Strands'] if re.match(strand_regex, strand.strand)]
    shs_subjects = [subject for subject in sheets['Subjects'] if \
        quarter_num in subject.quarterNum and \
        subject.sectionName in shs_sections and \
        subject.strand in shs_strands and \
        re.match(exclusion_regex, subject.Subject)]
    for (level, section_name, strand) in [(_level, _section_name, _strand) \
            for _level in levels_list \
            for _section_name in shs_sections \
            for _strand in shs_strands]:
        loaded_subjects = [s.Subject for s in shs_subjects if s.sectionName == section_name and s.strand == strand]
        if not loaded_subjects:
            continue
        num_subjects = len(loaded_subjects)
        string_1 = "\n".join(template_1 % (subject, num_subjects) for subject in loaded_subjects)
        string_2 = template_2 % (strand, section_name, level, string_1)
        with open("out.txt", "w+") as output: print(string_2, file=output)


import os
import pandas as pd

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_colwidth', -1)

cd = os.chdir('C:/Users/bphil/Documents/Data Visualization/JourNetwork/dataviscourse-pr-journetwork/Source Code/data')
files = os.listdir(cd)

count = 0
for ll in range(0, len(files)):
    str = files[ll].find('JournalCitedTab.csv') # Swap with a name = ['JournalProfileGrid.csv', 'JournalCitingTab.csv', 'JournalCitedTab.csv']
    if str > -1:
        if count is 0:
            print(files[ll])
            JIF = pd.read_csv(files[ll])
            count += 1
        else:
            print(files[ll])
            csv = pd.read_csv(files[ll])
            frames = [JIF, csv]
            JIF = pd.concat(frames)
JIF.to_csv('C:/Users/bphil/Documents/Data Visualization/JourNetwork/dataviscourse-pr-journetwork/Source Code/filtered data/AllJournalCitedTab.csv')


import yarl
from oauthlib import oauth1

import synapse.exc as s_exc

import synapse.lib.stormtypes as s_stormtypes

@s_stormtypes.registry.registerLib
class OAuthV1Lib(s_stormtypes.Lib):
    '''
    A Storm library to handle OAuth v1 authentication.
    '''
    _storm_locals = (
        {
            'name': 'client',
            'desc': '''
                Initialize an OAuthV1 Client to use for signing/authentication.
            ''',
            'type': {
                'type': 'function', '_funcname': '_methClient',
                'args': (
                    {'name': 'ckey', 'type': 'str',
                     'desc': 'The OAuthV1 Consumer Key to store and use for signing requests.'},
                    {'name': 'csecret', 'type': 'str',
                     'desc': 'The OAuthV1 Consumer Secret used to sign requests.'},
                    {'name': 'atoken', 'type': 'str',
                     'desc': 'The OAuthV1 Access Token (or resource owner key) to use to sign requests.)'},
                    {'name': 'asecret', 'type': 'str',
                     'desc': 'The OAuthV1 Access Token Secret (or resource owner secret) to use to sign requests.'},
                    {'name': 'sigtype', 'type': 'str', 'default': oauth1.SIGNATURE_TYPE_QUERY,
                     'desc': 'Where to populate the signature (in the HTTP body, in the query parameters, or in the header)'},
                ),
                'returns': {
                    'type': 'inet:http:oauth:v1:client',
                    'desc': 'An OAuthV1 client to be used to sign requests.',
                }
            },
        },
    )

    _storm_lib_path = ('inet', 'http', 'oauth', 'v1',)

    def getObjLocals(self):
        return {
            'client': self._methClient,
            'SIG_BODY': oauth1.SIGNATURE_TYPE_BODY,
            'SIG_QUERY': oauth1.SIGNATURE_TYPE_QUERY,
            'SIG_HEADER': oauth1.SIGNATURE_TYPE_AUTH_HEADER,
        }

    async def _methClient(self, ckey, csecret, atoken, asecret, sigtype=oauth1.SIGNATURE_TYPE_QUERY):
        return OAuthV1Client(self.runt, ckey, csecret, atoken, asecret, sigtype)

@s_stormtypes.registry.registerType
class OAuthV1Client(s_stormtypes.StormType):
    '''
    A client for doing OAuth V1 Authentication from Storm.
    '''
    _storm_locals = (
        {
            'name': 'sign',
            'desc': '''
                Sign an OAuth request to a particular URL.
            ''',
            'type': {
                'type': 'function', '_funcname': '_methSign',
                'args': (
                    {'name': 'baseurl', 'type': 'str', 'desc': 'The base url to sign and query.'},
                    {'name': 'method', 'type': 'dict', 'default': 'GET',
                     'desc': 'The HTTP Method to use as part of signing.'},
                    {'name': 'headers', 'type': 'dict', 'default': None,
                     'desc': 'Optional headers used for signing. Can override the "Content-Type" header if the signature type is set to SIG_BODY'},
                    {'name': 'params', 'type': 'dict', 'default': None,
                     'desc': 'Optional query parameters to pass to url construction and/or signing.'},
                    {'name': 'body', 'type': 'bytes', 'default': None,
                     'desc': 'Optional HTTP body to pass to request signing.'},
                ),
                'returns': {
                    'type': 'list',
                    'desc': 'A 3-element tuple of ($url, $headers, $body). The OAuth signature elements will be embedded in the element specified when constructing the client.'
                },
            },
        },
    )
    _storm_typename = 'inet:http:oauth:v1:client'

    def __init__(self, runt, ckey, csecret, atoken, asecret, sigtype, path=None):
        s_stormtypes.StormType.__init__(self, path=path)
        self.runt = runt
        self.locls.update(self.getObjLocals())
        self.sigtype = sigtype
        self.client = oauth1.Client(
            ckey,
            client_secret=csecret,
            resource_owner_key=atoken,
            resource_owner_secret=asecret,
            signature_type=sigtype
        )

    def getObjLocals(self):
        return {
            'sign': self._methSign,
        }

    async def _methSign(self, baseurl, method='GET', headers=None, params=None, body=None):
        url = yarl.URL(baseurl).with_query(await s_stormtypes.toprim(params))
        headers = await s_stormtypes.toprim(headers)
        body = await s_stormtypes.toprim(body)
        if self.sigtype == oauth1.SIGNATURE_TYPE_BODY:
            if not headers:
                headers = {'Content-Type': oauth1.rfc5849.CONTENT_TYPE_FORM_URLENCODED}
            else:
                headers['Content-Type'] = oauth1.rfc5849.CONTENT_TYPE_FORM_URLENCODED
        try:
            return self.client.sign(str(url), http_method=method, headers=headers, body=body)
        except ValueError as e:
            mesg = f'Request signing failed ({str(e)})'
            raise s_exc.StormRuntimeError(mesg=mesg) from None

@s_stormtypes.registry.registerLib
class OAuthV2Lib(s_stormtypes.Lib):
    '''
    A Storm library for managing OAuth V2 clients.
    '''
    _storm_lib_path = ('inet', 'http', 'oauth', 'v2')
    _storm_locals = (
        {
            'name': 'addProvider',
            'desc': '''
                Add a new provider configuration.

                Example:
                    Add a new provider which uses the authorization code flow::

                        $iden = $lib.guid(example, provider, oauth)
                        $conf = ({
                            "iden": $iden,
                            "name": "example_provider",
                            "client_id": "yourclientid",
                            "client_secret": "yourclientsecret",
                            "scope": "first_scope second_scope",
                            "auth_uri": "https://provider.com/auth",
                            "token_uri": "https://provider.com/token",
                            "redirect_uri": "https://local.redirect.com/oauth",
                        })

                        // Optionally enable PKCE
                        $conf.extensions = ({"pkce": $lib.true})

                        // Optionally disable SSL verification
                        $conf.ssl_verify = $lib.false

                        // Optionally provide additional key-val parameters
                        // to include when calling the auth URI
                        $conf.extra_auth_params = ({"customparam": "foo"})

                        $lib.inet.http.oauth.v2.addProvider($conf)
            ''',
            'type': {
                'type': 'function', '_funcname': '_addProvider',
                'args': (
                    {'name': 'conf', 'type': 'dict', 'desc': 'A provider configuration.'},
                ),
                'returns': {'type': 'null'},
            },
        },
        {
            'name': 'delProvider',
            'desc': 'Delete a provider configuration.',
            'type': {
                'type': 'function', '_funcname': '_delProvider',
                'args': (
                    {'name': 'iden', 'type': 'str', 'desc': 'The provider iden.'},
                ),
                'returns': {'type': 'dict', 'desc': 'The deleted provider configuration or None if it does not exist.'}
            },
        },
        {
            'name': 'getProvider',
            'desc': 'Get a provider configuration',
            'type': {
                'type': 'function', '_funcname': '_getProvider',
                'args': (
                    {'name': 'iden', 'type': 'str', 'desc': 'The provider iden.'},
                ),
                'returns': {'type': 'dict', 'desc': 'The provider configuration or None if it does not exist.'}
            },
        },
        {
            'name': 'listProviders',
            'desc': 'List provider configurations',
            'type': {
                'type': 'function', '_funcname': '_listProviders',
                'returns': {'type': 'list', 'desc': 'List of (iden, conf) tuples.'},
            },
        },
        {
            'name': 'setUserAuthCode',
            'desc': 'Set the auth code for the current user.',
            'type': {
                'type': 'function', '_funcname': '_setUserAuthCode',
                'args': (
                    {'name': 'iden', 'type': 'str', 'desc': 'The provider iden.'},
                    {'name': 'authcode', 'type': 'str', 'desc': 'The auth code for the user.'},
                    {'name': 'code_verifier', 'type': 'str', 'default': None, 'desc': 'Optional PKCE code verifier.'},
                ),
                'returns': {'type': 'null'}
            },
        },
        {
            'name': 'getUserAccessToken',
            'desc': '''
                Get the provider access token for the current user.

                Example:

                    Retrieve the token and handle needing an auth code::

                        $provideriden = $lib.globals.get("oauth:myprovider")

                        ($ok, $data) = $lib.inet.http.oauth.v2.getUserAccessToken($provideriden)

                        if $ok {
                            // $data is the token to be used in a request
                        else {
                            // $data is a message stating why the token is not available
                            // caller should now handle retrieving a new auth code for the user
                        }
            ''',
            'type': {
                'type': 'function', '_funcname': '_getUserAccessToken',
                'args': (
                    {'name': 'iden', 'type': 'str', 'desc': 'The provider iden.'},
                ),
                'returns': {'type': 'list', 'desc': 'List of (<bool>, <token/mesg>) for status and data.'},
            },
        },
        {
            'name': 'clearUserAccessToken',
            'desc': 'Clear the stored refresh data for the current user\'s provider access token.',
            'type': {
                'type': 'function', '_funcname': '_clearUserAccessToken',
                'args': (
                    {'name': 'iden', 'type': 'str', 'desc': 'The provider iden.'},
                ),
                'returns': {'type': 'dict', 'desc': 'The existing token state data or None if it did not exist.'},
            },
        }
    )

    def getObjLocals(self):
        return {
            'addProvider': self._addProvider,
            'delProvider': self._delProvider,
            'getProvider': self._getProvider,
            'listProviders': self._listProviders,
            'setUserAuthCode': self._setUserAuthCode,
            'getUserAccessToken': self._getUserAccessToken,
            'clearUserAccessToken': self._clearUserAccessToken,
        }

    async def _addProvider(self, conf):
        if not self.runt.isAdmin():
            raise s_exc.AuthDeny(mesg='addProvider() requires admin privs.',
                                 user=self.runt.user.iden, username=self.runt.user.name)
        conf = await s_stormtypes.toprim(conf)
        await self.runt.snap.core.addOAuthProvider(conf)

    async def _delProvider(self, iden):
        if not self.runt.isAdmin():
            raise s_exc.AuthDeny(mesg='delProvider() requires admin privs.',
                                 user=self.runt.user.iden, username=self.runt.user.name)
        iden = await s_stormtypes.tostr(iden)
        return await self.runt.snap.core.delOAuthProvider(iden)

    async def _getProvider(self, iden):
        if not self.runt.isAdmin():
            raise s_exc.AuthDeny(mesg='getProvider() requires admin privs.',
                                 user=self.runt.user.iden, username=self.runt.user.name)
        iden = await s_stormtypes.tostr(iden)
        return await self.runt.snap.core.getOAuthProvider(iden)

    async def _listProviders(self):
        if not self.runt.isAdmin():
            raise s_exc.AuthDeny(mesg='listProviders() requires admin privs.',
                                 user=self.runt.user.iden, username=self.runt.user.name)
        return await self.runt.snap.core.listOAuthProviders()

    async def _setUserAuthCode(self, iden, authcode, code_verifier=None):
        iden = await s_stormtypes.tostr(iden)
        authcode = await s_stormtypes.tostr(authcode)
        code_verifier = await s_stormtypes.tostr(code_verifier, True)

        useriden = self.runt.user.iden
        await self.runt.snap.core.setOAuthAuthCode(iden, useriden, authcode, code_verifier=code_verifier)

    async def _getUserAccessToken(self, iden):
        iden = await s_stormtypes.tostr(iden)
        return await self.runt.snap.core.getOAuthAccessToken(iden, self.runt.user.iden)

    async def _clearUserAccessToken(self, iden):
        iden = await s_stormtypes.tostr(iden)
        return await self.runt.snap.core.clearOAuthAccessToken(iden, self.runt.user.iden)


#!/usr/bin/python3
import random
import sys

class Skiplist:
    def __init__(self):
        #The main point of the skiplist object, other than defining functions for
        #manipulation of the nodes, is maintaining a head pointer.
        self.head = None

    '''
        From a deleted node "delnode", stitches together the prev and next nodes
        accordingly while clearing out dead ptrs.
    '''
    def __stitch__(self, delnode):
        if delnode.prevs is None:
            newhead = delnode.nexts[0]
            if len(delnode.nexts) > len(newhead.nexts):
                for node in delnode.nexts[len(newhead.nexts):]:
                    newhead.nexts.append(node)

            for i in range(len(newhead.prevs)):
                newhead.prevs[i] = None

            for i in range(1, len(delnode.nexts)):
                oldnext = delnode.nexts[i]
                if oldnext is not None:
                    oldnext.prevs[i] = newhead
            delnode.nexts[:] = [None] * len(delnode.nexts)
            delnode.nexts = None
            newhead.levels = delnode.levels
            #Head never has any prevs since it's the head.
            newhead.prevs = None
            self.head = newhead
        elif all(map(lambda x: x is None, delnode.nexts)):
            for i in range(len(delnode.prevs)):
                delnode.prevs[i].nexts[i] = None
                delnode.prevs[i] = None
        else:
            for i in range(len(delnode.prevs)):
                delnode.prevs[i].nexts[i] = delnode.nexts[i]
                if delnode.nexts[i] is not None:
                    delnode.nexts[i].prevs[i] = delnode.prevs[i]
                delnode.prevs[i] = None
                delnode.nexts[i] = None

    '''
        Proper algorithm for inserting a node at the head, tail, or otherwise,
        at the specified level for operations not involving new heads, default
        is the "ground" level, 0.
    '''
    def __insert__(self, lnode, mnode, rnode, level=0):
        if rnode is self.head: #insertion before the head. new head defined.
            #Move the previous head nexts to the new node mnode. clear old ptrs.
            mnode.nexts = [rnode] + rnode.nexts[1:]
            #reassign the prevs of our head's nexts to the new head.
            for i in range(1, rnode.levels):
                if rnode.nexts[i] is not None:
                    rnode.nexts[i].prevs[i] = mnode
            rnode.nexts[1:] = [None] * len(rnode.nexts[1:])
            rnode.nexts = [rnode.nexts[0]]
            mnode.levels = rnode.levels
            rnode.levels = 1
            self.head = mnode
            mnode.prevs = None
            rnode.prevs = [mnode]
        elif rnode is None: #insertion after the tail.
            lnode.nexts[level] = mnode
            mnode.prevs[level] = lnode
        else: #insertion in between two other nodes.
            lnode.nexts[level] = mnode
            mnode.prevs[level] = lnode
            rnode.prevs[level] = mnode
            mnode.nexts[level] = rnode

    '''
        Returns a pointer to the first node found with the requested target value.
    '''
    def __find__(self, target: int) -> object:
        curr = self.head
        level = self.head.levels - 1
        # Only case where we directly compare curr with the target.
        # This is because we are inspecting the next element otherwise.
        if curr is None:
            print("Empty list!")
            return None
        if target < curr.num:
            return None
        elif target == curr.num:
            return curr

        while curr is not None and level >= 0:
            n = curr.nexts[level]
            while n is None and level >= 0:
                level -= 1
                n = curr.nexts[level]
            if n is None:
                break
            if n.num == target:
                return n
            elif n.num < target:
                curr = n
            else:
                level -= 1
        return None

    def search(self, target: int) -> bool:
        node = self.__find__(target)
        if node is None:
            return False
        else:
            return True

    def add(self, num: int) -> None:
        newnode = Node(num)
        if self.head is None:
            self.head = newnode
            self.head.prevs = None
            return None
        curr = self.head
        level = self.head.levels - 1
        prevs = [None] * self.head.levels
        inserted = False

        while inserted == False:
            if curr is None and level == 0:
                self.__insert__(prevs[level], newnode, curr)
                inserted = True
            elif num <= curr.num:
                if level > 0:
                    prevs[level] = curr
                    level -= 1
                else:
                    if curr is not self.head:
                        theprev = curr.prevs[level]
                    else:
                        theprev = prevs[level]
                    self.__insert__(theprev, newnode, curr)
                    inserted = True
            else:
                prevs[level] = curr
                while (curr.nexts[level] is None or num <= curr.nexts[level].num) and level >= 1:
                    level -= 1
                    prevs[level] = curr
                if curr.nexts[level] is None or num > curr.nexts[level].num or level == 0:
                    curr = curr.nexts[level]

        #Level up.
        while random.randint(0, 1) == 1:
             level += 1
             newnode.levels += 1
             if level > self.head.levels - 1:
                self.head.levels += 1
                if newnode is not self.head:
                    self.head.nexts.append(newnode)
                    newnode.prevs.append(self.head)
                    newnode.nexts.append(None)
                else:
                    self.head.nexts.append(None)
             else:
                if newnode is not self.head:
                    newnode.prevs.append(None)
                    newnode.nexts.append(None)
                    newnode.prevs[level] = prevs[level]
                    newnode.nexts[level] = prevs[level].nexts[level]
                    if prevs[level].nexts[level] is not None:
                        prevs[level].nexts[level].prevs[level] = newnode
                    prevs[level].nexts[level] = newnode
                else:
                    newnode.nexts.append(None)
        print('added {}'.format(num))
    def erase(self, num: int) -> bool:
        val = False
        delnode = self.__find__(num)
        if delnode is not None:
            self.__stitch__(delnode)
            val = True
        if val == True:
            print('erased {}'.format(num))
        else:
            print('{} not found'.format(num))
        return val

    def printList(self, backwalk=False):
        forwards = ''
        backwards = ''
        for i in range(len(self.head.nexts)):
            curr = self.head
            prev = curr
            while curr is not None:
                forwards += '{} '.format(curr.num)
                prev = curr
                curr = curr.nexts[i]
            forwards += '\n'
            if backwalk == True:
                while prev is not None:
                    backwards += '{} '.format(prev.num)
                    if prev.prevs is not None:
                        try:
                            prev = prev.prevs[i]
                        except IndexError as I:
                            print(I)
                            print('prev causing the issue is {}'.format(prev.num))
                            print(forwards)
                            print('-' * 25)
                            print(backwards)
                            return
                    else:
                        prev = None
                backwards += '\n'
        sys.stdout.write(forwards)
        print('-' * 25)
        if backwalk == True:
            sys.stdout.write(backwards)
            print('-' * 25)

#Nodes for the skiplist
class Node:
    def __init__(self, num, levels=1):
        self.nexts = [None] * levels
        self.prevs = [None] * levels
        self.num = num
        self.levels = levels


"""
    Views module
"""
import os
import json
from django.http import HttpResponse
from django.shortcuts import render
from django.template import Context, Template
from .QBO_requests import create_bill, get_bill
from .helper import OAuth2_helper

# Create your views here.
def index(request):
    '''Index view of application does a POST and a GET API request'''
    read_config(request)
    config = {}
    for key, value in request.session.items():
        config[key] = value

    create_bill_status, create_bill_response = create_bill(config)

    # If HTTP status code 401 is returned by the API, getting a fresh access token is required since access tokens are valid only for 60 min.
    if create_bill_status == 401:
        fresh_tokens = OAuth2_helper.refresh_access_token(config)
        if fresh_tokens:
            update_session(request, fresh_tokens['access_token'], fresh_tokens['refresh_token'])
        else:
            return HttpResponse('Could not refresh access token.')

        # Update config with the right tokens
        config['access_token'] = request.session['access_token']
        config['refresh_token'] = request.session['refresh_token']

        # Make API requests with fresh acces token
        create_bill_status, create_bill_response = create_bill(config)

    get_bill_status, get_bill_response = get_bill(config, create_bill_response["Bill"]["Id"])

    # If HTTP status code 401 is returned by the API, getting a fresh access token is required since access tokens are valid only for 60 min.
    if get_bill_status == 401:
        fresh_tokens = OAuth2_helper.refresh_access_token(config)
        if fresh_tokens:
            update_session(request, fresh_tokens['access_tokens'], fresh_tokens['refresh_tokens'])
        else:
            return HttpResponse('Could not refresh access token.')

        # Update config with the right tokens
        config['access_token'] = request.session['access_token']
        config['refresh_token'] = request.session['refresh_token']

        # Make API requests with fresh acces token
        get_bill_status, get_bill_response = get_bill(config, create_bill_response["Bill"]["Id"])
    context = {
            'post_request': create_bill_response,
            'get_request': get_bill_response,
        }
    return render(request, 'index.html', context=context)

def update_session(request, access_token, refresh_token):
    '''Update session with fresh tokens and then write new values to config.json
        This is just for demo purposes. Actual refresh token with realm Id will be saved in database while access token in session.
    '''
    request.session['access_token'] = access_token
    request.session['refresh_token'] = refresh_token
    config = {}
    for key, value in request.session.items():
        config[key] = value
    file_path = os.path.abspath(os.path.join(__file__ , '../../config.json'))
    with open(file_path, 'w') as f:
        json.dump(config, f)
    f.close()

def read_config(request):
    '''Read config values from config.json and load them in session'''
    file_path = os.path.abspath(os.path.join(__file__ , '../../config.json'))
    with open(file_path, 'r') as f:
        config = json.load(f)
    f.close()
    request.session['access_token'] = config['access_token']
    request.session['refresh_token'] = config['refresh_token']
    request.session['realm_id'] = config['realm_id']
    request.session['qbo_base_url'] = config['qbo_base_url']
    request.session['client_id'] = config['client_id']
    request.session['client_secret'] = config['client_secret']
    request.session['discovery_doc'] = config['discovery_doc']


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import numpy as np
import torch.nn.functional as F
import cv2

from pysot.core.config import cfg
from pysot.utils.anchor import Anchors
from pysot.tracker.base_tracker import SiameseTracker
from matplotlib import pyplot as plt
from .external.nms import soft_nms

class SiamCORNERTracker(SiameseTracker):
    def __init__(self, model):
        super(SiamCORNERTracker, self).__init__()
        self.score_size = (cfg.TRACK.INSTANCE_SIZE - cfg.TRACK.EXEMPLAR_SIZE) // \
            cfg.ANCHOR.STRIDE + 1 + cfg.TRACK.BASE_SIZE
        self.anchor_num = len(cfg.ANCHOR.RATIOS) * len(cfg.ANCHOR.SCALES)
        #hanning = np.hanning(self.score_size)
        window = np.hanning(cfg.corners.hanning_score_size)
        #window = np.outer(hanning, hanning)
        self.window = np.tile(window.flatten(), cfg.corners.hanning_num)
        #self.anchors = self.generate_anchor(self.score_size)
        self.model = model
        self.model.eval()

    def generate_anchor(self, score_size):
        anchors = Anchors(cfg.ANCHOR.STRIDE,
                          cfg.ANCHOR.RATIOS,
                          cfg.ANCHOR.SCALES)
        anchor = anchors.anchors
        x1, y1, x2, y2 = anchor[:, 0], anchor[:, 1], anchor[:, 2], anchor[:, 3]
        anchor = np.stack([(x1+x2)*0.5, (y1+y2)*0.5, x2-x1, y2-y1], 1)
        total_stride = anchors.stride
        anchor_num = anchor.shape[0]
        anchor = np.tile(anchor, score_size * score_size).reshape((-1, 4))
        ori = - (score_size // 2) * total_stride
        xx, yy = np.meshgrid([ori + total_stride * dx for dx in range(score_size)],
                             [ori + total_stride * dy for dy in range(score_size)])
        xx, yy = np.tile(xx.flatten(), (anchor_num, 1)).flatten(), \
            np.tile(yy.flatten(), (anchor_num, 1)).flatten()
        anchor[:, 0], anchor[:, 1] = xx.astype(np.float32), yy.astype(np.float32)
        return anchor

    def _convert_bbox(self, delta, anchor):
        delta = delta.permute(1, 2, 3, 0).contiguous().view(4, -1) # delta:[4,3125]
        delta = delta.data.cpu().numpy()

        delta[0, :] = delta[0, :] * anchor[:, 2] + anchor[:, 0] # x
        delta[1, :] = delta[1, :] * anchor[:, 3] + anchor[:, 1] # y
        delta[2, :] = np.exp(delta[2, :]) * anchor[:, 2] # w
        delta[3, :] = np.exp(delta[3, :]) * anchor[:, 3] # h
        return delta

    def _convert_score_att(self, atts, attentions):
        att_score = []
        att_loc = []
        for att, attention in zip(atts, attentions):
            attention_ = attention.repeat(1, 5, 1, 1) # 复制5份[1,1,25,25]-->[1,5,25,25] 5份是因为5种不同的anchors
            attention_ = attention_.permute(1, 2, 3, 0).contiguous().view(1, -1).permute(1, 0) # [3125,1]
            att_score.append(F.softmax(attention_, dim=0).data[:, 0].cpu().numpy()) # [3125,] 注意力特征经过softmax激活函数
            A = []
            for i in range(len(att)): # 注意标注的位置在复制的5份对应的位置
                a_0 = (att[i][0]*25 + att[i][1]).astype(int) # 转化为[3125,]后的位置
                a_1 = a_0 + 25*25*1
                a_2 = a_1 + 25*25*1
                a_3 = a_2 + 25*25*1
                a_4 = a_3 + 25*25*1
                A.append(a_0)
                A.append(a_1)
                A.append(a_2)
                A.append(a_3)
                A.append(a_4)
            att_loc.append(A)

        return att_loc, att_score

    def _convert_score(self, score, att_locs, att_scores):
        W = cfg.atts.W # 注意力机制权值
        score = score.permute(1, 2, 3, 0).contiguous().view(2, -1).permute(1, 0) # [1,10,25,25]-->[3125,2] 后5个为正样本得分
        score = F.softmax(score, dim=1).data[:, 1].cpu().numpy() # [3125,] dim=1 对每一行进行softmax
        for att_loc, att_score, w in zip(att_locs, att_scores, W):
            for i in range(len(att_loc)):
                score[att_loc[i]] += w * att_score[att_loc[i]]
        return score

    def _bbox_clip(self, cx, cy, width, height, boundary):
        cx = max(0, min(cx, boundary[1]))
        cy = max(0, min(cy, boundary[0]))
        width = max(10, min(width, boundary[1]))
        height = max(10, min(height, boundary[0]))
        return cx, cy, width, height

    def rescale_dets_(self, dets_):
        input_size = cfg.corners.input_size  # [255,255]
        output_size = cfg.corners.output_size  # [25,25]

        ratios = [o / i for o, i in zip(output_size, input_size)]
        detect = []
        for dets in dets_:
            dets[..., 0:4:2] /= ratios[1]  # bbox在[255,255,3]中的坐标
            dets[..., 1:4:2] /= ratios[0]
            detect.append(dets)
        return detect

    def Centertocorner(self, det):
        det[:, :, 0] = det[:, :, 0] - det[:, :, 2] // 2 # x1
        det[:, :, 1] = det[:, :, 1] - det[:, :, 3] // 2  # y1
        det[:, :, 2] = det[:, :, 0] + det[:, :, 2]  # x2
        det[:, :, 3] = det[:, :, 1] + det[:, :, 3]  # y2
        return det

    def init(self, img, bbox):
        """
        args:
            img(np.ndarray): BGR image
            bbox: (x, y, w, h) bbox
        """
        self.center_pos = np.array([bbox[0]+(bbox[2]-1)/2, # center_x, center_y
                                    bbox[1]+(bbox[3]-1)/2])
        self.size = np.array([bbox[2], bbox[3]]) # w,h

        # calculate z crop size
        w_z = self.size[0] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)
        h_z = self.size[1] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)
        s_z = round(np.sqrt(w_z * h_z))

        # calculate channle average
        self.channel_average = np.mean(img, axis=(0, 1))

        # get crop
        z_crop = self.get_subwindow(img, self.center_pos, # self.center_pos:ground_truth中心点位置
                                    cfg.TRACK.EXEMPLAR_SIZE, # 按照ground_truth中心点裁剪为127*127的图片
                                    s_z, self.channel_average) # image:[1024,1024,3]-->z_crop:[1,3,127,127]
        self.model.template(z_crop)

    def track(self, img):
        """
        args:
            img(np.ndarray): BGR image
        return:
            bbox(list):[x, y, width, height]
        """
        w_z = self.size[0] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size) # self.size[0]:bbox宽  w+p
        h_z = self.size[1] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size) # self.size[1]:bbox高  h+p
        s_z = np.sqrt(w_z * h_z) # 对应论文中公式14
        scale_z = cfg.TRACK.EXEMPLAR_SIZE / s_z
        s_x = s_z * (cfg.TRACK.INSTANCE_SIZE / cfg.TRACK.EXEMPLAR_SIZE)
        x_crop = self.get_subwindow(img, self.center_pos,  # x_crop:[1,3,255,255] 按照中心点进行裁剪
                                    cfg.TRACK.INSTANCE_SIZE,
                                    round(s_x), self.channel_average)
        '''
        # 画图
        img1 = x_crop.squeeze(0)
        img_1 = img1.transpose(1, 0).transpose(2, 1).cpu().numpy()
        a = cv2.imwrite("4.jpg", img_1)  # save picture
        plt.axis('off')
        plt.imshow(img_1[:, :, 1])
        plt.show()
        '''

        outputs = self.model.track(x_crop) # cls:[1,10,25,25] loc:[1,20,25,25]
        dets_ = outputs['bbox']
        dets_1 = self.rescale_dets_(dets_)  # [25,25]-->[255,255] 对应的bbox缩放比例 [x1,y1,x2,y2]

        det = []
        for dets_2 in dets_1:
            dets_2 = dets_2.cpu()
            dets_2 = dets_2.detach().numpy()
            dets_2 = np.squeeze(dets_2)
            det.append(dets_2)

        detectect = np.concatenate((det[0], det[1]))
        det = np.concatenate((detectect, det[2])) # 在[255,255]中的位置，[x1,y1,x2,y2]

        def change(r): # r:[3125,]
            return np.maximum(r, 1. / r)

        def sz(w, h):
            pad = (w + h) * 0.5
            return np.sqrt((w + pad) * (h + pad)) # 对应论文中公式(15)

        # scale penalty
        s_c = change(sz(det[:, 2], det[:, 3]) / # s_c:[3125,]
                     (sz(self.size[0]*scale_z, self.size[1]*scale_z)))# 上一帧bbox在填充之后的

        # aspect ratio penalty
        r_c = change((self.size[0]/self.size[1]) / # self.size:bbox代表上一帧宽，高比
                     (det[:, 2]/det[:, 3]))

        penalty = np.exp(-(r_c * s_c - 1) * cfg.TRACK.PENALTY_K)  # penalty:[3125,]
        score = det[:, 5]
        #pscore = penalty * score  # 对相邻两帧之间过大的形状和尺度变化进行抑制

        # window penalty
        #pscore = pscore * (1 - cfg.TRACK.WINDOW_INFLUENCE) + \
        #         self.window * cfg.TRACK.WINDOW_INFLUENCE  # a cosine window is added to suppress the large displacement
        best_idx = np.argmax(score)
        bbox = det[best_idx, :4] / scale_z  # pred_bbox:[4,3125] 对应padding [x1,y1,x2,y2]
        #lr = penalty[best_idx] * score[best_idx] * cfg.TRACK.LR
        lr = 0.13104

        bbox[2], bbox[3] = bbox[2] - bbox[0], bbox[3] - bbox[1]  # 对应于padding宽，高
        bbox[0], bbox[1] = bbox[0] + bbox[2] // 2, bbox[1] + bbox[3] // 2  # 中心点坐标x,中心点坐标y
        s_x = round((s_x + 1) // 2)
        bbox[0], bbox[1] = bbox[0] - s_x, bbox[1] - s_x  # 中心点坐标x,y的偏移量
        bbox[0] = bbox[0] + self.center_pos[0]  # 对应于原图中心点在原图坐标x
        bbox[1] = bbox[1] + self.center_pos[1]  # 中心点在原图坐标y

        # smooth bbox
        width = self.size[0] * (1 - lr) + bbox[2] * lr  # self.size[0]:bbox代表上一帧宽
        height = self.size[1] * (1 - lr) + bbox[3] * lr

        # clip boundary
        cx, cy, width, height = self._bbox_clip(bbox[0], bbox[1], width,  # 目标框框不能超过图片边界
                                                height, img.shape[:2])

        # udpate state
        self.center_pos = np.array([cx, cy])
        self.size = np.array([width, height])

        bbox = [cx - width / 2,
                cy - height / 2,
                width,
                height]
        best_score = score[best_idx]
        return {
            'bbox': bbox,
            'best_score': best_score
        }

'''

        detection = []  # 对应于padding后的坐标
        for det1 in dets_1:
            det1[..., 0:4] /= scale_z
            detection.append(det1) # 对应于padding后的坐标 x1,y1,x2,y2

        det = []

        for det_ in detection: # 在原图位置
            det_[:, :, 2], det_[:, :, 3] = det_[:, :, 2]-det_[:, :, 0], det_[:, :, 3]-det_[:, :, 1] # 宽，高
            det_[:, :, 0], det_[:, :, 1] = det_[:, :, 0] + det_[:, :, 2] // 2, det_[:, :, 1] + det_[:, :, 3] // 2# 中心点坐标x,中心点坐标y
            s_x = round((s_x+1)//2)
            det_[:, :, 0], det_[:, :, 1] = det_[:, :, 0] - s_x, det_[:, :, 1] - s_x  # 中心点坐标x,y的偏移量
            det_[:, :, 0] = det_[:, :, 0] + self.center_pos[0] # 中心点在原图坐标x
            det_[:, :, 1] = det_[:, :, 1] + self.center_pos[1] # 中心点在原图坐标y
            detection = self.Centertocorner(det_) # x1,y1,x2,y2

            det.append(detection)

        detectection = []
        for detect in det: # Soft nms
            detect = detect.cpu()
            detect = detect.detach().numpy()
            detect = np.squeeze(detect)
            keep_inds = soft_nms(detect, Nt=cfg.corners.nms_threshold, method=cfg.corners.nms_algorithm,
                                 sigma=0.7)  # remove redundant ones by applying Soft-NMS
            det_ = detect[keep_inds, 0:5]
            detectection.append(det_)

        detectect = np.concatenate((detectection[0], detectection[1]))
        det = np.concatenate((detectect, detectection[2]))

        cx = bbox[0] + self.center_pos[0]
        cy = bbox[1] + self.center_pos[1]

        # clip boundary
        cx, cy, width, height = self._bbox_clip(cx, cy, width, # 目标框框不能超过图片边界
                                                height, img.shape[:2])

        # udpate state
        self.center_pos = np.array([cx, cy])
        self.size = np.array([width, height])

        bbox = [cx - width / 2,
                cy - height / 2,
                width,
                height]
        best_score = score[best_idx]
        return {
                'bbox': bbox,
                'best_score': best_score
               }
'''


"""
Event extraction script for optimism bias task.

Author:
Himanshu Aggarwal
himanshu.aggarwal@inria.fr
March 2022
"""

import pandas as pd
import os

def take_input():
    while True:
        try:
            sub_num = int(input("Enter subject number: "))
            design = int(input("Output 1- just the relevant events\n    or 2- all events?: "))
        except ValueError:
            print("Invalid input. Expecting integers.")
            continue
        else:
            break

    return sub_num, design

def setup_io_files(sub_num):
    path = os.getcwd()
    data_dir = os.path.join(path, 'log')
    data_files = sorted(os.listdir(data_dir))

    out_dir = os.path.join(path, 'output_paradigm_descriptors')
    try:
        os.mkdir(out_dir)
    except OSError:
        pass
    out_files = sorted(os.listdir(out_dir))

    practice = []
    main = []
    for file in data_files:
        if file.split('_')[0]=='pract':
            if int(file.split('_')[1].split('-')[1]) == sub_num:
                practice.append(file)
        elif file.split('_')[0]=='par':
            continue
        else:
            if int(file.split('_')[1].split('-')[1]) == sub_num:
                main.append(file)
    return data_dir, main, practice, out_dir, out_files

def check_presence(filename, list_of_files):
    if filename in list_of_files:
        count = 0
        for f in list_of_files:
            if f==filename:
                count+=1
        filename = filename.split('.')[0]+'('+str(count)+').'+filename.split('.')[1]
        return check_presence(filename,list_of_files)
    else:
        return filename

def extract_desc(design, file, data_dir, out_files, out_dir):

    file_path = os.path.join(data_dir, file)
    data = pd.read_csv(file_path)
    if len(data) == 0:
        print('Data file empty - {}'.format(file))
        return 0
    else:
        components = file.split('_')

        task = components[0]
        sub = components[1]
        run = components[2]

        data_ed = data.drop(index=[0,140])
        events = list(data_ed.eve)

        rel_eve = []
        decision = []
        i=0
        while i<len(events):
            toe = events[i].split('_')[1]
            if toe=="Passé":
                toe = "past"
            else:
                toe = "future"

            thinking = events[i+1].split('_')[0]
            if thinking=="thinking":
                thinking = True
            else:
                thinking = False

            arousal = events[i+3]
            valence = events[i+5]

            rel_eve.append(f'{toe}_{arousal}_{valence}')

            if thinking:
                if valence=='negative':
                    if arousal=='very' or arousal=='little':
                        decision.append(f'{toe}_negative')
                    else:
                        decision.append('inconclusive')
                elif valence=='positive':
                    if arousal=='very' or arousal=='little':
                        decision.append(f'{toe}_positive')
                    else:
                        decision.append('inconclusive')
                elif valence=='neutral':
                    if arousal=='little' or arousal=='not':
                        decision.append(f'{toe}_neutral')
                    else:
                        decision.append('inconclusive')
                else:
                    decision.append('inconclusive')
            else:
                decision.append('inconclusive')

            i = i + 7

        cnt = 0
        for i, row in data.iterrows():
            if (i-2)%7==0 or i==2:
                data.at[i,'eve'] = decision[cnt]
                cnt = cnt + 1

        data['duration'] = data['t'].shift(-1)-data['t']
        data = data[:-1]
        data = data.rename(columns={'t': 'onset', 'eve': 'trial_type'})
        data = data[['onset', 'duration', 'trial_type']]
        data = data.round(2)

        if design == 1:
            unique_dec = ['future_negative', 'future_neutral',
                         'future_positive', 'inconclusive',
                         'past_negative', 'past_neutral', 'past_positive']
            others = ['fix']
            data = data.loc[data.trial_type.isin(unique_dec+others)].reset_index(drop=True)

        save_as = f'{task}_{sub}_{run}_events.tsv'

        save_as = check_presence(save_as, out_files)
        save_as = os.path.join(out_dir, save_as)
        data.to_csv(save_as, index=False, sep='\t')

    print('Event file created for {}, {}'.format(sub, run))
    return 1

if __name__ == "__main__":

    sub_num, design = take_input()
    data_dir, main, practice, out_dir, out_files = setup_io_files(sub_num)

    if len(main) == 0:
        print("Can't find data for subject {}".format(sub_num))
        quit()
    else:
        for file in main:
            extract_desc(design, file, data_dir, out_files, out_dir)


#!/usr/bin/env python3

# It is a six-digit number.
# The value is within the range given in your puzzle input.
# Two adjacent digits are the same (like 22 in 122345).
# Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679).

# 111111 meets these criteria (double 11, never decreases).
# 223450 does not meet these criteria (decreasing pair of digits 50).
# 123789 does not meet these criteria (no double).

# An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits.

# 112233 meets these criteria because the digits never decrease and all repeated digits are exactly two digits long.
# 123444 no longer meets the criteria (the repeated 44 is part of a larger group of 444).
# 111122 meets the criteria (even though 1 is repeated more than twice, it still contains a double 22).

input_range = [273025, 767253]

def check(val):
    # Check adjacent
    s = str(val)
    found = False
    adjacent_list = []
    for x in range(len(s)):
        digit = s[x]
        if x+1 < len(s):
            if s[x] == s[x+1]:
                found = True
            if s[x+1] < s[x]:
                found = False
                break
        if not adjacent_list:
            adjacent_list.append({digit: 1})
            continue
        key = list(adjacent_list[-1].keys())[0]
        if key == digit:
            adjacent_list[-1][key] += 1
        else:
            adjacent_list.append({digit: 1})

        if x+1 >= len(s): continue
        if s[x] == s[x+1]:
            found = True
        if s[x+1] < s[x]:
            found = False
            break
    if found:
        for item in adjacent_list:
            if item[list(item.keys())[0]] == 2:
                return True
    return False

if __name__ == "__main__":
    count = 0
    for x in range(input_range[0], input_range[1]):
        found = check(x)
        if found: count += 1
    print('Solution: {}'.format(count))


import sys
from SPARQLWrapper import SPARQLWrapper, JSON
import random
import os
import shutil
from englisttohindi.englisttohindi import EngtoHindi

def create_PropMapFile(myList,mapFile):
    print("Writing in the  MAP file")
    print("Available size", len(myList))
    with open(mapFile, 'w') as f:
        for item in myList:
            f.write("%s\n" % item)

if(len(sys.argv)<2):
    print("Number of argument required is 2. \nFormat: python3 <progname>.py <lang>")
    exit(1)
LN = sys.argv[1]

#global vars
hnFile="ALL_"+LN+"_proplist.txt"
enFile="ALL_en_proplist.txt"
mapFile="map_proplist_"+LN+"_withtrans.txt"

fhn = open(hnFile, 'r')
fen = open(enFile, 'r')

hnlines = [line for line in fhn.readlines()]
enlines = [line for line in fen.readlines()]
maplines = []

for i in range(len(hnlines)):
    hnlabel=hnlines[i].strip().strip('\n')
    enlabel=enlines[i].strip().strip('\n')
    if(hnlabel[0] == 'P'):
        maplines.append(hnlabel+","+enlabel)

        # creating a EngtoHindi() object
        res = EngtoHindi(enlabel)
        # displaying the translation
        #print(res.convert)
        print(hnlabel+","+enlabel+","+str(res.convert))

        """
        try:
            print(hnlabel+","+enlabel+","+res.convert)
        except:
            print()

        """

create_PropMapFile(maplines,mapFile)
print("Map file created successfully. Please Check: ",mapFile)


import requests
import json
import socket
from flask import jsonify
import json
import jsonschema
from jsonschema import validate
import bson.json_util as json_util
from requests import get

def get_schema():
    with open('config_schema.json', 'r') as file:
        schema = json.load(file)
    return schema

def validate_config_structure(json_data):
    with open('dfs_contract.json', 'r') as f:
        jsonData = json.load(f)

    execute_api_schema = get_schema()

    try:
        validate(instance=json_data, schema=execute_api_schema)
    except jsonschema.exceptions.ValidationError as err:
        print(err)
        return False

    return True

def validate_config_entries(library_obj, user_config_contract):
    if library_obj == None and len(library_obj.keys()) == 0:
        return False

    user_language_choice = {}

    for language in user_config_contract['languages']:
        user_language_choice[language['language-name']] = language['libraries']

    for obj in library_obj["languages"]:
        lang_name = obj["name"]
        libraries_list_from_library = obj["libraries"]
        if lang_name in user_language_choice:
            diff = list(set(user_language_choice[lang_name]) - set(libraries_list_from_library))
            if len(diff) > 0:
                return False

    return True

def create_response(message):
    return jsonify({"response": message})

def create_bson_response(message):
    return json_util.dumps({"response": message})

def get_response(ip_address,data):
    ans = requests.get(ip_address, params=data).content.decode()
    ans = json.loads(ans)
    return ans

def post_response(ip_address,function,data):
    ans = requests.post(ip_address + function, json=data).json()
    # ans = json.loads(ans)
    return ans

def get_environment_details():
    file_desc = open('environment.json')
    data = json.load(file_desc)
    file_desc.close()
    return data

def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(0)
    try:
        s.connect(('10.254.254.254', 1))
        self_ip = s.getsockname()[0]
    except Exception:
        self_ip = '127.0.0.1'
    finally:
        s.close()

    print(self_ip)
    return self_ip

def next_free_port():
    port = 8000
    max_port = 65536
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    while port <= max_port:
        try:
            sock.bind(('', port))
            sock.close()
            return port
        except OSError:
            port += 1
    return None


from tokens import Integer, Float, Operation, Declaration, Variable, Boolean, Comparison, Reserved

class Lexer:
    digits = "0123456789"
    letters = "abcdefghijklmnopqrstuvwxyz"
    operations = "+-/*()="
    stopwords = [" "]
    declarations = ["make"]
    boolean = ["and", "or", "not"]
    comparisons = [">", "<", ">=", "<=", "=="]
    specialCharacters = "><=?"
    reserved = ["if", "elif", "else", "do", "while"]

    def __init__(self, text):
        self.text = text
        self.idx = 0
        self.tokens = []
        self.char = self.text[self.idx] if self.text else None
        self.token = None

    def tokenize(self):
        while self.idx < len(self.text):
            if self.char in Lexer.digits:
                self.token = self.extract_number()

            elif self.char in Lexer.operations:
                self.token = Operation(self.char)
                self.move()

            elif self.char in Lexer.stopwords:
                self.move()
                continue

            elif self.char in Lexer.letters:
                word = self.extract_word()

                if word in Lexer.declarations:
                    self.token = Declaration(word)
                elif word in Lexer.boolean:
                    self.token = Boolean(word)
                elif word in Lexer.reserved:
                    self.token = Reserved(word)
                else:
                    self.token = Variable(word)

            elif self.char in Lexer.specialCharacters:
                comparisonOperator = self.extract_comparison_operator()
                self.token = Comparison(comparisonOperator)

            if self.token is not None:
                self.tokens.append(self.token)
                self.token = None

        return self.tokens

    def extract_number(self):
        number = ""
        isFloat = False
        while self.char and (self.char in Lexer.digits or self.char == "."):
            if self.char == ".":
                if isFloat:  # Second decimal point encountered
                    break  # Invalid number format, break the loop
                isFloat = True
            number += self.char
            self.move()

        return Integer(number) if not isFloat else Float(number)

    def extract_word(self):
        word = ""
        while self.char and self.char in Lexer.letters:
            word += self.char
            self.move()

        return word

    def extract_comparison_operator(self):
        comparisonOperator = ""
        while self.char and self.char in Lexer.specialCharacters:
            comparisonOperator += self.char
            self.move()

        return comparisonOperator

    def move(self):
        self.idx += 1
        if self.idx < len(self.text):
            self.char = self.text[self.idx]
        else:
            self.char = None