import time
import argparse
import json
import tqdm
import torch
import numpy as np
import torch.nn.functional as F
from sklearn.metrics import roc_auc_score, f1_score
from model.model import Model
from model.data import get_data_frames, create_graph, create_hetero_graph, create_data_loaders

def train(model, optimizer, criterion, data_loader, device, run, epochs, eval_steps):
    train_loss, valid_scores, test_scores = [], [], []
    start_time = time.time()
    for epoch in range(1, epochs + 1):
        model.train()
        total_loss = total_examples = 0
        for batch_data in tqdm.tqdm(data_loader['train'], disable=True):
            optimizer.zero_grad()
            batch_data = batch_data.to(device)

            pred = model(batch_data)
            ground_truth = batch_data['user', 'item'].edge_label

            loss = criterion(pred, ground_truth)
            loss.backward()
            optimizer.step()
            total_loss += float(loss) * pred.numel()
            total_examples += pred.numel()

        epoch_loss = total_loss / total_examples
        train_loss.append(epoch_loss)

        if epoch % eval_steps == 0:
            print(f"\nEpoch: {epoch:03d}, Train Loss: {epoch_loss:.4f}")

            val_auc_score, val_f1_score = test(model, data_loader['val'], device)
            test_auc_score, test_f1_score = test(model, data_loader['test'], device)

            valid_scores.append((val_auc_score, val_f1_score))
            test_scores.append((test_auc_score, test_f1_score))

            spent_time = time.time() - start_time
            eval_results = (f'Run: {run + 1:02d}, '
                            f'Epoch: {epoch:02d}, '
                            f'Train Loss: {epoch_loss:.4f}, '
                            f'Valid AUC: {100 * val_auc_score:.2f}%, '
                            f'Valid F1: {100 * val_f1_score:.2f}%, '
                            f'Test AUC: {100 * test_auc_score:.2f}%, '
                            f'Test F1: {100 * test_f1_score:.2f}%')
            print(eval_results)
            print(f'---\nTraining Time Per Epoch: {spent_time / eval_steps: .4f} s\n---')
            start_time = time.time()

    return train_loss, valid_scores, test_scores

def test(model, data_loader, device):
    model.eval()
    predictions, ground_truths = [], []
    for batch_data in tqdm.tqdm(data_loader, disable=True):
        with torch.no_grad():
            batch_data = batch_data.to(device)
            predictions.append(model(batch_data))
            ground_truths.append(batch_data['user', 'item'].edge_label)

    predictions = torch.cat(predictions, dim=0).cpu().numpy()
    ground_truths = torch.cat(ground_truths, dim=0).cpu().numpy()

    out_sigmoid = torch.Tensor(predictions).sigmoid().cpu().numpy()
    out_probabilities = np.rint(out_sigmoid)

    auc_sc = roc_auc_score(ground_truths, out_sigmoid)
    f1_sc = f1_score(ground_truths, out_probabilities)

    return auc_sc, f1_sc

def main():
    parser = argparse.ArgumentParser(description='News Recommender GNN Model')
    parser.add_argument("--data", default="cit_pt", choices=["adressa_no","adressa_tr",
                                                             "cit_pt","cit_tr","cit_en",
                                                             "cit_pten","cit_tren",
                                                             "mind"],
                        help = "default: %(default)s")
    parser.add_argument('--plm', default="ptbert", choices=["mbert","enbert","nbbert",
                                                               "ptbert","xlm","gpt2"],
                        help = "plm model for item nodes, default: %(default)s")
    parser.add_argument('--use_seperate_test_data', action='store_true')
    parser.add_argument('--num_user_features', type=int, default=32,
                        help = "-1 for don't use user_features, default: %(default)i")
    parser.add_argument('--num_item_features', type=int, default=768,
                        help = "-1 for don't use item_features, default: %(default)i")
    parser.add_argument('--user_input_layer', default="lin", choices=["emb","lin"],
                        help = "input layer for user nodes, default: %(default)s")
    parser.add_argument('--item_input_layer', default="lin", choices=["emb","lin","emb+lin"],
                        help = "input layer for item nodes, default: %(default)s")
    parser.add_argument('--input_hidden_channels', type=int, default=64,
                        help = "default: %(default)i")
    parser.add_argument('--encoder', default="SAGE", choices=["SAGE","GAT","GCN"],
                        help = "default: %(default)s")
    parser.add_argument('--predictor', default="DOT", choices=["MLP","MLPDOT","DOT"],
                        help = "default: %(default)s")
    parser.add_argument('--encoder_layers', type=int, default=2,
                        help = "default: %(default)i")
    parser.add_argument('--predictor_layers', type=int, default=0,
                        help = "0 for DOT predictor, default: %(default)i")
    parser.add_argument('--encoder_hidden_channels', type=int, default=64,
                        help = "default: %(default)i")
    parser.add_argument('--predictor_hidden_channels', type=int, default=32,
                        help = "default: %(default)i")

    parser.add_argument('--dropout', type=float, default=0.0,
                        help = "default: %(default)f")
    parser.add_argument('--batch_size', type=int, default=1024,
                        help = "default: %(default)i")
    parser.add_argument('--lr', type=float, default=0.001,
                        help = "default: %(default)f")
    parser.add_argument('--epochs', type=int, default=-1,
                        help = "-1 to use model default value, default: %(default)i")
    parser.add_argument('--eval_steps', type=int, default=1,
                        help = "number of epochs at which logs printed, default: %(default)i")
    parser.add_argument('--device', type=int, default=0,
                        help = "default: %(default)i")
    parser.add_argument('--runs', type=int, default=1,
                        help = "default: %(default)i")
    args = parser.parse_args()
    print(str(args))

    # device setup
    device = f'cuda:{args.device}' if torch.cuda.is_available() else 'cpu'
    device = torch.device(device)
    print(f"Device: {device}")

    # get data
    with open('datasets/info.json', 'r') as f:
        datasets_info = json.load(f)

    users_csv = datasets_info[args.data]['users_csv']
    items_csv = datasets_info[args.data]['items_csv']
    user_naming = datasets_info[args.data]['user_naming']
    item_naming = datasets_info[args.data]['item_naming']
    feats_file = datasets_info[args.data]['plm'][args.plm]
    epochs = datasets_info[args.data]['epochs'] if args.epochs == -1 else args.epochs

    print(f'Loading user and item data frames for: {args.data}')
    df_users, df_items = get_data_frames(users_csv, items_csv, user_naming, item_naming)
    item_feature_tensor = torch.load(feats_file, map_location=device)
    user_features_init = '' if args.num_user_features == -1 else 'zero'

    disjoint_train_ratio = 0.3
    neg_sampling_ratio = 1.0
    num_neighbors = [10, 5]

    if args.use_seperate_test_data:
        print(f'Doing seperate user train and test data for {args.data}')
        users_train_csv = datasets_info[args.data]['users_train_csv']
        users_test_csv = datasets_info[args.data]['users_test_csv']

        print(f'Train:')
        df_users_train, _ = get_data_frames(users_train_csv, items_csv, user_naming, item_naming)
        train_edges_coo = create_graph(df_users_train, df_items, user_naming, item_naming)
        train_data = create_hetero_graph(edges_coo=train_edges_coo,
                                                user_features_init=user_features_init,
                                                user_feature_size=args.num_user_features,
                                                item_feature_tensor=item_feature_tensor)

        print(f'Test:')
        df_users_test, _ = get_data_frames(users_test_csv, items_csv, user_naming, item_naming)
        test_edges_coo = create_graph(df_users_test, df_items, user_naming, item_naming)
        test_data = create_hetero_graph(edges_coo=test_edges_coo,
                                        user_features_init=user_features_init,
                                        user_feature_size=args.num_user_features,
                                        item_feature_tensor=item_feature_tensor)

        val_ratio, test_ratio = 0.1, 0.1
        train_loader, val_loader, _ = create_data_loaders(data=train_data, val_ratio=val_ratio, test_ratio=test_ratio,
                                                                    disjoint_train_ratio=disjoint_train_ratio,
                                                                    num_neighbors=num_neighbors,
                                                                    neg_sampling_ratio=neg_sampling_ratio,
                                                                    batch_size=args.batch_size, shuffle=True)
        val_ratio, test_ratio = 0.0, 0.9
        _, _, test_loader = create_data_loaders(data=test_data, val_ratio=val_ratio, test_ratio=test_ratio,
                                                                    disjoint_train_ratio=disjoint_train_ratio,
                                                                    num_neighbors=num_neighbors,
                                                                    neg_sampling_ratio=neg_sampling_ratio,
                                                                    batch_size=args.batch_size, shuffle=True)
        data = train_data
    else:
        val_ratio, test_ratio = 0.1, 0.1
        edges_coo = create_graph(df_users, df_items, user_naming, item_naming)
        data = create_hetero_graph(edges_coo=edges_coo,
                                   user_features_init=user_features_init,
                                   user_feature_size=args.num_user_features,
                                   item_feature_tensor=item_feature_tensor)
        train_loader, val_loader, test_loader = create_data_loaders(data=data, val_ratio=val_ratio, test_ratio=test_ratio,
                                                                    disjoint_train_ratio=disjoint_train_ratio,
                                                                    num_neighbors=num_neighbors,
                                                                    neg_sampling_ratio=neg_sampling_ratio,
                                                                    batch_size=args.batch_size, shuffle=True)

    data_loader = {
        'train': train_loader,
        'val':   val_loader,
        'test':  test_loader
    }

    # TODO Pre-compute GCN normalization
    # if args.gnn_model == 'GCN': data.adj_t = gcn_normalization(data.adj_t)

    # data contains the whole graph
    num_user_nodes = data["user"].num_nodes if 'emb' in args.user_input_layer else -1
    num_item_nodes = data["item"].num_nodes if 'emb' in args.item_input_layer else -1
    graph_metadata = data.metadata()

    model = Model(
        graph_metadata=graph_metadata,
        num_user_feats=args.num_user_features,
        num_item_feats=args.num_item_features,
        num_user_nodes=num_user_nodes,
        num_item_nodes=num_item_nodes,
        user_input_layer=args.user_input_layer,
        item_input_layer=args.item_input_layer,
        input_hidden_channels=args.input_hidden_channels,
        encoder=args.encoder,
        predictor=args.predictor,
        num_encoder_layers=args.encoder_layers,
        num_predictor_layers=args.predictor_layers,
        encoder_hidden_channels=args.encoder_hidden_channels,
        predictor_hidden_channels=args.predictor_hidden_channels,
        dropout=args.dropout
    )
    model = model.to(device)
    print(model)

    for run in range(args.runs):
        # model.reset_parameters()
        optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)
        criterion = F.binary_cross_entropy_with_logits
        train_loss, valid_scores, test_scores = train(model, optimizer, criterion,
                                                      data_loader, device, run,
                                                      epochs, args.eval_steps)

    total_params = sum(p.numel() for param in model.parameters() for p in param)
    print(f'Total number of model parameters is {total_params}')

if __name__ == "__main__":
    main()


import pandas as pd
import tqdm
import numpy as np
import codecs
import glob
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score, f1_score
from sklearn.linear_model import LogisticRegression
import random
import matplotlib.pyplot as plt
import sys
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle

random.seed(16)
np.random.seed(16)

print("Without l1!")

liar_train = codecs.open("data/liar_xtrain.txt", 'r', 'utf-8').read().split('\n')
liar_train = [s.lower() for s in liar_train if len(s) > 1]
liar_train_labels = codecs.open('data/liar_ytrain.txt', 'r', 'utf-8').read().split('\n')
liar_train_lab = [s for s in liar_train_labels if len(s) > 1]

