import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

tarpath = r"5.27/maker.liquidation.surplus.20220403.csv"

def read():
        tarFile = pd.read_csv(tarpath)
        return tarFile

def dataProcess():
    target: pd.Series = read()
    features: list = [pd.to_datetime(target.deal_time, format='%m/%d/%Y %H:%M:%S').dt.strftime("%Y-%m-%d"),
                      pd.to_datetime(target.kick_time, format='%m/%d/%Y %H:%M:%S').dt.strftime("%Y-%m-%d"),
                      pd.to_datetime(target.tend_time, format='%m/%d/%Y %H:%M:%S').dt.strftime("%Y-%m-%d")]
    return target.bid_price_unit_of_mkr, features

def plotdrawing_Days():
    Pbid, features = dataProcess()
    features = pd.DataFrame(features).T
    frequency = [features[item].value_counts().sort_index() for item in features]
    x = frequency[0].index.values.tolist()
    x = [pd.to_datetime(items, format="%Y-%m-%d") for items in x]
    x1 = frequency[1].index.values.tolist()
    x1 = [pd.to_datetime(items, format="%Y-%m-%d") for items in x1]
    x2 = frequency[2].index.values.tolist()
    x2 = [pd.to_datetime(items, format="%Y-%m-%d") for items in x2]
    frequency = [features[item].value_counts().sort_index().to_numpy().astype(int) for item in features]
    plt.figure(figsize=(10, 10))
    plt.plot(x, frequency[0], color='lightcoral')
    plt.plot(x1, frequency[1], color="royalblue")
    plt.plot(x2, frequency[2], color="forestgreen")
    plt.legend(["Kick", "Tend", "Deal"])
    print(frequency)
    plt.show()

def plotDraw_Months():
    Pbid, features = dataProcess()
    features = [pd.to_datetime(item, format="%Y-%m-%d").dt.strftime("%y-%m") for item in features]
    # ---------------for pbid----merged with kick_time----------------------------
    Pbid = pd.concat([Pbid, features[1]], axis=1)
    Pbid.set_index("kick_time", drop=True, inplace=True)
    result = Pbid.groupby(level=0).sum()
    # -----Hence we get sum of price every month(only suit for kick time) -------------------------
    features = pd.DataFrame(features).T
    frequency = [features[item].value_counts().sort_index() for item in features]
    # x = frequency[0].index.values.tolist()
    x1Index = frequency[1].index.values.tolist()
    # x2 = frequency[2].index.values.tolist()
    width = 0.2
    x = [item - width for item in range(len(frequency[1]))]
    x1 = [item for item in range(len(frequency[1]))]
    x2 = [item + width for item in range(len(frequency[1]))]
    frequency = [features[item].value_counts().sort_index().to_numpy().astype(int) for item in features]
    # just show the trend
    avg = result["bid_price_unit_of_mkr"].div(frequency[1]) * 20
    fig, ax = plt.subplots()
    # fig(figsize=(10, 10))
    ax.bar(x, frequency[0], width, color='tomato')
    ax.bar(x1, frequency[1], width, color="slateblue")
    ax.bar(x2, frequency[2], width, color="forestgreen")
    ax.plot(x1Index, avg, color="darkorange", marker="o", linestyle="dashed")
    plt.legend(["Avg Monthly Price", "Deal", "Kick", "Tend"])
    plt.show()

plotDraw_Months()
#plotdrawing_Days()


import string

a = string.ascii_lowercase
b = string.ascii_uppercase
d = string.digits
psw = list(input())
digit = False
upper = False
lower = False
if len(psw) >= 8:
    for x in psw:
        if x in d:
            digit = True
        if x in b:
            upper = True
        if x in a:
            lower = True
print(digit , upper , lower)


from tqdm import tqdm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MultiLabelBinarizer
from python_file.kaggle.predict_winner.params_map import (
    WEAPON_MAP,
    RANK_MAP,
    STAGE_AREA_MAP,
    BUKI_MAP,
)

WEAPONS = [
    "A1-weapon",
    "A2-weapon",
    "A3-weapon",
    "A4-weapon",
    "B1-weapon",
    "B2-weapon",
    "B3-weapon",
    "B4-weapon",
]

WEAPONS_A = [
    "A1-weapon",
    "A2-weapon",
    "A3-weapon",
    "A4-weapon",
]

WEAPONS_B = [
    "B1-weapon",
    "B2-weapon",
    "B3-weapon",
    "B4-weapon",
]

BUKI_RANGE_CATEGORY = {
    "charger": 1,
    "splatling": 1,
    "brush": 0,
    "slosher": 0,
    "maneuver": 0,
    "reelgun": 0,
    "brella": 0,
    "roller": 0,
    "blaster": 0,
    "shooter": 0,
}

class Common:
    def __init__(self):
        ...

    def make_feature(self, df_train, df_test):
        mlb = MultiLabelBinarizer()
        mlb.fit([set(df_train["A4-weapon"].fillna("none").unique())])
        train_num = len(df_train)
        df = pd.concat([df_train, df_test])

        # cat_cols = ["lobby-mode", "mode", "stage"]  # 武器以外のカテゴリ変数
        # for c in cat_cols:
        #     vv, obj = pd.factorize(df[c])  # vv: 数値エンコーディングされた値、obj: 列の種類(unique)
        #     df[c] = vv

        A1 = ["A1-weapon", "A2-weapon", "A3-weapon", "A4-weapon"]
        B1 = ["B1-weapon", "B2-weapon", "B3-weapon", "B4-weapon"]

        t = mlb.transform(df[A1].fillna("none")[A1].values)
        t2 = mlb.transform(df[B1].fillna("none")[B1].values)

        for i in range(t.shape[1]):
            df["A-" + mlb.classes_[i]] = t[:, i]
            df["B-" + mlb.classes_[i]] = t2[:, i]

        s = ["A", "B"]
        p = ["1", "2", "3", "4"]
        for i in s:
            for j in p:
                df[i + j + "-level"] = df[i + j + "-level"] // 10
                df[i + j + "-level"] = df[i + j + "-level"].clip(0, 30)

        return df[:train_num], df[train_num:]

    def trans_weapon(
        self, df, columns=["A1-weapon", "A2-weapon", "A3-weapon", "A4-weapon"]
    ):
        mlb = MultiLabelBinarizer()
        mlb.fit([set(df["A1-weapon"].unique())])
        MultiLabelBinarizer(classes=None, sparse_output=False)

        weapon = df.fillna("none")
        weapon_binarized = mlb.transform(weapon[columns].values)
        return pd.DataFrame(weapon_binarized, columns=mlb.classes_)

    def make_input_output(self, df, with_y=False):
        # a_weapon = trans_weapon(df, ['A1-weapon', 'A2-weapon', 'A3-weapon', 'A4-weapon'])
        a_weapon = self.trans_weapon(df, ["A2-weapon", "A3-weapon", "A4-weapon"])
        b_weapon = self.trans_weapon(
            df, ["B1-weapon", "B2-weapon", "B3-weapon", "B4-weapon"]
        )
        a_weapon = a_weapon.add_suffix("_A")
        b_weapon = b_weapon.add_suffix("_B")
        X = pd.concat([a_weapon, b_weapon], axis=1)
        if with_y:
            y = df["y"]
            return X, y
        return X

    def add_buki_ability(self, df):
        buki_map_title = [
            "get_rank",
            "buki_rank",
            "range",
            "offensive_power",
            "hitting",
            "DPS",
        ]

        dummy_a = df.loc[:, WEAPONS_A].fillna(df.mode().iloc[0])
        dummy_b = df.loc[:, WEAPONS_B].fillna(df.mode().iloc[0])
        weapons_a = pd.DataFrame()
        weapons_b = pd.DataFrame()

        for i in range(len(buki_map_title)):
            buki_map = {k: v[i] for k, v in zip(BUKI_MAP.keys(), BUKI_MAP.values())}
            for name_a, col_a in dummy_a.iteritems():
                weapons_a[f"{name_a}_{buki_map_title[i]}"] = col_a.replace(buki_map)
            for name_b, col_b in dummy_b.iteritems():
                weapons_b[f"{name_b}_{buki_map_title[i]}"] = col_b.replace(buki_map)
        df = pd.concat([weapons_a, weapons_b], axis=1)
        return df.fillna(df.mode().iloc[0])

    # 武器の勝率を計算する。
    def win_rate(self, buki_name, df):
        count = len(df[df[buki_name + "_A"] == 1]) + len(
            df[df[buki_name + "_B"] == 1]
        )  # それぞれのチームで対象ブキが出現する試合数のカウント
        win = len(df[(df[buki_name + "_A"] == 1) & (df.y == 1)]) + len(
            (df[(df[buki_name + "_B"] == 1) & (df.y == 0)])
        )  # それぞれのチームで対象ブキが出現する試合のうち各チームが勝利する試合数のカウント
        rate = win / count
        return rate, count

    # 各チームで使用している武器の勝率の平均値を算出する
    def calc_weapons_win_rate_avg(self, df, win_rate_dict):
        weapons_rate_A = [
            "A1-weapon_win_rate",
            "A2-weapon_win_rate",
            "A3-weapon_win_rate",
            "A4-weapon_win_rate",
        ]
        weapons_rate_B = [
            "B1-weapon_win_rate",
            "B2-weapon_win_rate",
            "B3-weapon_win_rate",
            "B4-weapon_win_rate",
        ]
        for col in df.columns:
            if col in WEAPONS:
                df[f"{col}_win_rate"] = df[col].map(win_rate_dict)  # 各武器の勝率を新特徴量として追加
        df["team_A_win_rate_avg"] = df.loc[:, weapons_rate_A].mean(axis="columns")
        df["team_B_win_rate_avg"] = df.loc[:, weapons_rate_B].mean(axis="columns")
        return df.drop([*weapons_rate_A, *weapons_rate_B], axis=1)  # 平均値のみ特徴量として加える。

    def calc_weapons_win_rate_avg_per_mode(self, df, win_rate_mode_df):
        for mode in df["mode"].unique():
            mode_rate_dict = (
                win_rate_mode_df.loc[:, [f"{mode}_buki", f"{mode}_win_rate"]]
                .set_index(f"{mode}_buki")
                .to_dict()
            )[f"{mode}_win_rate"]
            for col in df.columns:
                if col in WEAPONS:
                    df[f"{col}_win_rate_mode"] = df[col].map(
                        mode_rate_dict
                    )  # 各modeにおける武器の勝率を新特徴量として追加
        return df

    # 各チームにおける遠距離武器人数と近接武器人数の特徴量を追加する(各チーム人数も)。
    def add_count_range_distance(self, df, buki_range_distance_dict):
        buki_category_list = list(set(buki_range_distance_dict.values()))
        count_buki_rangeA = pd.DataFrame()
        count_buki_rangeB = pd.DataFrame()

        teamA_counts = 4 - df.loc[:, WEAPONS_A].isnull().sum(axis=1)
        teamB_counts = 4 - df.loc[:, WEAPONS_B].isnull().sum(axis=1)

        weapons_of_teamA = (
            df.loc[:, WEAPONS_A]
            .replace(buki_range_distance_dict)
            .replace(BUKI_RANGE_CATEGORY)
        ).sum(axis=1)

        count_buki_rangeA["count_long_distance_A"] = weapons_of_teamA
        count_buki_rangeA["count_short_distance_A"] = teamA_counts - weapons_of_teamA
        count_buki_rangeA["count_team_A"] = weapons_of_teamA

        weapons_of_teamB = (
            df.loc[:, WEAPONS_B]
            .replace(buki_range_distance_dict)
            .replace(BUKI_RANGE_CATEGORY)
        ).sum(axis=1)
        count_buki_rangeB["count_long_distance_B"] = weapons_of_teamB
        count_buki_rangeB["count_short_distance_B"] = teamB_counts - weapons_of_teamB
        count_buki_rangeB["count_team_B"] = weapons_of_teamB
        return pd.concat([df, count_buki_rangeA, count_buki_rangeB], axis=1)

    # 各チームのレベル平均,最大値と最小値の差を算出する。
    def calc_team_level_avg(self, df):
        A_level_list = ["A1-level", "A2-level", "A3-level", "A4-level"]
        B_level_list = ["B1-level", "B2-level", "B3-level", "B4-level"]
        df["teamA_level_avg"] = df.loc[:, A_level_list].mean(axis=1)
        df["teamB_level_avg"] = df.loc[:, B_level_list].mean(axis=1)
        df["teamA_lebel_diff"] = df.loc[:, A_level_list].max(axis="columns") - df.loc[
            :, A_level_list
        ].min(axis="columns")
        df["teamB_lebel_diff"] = df.loc[:, B_level_list].max(axis="columns") - df.loc[
            :, B_level_list
        ].min(axis="columns")
        return df

    # 各チームのランク平均を算出する。
    def calc_team_rank_avg(self, df):
        A_rank_list = ["A1-rank", "A2-rank", "A3-rank", "A4-rank"]
        B_rank_list = ["B1-rank", "B2-rank", "B3-rank", "B4-rank"]
        df["teamA_rank_avg"] = df.loc[:, A_rank_list].mean(axis=1)
        df["teamB_rank_avg"] = df.loc[:, B_rank_list].mean(axis=1)
        return df