liar_dev = codecs.open("data/liar_xval.txt", 'r', 'utf-8').read().split('\n')
liar_dev = [s.lower() for s in liar_dev if len(s) > 1]
liar_dev_labels = codecs.open("data/liar_yval.txt", 'r', 'utf-8').read().split('\n')
liar_dev_lab = [s for s in liar_dev_labels if len(s) > 1]

liar_test = codecs.open("data/liar_xtest.txt", 'r', 'utf-8').read().split('\n')
liar_test = [s.lower() for s in liar_test if len(s) > 1]
liar_test_labels = codecs.open("data/liar_ytest.txt", 'r', 'utf-8').read().split('\n')
liar_test_lab = [s for s in liar_test_labels if len(s) > 1]

assert len(liar_train) == len(liar_train_lab)
assert len(liar_dev) == len(liar_dev_lab)
assert len(liar_test) == len(liar_test_lab)

le = preprocessing.LabelEncoder()
#classes = ['pants-fire','false','barely-true','half-true','mostly-true','true']
#le.fit_transform(classes)
liar_train_lab = le.fit_transform(liar_train_lab)
liar_dev_lab = le.transform(liar_dev_lab)
liar_test_lab = le.transform(liar_test_lab)

print(le.classes_) #['barely-true' 'false' 'half-true' 'mostly-true' 'pants-fire' 'true']
print(le.transform(le.classes_)) # [0 1 2 3 4 5]
# untrue classes (to be encoded as 0): 4, 1, 0
# true classes (to be encoded as 1): 2, 3, 5

def binarize_label(labels):
    labels_transformed = [1 if i in [2,3,5] else 0 for i in labels]
    return labels_transformed

def label_switch(labels):
    labels_transformed = [1 if i==0 else 0 for i in labels]
    return labels_transformed

liar_train_lab = binarize_label(liar_train_lab)
liar_dev_lab = binarize_label(liar_dev_lab)
liar_test_lab = binarize_label(liar_test_lab)

# Kaggle data
data = codecs.open("data/kaggle_trainset.txt", 'r', 'utf-8').read().split('\n')
data = data[:20800]
data = [s.lower() for s in data]

labels = codecs.open("data/kaggle_train_labels.txt", 'r', 'utf-8').read().split('\n')
labels = labels[:20800]
labels = [int(i) for i in labels]

tr, te, trlab, telab = train_test_split(data, labels, test_size=0.33, random_state=42)

kaggle_train = tr
kaggle_train_lab = label_switch(trlab)
kaggle_test = te
kaggle_test_lab = label_switch(telab)

# FakeNewsCorpus data (part of it, 25000 samples in each class)
FNC_fake = codecs.open("data/fake_part1.txt", 'r', 'utf-8').read().split('\n')
FNC_fake = FNC_fake[:25000]
FNC_true = codecs.open("data/true_part1.txt", 'r', 'utf-8').read().split('\n')
FNC_true = FNC_fake[:25000]
FNC_fake_labels = np.zeros(len(FNC_fake))
FNC_true_labels = np.ones(len(FNC_true))
FNC_samples = np.concatenate((FNC_fake, FNC_true))
FNC_labels = np.concatenate((FNC_fake_labels, FNC_true_labels))
assert len(FNC_samples) == len(FNC_labels)
FNC_samples, FNC_labels = shuffle(FNC_samples, FNC_labels, random_state=42)

FNC_Xtrain, FNC_Xtest, FNC_ytrain, FNC_ytest = train_test_split(FNC_samples, FNC_labels, test_size=0.33, random_state=42)

# FakeNewsNet Politifact data
# real = codecs.open("data/RealNewsContent.txt", 'r', 'utf-8').read().split('\n')
# real = [s.lower() for s in real if len(s) > 1]
# fake = codecs.open("data/FakeNewsContent.txt", 'r', 'utf-8').read().split('\n')
# fake = [s.lower() for s in fake if len(s) > 1]
# real_labels = np.ones(len(real))
# fake_labels = np.zeros(len(fake))
# FNN_labels = np.concatenate((real_labels, fake_labels))
# FNN_texts = np.concatenate((real, fake))
# assert len(FNN_labels) == len(FNN_texts)
# FNN_X, FNN_y = shuffle(FNN_texts,FNN_labels, random_state=42)

m= 5000 #number of feats 5000 or 10000
k=5#max ngram
v=1 #min mgram

# Vectorizing
print("Vectorizing...")
liar_vectorizer = TfidfVectorizer(ngram_range=(v,k), max_features=m)
X_train_liar = liar_vectorizer.fit_transform(liar_train)
X_test_liar = liar_vectorizer.transform(liar_test)
X_dev_liar = liar_vectorizer.transform(liar_dev)
liar_feats = ['_'.join(s.split()) for s in liar_vectorizer.get_feature_names()]

kaggle_vectorizer = TfidfVectorizer(ngram_range=(v,k), max_features=m)
X_train_kaggle = kaggle_vectorizer.fit_transform(kaggle_train)
X_test_kaggle = kaggle_vectorizer.transform(kaggle_test)
kaggle_feats = ['_'.join(s.split()) for s in kaggle_vectorizer.get_feature_names()]

FNC_vectorizer = TfidfVectorizer(ngram_range=(v,k), max_features=m)
FNC_Xtrain_vect = FNC_vectorizer.fit_transform(FNC_Xtrain)
FNC_Xtest_vect = FNC_vectorizer.transform(FNC_Xtest)
FNC_feats = ['_'.join(s.split()) for s in FNC_vectorizer.get_feature_names()]

print("Vectorizing done")
print("Fitting classifiers...")
# Classifiers
clf_liar=None
clf_liar = LogisticRegression(random_state=16, solver='saga',C=np.inf, max_iter=10000).fit(X_train_liar,liar_train_lab)
liar_coefs = clf_liar.coef_
allcoefs_liar = pd.DataFrame.from_records(liar_coefs, columns=liar_feats) #add ngrams as colnames
allcoefs_liar.to_csv('NEW_liar_coefs_final.csv', sep='\t', index=False)

clf_kaggle=None
clf_kaggle = LogisticRegression(random_state=16, solver='saga',C=np.inf, max_iter=10000).fit(X_train_kaggle,kaggle_train_lab)
kaggle_coefs = clf_kaggle.coef_
allcoefs_kaggle = pd.DataFrame.from_records(kaggle_coefs, columns=kaggle_feats) #add ngrams as colnames
allcoefs_kaggle.to_csv('NEW_kaggle_coefs_final.csv', sep='\t', index=False)

clf_FNC=None
clf_FNC = LogisticRegression(random_state=16, solver='saga',C=np.inf, max_iter=10000).fit(FNC_Xtrain_vect, FNC_ytrain)
FNC_coefs = clf_FNC.coef_
allcoefs_FNC = pd.DataFrame.from_records(FNC_coefs, columns=FNC_feats)
allcoefs_FNC.to_csv("NEW_FakeNewsCorpus_coefs.csv", sep="\t", index=False)

# get coefs from FakeNewsNet while your at it
# FNN_vectorizer = TfidfVectorizer(ngram_range=(v,k), max_features=m)
# FNN_vect = FNN_vectorizer.fit_transform(FNN_X)
# FNN_feats = ['_'.join(s.split()) for s in FNN_vectorizer.get_feature_names()]
# clf_FNN=None
# clf_FNN = LogisticRegression(random_state=16, solver='saga', penalty='l1', max_iter=10000).fit(FNN_vect,FNN_y)
# FNN_coefs = clf_FNN.coef_
# all_coefs_FNN = pd.DataFrame.from_records(FNN_coefs, columns=FNN_feats)
# all_coefs_FNN.to_csv('FakeNewsNet_coefs_final.csv', sep='\t', index=False)

print("Predicting...")
# Predicting
preds_liar_test = clf_liar.predict(X_test_liar)
preds_liar_valid = clf_liar.predict(X_dev_liar)
preds_liar_train = clf_liar.predict(X_train_liar)
#
preds_kaggle_test = clf_kaggle.predict(X_test_kaggle)
preds_kaggle_tain = clf_kaggle.predict(X_train_kaggle)

preds_FNC_test = clf_FNC.predict(FNC_Xtest_vect)
preds_FNC_train = clf_FNC.predict(FNC_Xtrain_vect)

# cross-dataset predictions
kaggle_test_vectorized_by_liar = liar_vectorizer.transform(kaggle_test)
kaggle_test_predicted_by_liar_classifier = clf_liar.predict(kaggle_test_vectorized_by_liar)
#
kaggle_train_vectorized_by_liar = liar_vectorizer.transform(kaggle_train)
kaggle_train_predicted_by_liar = clf_liar.predict(kaggle_train_vectorized_by_liar)

FNC_test_vectorized_by_liar = liar_vectorizer.transform(FNC_Xtest)
FNC_test_predicted_by_liar = clf_liar.predict(FNC_test_vectorized_by_liar)

FNC_test_vectorized_by_kaggle = kaggle_vectorizer.transform(FNC_Xtest)
FNC_test_predicted_by_kaggle = clf_kaggle.predict(FNC_test_vectorized_by_kaggle)

kaggle_test_vectorized_by_FNC = FNC_vectorizer.transform(kaggle_test)
kaggle_test_predicted_by_FNC = clf_FNC.predict(kaggle_test_vectorized_by_FNC)

liar_test_vectorized_by_FNC = FNC_vectorizer.transform(liar_test)
liar_test_predicted_by_FNC = clf_FNC.predict(liar_test_vectorized_by_FNC)

# using other models to predict on FakeNewsNet
# FNN_vectorized_by_liar = liar_vectorizer.transform(FNN_X)
# FNN_predicted_by_liar = clf_liar.predict(FNN_vectorized_by_liar)
#
# FNN_vectorized_by_kaggle = kaggle_vectorizer.transform(FNN_X)
# FNN_predicted_by_kaggle = clf_kaggle.predict(FNN_vectorized_by_kaggle)

def print_scores(y, y_hat, string):
    print(string)
    print("binary F1", f1_score(y, y_hat))
    print("micro f1:",f1_score(y, y_hat, average='micro'))
    print("macro f1:", f1_score(y, y_hat, average='macro'))
    print("weighted F1", f1_score(y, y_hat, average='weighted'))
    print("accuracy", accuracy_score(y, y_hat))
    print()

print_scores(liar_test_lab, preds_liar_test, "Liar Test Scores")
print_scores(liar_dev_lab, preds_liar_valid, "Liar Valid. Scores")
print_scores(liar_train_lab, preds_liar_train, "Liar Train Scores")
#
print_scores(kaggle_test_lab, preds_kaggle_test, "Kaggle Test Scores")
print_scores(kaggle_train_lab, preds_kaggle_tain, "Kaggle Train Scores")
#
print_scores(kaggle_test_lab, kaggle_test_predicted_by_liar_classifier, "Kaggle Test Set Predicted by Classifier Trained on Liar")
print_scores(kaggle_train_lab, kaggle_train_predicted_by_liar, "Kaggle Train Set Predicted by Classifier Trained on Liar")

print_scores(FNC_ytest, preds_FNC_test, "FakeNewsCorpus test prediction scores")
print_scores(FNC_ytrain, preds_FNC_train, "FakeNewsCorpus train prediction scores")
print_scores(FNC_ytest, FNC_test_predicted_by_liar, "FakeNewsCorpus test set predicted by Liar classifier")
print_scores(FNC_ytest, FNC_test_predicted_by_kaggle, "FakeNewsCorpus test set predicted by kaggle classifier")
print_scores(kaggle_test_lab, kaggle_test_predicted_by_FNC, "Kaggle Test Set Predicted by Classifier Trained on FakeNewsCorpus")
print_scores(liar_test_lab, liar_test_predicted_by_FNC, "Liar Test Set Predicted by Classifier Trained on FakeNewsCorpus")