import os
from models.model import UNet
from dataset.dataset import load_data_bmp
import torch
import torch.optim as optim
from models.loss import MaxPoolLoss, PerceptualLoss
from tqdm import trange
from tqdm import tqdm
from utils import metrics
import argparse
from models.projection import projections
from tensorboardX import SummaryWriter
import numpy as np

def main(input_root, output_root, checkpoint_path, end_epoch):
    writer = SummaryWriter()
    lr = 0.0001
    batch_size = 72
    min_list = torch.zeros((100), requires_grad=False)
    max_list = torch.ones((100), requires_grad=False)
    norm_list = torch.stack((min_list, max_list, min_list, max_list), dim = 0)
    val_loss_list = []

    dir_path = os.path.join(output_root, 'overfitnew_b2')
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)

    train_loader, val_loader, test_loader = load_data_bmp(batch_size=batch_size, data_dir=input_root)
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    model = UNet(n_channels=3, n_classes = 4).to(device)
    model.initialize()
    model = torch.nn.DataParallel(model)
    if checkpoint_path:
        model.load_state_dict(
            torch.load(checkpoint_path)['net'])

    criterion = MaxPoolLoss()
    criterion_pl = PerceptualLoss([2,2,2], [0.6,0.3,0.1], device)
    optimizer = optim.Adam(model.parameters(), lr=lr)
    scheduler = optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.99)

    for epoch in trange(0, end_epoch):
        min_max_list = torch.stack((max_list, min_list, max_list, min_list), dim = 0)
        train(model, optimizer, criterion, criterion_pl, train_loader, device, norm_list, min_max_list, dir_path, epoch)
        norm_list = min_max_list
        scheduler.step()
        val(model, criterion, val_loader, device, val_loss_list)

    loss_list = np.array(val_loss_list)
    index = loss_list.argmin()
    print('epoch %s is the best model' % (index))

    # print('==> Testing model...')
    # restore_model_path = os.path.join(
    #     dir_path, 'ckpt_%d_loss_%.5f.pth' % (index, loss_list[index]))
    # model.load_state_dict(torch.load(restore_model_path)['net'])
    # test(model, 'test', test_loader, device, flag, task, output_root=output_root)
    # writer.close()

def train(model, optimizer, criterion, criterion_pl, train_loader, device, norm_list, min_max_list, dir_path, epoch):
    model.train()
    train_loss = metrics.LossAverage()
    for batch_idx, (or_inputs, inputs, targets) in tqdm(enumerate(train_loader),total = len(train_loader)):
        optimizer.zero_grad()
        or_inputs, inputs, targets = or_inputs.to(device), inputs.to(device), targets.to(device)
        predict = model(inputs).to(device)
        norm_list = norm_list.to(device).detach()
        i = targets[:,0,:,0].cpu().numpy()
        coor_b2, coor_b3, result_b2, result_b3 = projections(or_inputs, predict, 64, 464, device)
        min1 ,max1 = torch.min(result_b2[:,0,:,:],2), torch.max(result_b2[:,0,:,:],2)
        resultn_b2 = torch.zeros((inputs.size(0), 3, 1, 464), requires_grad=True).to(device)
        min2 ,max2 = torch.min(result_b3[:,0,:,:],2), torch.max(result_b3[:,0,:,:],2)
        resultn_b3 = torch.zeros((inputs.size(0), 3, 1, 464), requires_grad=True).to(device)
        for j in range(len(i)):
            resultn_b2[j,:,:,:] = (result_b2[j,:,:,:]- norm_list[0, np.int(i[j][0])])/(norm_list[1, np.int(i[j][0])] - norm_list[0, np.int(i[j][0])])
            if min1[0].data[j, 0] < min_max_list[0, np.int(i[j][0])]:
                min_max_list[0, np.int(i[j][0])] = min1[0].data[j, 0]
            if max1[0].data[j, 0] > min_max_list[1, np.int(i[j][0])]:
                min_max_list[1, np.int(i[j][0])] = max1[0].data[j, 0]
            resultn_b3[j,:,:,:] = (result_b3[j,:,:,:]- norm_list[2, np.int(i[j][0])])/(norm_list[3, np.int(i[j][0])] - norm_list[2, np.int(i[j][0])])
            if min2[0].data[j, 0] < min_max_list[2, np.int(i[j][0])]:
                min_max_list[2, np.int(i[j][0])] = min2[0].data[j, 0]
            if max2[0].data[j, 0] > min_max_list[3, np.int(i[j][0])]:
                min_max_list[3, np.int(i[j][0])] = max2[0].data[j, 0]
        loss1 = criterion_pl(resultn_b2.view(-1, 3, 16,29), targets[:,:,:,1:465].view(-1, 3, 16,29))
        loss2 = criterion_pl(resultn_b3.view(-1, 3, 16,29), targets[:,:,:,465:929].view(-1, 3, 16,29))
        loss_b2 = criterion(resultn_b2, targets[:,:,:,1:465])
        loss_b3 = criterion(resultn_b3, targets[:,:,:,465:929])
        loss = loss_b2+0.25*loss1+0.5*(loss_b3+0.25*loss2)
        loss.backward()
        optimizer.step()
        train_loss.update(loss.item(),inputs.size(0))
    state = {
        'net': model.state_dict(),
        'loss': train_loss.avg,
        'epoch': epoch,
    }
    save_path = dir_path +'/checkpoint'
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    path = os.path.join(save_path, 'ckpt_%d_loss_%.5f.pth' % (epoch, train_loss.avg))
    torch.save(state, path)

def val(model, criterion,train_loader, device, val_loss_list):
    model.eval()
    train_loss_b2 = metrics.LossAverage()
    train_loss_b3 = metrics.LossAverage()
    train_loss = metrics.LossAverage()
    min_list = torch.zeros((20), requires_grad=False)
    max_list = torch.ones((20), requires_grad=False)
    min_max_list = torch.stack((max_list, min_list, max_list, min_list), dim = 0)
    with torch.no_grad():
        for batch_idx, (or_inputs, inputs, targets) in enumerate(train_loader):
            or_inputs, inputs, targets = or_inputs.to(device), inputs.to(device), targets.to(device)
            predict = model(inputs).to(device)
            i = targets[:,0,:,0].cpu().numpy()
            coor_b2, coor_b3, result_b2, result_b3 = projections(or_inputs, predict, 64, 464, device)  ##change
            min1 ,max1 = torch.min(result_b2[:,0,:,:],2), torch.max(result_b2[:,0,:,:],2)
            resultn_b2 = torch.zeros((inputs.size(0), 3, 1, 464), requires_grad=True).to(device)
            min2 ,max2 = torch.min(result_b3[:,0,:,:],2), torch.max(result_b3[:,0,:,:],2)
            resultn_b3 = torch.zeros((inputs.size(0), 3, 1, 464), requires_grad=True).to(device)
            for j in range(len(i)):
                if min1[0].data[j, 0] < min_max_list[0, np.int(i[j][0])]:
                    min_max_list[0, np.int(i[j][0])] = min1[0].data[j, 0]
                if max1[0].data[j, 0] > min_max_list[1, np.int(i[j][0])]:
                    min_max_list[1, np.int(i[j][0])] = max1[0].data[j, 0]
                if min2[0].data[j, 0] < min_max_list[2, np.int(i[j][0])]:
                    min_max_list[2, np.int(i[j][0])] = min2[0].data[j, 0]
                if max2[0].data[j, 0] > min_max_list[3, np.int(i[j][0])]:
                    min_max_list[3, np.int(i[j][0])] = max2[0].data[j, 0]
            for j in range(len(i)):
                resultn_b2[j,:,:,:] = (result_b2[j,:,:,:]-  min_max_list[0, np.int(i[j][0])])/( min_max_list[1, np.int(i[j][0])] -  min_max_list[0, np.int(i[j][0])])
                resultn_b3[j,:,:,:] = (result_b3[j,:,:,:]-  min_max_list[2, np.int(i[j][0])])/( min_max_list[3, np.int(i[j][0])] -  min_max_list[2, np.int(i[j][0])])

            loss_b2 = criterion(resultn_b2, targets[:,:,:,1:465])
            loss_b3 = criterion(resultn_b3, targets[:,:,:,465:929])

            loss = loss_b2 + loss_b3

            train_loss_b2.update(loss_b2.item(),inputs.size(0))
            train_loss_b3.update(loss_b3.item(),inputs.size(0))
            train_loss.update(loss.item(),inputs.size(0))
            val_loss_list.append(train_loss)
        print(train_loss_b2.avg, train_loss_b3.avg)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='RUN model')
    parser.add_argument('--input_root',
                        default='/data1/rong/OCT_and_OCTA/',
                        help='input root, the source of dataset files',
                        type=str)
    parser.add_argument('--output_root',
                        default='./output',
                        help='output root, where to save models and results',
                        type=str)
    parser.add_argument('--checkpoint_path',
                        default='None',
                        help='use checkpoint or not',
                        type=str)
    parser.add_argument('--end_epoch',
                        default=200,
                        help='num of epochs of training',
                        type=int)

    args = parser.parse_args()
    input_root = args.input_root
    output_root = args.output_root
    checkpoint_path = args.checkpoint_path
    end_epoch = args.end_epoch
    main(input_root, output_root, checkpoint_path, end_epoch)


import random
from turtle import Turtle, Screen

screen = Screen()
turtle_one = Turtle()
turtle_two = Turtle()
turtle_three = Turtle()
turtle_four = Turtle()

choice = screen.textinput(title="Place your bets!", prompt="Which turtle will you place your bet on?")
colours = ["red", "blue", "green", "yellow"]
y_startingpoints = [-100,-150,-200,-250]
turtles=[]
for i in range (0,4):
    turtle = Turtle(shape="turtle")
    turtle.penup()
    turtle.color(colours[i])
    turtle.goto(x=-200, y = y_startingpoints[i])
    turtle.pendown()
    turtles.append(turtle)

race = True
while(race):
    for turtle in turtles:
        if (turtle.xcor() >= 200):
            race = False
            win = turtle.pencolor()
            if (win == choice):
                print("you won!")
            else:
                print("you lost...")

        turtle.forward(random.randint(0,10))

screen.exitonclick()


import tensorflow as tf
import pathlib
import os
data_dir = pathlib.Path(os.path.abspath('webs/static/ImageToTrain'))

#Tạo tập dữ liệu
batch_size =3
img_height=224
img_width=224

#Chỉ dùng 80% hình ahr để đào tạo và 20% hình ảnh để xác thực
train_ds=tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,
    subset="training",
    seed=123,
    image_size=(img_height,img_width),
    batch_size=batch_size
)
val_ds=tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
  validation_split=0.2,
  subset="validation",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size
)
class_names=train_ds.class_names


from .utils import timestamps_collection, validate_publication_date, calculate_difference, timestamps_to_format, categorize_in_time_buckets