# print_scores(FNN_y, FNN_predicted_by_liar, "FakeNewsNet Predicted by Classifier Trained on Liar")
# print_scores(FNN_y, FNN_predicted_by_kaggle, "FakeNewsNet Predicted by Classifier Trained on Kaggle")

# random liar test set
# random_liar_labels = liar_test_lab.copy()
# np.random.shuffle(random_liar_labels)
# print_scores(random_liar_labels,preds_liar_test, "Scores between predictions on Liar test set and randomized 'true' test labels. Classifier trained on Liar trains set")

print("Done")


import curses
import math
import sys
import logging as log
from pprint import pformat

class Menu:

    DIRECTION_UP = 'UP'
    DIRECTION_DOWN = 'DOWN'

    def __init__(self, layout, border=True):
        self.win = curses.newwin(layout[0],
                                 layout[1],
                                 layout[2],
                                 layout[3])
        self.update()
        self.storage = []
        self.storage_event = []
        self.border = border
        # NOTE: Default setting
        self.selectable = False
        self.page_number = 1
        self.page_index = 0
        self.selected_index = 0
        self.draw_border()
        self.user_list = None
        self.buffered_line_count = 0
        # self.win.bkgd(' ', curses.color_pair(3))

    def set_user_list(self, user_list):
        self.user_list = user_list

    def update(self):
        self.win.refresh()

    def set_storage(self,data, index=None):
        if index:
            self.storage[index] = data
        else:
            self.storage = data

    def append_storage(self, data):
        self.storage.extend(data)

    def append_storage_event(self, events):
        self.storage_event.extend(events)

    def prepend_storage_event(self, events):
        self.storage_event = events + self.storage_event

    def prepend_storage(self, data):
        self.storage = data + self.storage

    def number_of_drawable_rows(self):
        return self.win.getmaxyx()[0]

    def clear(self):
        self.storage = []
        self.storage_event = []
        self.page_number = 1
        self.page_index = 0
        self.selected_index = 0
        self.buffered_line_count = 0
        self.win.clear()

    def draw_border(self):
        if self.border:
            self.win.border(0)

    def draw(self):
        self.win.clear()
        self.draw_border()
        self.write_storage()
        self.update()

    # TODO: Remove this at some point
    def write_clear(self):
        loc = self.draw_location()
        lines = self.page_length()
        blank_line = ' ' * self.draw_bounds()[1]
        for i in range(0, lines):
            draw_y = loc[0] + i
            draw_x = loc[1]
            if self.draw_inbounds(draw_y, draw_x):
                # TODO: Fix with try cache, because addstr \n places cursor, bottom right corner
                self.win.addstr(draw_y, draw_x, blank_line)

    def write_storage(self):
        loc = self.draw_location()
        lines = self.read_storage()
        local_selected = self.local_selected_index(self.selected_index);
        for i in range(0, len(lines)):
            draw_y = loc[0] + i
            draw_x = loc[1]
            line_to_draw = lines[i]
            line_width = self.draw_line_width()
            if len(line_to_draw) > line_width:
                line_to_draw = line_to_draw[0:line_width]

            if self.draw_inbounds(draw_y, draw_x):
                # TODO: Fix with try cache, because addstr \n places cursor, bottom right corner
                if i == local_selected and self.selectable:
                    self.win.addstr(draw_y, draw_x, line_to_draw, curses.color_pair(1))
                else:
                    self.win.addstr(draw_y, draw_x, line_to_draw)

    def local_selected_index(self, index):
        return abs(self.page_length() - ((self.page_length() * self.page_number)-self.selected_index))

    def read_storage(self):
        if self.page_number <= self.page_count():
            read = self.page_length() * self.page_number
            output = self.storage[self.page_index:read]
            return output
        return []

    def draw_location(self):
        if self.border:
            return (1,1)
        return (0,0)

    def draw_bounds(self):
        if self.border:
            y,x = self.win.getmaxyx()
            return (y - 2, x - 2)
        return self.win.getmaxyx()

    def draw_inbounds(self, y, x):
        b_y, b_x = self.draw_bounds()
        if y > b_y:
            return False
        if x > b_x:
            return False
        if y < 0:
            return False
        if x < 0:
            return False
        return True

    def draw_line_width(self):
        return self.draw_bounds()[1]

    def page_count(self):
        return math.ceil(len(self.storage)/self.draw_bounds()[0])

    def compute_page_count(self, lines):
        return math.ceil(len(lines)/self.draw_bounds()[0])

    def page_length(self):
        return self.draw_bounds()[0]

    def select_event(self):
        try :
            event = self.storage_event[self.selected_index]
            return event[0](event[1])
        except Exception as e:
            log.error(e)
            log.error('No Event Action off Select(enter)')

    def select_down(self):
        if self.selected_index < len(self.storage) - 1:
            self.selected_index = self.selected_index + 1
        if self.selected_index >= self.page_length() * self.page_number:
            self.scroll_down()

    def select_up(self):
        if self.selected_index > 0:
            self.selected_index = self.selected_index - 1
        if self.selected_index < self.page_length() * (self.page_number - 1):
            self.scroll_up()

    def select(self, direction):
        if direction == self.DIRECTION_UP:
            self.select_up()
        elif direction == self.DIRECTION_DOWN:
            self.select_down()

        self.write_clear()
        self.write_storage()
        self.update()

    def scroll_down(self):
        if self.page_number < self.page_count():
            self.page_index = self.page_index + self.page_length()
            self.selected_index = self.page_index
            self.page_number = self.page_number + 1

    def scroll_up(self):
        if self.page_number > 1:
            self.page_index = self.page_index - self.page_length()
            self.selected_index = self.page_index + self.page_length() - 1
            self.page_number = self.page_number - 1

    def scroll(self, direction):
        if direction == self.DIRECTION_UP:
            self.scroll_up()
        elif direction == self.DIRECTION_DOWN:
            self.scroll_down()

        self.draw()

    def scroll_to_bottom(self):
        self.page_index = self.page_length()
        self.selected_index = self.page_index
        self.page_number = self.page_count()
        self.draw()

    def focus(self):
        self.selectable = True
        self.draw()

    def defocus(self):
        self.selectable = False
        self.draw()

    def eat_key(self, c):
        if  c == ord('j'):
            self.select('DOWN')
            pass
        elif c == ord('k'):
            self.select('UP')
            pass
        elif c == 10:
            self.select_event()
            pass

    def buffer_lines(self, lines):
        number_of_pages = self.compute_page_count(lines)
        total_lines = number_of_pages * self.page_length()
        total_buffer = total_lines - len(lines)
        buffer = [' '] * total_buffer
        lines = buffer + lines
        return lines

    def scroll_to_last_page(self):
        self.page_index = self.page_length() * (self.page_count() - 1)
        self.selected_index = self.page_index
        self.page_number = self.page_count()

    def fake_window_scroll(self):
        self.clear_previous_scroll()
        page_length = self.page_length()
        line_count_in_window = len(self.read_storage())
        [self.prepend_storage([' ' * self.draw_line_width()]) for _ in range(page_length - line_count_in_window)]
        self.buffered_line_count = page_length - line_count_in_window

    def clear_previous_scroll(self):
        self.storage = self.storage[self.buffered_line_count:]
        self.buffered_line_count = 0


"""
Réalise une jointure spatiale entre deux DataFrame et en résulte une table de
liaison.
Par exemple, la table résultante peut donner la concordance entre les anciens
et les nouveaux biotopes.

@params old_df: GeoDataFrame
@params new_df: GeoDataFrame
@returns: GeoDataFrame
"""
def jointure(old_df, new_df):

    # Intersection de toutes les géométries entre elles
    # indice df1, indice df2, geometries
    overlay_intersection = old_df.overlay(new_df, how='intersection')
    valid_overlay = remove_invalid_geoms(overlay_intersection, 1) # SEUIL D' UN METRE CARRÉ

    # Remplie la table des colonnes des deux DataFrames initiaux
    joined_temp = valid_overlay.join(old_df, on='old_df', rsuffix='old_')
    joined = joined_temp.join(new_df, on='new_df', rsuffix='new_')

    # Selection des colonnes qui nous interessent
    # geometry fait référence aux intersections
    res = joined[['old_Geocode', 'new_Geocode', 'geometry']]

    return res

"""
Retire les géométries invalides et celles qui ont une aire inférieure au seuil

@params df: GeoDataFame
@params seuil: float
"""
def remove_invalid_geoms(df, seuil):
    # Selectionne les geometries voulues
    geom = df.geometry
    valid_geom = geom[geom.is_valid()]
    big_geom = valid_geom[valid_geom.area > seuil]
    # Selection des lignes de la table ayant une geometrie valide
    res_df = df[big_geom.index]

    return res_df


'''
Coin Change Problem Implementation using Dynamic Programming (Bottom-Up Approach)

Problem:
Given coins of certain denominations with unlimited quantity and a total,
what is the minimum number of coins would be needed to form that total.

Time complexity:
Space complexity:

'''

def coinchange():
    # given list of coins of certain denominations and a target total value to reach
    coins = [1, 2, 5]
    targetAmount = 11

    # list for memoization initialized with a placeholder value (targetAmount + 1) that will be replaced by a minimum value later
    # base case also added in the front of the list to satisfy the base case of value 0
    # each index in memoization list represents the minimum number of coins for that respective index and target value, i.e. index 3 represents targetAmount = 3
    memo = [targetAmount + 1 for x in range(targetAmount)]
    memo.insert(0, 0)

    # bottom-up approach
    # for each index, find the minimum amount of coins to create the targetAmount with each coin in the coins list
    for amount in range(1, targetAmount + 1):
        for currentCoin in coins:
            # check if current amount can even possible be created with the current coin being compared with
            if currentCoin <= amount:
                '''
                currentValue: the current value in our memoization list
                currentCoinWithPrev: the current coin (1, 2, or 5) along with the remaining and previous subsolution that has already been calculated

                For example, if the targetAmount is 8, then currentValue would be 12 (targetAmount + 1). If the current coin, in
                consideration, is 5, then 8 - 5 = 3 and 3 has already been calculated and so we will check the 'memo' list for the previous solution to
                create 3. We would then take this previous solution and simply add 1 to it (since its previous solution along with the coin = 5).
                '''

                currentValue = memo[amount]
                currentCoinWithPrev = memo[amount - currentCoin] + 1
                # take the minimum of the current existing value in 'memo' or the current coin along with the remaining/previous subsolution
                memo[amount] = min(currentValue, currentCoinWithPrev)

    # visual representation of the memoization matrix
    print(memo)

    print(f"The minimum number of coins that would be needed to make {targetAmount} is {memo[targetAmount]} coins.")
    return memo[targetAmount]

coinchange()


#!/usr/bin/python3

import os
import argparse
import time
import urllib.request
import email.mime.text
import socket
import getpass
import subprocess

def lookup_mac_vendor(mac_address):
    result = ""
    if mac_address:
        for i in range(3):
            vendor = None
            try:
                # Only first 3 octets are needed for manufacturer identification
                # The rest is ommited for privacy reasons
                response = urllib.request.urlopen("https://api.macvendors.com/" + mac_address[:8])
                vendor = response.read().decode(response.info().get_param('charset') or 'utf-8')
            except:
                time.sleep(1)
            if vendor:
                result = vendor
                break
    return(result)

def send_mail(vendor):
    msg = email.mime.text.MIMEText(
        "IP: {ip}\n"
        "Static: {is_static}\n"
        "MAC: {mac}\n"
        "Vendor: {vendor}\n"
        "Host: {host}\n"
        "Static host name: {static}".format(
            ip=options.ip,
            is_static="yes" if options.is_static == "1" else "no",
            mac=options.mac,
            vendor=vendor,
            host=options.host_name,
            static=options.static_host_name
        )
    )
    msg['From'] = getpass.getuser() + "@" + socket.gethostname()
    msg['To'] = options.mail_to
    msg['Subject'] = "New DHCP lease for {} on {}".format(options.host_name, socket.gethostname())
    proc = subprocess.Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=subprocess.PIPE)
    proc.communicate(bytes(msg.as_string(), "UTF-8"))

def forked_main():
    vendor = lookup_mac_vendor(options.mac)
    mac_is_known = False
    if options.mac:
        if os.path.isfile(options.known_macs_file):
            with open(options.known_macs_file) as f:
                for line in f:
                    if line.rstrip().upper() == options.mac.upper():
                        mac_is_known = True
    if not mac_is_known:
        send_mail(vendor)
        if options.mac:
            with open(options.known_macs_file, "a") as f:
                f.write(options.mac + "\n")

parser = argparse.ArgumentParser(description="New DHCP lease event handler")
parser.add_argument("known_macs_file", help="Known MAC-address list file")
parser.add_argument("ip", nargs="?", default="", help="IP address")
parser.add_argument("mac", nargs="?", default="", help="MAC address")
parser.add_argument("host_name", nargs="?", default="", help="Name of the client")
parser.add_argument("static_host_name", nargs="?", default="", help="Matched static host name")
parser.add_argument("is_static", nargs="?", default="", help="IP is static (0 or 1)")
parser.add_argument('-n', '--no-fork', dest='no_fork', action='store_true',
    default=False, help='Do not fork a child process')
parser.add_argument('-m', '--mail-to', dest='mail_to', default="root",
    help='Mail message recipient (default: root)', metavar="mail")

options = parser.parse_args()

if options.no_fork:
    print("--no-fork option is specified. Running in foreground")
    print("IP: {}".format(options.ip))
    print("MAC: {}".format(options.mac))
    print("Mail to: {}".format(options.mail_to))
    forked_main()
elif os.fork() == 0:
    forked_main()
    os._exit(0)


import re

def addfirst_calc(expr):
  add_re = r'\b(\d+?)\b\s+\+\s+\b(\d+?)\b'
  m = re.search(add_re, expr)
  while m:
    result = int(m.group(1)) + int(m.group(2))
    add_replace = r'\b%s\b' % m.group(0).replace('+', '\+')
    expr = re.sub(add_replace, str(result), expr)
    m = re.search(add_re, expr)

  mult_re = r'\b(\d+?)\b\s+\*\s+\b(\d+?)\b'
  m = re.search(mult_re, expr)
  while m:
    result = int(m.group(1)) * int(m.group(2))
    mult_replace = r'\b%s\b' % m.group(0).replace('*', '\*')
    expr = re.sub(mult_replace, str(result), expr)
    m = re.search(mult_re, expr)

  return int(expr)

def main():
  with open('input.txt') as f:
    raw = f.readlines()

  total = 0

  for line in raw:
    line = line.strip('\n')
    paren_re = r'\(([^()]+)\)'
    m = re.search(paren_re, line)
    while m:
      result = addfirst_calc(m.group(0)[1:-1])
      line = line.replace(m.group(0), str(result))
      m = re.search(paren_re, line)

    result = int(addfirst_calc(line))
    total += result

  print ('Total: %d' % (total, ))

main()


# -*- codeing = utf-8 -*-
# @Time : 2021/5/9 21:41
# @File ：校内赛识别图形最终版本.py
# @Software : PyCharm
import cv2 as cv