def calculate_historical_distance(iterable_of_nafs,
                                    event_date,
                                    time_buckets,
                                    xlsx_path=None,
                                    output_folder=None,
                                    start_from_scratch=True):
    '''
    provides the spread of historical distance in days for a corpus of reference texts
    :param path_to_nafs: path to a directory containing a collection of naf files
    :param event_date: the date of the event (YY-MM-DD)
    :param filename: name.type for the output table
    :type iterable_of_nafs: list
    :type event_date: datetime.datetime
    '''
    timestamps = timestamps_collection(collection=iterable_of_nafs)
    known_timestamps, unknown_timestamps = validate_publication_date(event_date=event_date,
                                                                    timestamps=timestamps)
    known_distance = calculate_difference(list_of_timestamps=known_timestamps,
                                                event_date=event_date)
    known_distance_time_buckets = categorize_in_time_buckets(known_distance=known_distance,
                                                            time_buckets=time_buckets)
    df = timestamps_to_format(known_timestamps=known_distance_time_buckets,
                            unknown_timestamps=unknown_timestamps,
                            xlsx_path=xlsx_path,
                            output_folder=output_folder,
                            start_from_scratch=start_from_scratch)
    return df


# @Version : Python3.6
# @Time    : 2018/9/10 17:34
# @Author  : zhcf1ess
# @Site    :
# @File    : 估计线性模型.py
# @Software: PyCharm

import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

def dnorm(mean, variance, size=1):
    if isinstance(size, int):
        size = size
    return mean + np.sqrt(variance) * np.random.randn(size)

np.random.seed(1234)

N = 100
X = np.c_[dnorm(0, 0.4, size=N), dnorm(0, 0.6, size=N), dnorm(0, 0.2, size=N)]

eps = dnorm(0, 0.1, size=N)

beta = [0.1, 0.3, 0.5]

y = np.dot(X, beta) + eps

# print(X[:5])
# print("============================================")
# print(y[:5])

# sm.add_constant(X)  添加一个截距到矩阵
# X_model = sm.add_constant(X)
# print(X_model)
model = sm.OLS(y, X)
result = model.fit()
# print(result.params)
# print(result.summary())
data = pd.DataFrame(X, columns=['col0', 'col1', 'col2'])
data['y'] = y
# print(data[:5])
results = smf.ols('y ~  col0  +  col1  +  col2', data=data).fit()
# print(results.params)
# print(results.tvalues)
print(result.predict(data[:5]))

notebook/第 13 章  Python 建模库介绍模库/13.3  statsmodels/估计线性模型.py


# -*- coding: utf-8 -*-
"""
Created on Tue Apr 25 21:47:51 2023

@author: GolkarE
"""

import nibabel as nib
import numpy as np
import os

from dipy.data import get_sphere
from dipy.reconst import shm
from dipy.direction import peak_directions
import sys

vol= str(sys.argv[1])

#vol = '300-800'
#ext='/noflip'

#ext= '/'+str(sys.argv[1])

path = str(sys.argv[2])
# '/cbica/home/golkare/Data/Multishell3-062'

mask = str(sys.argv[3]) # mask file

lmax = int(sys.argv[4])
sphere = get_sphere(name='symmetric724')

nii = nib.load(mask)
img = nii.get_fdata()
ii= np.where(img==0)

vf_bundle_aniso = np.zeros(img.shape, dtype=np.float)
vf_bundle_iso = np.zeros(img.shape, dtype=np.float)
vf_FW = np.zeros(img.shape, dtype=np.float)
vf_HW = np.zeros(img.shape, dtype=np.float)
vf_intra= np.zeros(img.shape, dtype=np.float)
vf_extra= np.zeros(img.shape, dtype=np.float)
fods = np.zeros((img.shape[0], img.shape[1], img.shape[2], int((lmax+1)*(lmax+2)/2) ), dtype=np.float)
AI= np.zeros(img.shape, dtype=np.float)

#print('img.shape[1]',img.shape[1])

for i in range(1,img.shape[1],1):

    if (os.path.exists(path+'/'+vol + '/results/'+str(i)+'/vf_bundle_aniso.nii.gz') == False):
        continue
    print('vol:',vol,' slice i:',i)
    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/vf_bundle_aniso.nii.gz')
    bundle_aniso = nii.get_fdata()
    vf_bundle_aniso[:,i:i+1,:]=bundle_aniso

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/vf_bundle_iso.nii.gz')
    bundle_iso = nii.get_fdata()
    vf_bundle_iso[:,i:i+1,:]=bundle_iso

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/vf_FW.nii.gz')
    FW = nii.get_fdata()
    vf_FW[:,i:i+1,:]=FW

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/vf_HW.nii.gz')
    HW = nii.get_fdata()
    vf_HW[:,i:i+1,:]=HW

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/vf_intra.nii.gz')
    intra = nii.get_fdata()
    vf_intra[:,i:i+1,:]=intra

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/vf_extra.nii.gz')
    extra = nii.get_fdata()
    vf_extra[:,i:i+1,:]=extra

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/fods.nii.gz')
    fod = nii.get_fdata()
    fods[:,i:i+1,:,:]=fod

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/AI.nii.gz')
    ai = nii.get_fdata()
    AI[:,i:i+1,:]=ai

vf_bundle_aniso[ii] = 0
img_vf_bundle_aniso = nib.Nifti1Image(vf_bundle_aniso, nii.affine)
nib.save(img_vf_bundle_aniso,path+'/'+vol+'/results' +'/vf_bundle_aniso.nii.gz')

vf_bundle_iso[ii]=0
img_vf_bundle_iso = nib.Nifti1Image(vf_bundle_iso, nii.affine)
nib.save(img_vf_bundle_iso,path+'/'+vol+'/results/vf_bundle_iso.nii.gz')

vf_FW[ii]=0
img_vf_FW = nib.Nifti1Image(vf_FW, nii.affine)
nib.save(img_vf_FW,path+'/'+vol+'/results' +'/vf_FW.nii.gz')

vf_HW[ii]=0
img_vf_HW = nib.Nifti1Image(vf_HW, nii.affine)
nib.save(img_vf_HW,path+'/'+vol+'/results' +'/vf_HW.nii.gz')

vf_intra[ii]=0
img_vf_intra = nib.Nifti1Image(vf_intra, nii.affine)
nib.save(img_vf_intra,path+'/'+vol+'/results' +'/vf_intra.nii.gz')

vf_extra[ii]=0
img_vf_extra = nib.Nifti1Image(vf_extra, nii.affine)
nib.save(img_vf_extra,path+'/'+vol+'/results' +'/vf_extra.nii.gz')

AI[ii]=0
img_AI = nib.Nifti1Image(AI, nii.affine)
nib.save(img_AI,path+'/'+vol+'/results' +'/AI.nii.gz')

freeWater = np.where(vf_bundle_iso>.9)
listIndex = list(zip(freeWater[0],freeWater[1],freeWater[2]))
index =0
for i in listIndex:
    fods[i[0],i[1],i[2],:] = np.zeros((1, 1, 1, int((lmax+1)*(lmax+2)/2) ), dtype=np.float)
    index +=1

wmfod= np.zeros(fods.shape)
sf = shm.sh_to_sf(fods,sphere,sh_order=lmax,basis_type = 'tournier07')
for i in range(1,img.shape[0],1):
    print ( 'vol: ', vol, ' i:',i )
    for j in range(1,img.shape[1],1):
        for k in range(1,img.shape[2],1):
                ps = peak_directions(sf[i,j,k,:], sphere, relative_peak_threshold=.25)
                if (len(ps[1]) != 0 and ps[1][0]<3.5):
                    wmfod[i,j,k,:] = fods[i,j,k,:]
                if (img[i,j,k] == 0 ):
                    wmfod[i,j,k,:] = np.zeros((1, 1, 1, int((lmax+1)*(lmax+2)/2) ), dtype=np.float)

img_wmfod = nib.Nifti1Image(wmfod, nii.affine)
nib.save(img_wmfod,path+'/'+vol+'/results' +'/fods_lmax'+str(lmax)+'.nii.gz')


import cv2
import numpy as np
import time
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
import pathlib

model = keras.models.load_model('./model/mymodel7')
model.summary()

image_size = (200, 200)

img = keras.preprocessing.image.load_img(
    "test/j.jpg", target_size=image_size
)

img_array = keras.preprocessing.image.img_to_array(img)

img_array = tf.expand_dims(img_array, 0)  # Create batch axis

predictions = model.predict(img_array)

print('le score est ')
#print( predictions[0] )
vect =[]
for i in predictions[0]:
   vect.append(int(i*100))

print("----")
print(vect)
myvect = ['bcheval', 'bfou', 'bpion', 'breine', 'broi', 'btour', 'ncheval', 'nfou', 'npion', 'nreine', 'nroi', 'ntour', 'vide']
#myvect = [ 'blanc' , 'noir','vide']
print(myvect)

for i in range(3):
    print('-'+str(myvect[i])+'->'+str(vect[i]))

#
#
#
#
#
#
#
#
#
#

#print("package  Imorted")
#
#cap = cv2.VideoCaoture(0)
#cap.set(3,640)
#cap.set(4,480)

#while True :
#    success , img = cap.read()
#    cv2.imshow("Video",img)
#    if cv2.waitKey(1) && 0xFF == ord('q'):
#        break


import numpy as np
import math
import sympy as sym
from scipy import linalg
from sympy import *

def limits_func_vec(vec, var, val):
    limits = np.array([])
    for i in range(0, len(vec)):
        limits = np.append(limits, sym.limit(vec[i], var, val))
    return limits

def deriv_func_vec(vec, var, num_of_derivs = 1, solve = False, val = None):
    if (solve == False and val == None):
        derivs = np.array([])
        for i in range(0, len(vec)):
            derivs = np.append(derivs, sym.diff(vec[i], var, num_of_derivs))
        return derivs
    else:
        derivs = np.array([])
        for i in range(0, len(vec)):
            derivs = np.append(derivs, sym.diff(vec[i], var, num_of_derivs))
        for i in range(0, len(vec)):
            derivs[i] = derivs[i].subs(var, val)
        return derivs

def integrate_func_vec(vec, var = None, start = None, end = None):
    if (start == None and end == None and var == None):
        integrals = np.array([])
        for i in range(0, len(vec)):
            integrals = np.append(integrals, sym.integrate(vec[i]))
        return integrals
    else:
        integrals = np.array([])
        for i in range(0, len(vec)):
            integrals = np.append(integrals, sym.integrate(vec[i], (var, start, end)))
        return integrals

def gradient_vector(expression):
    syms = [ symb for symb in expression.free_symbols ]
    partials = np.array([])

    for i in range (0, len(syms)):
        partials = np.append(partials, sym.diff(expression, syms[i]))

    return partials


'''
M 이상 N 이하의 소숙가 하나 이상 있는 입력만 주어진다
한 줄에 하나씩 증가하는 순서대로 소수를 출력
소수 구할때 2, 3, 5, 7 은 무조건 그냥 출력
'''
M, N = map(int, input().split())
# for i in range(M, N+1):
#     div = 2
#     while True:
#         # 종료조건
#         if i == div:
#             print(i)
#             break
#         if i % div == 0:
#             break
#         else:
#             div += 1

# i의 제곱근을 구해서 +1 해주면 해당 수의 제곱근이 나온다.
# 전체를 검사하면 M, N의 범위가 커지면 계산량이 많아져서 시간초과 뜸
# 에라토스테네스의 체가 2, 3, 5, 7 의 배수에 해당하는 모든 수는 무조건 소수가 아님
# 해당 수들을 제외한 나머지 수가 소수
for i in range(M, N+1):
    if i == 1:
        continue
    for j in range(2, int(i**0.5)+1):
        if i % j == 0:
            break
    else:
        print(i)


# Graham Williams
# grw400@gmail.com

# Apply ReLU activation function to a dense layer

import numpy as np
import nnfs

from nnfs.datasets import spiral_data

nnfs.init()