def detectShape(img):
    # 查找轮廓，cv2.RETR_ExTERNAL=获取外部轮廓点, CHAIN_APPROX_NONE = 得到所有的像素点
    contours, hierarchy = cv.findContours(img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
    # 循环轮廓，判断每一个形状
    global count
    global objectType
    count = 0
    objectType = None
    for cnt in contours:
        # 获取轮廓面积
        area = cv.contourArea(cnt)
        # 当面积大于1500，代表有形状存在
        if area > 1500:
            # 绘制所有的轮廓并显示出来
            cv.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
            # 计算所有轮廓的周长，便于做多边形拟合
            peri = cv.arcLength(cnt, True)
            # 多边形拟合，获取每个形状的边
            approx = cv.approxPolyDP(cnt, 0.02 * peri, True)
            objCor = len(approx)
            # 获取每个形状的x，y，w，h
            x, y, w, h = cv.boundingRect(approx)
            # 计算出边界后，即边数代表形状，如三角形边数=3
            if objCor == 3:
                objectType = "Triangle"
                print("形状是%s,面积是%d" % (objectType, area))
                count += 1
            elif objCor == 4:
                objectType = "Rectangle"
                print("形状是%s,面积是%d" % (objectType, area))
                count += 1
            # 大于4个边的就是五边形
            elif 5 <= objCor < 7:
                objectType = "Pentagon"
                print("形状是%s,面积是%d" % (objectType, area))
                count += 1
            elif objCor == 8:
                objectType = "Circle"
                print("形状是%s,面积是%d" % (objectType, area))
                count += 1
            elif objCor > 8:
                objectType = "Star"
                print("形状是%s,面积是%d" % (objectType, area))
                count += 1
            # 绘制文本时需要绘制在图形附件
            cv.rectangle(imgContour, (x, y), (x + w, y + h), (0, 255, 0), 2)
            cv.putText(imgContour, objectType,
                       (x + (w // 2) - 10, y + (h // 2) - 10), cv.FONT_HERSHEY_COMPLEX, 0.7,
                       (0, 0, 0), 2)

# 调用笔记本内置摄像头，所以参数为0，官方摄像头为1
cap = cv.VideoCapture(0, cv.CAP_DSHOW)
while True:
    # 从摄像头读取图片
    success, img = cap.read()
    # 转换大小
    img = cv.resize(img, (1000, 700))
    # 灰度化
    imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    # 高斯平滑
    imgBlur = cv.GaussianBlur(imgGray, (7, 7), 1)
    # 边缘检测
    imgCanny = cv.Canny(imgBlur, 200, 200)
    # 膨胀
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (2, 2))
    swell = cv.dilate(imgCanny, kernel=kernel)
    # 调用检测函数
    imgContour = img.copy()
    detectShape(swell)
    # 绘制文本
    cv.putText(imgContour, "%s,%d" % (objectType, count), (10, 50), cv.FONT_HERSHEY_PLAIN, 2.0,
               (0, 0, 0), 2)
    # 若参数delay≤0：表示一直等待按键；
    # 若delay取正整数：表示等待按键的时间，比如cv2.waitKey(100)，就是等待100毫秒
    k = cv.waitKey(100)
    # 保持画面的持续。
    cv.imshow("img", imgContour)
    if k == 27:
        # 通过esc键退出摄像
        cv.destroyAllWindows()
        break

# 关闭摄像头
cap.release()
cv.destroyAllWindows()

校内赛识别图形最终版本.py

校内赛识别图形最终版本.py


nim = [[1, 1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1], [1, 1], [1]]

player1 = "Human 1"

player2 = "Computer 2"

players = player1, player2

def make_move(row, number):
    if row < 0 or row >= len(nim):
        print("Bad row")
        return False
    elif number <= len(nim[row]) and number > 0:
        for i in range(number):
            nim[row].pop()
        return True
    else:
        print("Bad number of elements")
        return False

def num_to_binary(num):
    bin_rep = []
    while num:
        bin_rep.append(num % 2)
        num //= 2
    return bin_rep[::-1]

def compute_nim_sum(heaps):
    heaps = [heap for heap in heaps if heap]
    i = len(heaps[0])
    for j in heaps[1:] :
        i ^= len(j)
    return i

def binary_to_num(binary):
    binary = binary[::-1]
    num = 0
    for i, elem in enumerate(binary):
        num += binary[i] * 2**i
    return num

import random
def compute_move(nim):
    X = compute_nim_sum(nim)
    good_heaps = []
    bad_heaps = []
    for i, heap in enumerate(nim):
        if heap and len(heap) ^ X < len(heap) and X != 0:
            good_heaps.append((i, len(heap) - (len(heap) ^ X)))
        elif heap:
            bad_heaps.append(i)
    random.shuffle(good_heaps)
    random.shuffle(bad_heaps)
    if good_heaps:
        return good_heaps[0]
    else:
        return bad_heaps[0], random.randint(1, len(nim[bad_heaps[0]]))
    return good_heaps

assert(5 == binary_to_num(num_to_binary(5)))
assert(12 == binary_to_num(num_to_binary(12)))
assert(0 == binary_to_num(num_to_binary(0)))

while True:
    print("Current board.", nim)
    if "Human" in players[0]:
        values = input(str(players[0]) + ". Make a move. Move is row, number, for example 0, 3:")
        row, number = values.strip().split(",")
        row = int(row)
        number = int(number)
        result = make_move(row, number)
        if not any(nim):
            print(players[0] + " won.")
            break
        if result:
            players = players[1], players[0]
    if "Computer" in players[0]:
        print(players[0] + " makes a move.")
        row, number = compute_move(nim)
        make_move(row, number)
        if not any(nim):
            print(players[0] + " won.")
            break
        players = players[1], players[0]


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

def parse_file(f):
    grammar = {
        'N': [],
        'Sigma': [],
        'S': 'S',
        'P': []
    }
    for i in range(3):
        line = f.readline()
        line = line.rstrip()

        idx = line.find(' = ')
        s = line[:idx]
        elements = line[idx+3:].split(' ')
        grammar[s] = elements
        if s == 'S':
            grammar[s] = elements[0]
    for line in f:
        line = line.rstrip()

        idx = line.find(' -> ')
        left_hand_side = line[:idx]
        right_hand_side = line[idx+4:]
        grammar['P'].append((left_hand_side, right_hand_side))
    return grammar

# based on https://medium.com/100-days-of-algorithms/day-93-first-follow-cfe283998e3e
def compute_first_follow(grammar):
    first = {}
    follow = {}
    for terminal in grammar['Sigma']:
        first[terminal] = {terminal}
        follow[terminal] = set()

    for nonterminal in grammar['N']:
        first[nonterminal] = set()
        follow[nonterminal] = set()

    follow[grammar['S']].add('$')
    epsilon = set()
    for left, right in grammar['P']:
        if right == '$':
            epsilon.add(left)
    ok = True
    while ok == True:
        ok = False

        for left, right in grammar['P']:
            for symbol in right:
                ok |= union(first[left], first[symbol])
                if symbol not in epsilon:
                    break
                else:
                    ok |= union(epsilon, {left})

            new = follow[left]
            for symbol in reversed(right):
                ok |= union(follow[symbol], new)
                if symbol in epsilon:
                    new = new.union(first[symbol])
                else:
                    new = first[symbol]
    return first, follow, epsilon

def union(first, begins):
    n = len(first)
    first |= begins
    return len(first) != n

def make_csting(l):
   cstring = 'std::string(\"'
   for elem in l:
       cstring += elem
   cstring += '\")'
   return cstring

def main():
    parser = argparse.ArgumentParser(description='Tool for generating a recursive descent parser.')
    parser.add_argument('input', type=str, help='Path to input file (where the grammar in described)')
    parser.add_argument('output', type=str, help='Output file name.')

    args = parser.parse_args()
    inputFile = args.input
    outputFile = args.output

    f = open(inputFile, 'r')
    grammar = parse_file(f)
    f.close()
    first, follow, epsilon = compute_first_follow(grammar)
    print(first)
    print(follow)
    print(epsilon)

    o = open(outputFile, 'w')
    # include libraries
    o.write('#include <iostream>\n')
    o.write('#include <string>\n')
    o.write('\n')

    # global variables
    o.write('std::string s;\n')
    o.write('int i = -1;\n')
    o.write('char token;\n')
    o.write('\n')

    for nonterminal in grammar['N']:
        o.write('void ' + nonterminal + '();\n')
    o.write('void check(std::string alpha);\n')
    o.write('void parse_nonterminal(std::string alpha);\n')
    o.write('\n')

    # first functions
    o.write('std::string first(char c) {\n')
    o.write('  switch(c) {\n')
    for terminal in grammar['Sigma']:
        o.write('    case \'' + terminal + '\': return ' + make_csting(first[terminal]) + '; break;\n')
    for nonterminal in grammar['N']:
        o.write('    case \'' + nonterminal + '\': return ' + make_csting(first[nonterminal]) + '; break;\n')
    o.write('  }\n')
    o.write('}\n')
    o.write('\n')

    # follow functions
    o.write('std::string follow(char c) {\n')
    o.write('  switch(c) {\n')
    for terminal in grammar['Sigma']:
        o.write('    case \'' + terminal + '\': return ' + make_csting(follow[terminal]) + '; break;\n')
    for nonterminal in grammar['N']:
        o.write('    case \'' + nonterminal + '\': return ' + make_csting(follow[nonterminal]) + '; break;\n')
    o.write('  }\n')
    o.write('}\n')
    o.write('\n')

    # scan function which returns next token
    o.write('char scan() {\n')
    o.write('  ++i;\n')
    o.write('  if (i < s.size()) {\n')
    o.write('    return s[i];\n')
    o.write('  }\n')
    o.write('  return EOF;\n')
    o.write('}\n')
    o.write('\n')

    # check function
    o.write('void check_terminal(std::string alpha) {\n')
    o.write('  if (alpha[0] == token) {\n')
    o.write('    token = scan();\n')
    o.write('  }\n')
    o.write('  else {\n')
    o.write('    std::cout << alpha[0] + \" expected\\n\";\n')
    o.write('  }\n')
    o.write('  if (alpha.size() >= 2) {\n')
    o.write('    check(alpha.substr(1));\n')
    o.write('  }\n')
    o.write('}\n')
    o.write('\n')

    o.write('void check_nonterminal(std::string alpha) {\n')
    o.write('  parse_nonterminal(alpha);\n')
    o.write('}\n')
    o.write('\n')

    o.write('void check(std::string alpha) {\n')
    o.write('  switch(alpha[0]) {\n')
    for terminal in grammar['Sigma']:
        o.write('    case \'' + terminal + '\': check_terminal(alpha); break;\n')
    for nonterminal in grammar['N']:
        o.write('    case \'' + nonterminal + '\': check_nonterminal(alpha); break;\n')
    o.write('  }\n')
    o.write('}\n')
    o.write('\n')

    # parse function for terminals and nonterminals
    o.write('void parse_terminal(std::string alpha) {\n')
    o.write('  if (alpha[0] != \'l\') {\n')
    o.write('    token = scan();\n')
    o.write('  }\n')
    o.write('  if (alpha.size() >= 2) {\n')
    o.write('    check(alpha.substr(1));\n')
    o.write('  }\n')
    o.write('}\n')
    o.write('\n')
    o.write('void parse_nonterminal(std::string alpha) {\n')
    o.write('  switch(alpha[0]) {\n')
    for nonterminal in grammar['N']:
        o.write('    case \'' + nonterminal + '\':' + nonterminal + '(); break;\n')
    o.write('  }\n')
    o.write('  if (alpha.size() >= 2) {\n')
    o.write('    check(alpha.substr(1));\n')
    o.write('  }\n')
    o.write('}\n')
    o.write('\n')

    # function for every nonterminal A from N
    for nonterminal in grammar['N']:
        o.write('void ' + nonterminal + '() {\n')
        for left, right in grammar['P']:
            if left == nonterminal:
                if right[0] != 'l':
                    o.write('  if (first(\'' + right[0] + '\').find(token) != std::string::npos) {\n')
                    o.write('    std::cout << \"' + nonterminal + ' -> ' + right + '\\n\";\n')
                    if right[0] in grammar['N']:
                        o.write('    parse_nonterminal(\"' + right + '\");\n')
                    else:
                        o.write('    parse_terminal(\"' + right + '\");\n')
                    o.write('    return;\n')
                    o.write('  }\n')
                else:
                    o.write('  if (follow(\'' + left + '\').find(token) != std::string::npos) {\n')
                    o.write('    std::cout << \"' + nonterminal + ' -> ' + right + '\\n\";\n')
                    if right[0] in grammar['N']:
                        o.write('    parse_nonterminal(\"' + right + '\");\n')
                    else:
                        o.write('    parse_terminal(\"' + right + '\");\n')
                    o.write('    return;\n')
                    o.write('  }\n')

        o.write('  std::cout << \"Se asteapta un token diferit\\n\";\n')
        o.write('}\n')
        o.write('\n')

    o.write('int main() {\n')
    o.write('  std::cin >> s;\n')
    o.write('  token = scan();\n')
    o.write('  ' + grammar['S'] + '();\n')
    o.write('  if (token != EOF) {\n')
    o.write("      std::cout << \"ERROR: EOF expectd\\n\";\n")
    o.write('  }\n')
    o.write('  return 0;\n')
    o.write('}\n')

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


def solve(intervals):
    # CODE HERE
    # sorting according to start time
    intervals.sort(key = lambda x: x[0])
    kat = []
    for inter in intervals:

        if not kat or kat[-1][1] < inter[0]:
            kat.append(inter)

        else:
            kat[-1][1] = max(kat[-1][1], inter[1])

    return kat


import copy
from math import log
from cmath import e

class ProgressState:

    def __init__(self, progress, word=None):
        self.progress = progress
        self.word = word

    def getLegalActions(self, agentIndex):
        """
        Returns the legal actions for the agent specified.
        """
        if agentIndex == "computer":  # Computer is asking
            # representing which question can be asked
            return list(self.progress.keys())
        else: # Human is answering
            return [0,1]

    def generateSuccessor(self, agentIndex, action, time = 0):
        if agentIndex == "computer": # Computer is asking
            return ProgressState(self.progress, action) #remember which action is taken
        else: # Human is answering
            # work with the word that only matters
            penalty = 0
            if 2 < time < 5:
                penalty = time * - 0.03
            elif time >= 5:
                penalty = - 0.3
            progress_copy = copy.deepcopy(self.progress)

            def limit_value():
                if progress_copy[self.word][1] < 0.05:
                    progress_copy[self.word][1] = 0.05
                elif progress_copy[self.word][1] > 0.95:
                    progress_copy[self.word][1] = 0.95

            var = progress_copy[self.word][1]
            inner = - pow((var - 0.55), 2)
            middle = pow(e, inner)
            outer = pow(middle, 8)
            if action == 0: # if the user got the question wrong
                progress_copy[self.word][1] -= (outer * -log(var))/2
                limit_value()
            if action == 1: # if the user got the question right
                progress_copy[self.word][1] += (outer * -log(var))/2 + penalty
                limit_value()
            return ProgressState(progress_copy)

    def getnumberWords(self):
        return len(list(self.progress.keys()))

    def getProgress(self):
        return self.progress

    def getWord(self):
        return self.word

    def getProbability(self):
        return self.progress[self.word][1]

    def getAverage(self):
        sumProgress = 0
        for key in self.progress.keys():
            sumProgress = self.progress[key][1] + sumProgress
        return sumProgress/len(list(self.progress.keys()))


import tushare as ts
import numpy as np
import matplotlib.pyplot as plt
import random
import math

import datetime
import tushare as ts
import pymysql
import stock_one

# p = stock_one.oneday('sh.600123', '20150102', '20210218')
# print(p)
# exit()

starttime = '20170102'
endtime = '20210218'

all = []

a = ['SH.600206', datetime.date(2017, 1, 3), 10.0739, 496, datetime.date(2021, 2, 10), 11.33, 12.460511999999987, 236.9613760000003]
b = ['SH.600206', datetime.date(2017, 1, 3), 10.0739, 496, datetime.date(2021, 2, 10), 11.33, 12.460511999999987, 236.9613760000003]
all.append(a)
all.append(b)

x = []
y = []

db = pymysql.connect(host='127.0.0.1', user='root', passwd='', db='tushare', charset='utf8')
cursor = db.cursor()
try:
    sql = "select * from stock_basic order by ts_code;"
    cursor.execute(sql)
    stockbasic = np.array(cursor.fetchall())

    for i in range(stockbasic.shape[0]):
        isgo = 0
        #print(stockbasic[i,:][0], stockbasic[i,:][1])
        if int(stockbasic[i,:][1]) >= 600000 and int(stockbasic[i,:][1]) < 600589: #600589:
            isgo = 1
        if int(stockbasic[i,:][1]) >= 1 and int(stockbasic[i,:][1]) < 898:
            isgo = 1
        # if int(stockbasic[i,:][1]) == 600160:
        #     isgo = 1
        if isgo == 0:
            continue

        realcode = stockbasic[i,:][0][7]+stockbasic[i,:][0][8]+'.'+stockbasic[i,:][1]
        print(i, realcode)

        p = stock_one.oneday(realcode, starttime, endtime)
        print(p)
        all.append(p)

except Exception as err:
    print(err)

cursor.close()
db.close()

all = np.array(all)
v1 = np.sort(all[:,6])
v2 = np.sort(all[:,7])

x = np.arange(all.shape[0])

# out_list = np.array([list(item) for item in zip(x,y)])

# print(out_list)
# out_list = out_list[np.lexsort(out_list.T)]
# print(out_list)

np.savez('all_data', all)

plt.title("ALL")
plt.xlabel("x")
plt.ylabel("price")
plt.ylim([-100,300])
plt.plot(x,v1,linestyle='--',color='red')
plt.plot(x,v2,linestyle='--',color='green')
plt.show()


import numpy as np
import pandas as pd
import pickle
from flask import Flask ,app ,request ,jsonify ,render_template ,url_for
app=Flask(__name__)
reg_model=pickle.load(open('regm.pkl','rb'))        #load regression model
scaler=pickle.load(open('scale.pkl','rb'))          #load scaling model
@app.route('/')
def home():
    return render_template('home.html')             #redirect to home.html
@app.route('/predict_api',methods=['POST'])         #api with post request becuase we take input then generate output using it
def predict1():
    data=request.json['data']
    print(data)                                         #data is dictionory with elements in key value pair
    print(np.array(list(data.values())).reshape(1,-1))  #convert all inputs in a single file of data to add in prediction model
    transformed_data=scaler.transform(np.array(list(data.values())).reshape(1,-1))
    output=reg_model.predict(transformed_data)
    print(output[0])                                       #output recived is an 2d array
    return jsonify(output[0])                               #return jsonifoed output

@app.route('/predict',methods=['POST'])
def predict():
    input=[float(x) for x in request.form.values()]             #Get input from html form
    transformed_input=scaler.transform(np.array(input).reshape(1,-1))
    output=reg_model.predict(transformed_input)[0]
    return render_template("home.html",prediction_text="Predicted House Price is {}".format(output))

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


from win10toast import ToastNotifier
import feedparser
import time
toaster = ToastNotifier()

def getNews():
    url = "https://www.youm7.com/rss/SectionRss?SectionID=203" #url rss
    feed = feedparser.parse("https://www.youm7.com/rss/SectionRss?SectionID=203") #Get all feed from rss

    for item in feed["entries"]:
        toaster.show_toast("اليوم السابع",item["title"],duration=100)

    while toaster.notification_active():
        time.sleep(1000)

if __name__ == '__main__':
    getNews()


from veca.env_manager import EnvOrchestrator

if __name__ == "__main__":
    # Executing the Environment Orchestrator process at another server.
    env = EnvOrchestrator(
        ip = "127.0.0.1",   # ip and port of remote Envionment Orchestrator master
        port = 8872,        # Exposed port of Environment Orchestrator
        port_instance = 46490   # inter-process communication port with orchestrator and unity instances (localport ~ localport + num_envs)
        )


import discord
import random
import os
import csv
import paralleldots
from datetime import datetime
import asyncio
#please make you have installed the packages or just run on replit
from discord_components import *
from discord.ext.commands import bot
from discord.utils import get
from discord.ext import commands, tasks
import json
import requests

intents = discord.Intents.default()    #please make sure that you have enabled the Intents in discord dev portal
intents.members = True
intents = intents.all()

#client = discord.Client()
client=commands.Bot(command_prefix="!", intents=intents)
client.remove_command('help')        #to remove the default help command

sentiment_API = os.environ['SENTIMENT_API']
paralleldots.set_api_key(sentiment_API)

# Submission timeout   (hours and minutes need to update later accordingly)
PYCON_DATE = datetime(year=2021, month=11, day=21, hour=5, minute=30)
countdown = PYCON_DATE - datetime.now().replace(microsecond=0)

# Bot will only work on these channels
Bot_Channels=[
  881582264419500032, # Write your gaming channel id here
  857549642934124545,
  857569486303264768,
  857551907714760704,
  870716941663350825,
  857549120943292436,
  857549492324139059,
  863495216467804220,
  874356441069269032,
  874630819388473344,
  870532018054783027
]

# "$" special character is to replace with user name
words_response = [
    "Hi! $", "How are things with you $",
    "It’s good to see you $", "Howdy! $",
    "Hi, $. What’s new?",
    "Good to see you $",
    "Look who it is! $",
    "Oh, it’s you $! Hi there!",
    "Hi $, it’s me again!",
    "Hang in there $ ,i am busy!",
    "Yes Honey $"
]

# Dont mess with this names
Sentiments = [
    "Happy",
    "Sad",
    "Excited",
    "Angry",
    "Bored",
    "Fear"
]

sentiment_emojis = {}
# If you want bot to react with specific emoji add your user_name here
user_names = [
   "rehh",
   "EFFLUX",
   "moon57",
   "Here4Quantum",
   "Ryah",
   "Zoheb"
]

# You must have a emoji specific to your user_name in our server , if you dont have submit a emoji in "emoji-and-stickers submission" & ask Admin to add it with your user name
Custom_emojis = {}

#=============== EMOTIONS CHECK ========================
def check_sentiment(message):
  emotions= paralleldots.emotion( message ).get('emotion')
  Max_emotion=max(emotions, key=emotions.get)
  print(Max_emotion)
  if Max_emotion in Sentiments:
    return Max_emotion
  else:
     return 0;

# Turn this to true if you dont want sentiment analysis
disable_sentiment_analysis = True;

@client.event
async def on_ready():
  DiscordComponents(client)         #for discord buttons
  for name in user_names:
    Custom_emojis[name] = discord.utils.get(client.emojis, name=name)
  for sentiment in Sentiments:
    sentiment_emojis[sentiment] = discord.utils.get(client.emojis, name=sentiment)
    print("Updated sentiment emojis")
  print("Bot is ready {0.user}".format(client))

@client.event
async def on_message(message):
    if message.channel.id not in Bot_Channels:
       return
    text = message.content.lower().strip()
    if message.author == client.user:
        return
    if "limbo" in text:
        response_message = random.choice(words_response)
        user_name = message.author.name
        response_message = response_message.replace("$", user_name)
        await auto_response(True,message,response_message)

    if message.author.name in user_names:
       await message.add_reaction(Custom_emojis.get(message.author.name))

    # Direct links of limbohacks for easy access with '!' prefix
    await auto_response(text.startswith('!website'),message,"https://limbohacks.tech/")
    await auto_response(text.startswith('!devpost'),message,"https://limbo-hacks-12968.devpost.com/")
    await auto_response(text.startswith('!discord'),message,"https://discord.com/invite/8XJSzmtWPp")
    await auto_response(text.startswith('!time'), message, f"⏳ {countdown} Time left for the submission ⏳")

    await client.process_commands(message) # This line makes your other commands work.
    #Getting message sentiment
    if message.channel.id!=881582264419500032:
      result = check_sentiment(text)
      await auto_react(result ,message,sentiment_emojis.get(result))

async def auto_response(condition,message,content):
  if condition:
   await message.channel.send(content)

async def auto_react(condition,message,content):
  if condition:
   await message.add_reaction(content)
#===============LEVEL================
@client.command()
async def levels(ctx):
    with open('level.json') as f:
        users=json.load(f)
        values = list(users.values())
    new_dict = {}
    for k, v in users.items():
        new_dict.setdefault(v, []).append(k)
    values=list(new_dict.values())
    k=0
    top_users=['```POINTS   PLAYERS```']
    for i in values:
        for j in i:
            k+=1
            if k >5:         #for top 5 users
                break
            top_users.append(f"```{users[j]}       {client.get_user(int(j))}```")
    e1 = discord.Embed(title=" Leaderboard ", description='\n'.join(top_users),color=0x00FF00)
    await ctx.send(embed=e1)
    await ctx.reply(f"```Your points : {users[str(ctx.author.id)]}```")

#===============HELP==================
@client.command()
async def help(ctx):
  HELP=['**!website\n**:> Get official website\n','**!devpost\n**:> Get Devpost Link\n','**!discord\n**:> Discord server link\n','**!time\n**:> Time left for submission\n','**!games\n**:> Try amazing games']
  embed=discord.Embed(title="Limbo Hacks",description=''.join(HELP),color=0x3498db)
  await ctx.send(embed=embed)

#================QUIZ==================
@client.command()
async def quiz(ctx):
  e1 = discord.Embed(title=f"{ctx.author.name} , You Guessed It Right!", description="> You have scored! <",color=0x00FF00)
  e2 = discord.Embed(title=f"{ctx.author.name} , You Lost!", description=f"> Try again <",color=discord.Color.red())
  e3 = discord.Embed(title=f"{ctx.author.name}, You didn't Click on Time", description="> Timed Out! <",color=discord.Color.red())

  url='https://opentdb.com/api.php?amount=1&category=18&difficulty=easy&type=multiple'
  response=requests.get(url)
  json_data=json.loads(response.text)
  question=(list(json_data.values())[1][0]["question"])
  p=(list(json_data.values())[1][0]["correct_answer"])
  t=(list(json_data.values())[1][0]["incorrect_answers"])
  t.append(p)
  random.shuffle(t)

  def check(res):
      return ctx.author == res.user and res.channel == ctx.channel

  e = discord.Embed(title=f"{ctx.author.name}'s QUIZ Game!", description=f"**Q) {question}**",color=0x3498db)
  m = await ctx.reply(embed=e,components=[[Button(style=1, label=f"{t[0]}"),Button(style=3, label=f"{t[1]}"),Button(style=ButtonStyle.red,label=f"{t[2]}"),Button(style=ButtonStyle.grey,label=f"{t[3]}")]],)
  try:
    res = await client.wait_for("button_click", check=check, timeout=20)
  except asyncio.TimeoutError:
    await m.edit(embed=e3,components=[],)
    return

  if res.component.label==p:
    with open('level.json') as f:
            users=json.load(f)
            if str(ctx.author.id) not in users:
                users[str(ctx.author.id)]=1
            if str(ctx.author.id) in users:
                users[str(ctx.author.id)]+=3
                e1.set_footer(text="Your gained 3 points", icon_url=ctx.author.avatar_url)
                await m.edit(embed=e1,components=[],)
            see(users)
  else:
    await m.edit(embed=e2,components=[],)

#===========NEW USER FOR GAME==========
def see(users):
    with open('level.json','w') as fin:
        json.dump(users,fin)
#================GAMES=================
@client.command()
async def games(ctx):
  if ctx.message.channel.id != 881582264419500032:       #Please change this id to your game channel id
    await ctx.reply("Please go to gaming channel, I am waiting there...")
    return
  Game=['**!bonk\n**:> play Whac-A-Mole\n !bonk @member\n !bonk @member @member #for 3 players\n','**!rps\n**:> play Rock Paper Scissors (2 points)\n','**!guess\n**:> Can you guess which colour is it ?(1 point)\n','**!amongus\n**:> shhhhhhhhh!(1 point)\n','**!football\n**:> Wanna goal ?(2 points)\n','**!quiz\n**:> Answer Answer Answer whooo...(3 points)\n']
  game=discord.Embed(title='Games', description =''.join(Game),color=0x3498db)
  await ctx.send(embed=game)
  with open('level.json') as f:
    users=json.load(f)
    if str(ctx.author.id) not in users:
        users[str(ctx.author.id)]=1
    see(users)

#=================AMONG US==============
@client.command()
async def amongus(ctx):
    if ctx.message.channel.id != 881582264419500032:          #Please change this id to your game channel id
      await ctx.reply("Please go to gaming channel, I am waiting there...")
      return
    ch=['Blue ඞ','Green ඞ','Red ඞ','grey ඞ']
    comp=random.choice(ch)

    e = discord.Embed(title=f"{ctx.author.name}'s' amongus Game!", description="> Kill the imposter fast! <",color=0x3498db)

    e1 = discord.Embed(title=f"{ctx.author.name}, You Guessed It Right!", description="> You have won! <",color=0x00FF00)

    e3 = discord.Embed(title=f"{ctx.author.name}, You didn't Click on Time", description="> Timed Out! <",color=discord.Color.red())

    e2 = discord.Embed(title=f"{ctx.author.name}, You Lost!", description=f"> You have lost! < It was {comp}",color=discord.Color.red())

    m = await ctx.reply(
        embed=e,
        components=[[Button(style=1, label="Blue ඞ"),Button(style=3, label="Green ඞ"),Button(style=ButtonStyle.red,label="Red ඞ"),Button(style=ButtonStyle.grey,label="grey ඞ")]
        ],
    )

    def check(res):
      return ctx.author == res.user and res.channel == ctx.channel

    try:
      res = await client.wait_for("button_click", check=check, timeout=5)

      if res.component.label==comp:
        with open('level.json') as f:
            users=json.load(f)
            if str(ctx.author.id) not in users:
                users[str(ctx.author.id)]=1
            if str(ctx.author.id) in users:
                users[str(ctx.author.id)]+=1
                e1.set_footer(text="Your gained 1 point", icon_url=ctx.author.avatar_url)
                await m.edit(embed=e1,components=[],)
            see(users)
      else:
        await m.edit(embed=e2, components=[],)
    except asyncio.TimeoutError:
      await m.edit(
          embed=e3,
          components=[],
      )

#=============Rock Paper Scissors========
@client.command()
async def rps(ctx):
    if ctx.message.channel.id != 881582264419500032:             #Please change this id to your game channel id
      await ctx.reply("Please go to gaming channel, I am waiting there...")
      return
    ch1 = ["Rock","Scissors","Paper"]
    comp = random.choice(ch1)

    yet = discord.Embed(title=f"{ctx.author.display_name}'s ROCK PAPER SCISSORS Game",description=">status: Waiting for a click , 5 sec left" )

    win = discord.Embed(title=f"{ctx.author.display_name}, You won!",description=f">status: You Won -- Bot had chosen {comp}")

    out = discord.Embed(title=f"{ctx.author.display_name}' You didn't click on time",description=">status: Time Out!!")

    lost = discord.Embed(title=f"{ctx.author.display_name}You lost the Game",description=f">status: bot had chosen {comp}")

    tie = discord.Embed(title=f"{ctx.author.display_name} Game Tie>",description=">status: It was tie")

    m = await ctx.reply(
        embed=yet,
        components=[[Button(style=1, label="Rock",emoji="💎"),Button(style=3, label="Paper",emoji="📝"),Button(style=ButtonStyle.red, label="Scissors",emoji="✂")]
        ],
    )

    def check(res):
        return ctx.author == res.user and res.channel == ctx.channel

    try:
      res = await client.wait_for("button_click", check=check, timeout=7)
      player = res.component.label

      if player==comp:
        await m.edit(embed=tie,components=[])

      if player=="Rock" and comp=="Paper":
        await m.edit(embed=lost,components=[])

      if player=="Rock" and comp=="Scissors":
        with open('level.json') as f:
            users=json.load(f)
            if str(ctx.author.id) not in users:
                users[str(ctx.author.id)]=1
            if str(ctx.author.id) in users:
                users[str(ctx.author.id)]+=2
                win.set_footer(text="Your gained 2 points", icon_url=ctx.author.avatar_url)
                await m.edit(embed=win,components=[])
            see(users)

      if player=="Paper" and comp=="Rock":
        with open('level.json') as f:
            users=json.load(f)
            if str(ctx.author.id) not in users:
                users[str(ctx.author.id)]=1
            if str(ctx.author.id) in users:
                users[str(ctx.author.id)]+=2
                win.set_footer(text="Your gained 2 points", icon_url=ctx.author.avatar_url)
                await m.edit(embed=win,components=[])
            see(users)

      if player=="Paper" and comp=="Scissors":
        await m.edit(embed=lost,components=[])

      if player=="Scissors" and comp=="Rock":
        await m.edit(embed=lost,components=[])

      if player=="Scissors" and comp=="Paper":
        with open('level.json') as f:
            users=json.load(f)
            if str(ctx.author.id) not in users:
                users[str(ctx.author.id)]=1
            if str(ctx.author.id) in users:
                users[str(ctx.author.id)]+=2
                win.set_footer(text="Your gained 2 points", icon_url=ctx.author.avatar_url)
                await m.edit(embed=win,components=[])
            see(users)

    except asyncio.TimeoutError:
      await m.edit(
          embed=out,
          components=[],
      )

#=========Whac-A-Mole===========
@client.command(aliases=["wam", "whac"])
async def bonk(ctx, member : discord.Member=None, member1 : discord.Member=None):
  if ctx.message.channel.id != 881582264419500032:            #Please change this id to your game channel id
    await ctx.reply("Please go to gaming channel, I am waiting there...")
    return
  await ctx.reply('```By default quit time is 10 sec of inactivity```')
  points = {ctx.author: 0, member: 0,member1: 0}
  random_time = random.randrange(5,25)
  if member == None:
    await ctx.send(f"{ctx.author.mention}, You need to mention a member to play with.")
  if member == client.user:
    await ctx.send(f"{ctx.author.mention}, Hey! Are you trying to catch me??! Mention someone else.")
  if member.bot == True:
    await ctx.send(f"{ctx.author.mention}, You can't play with a bot.")
  else:
    game = True
    try:
      await ctx.send(f"{ctx.author.mention} and {member.mention} and {member1.mention}, I will alert you when a Mole will jump so you can bonk it 🔨")
    except:
      await ctx.send(f"{ctx.author.mention} and {member.mention}, I will alert you when a Mole will jump so you can bonk it 🔨")

    def check(m):
      return m.author.id == member.id or m.author.id == ctx.author.id or m.author.id == member1.id
    while game:
      try:
        await asyncio.sleep(random_time)
        try:
          await ctx.send(f"{ctx.author.mention}, {member.mention}and {member1.mention}, A Mole has jumped! Type `bonk` to bonk it!")
        except:
          await ctx.send(f"{ctx.author.mention} and {member.mention}, A Mole has jumped! Type `bonk` to bonk it!")

        message = await client.wait_for("message", check=check, timeout=15)

        if message.author.id == member.id and message.content.lower() == "bonk":
          points[member] += 1
          await ctx.send(f"{member.name} has bonk the mole! They have **{points[member]}** point(s)!")

        elif message.author.id == ctx.author.id and message.content.lower() == "bonk":
          points[ctx.author] += 1
          await ctx.send(f"{ctx.author.name} has bonk the mole! They have **{points[ctx.author]}** point(s)!")
        elif message.author.id == member1.id and message.content.lower() == "bonk":
          points[member1] += 1
          await ctx.send(f"{member1.name} has bonk the mole! They have **{points[member1]}** point(s)!")

      except:
        game = False
        embed = discord.Embed(
          title = "Game Over",
          description = "No one bonk 🔨 the mole in time so the game is over. Final Scores Below.")
        try:
          embed.add_field(name = f"{member.name}'s score", value = f"{points[member]}")
          embed.add_field(name = f"{member1.name}'s score", value = f"{points[member1]}")
          embed.add_field(name = f"{ctx.author.name}'s score", value = f"{points[ctx.author]}")
        except:
          embed.add_field(name = f"{member.name}'s score", value = f"{points[member]}")
          embed.add_field(name = f"{ctx.author.name}'s score", value = f"{points[ctx.author]}")
        await ctx.send(embed=embed)

#=============Football========
@client.command()
async def football(ctx):
  if ctx.message.channel.id != 881582264419500032:        #Please change this id to your game channel id
    await ctx.reply("Please go to gaming channel, I am waiting there...")
    return
  options=["LEFT",'MIDDLE','RIGHT']
  computerOption = random.choice(options)
  def goal():
    if computerOption=='LEFT':
        return('.🧍♂')
    if computerOption=='MIDDLE':
        return ('⁃⁃⁃⁃⁃⁃⁃🧍♂⁃⁃⁃⁃⁃')
    if computerOption=='RIGHT':
        return ('⁃⁃⁃⁃⁃⁃⁃⁃⁃⁃⁃⁃⁃🧍♂')

  yet = discord.Embed(title=f"{ctx.author.display_name}'s PENALTY SHOOTOUT GAME",description=">status: Waiting for a click , 5 sec left" )
  yet.add_field(name=".🥅    🥅    🥅", value=goal() , inline=False)
  out = discord.Embed(title=f"{ctx.author.display_name}' You didn't click on time",description=">status: Time Out!!")
  win = discord.Embed(title=f"{ctx.author.display_name}, congratulations!",description="GOOOOOAL !!!!")
  miss = discord.Embed(title="MISSED !!",description="Keeper dived")
  save = discord.Embed(title="SAVED !!",description="Keeper saved")

  def check(msg):
    return msg.author == ctx.author and msg.channel == ctx.channel

  m = await ctx.reply(
        embed=yet,
        components=[[Button(style=1, label="LEFT",emoji="⚽"),Button(style=3, label="MIDDLE",emoji="⚽"),Button(style=ButtonStyle.red, label="RIGHT",emoji="⚽")]
        ],
    )
  missChance=random.randint(1,2)
  try:
    res = await client.wait_for("button_click", check=check, timeout=7)
    shoot = res.component.label
    if shoot == computerOption :
      await m.edit(embed=save,components=[])
    elif missChance == 1:
      await m.edit(embed=miss,components=[])
    else :
      with open('level.json') as f:
            users=json.load(f)
            if str(ctx.author.id) not in users:
                users[str(ctx.author.id)]=1
            if str(ctx.author.id) in users:
                users[str(ctx.author.id)]+=2
                win.set_footer(text="Your gained 2 points", icon_url=ctx.author.avatar_url)
                await m.edit(embed=win,components=[])
            see(users)

  except asyncio.TimeoutError:
    await m.edit(
          embed=out,
          components=[],
      )

#=======GUESS===========
@client.command()
async def guess(ctx):
    if ctx.message.channel.id != 881582264419500032:        #Please change this id to your game channel id
      await ctx.reply("Please go to gaming channel, I am waiting there...")
      return
    ch=['Blue','Green','Red','Grey']
    comp=random.choice(ch)

    e = discord.Embed(title=f"{ctx.author.name}'s' Guessing Game!", description="> Click a button to choose! <",color=0x3498db)
    e1 = discord.Embed(title=f"{ctx.author.name}, You Guessed It Right!", description="> You have won! <",color=0x00FF00)
    e3 = discord.Embed(title=f"{ctx.author.name}, You didn't Click on Time", description="> Timed Out! <",color=discord.Color.red())
    e2 = discord.Embed(title=f"{ctx.author.name}, You Lost!", description=f"> You have lost! < It was {comp}",color=discord.Color.red())

    m = await ctx.reply(
        embed=e,
        components=[[Button(style=1, label="Blue"),Button(style=3, label="Green"),Button(style=ButtonStyle.red,label="Red"),Button(style=ButtonStyle.grey,label="Grey")]
        ],
    )
    def check(res):
        return ctx.author == res.user and res.channel == ctx.channel
    try:
        res = await client.wait_for("button_click", check=check, timeout=5)
        if res.component.label==comp:
          with open('level.json') as f:
            users=json.load(f)
            if str(ctx.author.id) not in users:
                users[str(ctx.author.id)]=1
            if str(ctx.author.id) in users:
                users[str(ctx.author.id)]+=1
                e1.set_footer(text="Your gained 1 point", icon_url=ctx.author.avatar_url)
                await m.edit(embed=e1,components=[],)
            see(users)
        else:
          await m.edit(embed=e2, components=[],)

    except asyncio.TimeoutError:
        await m.edit(
            embed=e3,
            components=[],
        )

client.run(os.environ['TOKEN'])


'''
The following codes are from https://github.com/d-li14/mobilenetv2.pytorch
Some helper functions for PyTorch, including:
    - get_mean_and_std: calculate the mean and std value of dataset.
    - msr_init: net parameter initialization.
    - progress_bar: progress bar mimic xlua.progress.
'''

import errno
import os

import torch
from torch import nn
from torch.nn import init

__all__ = ['get_mean_and_std', 'init_params', 'mkdir_p', 'AverageMeter']

def get_mean_and_std(dataset):
    '''
    Compute the mean and std value of dataset.

    :param dataset: input data
    :return: (mean, std): mean value of dataset, and standard deviation value of dataset
    '''
    dataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=2)

    mean = torch.zeros(3)
    std = torch.zeros(3)
    print('==> Computing mean and std..')
    for inputs, _ in dataloader:
        for i in range(3):
            mean[i] += inputs[:,i,:,:].mean()
            std[i] += inputs[:,i,:,:].std()
    mean.div_(len(dataset))
    std.div_(len(dataset))
    return mean, std

def init_params(net):
    '''
    Init layer parameters.

    :param net: input network to be initialized
    '''
    for module in net.modules():
        if isinstance(module, nn.Conv2d):
            init.kaiming_normal(module.weight, mode='fan_out')
            if module.bias:
                init.constant(module.bias, 0)
        elif isinstance(module, nn.BatchNorm2d):
            init.constant(module.weight, 1)
            init.constant(module.bias, 0)
        elif isinstance(module, nn.Linear):
            init.normal(module.weight, std=1e-3)
            if module.bias:
                init.constant(module.bias, 0)

def mkdir_p(path):
    '''
    make dir if not exist

    :param path: directory path we make
    '''
    try:
        os.makedirs(path)
    except OSError as exc:  # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

class AverageMeter:
    """
    Computes and stores the average and current value
       Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262
    """
    def __init__(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def reset(self):
        """ reset function """
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, num=1):
        """
        update function

        :param val: input current average value
        :param n: number of items for val
        """
        self.val = val
        self.sum += val * num
        self.count += num
        self.avg = self.sum / self.count


#!/usr/bin/python3
"""
 Function that appends a string at the end of a file
"""

def append_write(filename="", text=""):
    """
    return file and a string append
    """

    with open(filename, 'a') as f:
        txt = f.write(text)
    f.closed
    return (txt)


"""
Created on Fri Nov  8 23:23:22 2019

@author: Pratiksha
"""

# app.py for Scara Web App

from flask import Flask, render_template, request
from data import Articles
import cv2
from pyzbar import pyzbar

app = Flask(__name__)

Articles = Articles()
S = []

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

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

@app.route('/articles')
def articles():
	return render_template('articles.html', articles = Articles)

@app.route("/submit", methods=['GET', 'POST'])
def submit():

	if request.method == 'POST':
		f = request.files['file']
		f.save(f.filename)
		image = cv2.imread(f.filename)
		barcodes = pyzbar.decode(image)
		data = ""
		for barcode in barcodes:
		# extract the bounding box location of the barcode and draw the
		# bounding box surrounding the barcode on the image
			(x, y, w, h) = barcode.rect
			cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)

		# the barcode data is a bytes object so if we want to draw it on
		# our output image we need to convert it to a string first
			data = barcode.data.decode("utf-8")

			for i in range(len(Articles)):
				if data==Articles[i]['id']:
					S.append([Articles[i]['title'],Articles[i]['mrp']])

	return render_template('bill.html', data=S)

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