class Layer_Dense:

    def __init__(self, n_inputs, n_neurons):
        self.weights = 0.01 * np.random.randn(n_inputs, n_neurons)

        self.biases = np.zeros((1, n_neurons))

    def forward(self, inputs):
        self.output = np.dot(inputs, self.weights) + self.biases

class Activation_ReLU:

    # Forward pass
    def forward(self, inputs):
        # Calculate output values from input
        self.output = np.maximum(0, inputs)

# Create dataset
X, y = spiral_data(samples=100, classes=3)

# Create Dense Layer with 2 input features and 3 output values
dense1 = Layer_Dense(2,3)

# Create ReLU activation
activation1 = Activation_ReLU()

# Forward pass training data through layer
dense1.forward(X)

# Forward pass through activation func.
# Takes in output from previous layer
activation1.forward(dense1.output)

print(activation1.output[:5])


'''
This program uses the googletrans library for language detection and translation.
To install it, you can use pip: pip install googletrans==4.0.0-rc1.

The program creates a window with a language selection dropdown, a comparison tool
radio button group, and two text boxes for the source and target articles. It also
includes buttons for clearing the text boxes, comparing the articles, and translating
the target article to match the language of the source.

The compare function compares the source and target articles using either the difflib
library for line-by-line comparison or simple string matching. The result is displayed
in a third text box labeled "Comparison result".
'''

import PySimpleGUI as sg
from googletrans import LANGUAGES, Translator

# Define available language options
languages = [LANGUAGES[key] for key in LANGUAGES.keys()]

# Define GUI layout
layout = [

    [sg.Text("Select language:"), sg.Combo(languages, default_value="English", key="language")],
    [sg.Text("Select comparison tool:"), sg.Radio("Diff", "RADIO1", default=True, key="diff"), sg.Radio("Match", "RADIO1", key="match")],
    [sg.Text("Source article:"), sg.Multiline(key="source", size=(60, 10))],
    [sg.Text("Target article:"), sg.Multiline(key="target", size=(60, 10))],
    [sg.Button("Clear"), sg.Button("Compare"), sg.Button("Translate")],
    [sg.Text("Comparison result:"), sg.Multiline(key="result", size=(60, 10), disabled=True)]
]

# Create the GUI window
#window = sg.Window("Messaging Helper Tool", layout) #Article Comparison Tool

window = sg.Window("Messaging Helper Tool",layout=layout, element_justification="c", resizable = True, font=("Arial", 18)).Finalize()
window.Maximize()

# Create a translator object for later use
translator = Translator()

# Define comparison function
def compare(source_text, target_text, tool):
    if tool == "Diff":
        # Perform comparison using difflib library
        import difflib
        result = difflib.ndiff(source_text.splitlines(), target_text.splitlines())
        result = "\n".join(list(result))
    elif tool == "Match":
        # Perform comparison using string matching
        result = ""
        for sentence in source_text.split("."):
            if sentence in target_text:
                result += sentence + ".\n"
    return result

#Define translate function
def translate(target_text, src="auto", dest="en"):
    # Create a translator object for later use
    translator = Translator()

    # Detect the source language of the target text
    source_lang = translator.detect(target_text).lang

    # Translate target text to match the specified source language
    if src != "auto" and source_lang != src:
        target_text = translator.translate(target_text, src=src, dest=source_lang).text

    # Translate target text to the specified destination language
    if dest != "auto" and source_lang != dest:
        target_text = translator.translate(target_text, src=source_lang, dest=dest).text

    return target_text

# Event loop to process GUI events
while True:
    event, values = window.read()

    # Handle window closed event
    if event == sg.WINDOW_CLOSED:
        break

    # Handle clear button event
    elif event == "Clear":
        window["source"].update("")
        window["target"].update("")
        window["result"].update("")

    # Handle compare button event
    elif event == "Compare":
        source_text = values["source"]
        target_text = values["target"]
        tool = "Diff" if values["diff"] else "Match"
        result = compare(source_text, target_text, tool)
        window["result"].update(result)

    # Handle translate button event
    elif event == "Translate":
        source_text = values["source"]
        target_text = values["target"]
        source_lang = translator.detect(source_text).lang    #lang
        target_lang = values["language"]
        if source_lang != target_lang:
            # Translate target text to match source language
            translation = translator.translate(target_text, src=target_lang, dest=source_lang)
            window["target"].update(translation.text)
            window["result"].update("")

# Close the window when the event loop is exited
window.close()


import os
import sys
from optparse import OptionParser, OptionGroup

def printRed(str):
    """
    @type  str: string
    @param str: String to print to stderr in red.
    @return   : Nothing, just prints the string.

    Prints given string to stderr using red color.
    """
    print >>sys.stderr, '\033[0;31m%s\033[m' % str

def createOptionParser():
    """
    @return: C{OptionParser}
    Creates and returns OptionParser object suited for command line arguments processing.
    """
    parser = OptionParser()

    parser.add_option("-p", "--parsingModule", dest="parsingModule",
            action="store", help="Atlas parser for dedicated atlas", metavar="parsingModule")
    parser.add_option("-s", "--startpage", dest="startpage", action="store",
            help="First page of parsing sequence", metavar="page_number", type="int")
    parser.add_option("-e", "--endpage", dest="endpage", action="store",
            help="Last page of parsing sequence", metavar="page_number", type="int")
    parser.add_option("-o", "--outputAtlasDirecotry", dest="outputDir", action="store",
            help="Directory, where parsed file will be stored.", metavar="DIR")
    parser.add_option("-i", "--sourceDirecotry", dest="sourceDir", action="store",
            help="Directory, from which source data fill be read.", metavar="DIR")
    parser.add_option("--create-only-index-file", action="store_true", dest="only_index",
            default=False, help="Create only index file")
    return parser

def validateOptions(opts):
    """
    @type  opts: parsed OptionParsed object
    @param opts: Set of options extracted and parsed by OptionParser
    @return    : True when options set passes all validation rules, False otherwise.

    Validates provided options formally and logicaly.
    Detail of validation process are explained in comments.
    """

    # Check, if name of parsing module is correct:
    if opts.parsingModule == "":
        printRed("Pasing module defined incorrectly!")
        return False

    # Check, if the arguments are defined
    if opts.endpage<0 or opts.startpage<0 or opts.outputDir=="":
        printRed("Some arguments are not provided or has incorrect values.")
        return False

    # Check, if ending page is equal or greater than starting page
    if not opts.endpage>=opts.startpage:
        printRed("Endpage page should be greater or equal than startpage.")
        return False

    # Check, if provided output directory exists
    if not os.path.isdir(opts.outputDir):
        printRed("Provided directory is not a valid directory.")
        return False
    return True

if __name__=='__main__':
    # Create OptionParser object and parse provided command-line arguments.
    parser=createOptionParser()
    (options, args) = parser.parse_args()

    # Validate command line arguments
    # When arguments turns out invalid, print notification and quit script
    if not validateOptions(options):
        printRed("Invalid command line arguments. Please correct.")
        parser.print_help()
        exit(1)

    # Import atlas parsing module
    sys.path.append('bin/parsers')
    atlasparser = __import__(options.parsingModule, globals(), locals(), [], -1)

    # Define page range ('+1' is added due to pythonic way of indexing lists)
    pagesRange = range(options.startpage, options.endpage+1)
    ap = atlasparser.AtlasParser(options.sourceDir,  options.outputDir)

    #If only index should be created, od it and then exit the program:
    if options.only_index:
        printRed("Creating index file now.")
        ap.parseAll()
        exit(0)

    for slide in pagesRange:
        ap.parse(slide)


import random

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

        pivot = random.choice(nums)

        left = [x for x in nums if x > pivot]
        right = [x for x in nums if x < pivot]
        mid = [x for x in nums if x == pivot]

        len_left, len_mid = len(left), len(mid)

        if k <= len_left:
            return self.findKthLargest(left, k)
        elif k > len_left + len_mid:
            return self.findKthLargest(right, k - len_left - len_mid)
        else:
            return mid[0]

    def findKthLargest1(self, nums, k):
        return self.qsort(nums, 0, len(nums)-1, k)

    def qsort(self, nums, low, high, k):
        randomindex = random.randint(low, high)
        nums[randomindex], nums[high] = nums[high], nums[randomindex]
        pivot = high

        i = low
        for j in range(low, high):
            if nums[j] <= nums[pivot]:
                nums[i], nums[j] = nums[j], nums[i]
                i += 1
        nums[i], nums[high] = nums[high], nums[i]

        right = high - i + 1

        if k == right:
            return nums[i]

        if right > k:
            return self.qsort(nums, i+1, high, k)

        return self.qsort(nums, low, i-1, k-right)

solution = Solution()
print(solution.findKthLargest([3,2,1,5,6,4], 2))
print(solution.findKthLargest1([3,2,1,5,6,4], 2))


# -*- coding: utf-8 -*-
"""
estimate the stellar density, and mass.
"""
from __future__ import division, print_function
import numpy as np
import pickle

from astropy import units as u, constants as const

# Keivan value
Rstar = 0.893*u.Rsun
Rstar_err = 0.024*u.Rsun

# parameters from Table 4 of Hoyer+2013, for comparison
i_hoyer13 = 88.52*u.deg
a_by_Rs_hoyer13 = 5.463
a_by_Rs_perr_hoyer13 = 0.025
a_by_Rs_merr_hoyer13 = 0.020
P_hoyer13 = 1.33823204*u.day
hoyer_params = [i_hoyer13, a_by_Rs_hoyer13, a_by_Rs_perr_hoyer13,
                a_by_Rs_merr_hoyer13, P_hoyer13]

# get parameters from fit to phase-folded lightcurve
picklepath = ('/home/luke/Dropbox/proj/tessorbitaldecay/results/'
              'tess_lightcurve_fit_parameters/402026209/sector_2/'
              '402026209_phased_mandelagol_fit_empiricalerrs.pickle' )

d = pickle.load(open(picklepath, 'rb'))
i = d['fitinfo']['finalparams']['incl']*u.deg
i_upper = i + 0.39*u.deg

i = 88.52*u.deg # Hoyer+ 2013, table 4
i_upper = i + d['fitinfo']['finalparamerrs']['std_perrs']['incl']*u.deg
i_lower = i - d['fitinfo']['finalparamerrs']['std_merrs']['incl']*u.deg
a_by_Rs = d['fitinfo']['finalparams']['sma']
a_by_Rs_perr = d['fitinfo']['finalparamerrs']['std_perrs']['sma']
a_by_Rs_merr = d['fitinfo']['finalparamerrs']['std_merrs']['sma']
P = d['fitinfo']['finalparams']['period']*u.day

a_by_Rs = d['fitinfo']['finalparams']['sma']
a_by_Rs_perr = d['fitinfo']['finalparamerrs']['std_perrs']['sma']
a_by_Rs_merr = d['fitinfo']['finalparamerrs']['std_merrs']['sma']

Rp_by_Rs = d['fitinfo']['finalparams']['rp']
Rp_by_Rs_err = np.mean(
    [d['fitinfo']['finalparamerrs']['std_perrs']['rp'],
    d['fitinfo']['finalparamerrs']['std_merrs']['rp']
    ]
)
Rp = Rp_by_Rs * Rstar
Rp_upper = (Rp_by_Rs + Rp_by_Rs_err)*(Rstar+Rstar_err)
Rp_lower = (Rp_by_Rs - Rp_by_Rs_err)*(Rstar-Rstar_err)

my_params = [i, a_by_Rs, a_by_Rs_perr, a_by_Rs_merr, P]

paramnames = ['incl','a/Rstar','a/Rstar_perr','a/Rstar_merr','P']

# the period you adopt here does not particularly matter! the one reported in
# the transit time table does. so using my less precise TESS-only BLS period
# (1.33814, vs hoyer+13: 1.338232 d, is fine.

print('-'*42)
for hparam, mparam, pname in zip(hoyer_params, my_params, paramnames):
    print('{:s}: me: {:.5f}, hoyer+13: {:5f}\n\tme-h13: {:.5f}'.
          format(pname, mparam, hparam, mparam-hparam))