# -*- coding:utf-8 -*-
from __future__ import print_function
import numpy
import theano.tensor as T
import cv2
import cPickle
numpy.random.seed(1337)  # for reproducibility

from PIL import Image

from keras.models import Sequential
from keras.layers import Input, Dense, Dropout, LSTM
from keras.layers.convolutional import Conv2D, MaxPooling2D, AveragePooling2D
from keras.optimizers import SGD
from keras.utils import np_utils
from keras import backend as K

img_rows, img_cols = 143, 143
nb_classes = 2
nb_epoch = 60
batch_size = 10

def loadData(file):
    with open(file, 'r') as f:
        train_x, train_y = cPickle.load(f)
        valid_x, valid_y = cPickle.load(f)
        test_x, test_y = cPickle.load(f)
    rval = [(train_x, train_y), (valid_x, valid_y), (test_x, test_y)]
    return rval

'''
def Net_model():

    input = Input(shape=(img_rows, img_cols))

    lstm = LSTM(64)
    #lstm = LSTM(32, return_state=True)(lstm)
    #lstm = LSTM(32, return_state=True)(lstm)

    hidden = Dense(1000, activation='relu')
    out = Dropout(0.5)
    predictions = Dense(nb_classes, activation = 'softmax')

    model = Model(inputs = input, output=predictions)
    model.compile(optimizer=['rmsprop'],
                  loss = 'categorical_crossentropy',
                  metrix = ['accuracy'])
    return model
'''