print('-'*42)
print('for selected system parameters table:')
# Rp/Rstar, incl, a/Rstar, ulinear, uquad:
params = ['rp','incl','sma','u_linear','u_quad']
precisions = [5, 2, 3, 3, 3]
for param, precision in zip(params, precisions):
    value = d['fitinfo']['finalparams'][param]
    value_perr = d['fitinfo']['finalparamerrs']['std_perrs'][param]
    value_merr = d['fitinfo']['finalparamerrs']['std_merrs'][param]
    outstr = ('{:s}: '.format(param)+
              '{1:.{0}f}'.format(precision, value)+
              ' +{1:.{0}f}'.format(precision, value_perr)+
              ' -{1:.{0}f}'.format(precision, value_merr)
    )
    print(outstr)
print('-'*42)

# eq 30 of Winn (2010).
# note k^3 = 3e-3, and the density of jupiter is about equal to the density of
# the sun, so neglect the k^3*rho_planet term.

rho_star = 3*np.pi/(const.G*P**2) * a_by_Rs**3
print(rho_star.cgs)

rho_star_upper = 3*np.pi/(const.G*P**2) * (a_by_Rs+a_by_Rs_perr)**3
print(rho_star_upper.cgs)

rho_star_lower = 3*np.pi/(const.G*P**2) * (a_by_Rs-a_by_Rs_merr)**3
print(rho_star_lower.cgs)

print(
    'rhostar = {:.3f} +({:.3f}) -({:.3f}) g/cm^3'.format(
        rho_star.cgs.value,
        (rho_star_upper-rho_star).cgs.value,
        (rho_star-rho_star_lower).cgs.value
    )
)

Mstar = (4*np.pi)/3*rho_star*Rstar**3
Mstar_lower = (4*np.pi)/3*rho_star_lower*(Rstar-Rstar_err)**3
Mstar_upper = (4*np.pi)/3*rho_star_upper*(Rstar+Rstar_err)**3

print(
    'Mstar = {:.3f} +({:.3f}) -({:.3f}) Msun'.format(
        Mstar.to(u.Msun).value,
        (Mstar_upper-Mstar).to(u.Msun).value,
        (Mstar-Mstar_lower).to(u.Msun).value,
    )
)

##########################################
# now get R_p

print(
    'Rp = {:.3f} +({:.3f}) -({:.3f}) Rjup'.format(
        Rp.to(u.Rjup).value,
        (Rp_upper-Rp).to(u.Rjup).value,
        (Rp-Rp_lower).to(u.Rjup).value,
    )
)

# semimajor axis
sma = a_by_Rs * Rstar
sma_upper = (a_by_Rs+a_by_Rs_perr) * (Rstar+Rstar_err)
sma_lower = (a_by_Rs-a_by_Rs_merr) * (Rstar-Rstar_err)

print(
    'sma = {:.4f} +({:.4f}) -({:.4f}) AU'.format(
        sma.to(u.AU).value,
        (sma_upper-sma).to(u.AU).value,
        (sma-sma_lower).to(u.AU).value,
    )
)

# now get M_p

K = 241.1 * u.m/u.s
K_perr = 2.8 * u.m/u.s
K_merr = 3.1 * u.m/u.s

sini = float(np.sin(i))
sini_upper = float(np.sin(i_upper))
sini_lower = float(np.sin(i_lower))

# assume e = 0

Mp = K * (const.G)**(-1/2) * sini**(-1) * Mstar**(1/2) * sma**(1/2)

Mp_upper = (
    (K+K_perr) * (const.G)**(-1/2) * sini_upper**(-1) *
    Mstar_upper**(1/2) * sma_upper**(1/2)
)

Mp_lower = (
    (K-K_merr) * (const.G)**(-1/2) * sini_lower**(-1) *
    Mstar_lower**(1/2) * sma_lower**(1/2)
)

print(
    'Mp = {:.3f} +({:.3f}) -({:.3f}) Mjup'.format(
        Mp.to(u.Mjup).value,
        (Mp_upper - Mp).to(u.Mjup).value,
        (Mp - Mp_lower).to(u.Mjup).value,
    )
)

# finally, Rstar/d
F_bol = 2.8e-10 * u.erg/(u.cm**2 * u.s)
F_bol_err = 0.1e-10 * u.erg/(u.cm**2 * u.s)
Teff = 5400 * u.K
Teff_err = 90 * u.K

Rstar_by_dist = (F_bol / (const.sigma_sb * Teff**4 ) )**(1/2)
Rstar_by_dist_upper = ( (F_bol+F_bol_err) / (const.sigma_sb * (Teff-Teff_err)**4 ) )**(1/2)
Rstar_by_dist_lower = ( (F_bol-F_bol_err) / (const.sigma_sb * (Teff+Teff_err)**4 ) )**(1/2)

print(
    'Rs/dist = {:.3e}, +{:.3e} -{:.3e}'.format(
        Rstar_by_dist.cgs,
        (Rstar_by_dist_upper-Rstar_by_dist).cgs,
        (Rstar_by_dist-Rstar_by_dist_lower).cgs,
    )
)

plx = 3.7145e-3 * u.arcsec
plx_offset = 82e-6 * u.arcsec
plx += plx_offset

plx_err = 0.0517e-3 * u.arcsec

dist_pc = (1/plx.value)*u.pc

Rs_calcd = (Rstar_by_dist * dist_pc).to(u.Rsun)

print(
    'dist = {:.2f}'.format(dist_pc)+
    '\nmy Rstar (but use Keivan\'s) = {:.3f}'.format(Rs_calcd)
)


from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import threading
import cv2
from uiwindow import Ui_window
from hrnet.tools import pose
from mmaction2.demo import webcam_demo
from PyQt5 import QtCore
import os
class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        # 从文件中加载UI定义
        # 从 UI 定义中动态 创建一个相应的窗口对象
        flag=0
        self.ui = Ui_window()
        self.ui.setupUi(self)  #画出窗口
        styleFile = os.getcwd() + '\style.qss'
        self.setStyleSheet(str(self.LoadStyleFromQss(styleFile)))
        self.setWindowFlags(QtCore.Qt.CustomizeWindowHint)
        # self.ui.pose.clicked.connect(self.play_video_pose) #拍照识别
        # self.ui.action.clicked.connect(self.play_video_activity)  # 动作识别

        self.ui.pose.clicked.connect(self.modechange(1))  # 拍照识别
        self.thread = None  # 创建线程

    def play_video_pose(self):  #创建线程不断调用摄像头捕捉画面
        self.thread = threading.Thread(target=self.detect)  #线程调用的是detect
        self.thread.start()
        print("线程开启")

    def play_video_activity(self):  #创建线程不断调用摄像头捕捉画面
        self.thread = threading.Thread(target=self.react)  #线程调用的是detect
        self.thread.start()
        print("线程开启")

    def LoadStyleFromQss(self, f):
        file = open(f)
        lines = file.readlines()
        file.close()
        res = ''
        for line in lines:
            res += line
        return res
    # def windowmode(self):

    # def modechange(self):

    def detect(self):
        self.cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # 拿到摄像头的流
        while self.cap.isOpened():
            ret, frame = self.cap.read()
            img = pose.main(frame)

            convert_to_qt_format = QImage(img.data, img.shape[1], img.shape[0],
                                          QImage.Format_RGB888)  #转成qt格式！！！！！
            self.ui.show.setPixmap(QPixmap.fromImage(convert_to_qt_format))  #显示
        # self.cap.release()
        cv2.destroyAllWindows()

    def react(self):
        webcam_demo.main()

# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助

app = QApplication([])
mainwindow = MainWindow()
mainwindow.show()
app.exec_()


# GrammarBot v1.0

# Import external dependencies
import discord
import logging
from yaml import load
from sys import exit as sys_exit
from os import startfile

# Import internal dependencies
from src import talk, cli

# Constants
CONFIG = "./data/config.yaml"
PERMS = 3136

# Get arguments form the command line
args = cli.parse()

# Sets up the logging system
logging.basicConfig(level=logging.INFO if args.info else logging.ERROR)
log = logging.getLogger()

# Get setup information from config
try:
    with open(CONFIG, "r") as file:
        try:
            data = load(file.read())
            token = data["token"]
            owner_id = str(data["owner_id"])
        except:
            log.error("Parsing the config.yaml file. Please make sure that it is formatted correctly.")
except:
    log.error("Reading the config.yaml file. Make sure such a file exists.")
    sys_exit()

# Initalise the client
client = discord.Client()
reload = False

# Events

@client.event
async def on_ready():
    global client, log
    print("GrammarBot is ready!")
    id = client.user.id
    print("With the id ~", id)
    print("Link to add the bot to a server")
    print(f"  https://discordapp.com/api/oauth2/authorize?client_id={id}&scope=bot&permissions={PERMS}")
    servers = client.servers
    n = len(servers)
    if n != 0:
        print("On", n, "Servers =>")
        for s in servers:
            print(" ", s.name)
    else:
        print("On no servers")
    print("="*8)
    await client.change_presence(game=discord.Game(name="with the 1%ers", type=1))

@client.event
async def on_message(message):
    msg = message.content.lower()
    ch = message.channel
    if msg.startswith("!ping"):
        await client.send_message(ch, "Pong!")
    elif msg.startswith("!read"):
        await client.send_message(ch, talk.reading())
    elif msg.startswith("!eval"):
        await client.send_message(ch, talk.eval(message.content[5:]))
    elif msg.startswith("!quit"):
        if message.author.id == owner_id:
            print("Exit command called from Discord. Exiting.")
            await client.logout()

# Run the bot
client.run(args.token if (args.token is not None) else token)
# End the bot
sys_exit()


"""
522 longest uncommon subsequence II
"""

def findLongestUncommon(strs):
  def isSubsequence(a, b):
    if len(a) > len(b): return False
    start = 0
    for i, v in enumerate(b):
      if start < len(a) and a[start] == v:
        start += 1
    return start == len(a)
  if not strs: return -1
  strs.sort(key=len, reverse=True)
  for i, s in enumerate(strs):
    if all(not isSubsequence(w, s) for j, w in enumerate(strs) if i != j):
      return len(s)
  return -1

print(findLongestUncommon(["aba", "cdc", "eae"])) # 3


def complement(target, op):
    return target - op

def bounded_sum_ops(els, target):
    left_index = 0
    right_index = len(els) - 1
    while left_index != right_index:
        left_value = els[left_index]
        right_value = els[right_index]

        if left_value + right_value == target:
            return True, left_value, right_value

        if complement(target, right_value) > right_value:
            break

        if complement(target, left_value) < left_value:
            break

        if complement(target, left_value) < right_value:
            right_index -= 1
        else:
            left_index += 1

    return False, None, None

def sum_ops(els, target):
    return bounded_sum_ops(list(sorted(els)), target)


"""
Дано два списка значений, вывести значения которые есть в обоих списках.
[1,2,3,4] [3, 5, 7, 1] -> [1, 3]
"""
import random
LIST_SIZE = 5

def list_generator(list_dimension):
    my_list = []
    for i in range(list_dimension):
        my_list.append(random.randint(-9, 9))
    return my_list

def list_comparison(list_1, list_2):
    new_list = []
    for i in range(len(list_1)):
        for j in range(len(list_2)):
            if list_1[i] == list_2[j]:
                new_list.append(list_1[i])
    return new_list

if __name__ == '__main__':
    list_1 = list_generator(LIST_SIZE)
    list_2 = list_generator(LIST_SIZE)
    print('Для списков:', list_1, 'и :', list_2, '\n'
          'общими значениями являются:', list_comparison(list_1, list_2)
         )


# (c) 2019 Amazon Web Services, Inc. or its affiliates. All Rights Reserved.
# License:
# This sample code is made available under the MIT-0 license. See the LICENSE file.
from inventory.readers import AwsConfigInventoryReader
from inventory.reports import CreateReportCommandHandler, DeliverReportCommandHandler

def lambda_handler(event, context):
    inventory = AwsConfigInventoryReader(lambda_context=context).get_resources_from_all_accounts()

    report_path = CreateReportCommandHandler().execute(inventory)
    report_url = DeliverReportCommandHandler().execute(report_path)

    return {'statusCode': 200,
            'body': {
                    'report': { 'url': report_url }
                }
            }