def Net_model():
    model = Sequential()
    model.add(LSTM(32, return_sequences=True, input_shape=(img_rows, img_cols)))
    model.add(LSTM(128,return_sequences=True))
    model.add(Dropout(0.5))
    model.add(LSTM(256))
    model.add(Dense(1000, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(nb_classes, activation='softmax', name='output_layer'))

    model.compile(loss='categorical_crossentropy',
                  optimizer = 'rmsprop',
                  metrics = ['accuracy']
                  )
    return model

def train_model(model, x_train, y_train, x_val, y_val):
    model.fit(x_train, y_train, batch_size = batch_size, epochs = nb_epoch,
              verbose=1, validation_data=(x_val, y_val))
    model.save_weights('./weights/model_weights.h5', overwrite = True)

def test_model(model, x_test, y_test):
    model.load_weights('./weights/model_weights.h5')
    score = model.evaluate(model, x_test, y_test)
    print('Test loss:', score[0])
    print('Test accuracy:', score[1])
    return score

if __name__ == '__main__':
    (X_train, Y_train), (X_val, Y_val), (X_test, Y_test) = loadData('./data/Data2.pkl')

    X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols)
    X_val = X_val.reshape(X_val.shape[0], img_rows, img_cols)
    X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols)

    print('X_train shape:', X_train.shape)
    print(X_train.shape[0], 'train samples')
    print(X_val.shape[0], 'validate samples')
    print(X_test.shape[0], 'test samples')

    Y_train = np_utils.to_categorical(Y_train, nb_classes)
    Y_val = np_utils.to_categorical(Y_val, nb_classes)
    Y_test = np_utils.to_categorical(Y_test, nb_classes)

    model = Net_model()
    train_model(model, X_train, Y_train, X_val, Y_val)
    print (' the code is ok!!!')