if __name__ == "__main__":
    class Context(object):
        def __init__(self):
            self.invoked_function_arn = "arn:aws-us-gov:lambda:us-east-1:123456789012:function:testing"

    result = lambda_handler(None, Context())

    print(result)


class Dinosaur:
    X_POS = 80
    JUMP_VEL = 7.25
    score = 0

    def __init__(self, Y_POS, DUCKING, RUNNING, JUMPING):
        self.duck_img = DUCKING
        self.run_img = RUNNING
        self.jump_img = JUMPING

        self.dino_duck = False
        self.dino_run = True
        self.dino_jump = False

        self.step_index = 0
        self.jump_vel = self.JUMP_VEL
        self.image = self.run_img[0]
        self.dino_rect = self.image.get_rect()
        self.dino_rect.x = self.X_POS
        self.dino_rect.y = Y_POS

        self.Y_POS = Y_POS
        self.Y_POS_DUCK = Y_POS+30
        self.DUCKING = DUCKING
        self.RUNNING = RUNNING
        self.JUMPING = JUMPING

    # updates what the dino is doing
    def update(self, userInput):
        if self.dino_duck:
            self.duck()
        if self.dino_run:
            self.run()
        if self.dino_jump:
            self.jump()

        if self.step_index >= 10:
            self.step_index = 0

        if userInput==0 and not self.dino_jump:
            self.dino_duck = False
            self.dino_run = False
            self.dino_jump = True
        elif userInput==1 and not self.dino_jump:
            self.dino_duck = False
            self.dino_run = True
            self.dino_jump = False
        elif userInput==2 and not self.dino_jump:
            self.dino_duck = True
            self.dino_run = False
            self.dino_jump = False

        self.score += 0.25

    def duck(self):
        self.image = self.duck_img[self.step_index // 5]
        self.dino_rect = self.image.get_rect()
        self.dino_rect.x = self.X_POS
        self.dino_rect.y = self.Y_POS_DUCK
        self.step_index += 1

    def run(self):
        self.image = self.run_img[self.step_index // 5]
        self.dino_rect = self.image.get_rect()
        self.dino_rect.x = self.X_POS
        self.dino_rect.y = self.Y_POS
        self.step_index += 1

    def jump(self):
        self.image = self.jump_img
        if self.dino_jump:
            self.dino_rect.y -= self.jump_vel * 4
            self.jump_vel -= 0.8
        if self.jump_vel < - self.JUMP_VEL:
            self.dino_jump = False
            self.jump_vel = self.JUMP_VEL

    def draw(self, SCREEN):
        SCREEN.blit(self.image, (self.dino_rect.x, self.dino_rect.y))

    def getY(self):
        return self.dino_rect.y

    def getV(self):
        return self.jump_vel

    def changeScore(self, num):
        self.score = num

    def getScore(self):
        return self.score


import torch
import torchvision
import torchvision.transforms as transforms

def get_mnist(path: str = './data', batch_size: int = 64):
    transform = transforms.Compose(
        [
            transforms.ToTensor(),
        ]
    )

    trainset = torchvision.datasets.MNIST(root=path, train=True, download=True, transform=transform)
    trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=0)

    testset = torchvision.datasets.MNIST(root=path, train=False, download=True, transform=transform)
    testloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=0)

    return trainset, trainloader, testset, testloader

def get_images_for_class(dataset, num_class):
    return dataset.data[dataset.targets == num_class]

def generate_mean_image(images):
    image_sum = torch.zeros(images[0].size())

    for image in images:
        image_sum += image
    return image_sum / len(images)

def generate_mean_image_for_class(dataset, num_class):
    images = get_images_for_class(dataset, num_class)

    return generate_mean_image(images)

def get_random_image(dataset_loader):
    dataiter = iter(dataset_loader)
    images, labels = dataiter.next()

    image = images[0].expand(1, 1, 28, 28)
    label = labels[0]

    return image, label


from django.conf.urls import include, url
from django.urls import path
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView
from rest_framework import routers
from rest_framework_simplejwt import views as jwt_views

from .resources import ObtainTokenPairView, SubscriptionsViewSet, StripeWebookView

router = routers.DefaultRouter()
router.register(r'subscriptions', SubscriptionsViewSet, basename='subscriptions')

urlpatterns = [
    path('token/obtain/', ObtainTokenPairView.as_view(), name='token_create'),
    path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
    path('stripe-webhook/', StripeWebookView.as_view(), name='stripe-webhook'),
    url(r'', include(router.urls)),
]

urlpatterns += [
    url(r'schema/', SpectacularAPIView.as_view(), name="schema"),
    url(
        r'docs/',
        SpectacularSwaggerView.as_view(
            url_name="schema"
        ),
        name="swagger-ui",
    ),
]


import numpy as np
import re
from scipy.optimize import linear_sum_assignment

def linear_sum():
    cost_matrix = np.array([
        [15, 40, 45],
        [20, 60, 35],
        [20, 40, 25]
    ])

    matches = linear_sum_assignment(cost_matrix)
    print('scipy API result:\n', matches)

"""Outputs
sklearn API result:
 [[0 1]
  [1 0]
  [2 2]]
scipy API result:
 (array([0, 1, 2], dtype=int64), array([1, 0, 2], dtype=int64))
"""

def testlistfor():
    a=[x for x in range(5) if x%2 ==0 ]  # [0, 1, 2, 3, 4]
    return a
def testmtricmax():
    maxnum=20
    a=np.array([[1,2,32],[3,5,6],[34,54,3]])
    a[a>maxnum]=maxnum+2
    return a
def argmin_min():
    lst1 = [1, 100, 56, 78, 0]
    lst2 = [[100, 4, 5], [3, 5, 7], [5, 0, 6]]
    print("lst列表中的最小值是:")
    print(np.min(lst1))
    print("lst1列表中最小值的索引是：")
    print(np.argmin(lst1))
    print("lst2列表中最小值的索引是：")
    print(np.argmin(lst2))
    print("lst2列表中最值，按照轴0方向：")
    print(lst2)
    print(np.min(lst2,axis=0))
def findkuohao():
    string = 'abe(ac)ad)'
    p1 = re.compile(r'[(](.*?)[)]', re.S)  # 最小匹配
    p2 = re.compile(r'[(](.*)[)]', re.S)  # 贪婪匹配
    print(re.findall(p1, string))
    print(re.findall(p2, string))

def main():
    findkuohao()

if __name__ == '__main__':
    main()


from django.shortcuts import render, redirect
from .forms import *

def post_book_view(request):
    user = PublisherProfileModel.objects.get(user=request.user)
    task = "Post New"
    form = PostBookForm()
    if request.method == 'POST':
        form = PostBookForm(request.POST, request.FILES)
        if form.is_valid():
            new_ad = form.save(commit=False)
            new_ad.publisher = user
            form.save()
            return redirect('home')
        else:
            context = {
                'task': task,
                'form': form
            }
            return render(request, 'book_control/post-update-book.html', context)

    context = {
        'task': task,
        'form': form
    }
    return render(request, "publisher/post-update-book.html", context)


from flask import Flask, render_template, redirect, request

app = Flask(__name__)

# Quiz questions
questions = [
    {
        'id': 1,
        'question': 'Who is the leader of the Avengers?',
        'options': ['Iron Man', 'Captain America', 'Thor', 'Black Widow'],
        'answer': 'Captain America'
    },
    {
        'id': 2,
        'question': 'What is the real name of Black Widow?',
        'options': ['Natasha Romanoff', 'Wanda Maximoff', 'Carol Danvers', 'Hope van Dyne'],
        'answer': 'Natasha Romanoff'
    },
    {
        'id': 3,
        'question': 'Which Infinity Stone was embedded in Vision\'s forehead?',
        'options': ['Time Stone', 'Mind Stone', 'Soul Stone', 'Power Stone'],
        'answer': 'Mind Stone'
    }
]

# Global variables
current_question = 0
score = 0

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/start')
def start_quiz():
    global current_question, score
    current_question = 0
    score = 0
    return redirect('/quiz')

@app.route('/quiz', methods=['GET', 'POST'])
def quiz():
    global current_question, score

    if request.method == 'POST':
        answer = request.form.get('answer')

        # Check if the answer is correct
        if answer == questions[current_question]['answer']:
            score += 1

        # Move to the next question
        current_question += 1

        # If all questions are answered, redirect to the result page
        if current_question >= len(questions):
            return redirect('/result')

    # Check if there are more questions available
    if current_question < len(questions):
        question = questions[current_question]
        return render_template('quiz.html', question=question)
    else:
        # If there are no more questions, redirect to the result page
        return redirect('/result')

@app.route('/result')
def result():
    global score
    return render_template('result.html', score=score, total_questions=len(questions))

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


# **************************************************************************************
# hangman.py
#
# Fulltime Programmeren 2
# Robin Laponder
#
# A program that allows someone to play Evil Hangman against the computer.
# **************************************************************************************
from cs50 import get_int
from cs50 import get_string

class Lexicon:
    def __init__(self):
        # Open dictionary file and make a set of all the words in it.
        self.words = set()
        self.dictionary = open("dictionary.txt", "r")
        for line in self.dictionary:
            self.words.add(line.rstrip("\n"))

    def get_words(self, length):
        # Return a list of all words from the dictionary of the given length.
        self.length = length
        self.list = []
        for word in self.words:
            if len(word) == length:
                self.list.append(word.rstrip("\n"))
        if not self.list:
            return False
        return self.list

class Hangman:
    def __init__(self, length, num_guesses):
        # Define exceptions.
        if length < 1:
            raise Exception("Hangman word needs to have positive length. >=(")
        if num_guesses < 1:
            raise Exception("You need at least one guess to play Hangman. >=(")

        # Initialization of Hangman class.
        self.length = length
        self.num_guesses = num_guesses

        # Declaration of variables.
        self.check_won = "not "
        self.guessed = ''
        self.letter = ''
        self.longest_key = ''
        self.pattern_before = []
        for elem in range(length):
            self.pattern_before.append('_')
        self.pattern_after = []
        for elem in range(length):
            self.pattern_after.append('_')
        self.pattern_after = ''.join(self.pattern_after)
        self.words = Lexicon().get_words(self.length)

    def guess(self, letter):
        # Define exceptions.
        if len(letter) > 1:
            raise Exception("You can only guess one letter at a time! >=(")
        if (letter.isalpha()) == False:
            raise Exception("You can only guess letters! >=(")
        if letter in self.guessed:
            raise Exception("You already guessed this letter! >=(")

        # Make a string of letters that are guessed.
        self.letter = letter
        self.guessed += self.letter

        # Make word families by making unique keys and adding wordlists.
        self.dictionary = {}
        for word in self.words:
            key = list(word)
            for char in range(len(key)):
                if key[char] == letter:
                    key[char] = letter
                else:
                    key[char] = '0'
            key = ''.join(key)
            if key in self.dictionary:
                self.dictionary[key].append(word)
            else:
                self.dictionary[key] = []
                self.dictionary[key].append(word)

        # Find the key with the longest wordlist and make a new list with it.
        self.longest_key = max(self.dictionary, key=lambda k: len(self.dictionary[k]))
        self.words = self.dictionary[self.longest_key]

        # Create a pattern of underscores and correctly guessed letters.
        pattern_letter = list(self.longest_key)
        for char in range(len(pattern_letter)):
            if pattern_letter[char] == '0':
                if self.pattern_before[char] == '_':
                    self.pattern_before[char] = '_'
                if self.pattern_before[char] != '_':
                    self.pattern_before[char] = self.pattern_before[char]
            elif pattern_letter[char] == self.letter:
                self.pattern_before[char] = self.letter
            else:
                self.pattern_before[char] = pattern_letter[char]
        self.pattern_after = ''.join(self.pattern_before)

        # Check if the guessed letter is in the secret word.
        joinedwords = ''.join(self.words)
        if self.letter in joinedwords:
            print("It's in the word :(")
            return True
        else:
            print("That's not in the word >=)")
            self.num_guesses -= 1
            return False

    def pattern(self):
        # Return the pattern.
        return self.pattern_after

    def guessed_string(self):
        # Return the string of guessed letters.
        return self.guessed

    def consistent_word(self):
        # Produce a word that matches the current pattern.
        self.secretword = self.words[0]
        return self.secretword

    def finished(self):
        # Return True if the game is won or lost, otherwise False.
        if self.won():
            return True
        if self.lost():
            return True
        return False

    def won(self):
        # Return True if the player has won, otherwise False.
        self.check_won = self.pattern_after
        for char in range(len(self.check_won)):
            if self.check_won[char] == '_':
                self.check_won = "not "
                return False
        self.check_won = ""
        return True

    def lost(self):
        # Return True if the player has lost, otherwise False.
        if self.num_guesses == 0:
            check_lost = list(self.pattern_after)
            for char in range(len(check_lost)):
                if check_lost[char] == '_':
                    return True
        return False

    def __str__(self):
        if statistics == 'y':
            return "letters guessed are '{}', {} words remaining, {} guesses remaining, game {}won".format(self.guessed, len(self.words),
                                                                                self.num_guesses, self.check_won)
        else:
            return "{} guesses remaining".format(self.num_guesses)