"""
uniquePath1
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?
"""

class Solution(object):
    def uniquePathsA(self, m, n):
        """

        :param m:
        :param n:
        :return:
        """
        dp = [[0]*n for x in range(m)]
        dp[0][0] = 1
        for x in range(m):
            for y in range(n):
                if x + 1 <m:
                    dp[x+1][y] += dp[x][y]
                if y + 1 < n:
                    dp[x][y+1] += dp[x][y]
        return dp[m-1][n-1]

    def uniquePathsB(self, m, n):
        """

        :param m:
        :param n:
        :return:
        """
        if m < n:
            m, n = n, m
        dp = [n] * n
        dp [0] = 1
        for x in range(m):
            for y in range(n - 1):
                dp[y + 1] += dp[y]
        return dp[n - 1]

    #m行n列, 需要往下走m-1步, 往右走n-1步, 也就是求C(m-1+n-1, n-1)或C(m-1+n-1, m-1)。

    # @return an integer
    def uniquePathsC(self, m, n):
        N = m - 1 + n - 1
        K = min(m, n) - 1
        # calculate C(N, K)
        res = 1
        for i in xrange(K):
            res = res * (N - i) / (i + 1)
        return res

"""
Unique Paths II
Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

"""

"""
Minimum Path Sum
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

"""

"""
Dungeon Game
The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.

The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.

Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).

In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.

Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.

For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
"""

class Solution(object):
    def __init__(self):
        self.depth = 0
        self.nestedList = []
    def depthSum(self, nestedList):
        """
        :type nestedList: List[NestedInteger]
        :rtype: int
        """
        nest = nestedList

        if isinstance(type(nest), int):
            return self.depth + 1
        else:
            for n in nest:
                if isinstance(type(n), int):
                    self.depth = self.depth + 1
                else:
                    self.depth = self.depth + self.depthSum(n)
        return self.depth

class Solution(object):
    def depthSum(self, nestedList):
        """
        :type nestedList: List[NestedInteger]
        :rtype: int
        """
        if len(nestedList) == 0: return 0
        stack = []
        sum = 0
        for n in nestedList:
            stack.append((n, 1))
        while stack:
            next, d = stack.pop(0)
            if next.isInteger():
               sum += d * next.getInteger()
            else:
                for i in next.getList():
                    stack.append((i,d+1))
        return sum


#!/usr/bin/env python3
#
#     CLIMPORN
#
#  Prepare 2D maps (monthly) that will later become a movie!
#  NEMO output and observations needed
#
#    L. Brodeau, January 2019
#
import sys
import glob
#import argparse as ap
import numpy as nmp
from PIL import Image
#
# ClimPorn:
from   climporn.utils import chck4f
import climporn.nemo_hboxes as nhb

#nghost = 3

# About files to use:
fpref_p = './figs/CURLOF/CURLOF_TROPICO05_NST-_ALL_'
fsuff_p = '_on2.png'

fpref_c = './figs/CURLOF/CURLOF_CALEDO10-_ALL_'
fsuff_c = '_on2.png'

fpref_o = './figs/montage_CURLOF_TROPICO05-CALEDO10_'

nratio  = 5

ncrop_chld = 3
#ncrop_chld = 1
#ncrop_chld = 3
#ncrop_chld = 10

ipc = 35 ; # location (Fortran indexing) of bottom left corner AGRIF_FixedGrids.in)
jpc = 43 ; # of the child box into parent box in Agrif ! (as in

cdate = '2016-12-22_00'

# Final box to keep (mind that for images it's flipped upside down!):
j1b = 336 ; i1b = 0
j2b = 680 ; i2b = int(16./9.*float(j2b-j1b))

# COLOR FOR THE NESTING BOX LINE:
# (0-255)     R   G   B  transparency
#rgb_f = [ 0 , 0 , 0 , 255 ] ; # solid black
rgb_f = [ 255, 237, 0 , 255 ] ; # yellow ON (255,237,0)
npf = 2 ; # number of poins for frame...

list_im_p = glob.glob(fpref_p+"*"+fsuff_p)
list_im_c = glob.glob(fpref_c+"*"+fsuff_c)

nbf = len(list_im_c)
if len(list_im_p) != nbf:
    print(' Problem different number of images between parent and child!', len(list_im_p), nbf) ; sys.exit(0)

for j in range(nbf):

    cf_prnt = list_im_p[j]
    chck4f(cf_prnt)

    cdate = str.replace( cf_prnt, fpref_p, '')
    cdate = str.replace( cdate, fsuff_p, '')

    cf_chld =  fpref_c+cdate+fsuff_c ; # that's what we expect
    chck4f(cf_chld)

    cf_out = str.replace( cf_prnt, fpref_p, fpref_o)
    cf_out = str.replace( cf_out, fsuff_p, '.png')

    #print(cf_prnt,' ',cf_chld,' ', cdate, )
    #print(cf_out)
    #sys.exit(0)

    chld = Image.open(cf_chld)
    prnt = Image.open(cf_prnt)

    (nyc,nxc,nrgb_c) = nmp.shape(chld)
    (nyp,nxp,nrgb_p) = nmp.shape(prnt)

    #print(' *** Image array shape for child  = ', nyc,nxc,nrgb_c)
    #print(' *** Image array shape for parent = ', nyp,nxp,nrgb_p)

    if nrgb_c != 4: print(' Problem #1 with your child image, not what we expected!') ; sys.exit(0)
    if nrgb_p != 4: print(' Problem #1 with your parent image, not what we expected!') ; sys.exit(0)

    if nxp%nratio!=0 or nyp%nratio!=0: print(' Problem #1 with your parent image, it shoud be a multiple of '+str(nratio)+'!') ; sys.exit(0)

    xchld = nmp.array(chld)
    xprnt = nmp.array(prnt)

    chld.close()
    prnt.close()

    print("xchld", nmp.shape(xchld))
    print("xprnt", nmp.shape(xprnt))
    #print(xprnt[0,0,:])
    #print(xprnt[100,100,:])

    #ip = (ipc - 1) * nratio + nghost
    #jp = (jpc - 1) * nratio + nghost
    ip = (ipc + 1) * nratio + 2  # I have no fucking clue why ????
    jp = (jpc + 1) * nratio + 2  # I have no fucking clue why ????
    #ip = ipc * nratio
    #jp = jpc * nratio

    # Child array we keep after croping:
    if ncrop_chld >= 1:
        XC = xchld[ncrop_chld:-ncrop_chld,ncrop_chld:-ncrop_chld]
    else:
        XC = xchld[:,:]
    (Ny,Nx,Nr) = nmp.shape(XC)

    #print(" shape XC =", Ny,Nx,Nr)

    # Drawing  frame:
    for i in range(4):
        XC[     0:npf,:,i] = rgb_f[i]
        XC[Ny-npf:Ny ,:,i] = rgb_f[i]
        XC[:,     0:npf,i] = rgb_f[i]
        XC[:,Nx-npf:Nx ,i] = rgb_f[i]

    j1 = nyp-jp-Ny - ncrop_chld
    i1 = ip        + ncrop_chld
    xprnt[j1:j1+Ny,i1:i1+Nx,:] = XC[:,:,:]

    image_out  = Image.fromarray(xprnt[j1b:j2b,i1b:i2b,:])

    #cf_chld = './child.png'
    ## Then save it:
    #image_chld.save(cf_chld)
    #print(' *** Image '+cf_chld+' saved!\n')

    # Then save it:
    image_out.save(cf_out)
    print(' *** Image '+cf_out+' saved!\n')

    del XC, xprnt, xchld