if __name__ == "__main__":
    # Start the game
    startgame = 1
    while startgame > 0:
        # Greet the user.
        print("WELCOME TO EVIL HANGMAN >=)")

        # Ask the user to enter the length of the word, a number of guesses and if he/she wants statistics.
        length = get_int("Enter an amount of letters you want in the word: ")
        num_guesses = get_int("Enter the number of guesses you would like: ")
        statistics = get_string("Would you like detailed statistics of this game? Type 'y' of 'n': ")

        # Create a new game with the entered parameters.
        lex = Lexicon()
        game = Hangman(length, num_guesses)

        # Check if there are words with the entered length, if not reprompt.
        while lex.get_words(length) == False:
            length = get_int("Enter an amount of letters you want in the word: ")
            game = Hangman(length, num_guesses)

        # Keep playing the game while it is not finished.
        while game.finished() == False:
            letter = input("Guess a letter: ")
            game.guess(letter)
            print(game.pattern())
            print(game)
            game.finished()
            if game.won():
                print("YOU WON! (ﾉ*ﾟｰﾟ)ﾉ")

        # Check if the game is lost and reveal the secret word.
        if game.lost():
            print("YOU LOST! (~˘▾˘)~")
            print("The secret word is ", end='')
            print(game.consistent_word())

        # Ask the user if he/she wants to start a new game.
        newgame = input("Would you like to play again? Enter 'y' or 'n': ")
        if newgame == 'y':
            startgame += 1
        else:
            startgame = 0


import uuid

from django.contrib.auth import get_user_model

from bothub.common.models import Repository
from bothub.project.models import Project, TemplateType, ProjectIntelligence
from bothub.project.usecases.exceptions import InvalidTemplateTypeData

User = get_user_model()

class TemplateTypeIntegrationUseCase:

    def integrate_template_type_in_project(self, project: Project, template_type_uuid: str, user: User) -> bool:
        if project.template_type is not None:
            raise InvalidTemplateTypeData(f"The project `{project.uuid}` already has an integrated template!")

        if template_type_uuid is None:
            raise InvalidTemplateTypeData("'template_type_uuid' cannot be empty when 'is_template' is True!")

        try:
            template_type = TemplateType.objects.get(uuid=template_type_uuid)
        except TemplateType.DoesNotExist:
            raise InvalidTemplateTypeData(f"Template Type with uuid `{template_type_uuid}` does not exists!")

        for repository_data in template_type.setup["repositories"]:
            repository_uuid = repository_data.get("uuid")

            repository = Repository.objects.get(uuid=repository_uuid)

            organization_authorization = project.organization.get_organization_authorization(user)

            if not organization_authorization.can_contribute:
                raise InvalidTemplateTypeData("The user dont have permission on that organization")

            access_token = str(repository.get_user_authorization(
                    organization_authorization.organization
                ).uuid
            )

            project_intelligence = ProjectIntelligence.objects.create(
                uuid=uuid.uuid4(),
                access_token=access_token,
                integrated_by=user,
                project=project,
                name=repository.name,
                repository=repository,
            )
            print(f"[ TemplateTypeIntegration ] - adding integration to `{project.uuid}` with access token `{project_intelligence.access_token}` and uuid `{project_intelligence.uuid}`")


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

from django import forms
from website.models import *

from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

class AnalyseMgfForm(forms.ModelForm):
    class Meta:
        model = AnalyseMgf
        exclude = ["owner","ignore"]

    def __init__(self, *args, **kwargs):
        super(AnalyseMgfForm, self).__init__(*args, **kwargs)
        self.fields['AAs'].initial = AA.objects.filter(type=2)
        self.fields['modifications'].initial = AAModification.objects.filter(type=2)

    def clean_mgf(self):
        return self.cleaned_data["mgf"]

    def save(self,commit=True,request=None):
        object = super(forms.ModelForm,self).save(commit=False)
        object.owner = request.user
        object.ignore = False

        if commit :
            object.save()
        return object

class CreatUserForm(UserCreationForm):
    #~ _('mail') was in EmailField django 1.5
    email = forms.EmailField(label = _('mail'))

    class Meta:
        model = User
        fields = ("email",)

    def save(self, commit=True):
        user = super(CreatUserForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        user.username= self.cleaned_data["username"]
        if commit:
            user.save()
            pass
        return user

class CreateBlastForm(forms.ModelForm):
    class Meta:
        model = BlastAnalyse
        exclude = ["xml","fasta"]

    def __init__(self,*args,**kwargs):
        user = kwargs.pop('user')
        ana = kwargs.pop('ana')
        super(forms.ModelForm, self).__init__(*args, **kwargs)
        self.fields["analyse"].queryset = AnalyseMgf.objects.filter(owner=user)
        self.fields["analyse"].initial = ana


#from django.shortcuts import render
#from django.http import HttpResponse
from google.cloud import storage
import os
import posixpath
import math
import requests

from PIL import Image

from flask import Flask  , jsonify
from flask import render_template
from flask import current_app

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
Static_Directory_Path = Flask.static_folder

print("PATH :" + BASE_DIR)

def download_blob(bucket_name, background_source_blob_name,  item_source_blob_name):
    """Downloads a blob from the bucket."""

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    bucketFurkan = storage_client.bucket("image-processing-module.appspot.com")

    # Construct a client side representation of a blob.
    # Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve
    # any content from Google Cloud Storage. As we don't need additional data,
    # using `Bucket.blob` is preferred here.
    BG_blob = bucket.blob(background_source_blob_name)
    BG_blob.download_to_filename("/tmp/bg_destination_file_name")

    item_blob = bucketFurkan.blob(item_source_blob_name)
    item_blob.download_to_filename("/tmp/item_destination_file_name")

    #combine_tmp_images(faceAnnotations)

    #print(
    #    "Blob {} downloaded to {}.".format(
    #        background_source_blob_name, bg_destination_file_name
    #    )
    #)

def upload_blob(bucket_name, source_file_name, destination_blob_name):

    """Uploads a file to the bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The path to your file to upload
    # source_file_name = "local/path/to/file"
    # The ID of your GCS object
    # destination_blob_name = "storage-object-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    #blob.upload_from_filename(source_file_name)
    blob.upload_from_filename("/tmp/final_image_directory.jpg")

    print(
        "File {} uploaded to {}.".format(
            source_file_name, destination_blob_name
        )
    )

# create() combines the background image (containing faces) with items (hats, glasses etc.)
def create(disguise_request):

    upload_bucket_name = "image-processing-module.appspot.com"
    bucket_name = disguise_request['bucket_name']
    #background_source_blob_name = "input_images/The_Traitorous_Eight.jpeg"
    background_source_blob_name = disguise_request['image_file_name']
    #item_source_blob_name = "items/glasses0.png"
    item_source_blob_name = disguise_request['faces'][0]['item_file_name']

    #bg_destination_file_name = os.path.join(BASE_DIR, "tmp/static/face_images/background_image.jpg")
    #item_destination_file_name = os.path.join(BASE_DIR, "static/items/item1.png")

    final_image_directory = os.path.join(BASE_DIR, "static/output_images/final.png")
    destination_blob_name = "output_images/final_" + background_source_blob_name + ".jpeg"

    download_blob(bucket_name, background_source_blob_name,  item_source_blob_name)

    combine_tmp_images(disguise_request)

    #combine_images(item_destination_file_name , bg_destination_file_name , final_image_directory)

    upload_blob(upload_bucket_name, final_image_directory, destination_blob_name)

    return upload_bucket_name + "/" + destination_blob_name

    # send the output image url to the manager service
    #url = 'https://www.w3schools.com/python/demopage.php'
    #myobj = {'somekey': 'somevalue'}

    #x = requests.post(url, data = myobj)

    #print(x.text)

    #print(*args)
    #bg_destination_file_name = os.path.join(BASE_DIR, "imageCreator/face_images/downloadedFile.jpg")
    #path = "F:\ImageProcessingModule\ImageProcessingModule\ImageProcessingModule\imageCreator\face_images\downloadedFile.jpg"

    #html = "
IMAGE:
 "

    #return HttpResponse(html)
    #return render_template('index.html')

def combine_images(item_image_path, bg_image_path, final_image_directory):

    bg = Image.open(bg_image_path)
    item = Image.open(item_image_path)
    new_item_size = (370, 125)
    item = item.resize(new_item_size).rotate(20, expand = True)
    back_im = bg.copy()
    back_im.paste(item, (260,340) , item)
    back_im.save(final_image_directory, quality=95)

    #return null
def vector_length(v):
    return math.sqrt(v[0]*v[0] + v[1]*v[1])

def combine_tmp_images(diguise_request):

    bg = Image.open("/tmp/bg_destination_file_name")
    item = Image.open("/tmp/item_destination_file_name")

    back_im = bg.copy()

    lefteye = diguise_request['faces'][0]['detection']['lefteye']
    midpoint = diguise_request['faces'][0]['detection']['midpoint']
    rigtheye = diguise_request['faces'][0]['detection']['righteye']

    #for face in faceAnnotations:

    """lefteye = faceAnnotations[face]['lefteye']

    midpoint = faceAnnotations[face]['midpoint']
    rigtheye = faceAnnotations[face]['rigtheye']"""

    item_rotation = (rigtheye['y'] - lefteye['y'] ) / (rigtheye['x'] - lefteye['x'] )
    item_rotation = -math.degrees(math.atan(item_rotation))
    eyes_vector =  (rigtheye['x'] - lefteye['x'] , rigtheye['y'] - lefteye['y'] )  # the 2d vector from left eye to right eye

    print("eyes_vector: ")
    print(eyes_vector)

    print("item.size: ")
    print(item.size)

    coef = vector_length(eyes_vector) / vector_length(item.size)
    coef *= 2 # this constant is determined experimentally
    print("coef: ")
    print(coef)

    new_item_size = (int(item.size[0] * coef) , int(item.size[1] * coef)  )

    print("new_item_size: ")
    print(new_item_size)
    #item_rotation = 20

    #faceAnnotations.x = 260
    #faceAnnotations.y = 340
    #faceAnnotations = jsonify(faceAnnotations)

    item = item.resize(new_item_size).rotate(int(item_rotation), expand = True)

    x_coordinate = int(midpoint['x'] - item.size[0] / 2)
    y_coordinate = int(midpoint['y'] - item.size[1] / 2)

    back_im.paste(item, (x_coordinate, y_coordinate) , item)

    #back_im.show()
    back_im.save("/tmp/final_image_directory.jpg", quality=95)


from utils                  import *
from circlepackingbao       import *
from circlepackingbaoswitch import *
from baopattern             import *

#
# Extension of BaoPattern for layer, to have a hook for drawing layers altogether
#
class BaoPatternLayer(BaoPattern):
    def __init__(self):
        self.mradiuspattern      = [1.0]
        self.mcolorpattern       = [Color.black()]
        self.mindex              = 0
        self.mindexlayer         = 0
        self.mfdraw              = None
        self.mfdrawlayer         = None
        self.mradiuspatternlayer = None
        self.mcolorpatternlayer  = None

    def nextlayer(self):
        self.mindexlayer += 1
        return self

    def radiuspatternlayer(self,radiuspattern):
        self.mradiuspatternlayer = radiuspattern
        return self

    def colorpatternlayer(self,colorpattern):
        self.mcolorpatternlayer = colorpattern
        return self

    def radius(self):
        if self.mradiuspatternlayer == None:
            return  super(BaoPatternLayer,self).radius()
        else:
            return lcircular(self.mradiuspatternlayer,self.mindexlayer)

    def colorlayer(self,index=None):
        if index == None:
            index = self.mindexlayer
        return lcircular(self.mcolorpatternlayer,index)

    def fdrawlayer(self, v = None):
        if v == None:
            return self.mfdrawlayer
        else:
            self.mfdrawlayer = v
            return self

    def draw(self,newnode,index):
        if not self.fdraw() == None:
            self.fdraw()(newnode,index,self.color(index))

    def drawlayer(self,nodes,ilayer):
        if not self.fdrawlayer() == None:
            self.fdrawlayer()(nodes,ilayer,self.colorlayer(ilayer))

#
# TODO: create layerstack to take care of layers
#
class BaoStackLayer(BaoStack):

    def __init__(self,nodes):
        super(BaoStackLayer,self).__init__(nodes)
        self.mlayers = []
        self.mclayer = nodes[:]

    def stacklayer(self):
        self.mlayers.append(self.mclayer)
        self.mclayer = []

    def lastlayer(self):
        return self.mlayers[-1]

    def layers(self):
        return self.mlayers

    def nlayers(self):
        return len(self.mlayers)

    def stack(self,newnode,othernode):
        self.mclayer.append(newnode)
        return super(BaoStackLayer,self).stack(newnode,othernode)

    def currentLayerEmpty(self):
        return (len(self.mclayer) == 0)

#
# PackingBao with direction changed when colliding, defining layers of nodes
#
class CirclePackingBaoLayer(CirclePackingBao):

    def __init__(self,boundaries=None,nodes=None,baopattern_=None,side0=None,quadtree=None):
        self.mstack       = BaoStackLayer(nodes)
        self.mlastindex   = self.mstack.lastindex()
        self.mcside       = side0
        self.mbaopattern  = baopattern_
        self.mquadtree    = iff(quadtree == None, QuadTree(), quadtree)
        self.mquadtree.adds( boundaries + nodes )
        for node in nodes:
            node.packing(self)
        self.miterperlayer = 0

    def niterperlayer(self):
        return self.miterperlayer

    def computenextnode(self,quadtree,node2,node1,newr,index,side):
        result = (None,False)
        newcircle = circles2tangentout(node2,node1,newr,side)
        if not newcircle == None:
            collidings  = lsubstract(quadtree.colliding(newcircle),[node1,node2])
            # puts("newcircle",newcircle.coords(),"collidings",[(c,c.coords()) for c in collidings])
            if len(collidings) == 0:
                newbaonode = BaoNode(self,newcircle,node2.colorindex() + 1,index + 1)
                return (newbaonode,False)
            else:
                endlayer = False
                for colliding in collidings:
                    if not isinstance(colliding,BaoNode) or not colliding.packing() == self:
                        endlayer = True
                        break
                result = (None,endlayer)
        return result

    def iter(self,niter=1):

        for iiter in range(niter):
            self.miterperlayer += 1

            ifputs(iiter != 0 and iiter % 1000 == 0,"niter",iiter)

            # get current paramaters
            (lastnode,othernode) = self.mstack.lastseed()
            newr                 = self.mbaopattern.next().radius()
            # puts("current paramaters",lastnode,othernode)

            # compute new node if possible
            newbaonode = None

            foreigncollision = False
            for othernode in CirclePackingBao.genothernodes(othernode,self.mquadtree,lastnode,self.mstack,newr):
                (newbaonode,foreigncollision) = self.computenextnode(self.mquadtree,lastnode,othernode,newr,self.mstack.newindex(),self.mcside)
                # puts("genothernodes",lastnode,othernode,"newbaonode,foreigncollision",newbaonode,foreigncollision,"cside",cside)
                if not newbaonode == None:
                    break
                else:
                    if foreigncollision:
                        break

            if foreigncollision and not self.mstack.currentLayerEmpty():
                # puts("foreigncollision")
                self.mstack.stacklayer()
                self.mbaopattern.drawlayer(self.mstack.lastlayer(),self.mstack.nlayers())
                self.mbaopattern.nextlayer()
                self.miterperlayer = 0
                self.mstack.switch()
                (lastnode,othernode) = self.mstack.lastseed()
                self.mcside = -self.mcside
                # TODO: find a way to factorize the two genothernodes calls
                for othernode in CirclePackingBao.genothernodes(othernode,self.mquadtree,lastnode,self.mstack,newr):
                    # puts("genothernodes after foreigncollision",lastnode,othernode,"cside",cside)
                    (newbaonode,foreigncollision) = self.computenextnode(self.mquadtree,lastnode,othernode,newr,self.mstack.newindex(),self.mcside)
                    # puts("genothernodes after foreigncollision",lastnode,othernode,"newbaonode,foreigncollision",newbaonode,foreigncollision)
                    if not newbaonode == None:
                        break

            # update according to result
            if newbaonode == None:
                lastnode.notfound(True)
                self.mlastindex = self.mstack.rewindtofreenode(self.mlastindex)
                # puts("no new node found, new lastindex",lastindex)
            else:
                # puts("found newbao node",newbaonode)
                othernode.retouch(True)
                self.mquadtree.add(newbaonode)
                self.mbaopattern.draw(newbaonode,newbaonode.colorindex())
                self.mlastindex = self.mstack.stack(newbaonode,othernode)

            if self.mlastindex < 1:
                break

        return self


# coding=utf-8
import scrapy
import re
import os
import urllib
import pymysql
import sys
from scrapy.selector import Selector
from scrapy.http import HtmlResponse, Request
from webCrawler_scrapy.items import  XrldSpiderItem

class XrldSpider(scrapy.spiders.Spider):
    name = 'xrld'
    allowed_domains = ["bnu.edu.cn"]
    start_urls = ["http://www.bnu.edu.cn/xxgk/xrld/index.htm" ]

    def parse(self, response):
        se = Selector(response)  # 创建查询对象，HtmlXPathSelector已过时
        src_a = response.xpath("//div[@class='leader_row']" )
        print("----------------------------")
        print(len(src_a))
        for i in range(len(src_a)):  # 遍历li个数
            ii = i+1
            src_list1 = response.xpath("//div[@class='leader_row'][%d]/ul/li"% ii)
            for m in range(len(src_list1)):
                mm = m+1
                item = XrldSpiderItem()
                item['zwmc'] = se.xpath("//div[@class='leader_row'][%d]/h4/text()" % ii).extract()
                item['name'] = se.xpath("//div[@class='leader_row'][%d]/ul/li[%d]/a/p/text()" % (ii,mm)).extract()
                yield item

        src_b = response.xpath("//div[@class='leader_row last-noborder']")
        print(len(src_b))
        for j in range(len(src_b)):  # 遍历li个数
            jj = j+1
            src_list2 = response.xpath("//div[@class='leader_row last-noborder'][%d]/ul/li"% jj)
            for n in range(len(src_list2)):
                nn = n+1
                item = XrldSpiderItem()
                item['zwmc'] = se.xpath("//div[@class='leader_row last-noborder'][%d]/h4/text()" % jj).extract()
                item['name'] = se.xpath("//div[@class='leader_row last-noborder'][%d]/ul/li[%d]/a/p/text()" % (jj,nn)).extract()
                yield item


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 13:07:46 2018

@author: r38411
"""
def fun1():
    s = "abcdefgh"
    startInd = 0
    #endInd = 0
    total = 1
    #result = s[0]
    curTotal = 1
    for i in range(1,len(s)):
        if s[i-1] <= s[i]:
            #endInd = i
            curTotal = curTotal + 1
        else:
            if (curTotal > total):
                total = curTotal
                result = s[startInd:i]
            curTotal = 1
            startInd = i
            endInd = i
    if (curTotal == len(s)):
        result = s
    print("Longest substring in alphabetical order is: " + result)

    while (True):
        x = int(input("Please think of a number between 0 and 100!"))
        low = 0
        high = 100
        ans = (low + high)/2

    def is_even(i):
        """
        Input: i, a positive int
         Returns True if i is even, otherwise False
        """
        return(i%2==0)

def isIn(char, aStr):
    # test the middle char
    if (char == aStr[len(aStr)//2]):
        return True
    elif (len(aStr) == 1):
        return False
    elif (not aStr):
        return False
    elif (char < aStr[len(aStr)//2]):
        return isIn(char, aStr[:len(aStr)//2])
    else:
        return isIn(char, aStr[len(aStr)//2 +1:])

#theChar = 'm'
#theStr = 'abcdlmno'
#_4result = isIn(theChar, theStr)

def debtPayOff1(balance, annualInterestRate):
    monthlyInterestRate = annualInterestRate/12.0
    minMonthlyPay = 0
    nextBal = balance
    while (nextBal > 0):
        minMonthlyPay += 10
        curBal = balance
        nextBal = balance
        numMonth = 0
        #print("monthly payment : " + str(minMonthlyPay))
        while (numMonth <= 11):
            curBal = nextBal
            unpaidMonthlyBal = curBal - minMonthlyPay
            nextBal = unpaidMonthlyBal + (monthlyInterestRate * unpaidMonthlyBal)
            numMonth += 1
        #print("by end of Month 12, remaining balance: " + str(round(nextBal,2)))
    print("Lowest Payment: " + str(minMonthlyPay))

def debtPayOff2(balance, annualInterestRate):
    monthlyInterestRate = annualInterestRate/12.0
    lower = balance/12
    upper = (balance * (1+monthlyInterestRate)**12)/12.0
    nextBal = balance
    spare = 0.0
    while (nextBal > 0):
        minMonthlyPay = (lower + upper)/2
        curBal = balance
        nextBal = balance
        numMonth = 0
        #print("monthly payment : " + str(minMonthlyPay))
        while (numMonth <= 11) and (nextBal > 0):
            curBal = nextBal
            unpaidMonthlyBal = curBal - minMonthlyPay
            nextBal = unpaidMonthlyBal + (monthlyInterestRate * unpaidMonthlyBal)
            numMonth += 1
        #print("by end of Month 12, remaining balance: " + str(round(nextBal,2)))
        if (numMonth >= 12) and (nextBal >0):
            lower = minMonthlyPay
        elif (numMonth <=11) and (nextBal < 0):
            upper = minMonthlyPay
        elif (numMonth == 12) and (nextBal < -0.05):
            upper = minMonthlyPay
        else:
            break
        nextBal = balance
    print("Lowest Payment: " + str(round(minMonthlyPay,2)))
    #return minMonthlyPay

balance = 999999
annualInterestRate = 0.18
debtPayOff2(balance, annualInterestRate)


class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.isEmpty():
            return self.items.pop()

    def isEmpty(self):
        return len(self.items) == 0

    def size(self):
        return len(self.items)

def check_parentheses(expression):
    stack = Stack()
    opening_parentheses = ['(', '[', '{']
    closing_parentheses = [')', ']', '}']
    pairs = {
        ')': '(',
        ']': '[',
        '}': '{'
    }
    for char in expression:
        if char in opening_parentheses:
            stack.push(char)
        elif char in closing_parentheses:
            if stack.isEmpty():
                return f"{expression} close paren excess"
            elif stack.pop() != pairs[char]:
                return f"{expression} Unmatch open-close"
    if not stack.isEmpty():
        if stack.size() == 1:
            return f"{expression} open paren excess   1 : {stack.items[0]}"
        else:
            return f"{expression} open paren excess   {stack.size()} : {''.join(stack.items)}"
    return f"{expression} MATCH"

print(check_parentheses(input("Enter expresion : ")))