import math
from typing import List

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

def get_data(file_name,p = 0.6,add_intent = False):
    with open("./data/train_data/{}.train".format(file_name),'r') as f:
        lines = f.readlines()

    train_x = []
    train_y = []
    x = []; y = []
    for line in lines:
        line = line.strip().split('\t')
        if(len(line)>1):
            x.append(line[0])
            y.append(line[1])
        else:
            if add_intent:
                x.append('intent');y.append('B-'+file_name+'_intent')
            train_x.append(x);train_y.append(y)
            x = [];y = []
    if(x!=[]):
        if add_intent:
            x.append('intent');y.append('B-'+file_name+'_intent')
        train_x.append(x);train_y.append(y)
    nums = len(train_x)
    x_train = train_x[0:int(p*nums)];x_valid = train_x[int(0.8*nums):int(0.9*nums)];x_test = train_x[int(0.9*nums):]
    y_train = train_y[0:int(p*nums)];y_valid = train_y[int(0.8*nums):int(0.9*nums)];y_test = train_y[int(0.9*nums):]
    return x_train,x_valid,x_test,y_train,y_valid,y_test

def get_combined_data(p=0.6,add_intent = False):
    x_train = [];x_valid=[];x_test=[];y_train=[];y_valid=[];y_test=[]
    for file_name in ['ask_price','time_delay']:
        x_train_t,x_valid_t,x_test_t,y_train_t,y_valid_t,y_test_t = get_data(file_name,p,add_intent)
        x_train.extend(x_train_t);x_valid.extend(x_valid_t);x_test.extend(x_test_t)
        y_train.extend(y_train_t);y_valid.extend(y_valid_t);y_test.extend(y_test_t)
    return x_train,x_valid,x_test,y_train,y_valid,y_test

def get_combined_data_sep_label(p=0.6):
    x_train = [];x_valid=[];x_test=[];y_train=[];y_valid=[];y_test=[]
    for file_name in ['ask_price','time_delay','price']:
        x_train_t,x_valid_t,x_test_t,y_train_t,y_valid_t,y_test_t = get_data(file_name,p)

        y_train_t = [[i.replace('price','price.{}'.format(file_name)) for i in sample] for sample in y_train_t]
        y_valid_t = [[i.replace('price','price.{}'.format(file_name)) for i in sample] for sample in y_valid_t]
        y_test_t = [[i.replace('price','price.{}'.format(file_name)) for i in sample] for sample in y_test_t]

        x_train.extend(x_train_t);x_valid.extend(x_valid_t);x_test.extend(x_test_t)
        y_train.extend(y_train_t);y_valid.extend(y_valid_t);y_test.extend(y_test_t)
    return x_train,x_valid,x_test,y_train,y_valid,y_test

def batch_iter(data, batch_size, shuffle=False):
    batch_num = math.ceil(len(data) / batch_size)
    index_array = list(range(len(data)))

    if shuffle:
        np.random.shuffle(index_array)

    for i in range(batch_num):
        indices = index_array[i * batch_size: (i + 1) * batch_size]
        examples = [data[idx] for idx in indices]

        examples = sorted(examples, key=lambda e: len(e[0]), reverse=True)
        src_sents = [e[0] for e in examples]
        tgt_sents = [e[1] for e in examples]

        yield src_sents, tgt_sents


""" Code forloading data. """
import numpy as np
import random
import tensorflow as tf
import pickle
import os
import time

from utils import get_image_from_embedding

class DataGenerator_embedding_one_instance(object):

    def __init__(self, num_classes, num_samples_per_class, batch_size):
        self.batch_size = batch_size
        self.num_samples_per_class = num_samples_per_class  # K=1+15
        self.num_classes = num_classes
        self.dim_input = 640
        self.dim_output = self.num_classes
        self.dataset_name = 'train' # set as default

    def get_instance(self, filenames_by_label, embedding_by_filename):
        def _build_one_instance_py(): # 一个Task，不包含label，仅embeddings
            classes_list = list(filenames_by_label.keys())
            sampled_character_folders = random.sample(classes_list, self.num_classes)
            random.shuffle(sampled_character_folders)
            images = []
            # images_test = []

            for i in range(self.num_classes):
                # 目标种类集：shuffled_folders
                class_now = sampled_character_folders[i]
                print('class now: {}'.format(class_now))
                # files_of_class_now = np.random.choice(filenames_by_label[class_now], nb_samples, replace=False)
                files_of_class_now = random.sample(filenames_by_label[class_now], self.num_samples_per_class)
                # files_of_class_now_test = [[i] for i in files_of_class_now]
                # 当前类下所有图片文件
                samples_of_this_class = [embedding_by_filename[filename] for filename in files_of_class_now]
                images.extend(samples_of_this_class)
                # images_test.extend(files_of_class_now_test)
            embedding_array = np.array(images, dtype=np.float32)
            # embedding_array_test = np.array(images_test, dtype=np.str)
            # print('shape: {}'.format(embedding_array_test.shape))
            # for class_id, class_name in enumerate(shuffled_folders):
            #     all_images_this_class = np.random.choice(filenames_by_label[class_name], nb_samples, replace=False)
            #     image_paths.append(all_images_this_class)
            #     # class_ids.append([[class_id]] * nb_samples)
            #     class_ids.append(self.one_hot(class_id, num_classes) * nb_samples)
            # label_array = np.array(class_ids, dtype=np.int32)
            # path_array = np.array(image_paths)
            # embedding_array = np.array([[embedding_by_filename[image_path]
            #                              for image_path in class_paths]
            #                             for class_paths in path_array])
            # embedding_array = np.reshape(embedding_array, [num_classes*nb_samples, self.dim_input])
            # label_array = np.reshape(label_array, [num_classes*nb_samples, num_classes])
            # print(embedding_array.shape)
            # print(label_array.shape)
            return embedding_array

        # 避免直接操作 Tensor，使用py_fun
        output_list = tf.py_func(_build_one_instance_py, [], [tf.float32])
        instance_input = output_list
        # 对 input data进行切分
        return instance_input

    def get_batch(self):
        dataset_path = 'data/miniimagenet/train_embeddings.pkl'
        print('reading the raw_file...')
        raw_data = pickle.load(tf.gfile.Open(dataset_path, 'rb'), encoding='iso-8859-1')
        filenames_by_label = {}
        embedding_by_filename = {}
        for key_, value_ in enumerate(raw_data['keys']):
            _, class_label_name, image_file_name = value_.split('-')
            image_file_class_name = image_file_name.split('_')[0]
            # print('image_file_class_name is : {}'.format(image_file_class_name))
            assert class_label_name == image_file_class_name
            embedding_by_filename[image_file_name] = raw_data['embeddings'][key_]
            if class_label_name not in filenames_by_label:
                filenames_by_label[class_label_name] = []
            filenames_by_label[class_label_name].append(image_file_name)
        # 来自 LEO的Batch方式，获取单个Task
        one_instance = self.get_instance(filenames_by_label, embedding_by_filename)
        # task_batch = tf.train.batch(one_instance,
        #                                     batch_size=self.batch_size,
        #                                     capacity=1000,
        #                                     shapes=[80, 640],
        #                                     min_after_dequeue=0,
        #                                     enqueue_many=False,
        #                                     num_threads=1)
        task_batch = tf.train.shuffle_batch(one_instance,
                                    batch_size=self.batch_size,
                                    capacity=1000,
                                    shapes=[self.num_classes*self.num_samples_per_class, self.dim_input],
                                    min_after_dequeue=0,
                                    enqueue_many=False,
                                    num_threads=1)
        # label预处理：首先为：[0, 0, 0..0, 1, 1, 1..1,..]
        all_image_batches, all_label_batches = [], []
        labels = [num for num in range(self.num_classes) for _ in range(self.num_samples_per_class)]
        examples_per_task = self.num_classes*self.num_samples_per_class
        examples_per_batch = examples_per_task * self.batch_size
        # 原本task_batch的shape为：[4, 5, 1 ,640]，不确定长度可使用tf.reshape(t, [-1, self.dim_input])
        task_batch = tf.reshape(task_batch, [examples_per_batch, self.dim_input])

        for i in range(self.batch_size):
            image_batch = task_batch[i * examples_per_task: (i+1) * examples_per_task] # 一个task的数据
            label_batch = tf.convert_to_tensor(labels)
            new_label_list = []
            new_list = []

            for k in range(self.num_samples_per_class):
                class_idx = tf.range(0, self.num_classes)
                # class_idx = tf.random_shuffle(class_idx)  # 使用shuffle与否在训练阶段应该没影响。
                true_idx = class_idx * self.num_samples_per_class + k # 每隔num_sampler_per_class个距离选一个
                new_list.append(tf.gather(image_batch, true_idx)) # 使用append是为了把array数据包含，不能使用extend，因为这里的
                                                                  # tf.gather()返回一个tensor，并不是可迭代对象，也造成需要使用
                                                                  # tf.concat()函数
                new_label_list.append(tf.gather(label_batch, true_idx))

            new_list = tf.concat(new_list, 0)
            new_label_list = tf.concat(new_label_list, 0)
            all_label_batches.append(new_label_list)
            all_image_batches.append(new_list)

        all_image_batches = tf.stack(all_image_batches)
        all_label_batches = tf.stack(all_label_batches)
        all_label_batches = tf.one_hot(all_label_batches, self.num_classes)
        return all_image_batches, all_label_batches

def main():
    num_classes = 5
    k_tr = 1
    k_val = 15
    batch_size = 4
    data_generator = DataGenerator_embedding_one_instance(num_classes=num_classes,
                                                          num_samples_per_class=k_tr+k_val,
                                                          batch_size=batch_size)
    a_batch_data = data_generator.get_batch()
    with tf.Session() as sess:
        sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])
        coord = tf.train.Coordinator() # 控制 tf.train.shuffle_batch()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)
        # feed_dict中数据不能为 tensor
        # feed_dict = {x: data[0], y:data[1]}
        inputa, labela = sess.run(a_batch_data) # 分别为 (4, 80, 640)与(4, 80, 5)
        print('shape of input: {} and label: {}'.format(inputa.shape, labela.shape))
        # print('input[0][0][:3]: {}'.format(inputa[0][0][:3]))
        # print('label[0][0]: {}'.format(labela[0][0]))
        print('label_all:{}'.format(labela))

        coord.request_stop()
        coord.join(threads)

if __name__ == '__main__':
    main()


import unittest
import HTMLTestRunner

if __name__ == '__main__':
    testsuite = unittest.TestLoader().discover('.')
    unittest.TextTestRunner(verbosity=2).run(testsuite)
    file_name = r'G:\First-Repository\test\HTMLTestRunner_output.html'
    with open(file_name, 'wb') as f:
        runner = HTMLTestRunner.HTMLTestRunner(stream=f, title='报告标题', description='报告描述')
        runner.run(testsuite)


import lcm
import time

from ppar import msg_t

lc = lcm.LCM()

msg = msg_t()
msg.utime = int(time.time() * 1000000)
msg.RE_VERSION = 1
msg.requeID = 1
msg.requeOrig = "testPPARmsg_t.py"

msg.datastr = "['constants']['earth']['gravity']"
#msg.datastr = "['plots'][1]['signals'][0]['channel']"
#msg.datastr = "['sensors']['microstrain']['dt']"
#msg.datastr = "['other']"

lc.publish("PPAR_REQUEST_EXAMPLE", msg.encode())


import tkinter as tk
from tkinter import *
from PIL import ImageTk
from tkinter import font
from moviepy.editor import VideoFileClip
from moviepy.editor import TextClip

root = tk.Tk()
root.geometry("700x500")

goofyfont = font.Font(size=24)
smolgofyfont = font.Font(family="Fixedsys Regular",size=18)
img= PhotoImage(file='content/right.png', master= root)
img_label= Label(root,image=img)
img_label.place(x=0, y=0)

def india5():
    video_path = "content/top5india.mp4"
    video = VideoFileClip(video_path)
    video.preview()

def india4():
    video_path = "content/top4india.mp4"
    video = VideoFileClip(video_path)
    video.preview()
def india3():
    video_path = "content/top3india.mp4"
    video = VideoFileClip(video_path)
    video.preview()
def india2():
    video_path = "content/top2india.mp4"
    video = VideoFileClip(video_path)
    video.preview()
def india1():
    video_path = "content/top1india.mp4"
    video = VideoFileClip(video_path)
    video.preview()

button1 = Button(text="",font=smolgofyfont, fg="red",command=india5)
button1.pack()

button2 = Button(text="SUfSSSS",font=smolgofyfont,fg="blue",command=india4)
button2.pack()

button3 = Button(text="SUSSasdSS",font=smolgofyfont,fg="green",command=india3)
button3.pack()

button4 = Button(text="sussy black people",font=smolgofyfont,fg="pink",command=india2)
button4.pack()

button5 = Button(text="SUSSfdasSS",font=smolgofyfont,fg="gray",command=india1)
button5.pack()

Title = Label(text="TOP 5 INDA",font=goofyfont)
Title.pack()

root.mainloop()


import numpy as np
import random

# Constant value deciding if 0 or -1 (or any other value) indicates no connection between two vertices
NOCON = 0

# Traveling Salesman Problem
# Author: Thomas Aamand Witting
# email:  wittingt@oregonstate.edu
##### DESCRIPTION #####
# The implemented algorithm is a greedy approach at solving the Traveling Salesman Problem.
# The algorithm will consider multiple visits to the same vertex if necessary - however, it
# will only do this in cases where it is strictly necessary - i.e. no other option is available.
# In a such case, it will always go to an unexplored vertex if possible, no matter if it is
# cheaper to do otherwise. In general, the algorithm will always travel along the cheapest edge
# which goes to an unvisited vertex.
#
# Arguments:
#   M: weighted adjacency matrix, numpy array of dim(n, n)
#   K: Max computational steps, int
def tsp(M, K):
    optimal_tour = [0]
    optimal_value = 0

    # Current city, initialize to 0 (city 1)
    c_cur = 0

    # Blacklisted city used when backtracking
    backtrack = False
    blacklist = -1

    for _ in range(K):
        min_cost = np.inf
        min_city = -1

        # Find closest relevant neighbour
        for j in range(len(M)):
            # If we just backtracked we do not want to explore a
            # previously discovered route
            if backtrack and j == blacklist:
                continue

            # Check if neighbour is closer than previous neighbours
            if M[c_cur][j] != NOCON and j not in optimal_tour and M[c_cur][j] < min_cost:
                min_cost = M[c_cur][j]
                min_city = j

        # Reset backtracking variables
        backtrack = False
        blacklist = -1

        # If no relevant neighbour is found, it either means
        # we have visited all cities or that we are stuck
        if min_city == -1:
            # If we have visited all cities
            if len(optimal_tour) >= len(M):
                tour_idx = len(optimal_tour) - 1
                city = c_cur
                while tour_idx >= 0:
                    # See if we can go directly back to initial city: if yes, we're done.
                    # Otherwise go back through optimal_tour until we are able to (but keeping the already visited cities in the tour)
                    if M[city][0] != NOCON:
                        optimal_tour.append(0)
                        optimal_value = 0

                        # Recompute optimal value along the tour
                        for i in range(1, len(optimal_tour)):
                            optimal_value += M[optimal_tour[i-1]][optimal_tour[i]]

                        # return optimal tour and its cost. (adds 1 to each city 'name' to be consistent with the
                        # assignment notation (1-index based)
                        return [[c + 1 for c in optimal_tour], optimal_value]
                    else:
                        optimal_tour.append(optimal_tour[tour_idx-1])
                        optimal_value = M[city][optimal_tour[tour_idx-1]]
                        tour_idx -= 1
                        city = optimal_tour[tour_idx]

                raise Exception("Could not find a route in Graph")

            # If we are stuck
            else:
                # Backtrack to random city
                # Get random index in optimal_tour that is not
                # the latest city
                idx = random.randint(0, len(optimal_tour) - 2)
                backtrack = True

                # Blacklist the closest neighbour to the random city
                blacklist = optimal_tour[idx+1]

                # Update variables
                c_cur = optimal_tour[idx]
                optimal_tour = optimal_tour[:idx+1]
                optimal_value = 0

                for i in range(len(optimal_tour) - 1):
                    optimal_value += M[i][optimal_tour[i+1]]

                # Continue search
                continue

        c_next = min_city

        # Update tour and cost of tour so far
        optimal_tour.append(c_next)
        optimal_value += M[c_cur][c_next]

        c_cur = c_next

    raise Exception("Could not find a route in K steps")

# Actual cheapest cost: 88
# Found cost: 88
M1 = np.array([[0, 1, 0, 0, 1],
[1, 0, 42, 1, 0],
[0, 42, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 0, 1, 0]])

# Actual cheapest cost: 5
# Found cost: 5
M2 = np.array([[0, 1, 0, 0, 1],
[1, 0, 42, 1, 1],
[0, 42, 0, 1, 1],
[0, 1, 1, 0, 1],
[1, 1, 1, 1, 0]])

# Actual cheapest cost: 37
# Found cost: can't solve in reasonable K? (bug with code is likely)
M3 = np.array([[0, 1, 0, 0, 1, 0, 1, 0],
[1, 0, 42, 1, 1, 10, 0, 0],
[0, 42, 0, 1, 1, 0, 0, 1],
[0, 1, 1, 0, 1, 0, 0, 0],
[1, 1, 1, 1, 0, 4, 0, 0],
[0, 10, 0, 0, 4, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 10],
[0, 0, 1, 0, 0, 0, 10, 0]])

# Example of "weakness"
# "Weakness" as it depends on context:
# Do we want cheaper cost or less vertex visits on the tour?
# Actual cheapest cost: 18
# Found cost: 113
M4 = np.array([[0, 1, 0, 0, 0, 100, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 0, 0, 0, 0],
[100, 0, 0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]])

K = 1000000
tour, cost = tsp(M5, K)
print("Cost of tour: " + str(cost))
print("Optimal tour: " + str(tour))


from flask import Flask, render_template, request, jsonify
import requests
from Downloads.Models import *
from Downloads.helper import *

app = Flask(__name__)
@app.route('/extendDeadline/', methods=['GET','POST'])
def extendDeadline():
    if request.method == 'POST':
        details = request.form
        contestID = details['contest_id']  # contest ID
        deadline = details['deadline']  # contest deadline
        extendDead(contestID,deadline)
        return "success"

    return render_template("extendDeadline.html")

if __name__=='__main__':
    app.run(host='127.0.0.1',port = '5050')


'''
Author: Melissa Dunn
'''
import re
import tkinter as tk

class IO:
	def read(self, location, memory):
		'''Read a word from the keyboard into a specific location in memor'''

		while True:
			print("Enter an integer: ", end="")

			user_input = input()

			if(re.fullmatch("^[+-]?\d{1,6}", user_input) is None):
				print("Invalid input. Try again.")
			else:
				break

		memory.store(location, (user_input).zfill(5))
		if user_input.startswith("-"):
			user_input = (user_input).zfill(5)
			user_input = user_input.replace("-","1")
		else:
			user_input = user_input.replace("+", "0")
		memory.store(location, (user_input).zfill(5))

	def write(self, location, memory):
		'''Write a word from a specific location in memory to screen.'''

		output = re.sub(r'^1', "-", memory.get(location))
		print(f"Contents of {int(location)} is {int(output)}")

	def read_gui(self, location, memory):
		'''Read a word from the keyboard into a specific location in memory'''
		loop_bool = True
		def enter(wait):
			nonlocal loop_bool

			wait.set(1)
			user_input = inputtxt.get(1.0, "end-1c")

			if re.fullmatch("^[+-]?\d{1,4}", user_input) is None:
				loop_bool = True
			else:
				if user_input.startswith("-"):
					user_input = (user_input).zfill(5)
					user_input = user_input.replace("-","1")
				else:
					user_input = user_input.replace("+", "0")
				memory.store(location, user_input)
				loop_bool = False

		while loop_bool:
			integer_label = tk.Label(name="int_lbl", fg="#000", text=f"Enter an integer for location {location}:")
			integer_label.grid(columnspan=1, column=0, row=4)
			inputtxt = tk.Text(height = 1, width = 5, fg="black", bg="white", name="inputtxt")
			inputtxt.config(highlightbackground = "black", highlightcolor= "blue", highlightthickness=2)
			inputtxt.grid(columnspan=1, column=1, row=4)
			wait_var = tk.IntVar()
			printbutton = tk.Button(text="Enter", fg="#000", command=lambda:enter(wait_var), name="printbutton")
			printbutton.grid(columnspan=1, column=2, row=4)
			printbutton.wait_variable(wait_var)

	def write_gui(self, location, memory):
		'''Write a word from a specific location in memory to screen.'''
		output = re.sub(r'^1', "-", memory.get(location))
		tk.Label(fg="green", text=f"Contents of {int(location)} is {int(output)}", name="contents").grid(columnspan=1, column=2, row=5)


import discord
import os
import traceback

from discord.ext import commands

def list_module(directory):
    return (f for f in os.listdir(directory) if f.endswith('.py'))

class HeyShawarma(commands.Bot):
    def __init__(self, *args, **kwargs):
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(command_prefix="hs.", intents=intents, *args, **kwargs)

    async def setup_hook(self) -> None:
        moduleFolders = ['commands']
        for module in moduleFolders:
            for extension in list_module(module):
                extensionToLoad = f'{module}.{os.path.splitext(extension)[0]}'
                try:
                    await self.load_extension(extensionToLoad)
                    print(f'Loaded module extension {extensionToLoad}')
                except Exception:
                    print(f'Failed to load module {extensionToLoad}', file=sys.stderr)
                    traceback.print_exc()


import random
import os
import json
import networkx as nx
import matplotlib.pyplot as plt

MAX_POPULATION = 8
INITIAL_POPULATION_PER_REGION = 4

class Region:

    country_id = -1
    id = -1
    adjacency_vector = []
    population = 0

    def __init__(self):
        pass

class Arena:

    regions = []
    regions_count = 0
    adjacency_matrix = []
    countries = 0
    country_regions = []
    country_scores = []
    selected_region = -1
    scores = []
    G = 0
    _op = 0

    active_player = 0
    max_players = 0
    round = 0

    def __init__(self):
        pass

    def _throw_dices(self, dices):
        result = 0
        for dice in range(dices):
            result = result + random.randint(1, 6)
        return dices  # debug

    def act(self, region_id, end_turn=False):
        if end_turn:
            self.end_turn()
            return 0

        if self.selected_region == -1:
            if self.regions[region_id].country_id != self.active_player or region_id == self.selected_region:
                return -1
            else:
                self.selected_region = region_id
                # print('SEL: ', region_id, 'CO:', self.active_player)
                return 0

        src_region_id = self.selected_region
        target_region_id = region_id

        src_region = self.regions[src_region_id]
        target_region = self.regions[target_region_id]

        if target_region.country_id == self.active_player:
            return -1

        if src_region.adjacency_vector[target_region_id] == 0:
            return -1

        # print('BAT: ', self.selected_region, '->', target_region_id)

        score_before = self.scores[src_region.country_id]

        src = self._throw_dices(src_region.population)
        target = self._throw_dices(target_region.population)

        if src > target:
            target_region.population = src_region.population - 1
            src_region.population = 1

            self.country_regions[target_region.country_id].remove(
                target_region_id)
            target_region.country_id = src_region.country_id
            self.country_regions[target_region.country_id].extend([
                target_region_id])
            self._calculate_scores()
        else:
            src_region.population = 1

        score_after = self.scores[src_region.country_id]
        score_diff = score_after - score_before
        self.selected_region = -1
        return score_after * 0.2
        # if score_diff > 0:
        #     return 0.2 * score_diff
        # else:
        #     return 0

    def new_game(self):
        self._build_country_map()
        self._plant_population()
        self._calculate_scores()
        self.max_players = len(self.scores)
        # self.print_country(0)

    def end_turn(self):
        tod = self.scores[self.active_player]
        rgs = self.country_regions[self.active_player]

        if len(rgs) > 0:
            gltod = 1000
            while tod > 0:
                idx = 0
                gltod -= 1
                if gltod <= 0:
                    tod = 0
                if len(rgs) > 1:
                    idx = rgs[random.randint(
                        0, len(rgs) - 1)]
                canbe = False
                for i in range(len(rgs)):
                    if self.regions[rgs[i]].population < MAX_POPULATION:
                        canbe = True
                if not canbe:
                    tod = 0
                if self.regions[idx].population < MAX_POPULATION:
                    tod = tod - 1
                    self.regions[idx].population = self.regions[idx].population + 1

        self.active_player = self.active_player + 1
        if self.active_player >= self.max_players:
            self.active_player = 0
        self.selected_region = -1
        pass

    def draw_country_network(self, country_id, file_name, label=''):
        nodelist = []
        edgelist = []
        for i in range(self.regions_count):
            nodelist.extend([i])
        for region_id in self.country_regions[country_id]:
            # nodelist.extend([region_id])
            for edge in self.G.edges(region_id):
                if self.country_regions[country_id].count(edge[0]) > 0 and self.country_regions[country_id].count(edge[1]) > 0:
                    edgelist.extend([edge])

        options = {
            'node_size': 300,
            'width': 1,
            'node_color': '#EFEFEF',
            'font_size': 10,
            'nodelist': list(nodelist),
            'edgelist': list(edgelist),
            'with_labels': True
        }
        plt.get_current_fig_manager().canvas.figure.clear()
        nx.draw_kamada_kawai(self.G, **options)  # best so far
        plt.suptitle(label, y=0.05, x=0.3)
        plt.savefig(file_name)

    def draw_network(self):
        options = {
            'node_size': 300,
            'width': 1,
            'node_color': '#EFEFEF',
            'font_size': 10,
            'with_labels': True
        }
        nx.draw_kamada_kawai(self.G, **options)  # best so far
        plt.get_current_fig_manager().canvas.figure.clear()
        plt.savefig('env/graph.png')

    def _get_connections(self, node, nodes):
        cid = 0
        connections = 0
        for i in self.adjacency_matrix[node]:
            self._op += 1
            if nodes.count(cid) == 0 and i == 1 and self.regions[cid].country_id == self.regions[node].country_id:
                nodes.extend([cid])
                connections = connections + 1 + \
                    self._get_connections(cid, nodes)
            cid += 1
        return connections

    def _calculate_scores(self, country_id=-1):
        if country_id == -1:
            self.scores = list(map(lambda x: 1, range(self.countries)))
        for region in self.regions:
            if country_id >= 0 and region.country_id != country_id:
                continue
            score = self._get_connections(region.id, [])
            if score > self.scores[region.country_id]:
                self.scores[region.country_id] = score

    def _plant_population(self):
        for country_id in range(self.countries):
            pool = len(self.country_regions[country_id]
                       ) * INITIAL_POPULATION_PER_REGION
            while pool > 0:
                for region_id in self.country_regions[country_id]:
                    region = self.regions[region_id]
                    if region.population == 0:
                        region.population = 1
                        pool -= 1
                        continue
                    if pool > 0 and region.population < MAX_POPULATION and random.random() > 0.5:
                        pool -= 1
                        region.population += 1

    def _build_country_map(self):
        for region in self.regions:
            self.country_regions[region.country_id].extend([region.id])

    def print_country(self, country_id):
        pops = []
        for i in range(len(self.regions)):
            if self.regions[i].country_id == self.active_player:
                pops.append(self.regions[i].population)
        print('CO: ', country_id, ' Score: ',
              self.scores[country_id], ' Pops: ', pops, ' / ', sum(pops))

    def get_country_sizes(self):
        rets = []
        for i in range(self.countries):
            rets.append(len(self.country_regions[i]))
        return rets

    def load_from_file(self, file_name):
        self.country_regions = []
        self.country_scores = []
        self.regions = []
        self.adjacency_matrix = []
        self.active_player = 0
        self.selected_region = -1

        with open(file_name) as f:
            data = json.load(f)
        self.adjacency_matrix = data['full']

        self.G = nx.Graph()
        self.G.add_nodes_from(range(0, len(self.adjacency_matrix)))

        region_id = 0
        max_country = 0
        for adjacency_vector in self.adjacency_matrix:
            region = Region()
            region.id = region_id
            region.country_id = data['country_map'][str(region_id)] - 1
            region.adjacency_vector = adjacency_vector

            cid = 0
            for connected in adjacency_vector:
                if connected:
                    self.G.add_edge(region_id, cid)
                cid += 1

            self.regions.extend([region])
            if region.country_id > max_country:
                max_country = region.country_id
            region_id += 1

        self.countries = max_country + 1
        for country_id in range(0, self.countries):
            self.country_regions.extend([[]])
            self.country_scores.extend([0])

        self.regions_count = len(self.regions)

if __name__ == '__main__':
    arena = Arena()
    print('SelfTest', os.getcwd())
    arena.load_from_file(os.getcwd().replace('/env', '') + '/models/map.json')
    print('Regions: ', len(arena.regions), ' / Countrzises: ', arena.countries)
    arena.new_game()
    print('Reward: ', arena.act(29, 30))


# -*- coding: utf-8 -*-
"""
Forms of customers app
"""

from django import forms
from django.conf import settings

from obp.api import APIError

class CreateCustomerForm(forms.Form):
    bank_id = forms.ChoiceField(
        label='Bank',
        widget=forms.Select(
            attrs={
                'class': 'form-control',
            }
        ),
        choices=[],
    )
    username = forms.CharField(
        label='Username',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'The name of the user',
                'class': 'form-control',
            }
        ),
    )
    customer_number = forms.CharField(
        label='Customer Number',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'E.g. `007`',
                'class': 'form-control',
            }
        ),
    )
    legal_name = forms.CharField(
        label='Legal Name',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'NONE',
                'class': 'form-control',
            }
        ),
        required=False,
    )
    mobile_phone_number = forms.CharField(
        label='Mobile Phone Number',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'E.g. +49 123 456 78 90 12',
                'class': 'form-control',
            }
        ),
        required=False,
    )
    email = forms.CharField(
        label='Email',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'E.g. person@example.com',
                'class': 'form-control',
            }
        ),
        required=False,
    )
    face_image_url = forms.CharField(
        label='Face Image URL',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'https://static.openbankproject.com/images/OBP/favicon.png',  # noqa
                'class': 'form-control',
            }
        ),
        required=False,
    )
    face_image_date = forms.DateTimeField(
        label='Face Image Date',
        input_formats=[settings.API_DATETIMEFORMAT],
        widget=forms.DateTimeInput(
            attrs={
                'placeholder': '2013-01-22T00:08:00Z',
                'class': 'form-control',
            }
        ),
        required=False,
    )
    date_of_birth = forms.DateTimeField(
        label='Date of Birth',
        input_formats=[settings.API_DATETIMEFORMAT],
        widget=forms.DateTimeInput(
            attrs={
                'placeholder': '2013-01-22T00:08:00Z',
                'class': 'form-control',
            }
        ),
        required=True,
    )
    relationship_status = forms.CharField(
        label='Relationship Status',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Single',
                'class': 'form-control',
            }
        ),
        required=False,
    )
    dependants = forms.IntegerField(
        label='Dependants',
        widget=forms.TextInput(
            attrs={
                'placeholder': '0',
                'class': 'form-control',
            }
        ),
        initial=0,
        required=True,
    )
    dob_of_dependants = forms.CharField(
        label='Date of Birth of Dependants',
        widget=forms.TextInput(
            attrs={
                'placeholder': '2013-01-22T00:08:00Z, 2010-01-22T00:08:00Z',
                'class': 'form-control',
            }
        ),
        required=False,
    )
    credit_rating_rating = forms.CharField(
        label='Credit Rating (Rating)',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'OBP',
                'class': 'form-control',
            }
        ),
        required=False,
    )
    credit_rating_source = forms.CharField(
        label='Credit Rating (Source)',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'OBP',
                'class': 'form-control',
            }
        ),
        required=False,
    )
    credit_limit_currency = forms.CharField(
        label='Credit Limit (Currency)',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'EUR',
                'class': 'form-control',
            }
        ),
        required=False,
    )
    credit_limit_amount = forms.CharField(
        label='Credit Limit (Amount)',
        widget=forms.TextInput(
            attrs={
                'placeholder': '10',
                'class': 'form-control',
            }
        ),
        required=False,
    )
    highest_education_attained = forms.CharField(
        label='Highest Education Attained',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Bachelor’s Degree',
                'class': 'form-control',
            }
        ),
        required=False,
    )
    employment_status = forms.CharField(
        label='Employment Status',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Employed',
                'class': 'form-control',
            }
        ),
        required=False,
    )
    kyc_status = forms.BooleanField(
        label='KYC Status',
        widget=forms.CheckboxInput(
            attrs={
                'class': 'form-control',
            }
        ),
        initial=True,
        required=False,
    )
    last_ok_date = forms.DateTimeField(
        label='Last OK Date',
        input_formats=[settings.API_DATETIMEFORMAT],
        widget=forms.DateTimeInput(
            attrs={
                'placeholder': '2013-01-22T00:08:00Z',
                'class': 'form-control',
            }
        ),
        required=True,
    )

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(CreateCustomerForm, self).__init__(*args, **kwargs)

    def clean_face_image_date(self):
        data = self.cleaned_data['face_image_date']
        if data:
            return data.strftime(settings.API_DATETIMEFORMAT)
        else:
            return None

    def clean_date_of_birth(self):
        data = self.cleaned_data['date_of_birth']
        if data:
            return data.strftime(settings.API_DATETIMEFORMAT)
        else:
            return None

    def clean_dob_of_dependants(self):
        data = self.cleaned_data['dob_of_dependants']
        if data:
            return data.split(',')
        else:
            return []

    def clean_username(self):
        username = self.cleaned_data['username']
        if not hasattr(self, 'api'):
            raise forms.ValidationError('No API object available')
        try:
            user = self.api.get('/users/username/{}'.format(username))
        except APIError as err:
            raise forms.ValidationError(err)
        else:
            self.cleaned_data['user_id'] = user['user_id']
        return username


from PIL import Image, ImageDraw
import glob
import random
import os

classes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
               'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
               'u', 'v', 'w', 'x', 'y', 'z', 'dxb', 'uaq', 'shj', 'auh', 'ajm', 'fuj', 'rak',
               'prefix', 'platenum', 'others', 'taxi', 'dubai_police', 'consulate']

print(len(classes))
def yolo_to_xml_bbox(bbox, w, h):
    # x_center, y_center width heigth
    w_half_len = (bbox[2] * w) / 2
    h_half_len = (bbox[3] * h) / 2
    xmin = int((bbox[0] * w) - w_half_len)
    ymin = int((bbox[1] * h) - h_half_len)
    xmax = int((bbox[0] * w) + w_half_len)
    ymax = int((bbox[1] * h) + h_half_len)
    return [xmin, ymin, xmax, ymax]

def draw_image(img, bboxes, classes_idxes):
    draw = ImageDraw.Draw(img)
    for bbox, class_idx in zip(bboxes,classes_idxes):
        draw.rectangle(bbox, outline="red", width=2)
        print(class_idx)
        if not class_idx == '100':
            class_name = classes[int(class_idx)]
            draw.text((bbox[0], bbox[1] - 10), class_name.upper(), fill=(0, 255, 0))
    img.save("example.jpg")
    img.show()

# image_filename = "Data/OCR_Data/Cropped_Plates_Img/0010100015220906171354.jpg"
# label_filename = "Data/OCR_Data/Cropped_Plates_Anno/0010100015220906171354.txt"

# img_dir = 'Data/OCR_Data/test/images/'
# anno_dir = 'Data/OCR_Data/test/labels/'
img_dir = 'Data/vizthis/img'
anno_dir = 'Data/vizthis/labels'
file_list = glob.glob(img_dir + "/*")

image_filename = random.choice(file_list)
label_filename = os.path.join(anno_dir,
                              os.path.basename(image_filename).split('.')[0] + '.txt')

bboxes = []
classes_idxs = []
img = Image.open(image_filename)

#0010200034220906192858
# img = Image.open("Data/test/images/0010200034220906192858.jpg")
# label_filename = "Data/test/labels/0010200034220906192858.txt"

print(label_filename)
with open(label_filename, 'r', encoding='utf8') as f:
    for line in f:

        data = line.strip().split(' ')
        class_idx = data[0]
        print(data, classes[int(class_idx)])
        # bbox = [float(x) for x in data[1:] if data[0] == '5']
        bbox = [float(x) for x in data[1:]]

        # if class_idx != '2' and class_idx != '0' and class_idx != '43' and class_idx != '44' and class_idx != '7':

        if class_idx == '36':
            classes_idxs.append(class_idx)
            if bbox:
                bboxes.append(yolo_to_xml_bbox(bbox, img.width, img.height))
draw_image(img, bboxes, classes_idxs)


# https://leetcode.com/problems/add-two-numbers/

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:

        resHead = ListNode()
        resTracker = resHead
        carry = 0
        crit = l1.next or l2.next or l1.val or l2.val or carry

        while crit:
            tempSum = (l1.val if l1.val > 0 else 0) + (l2.val if l2.val > 0 else 0) + carry
            resTracker.val = tempSum % 10
            carry = 1 if tempSum >= 10 else 0
            if(l1.next):
                l1 = l1.next
            else:
                l1.val = 0
            if(l2.next):
                l2 = l2.next
            else:
                l2.val = 0
            crit = l1.next or l2.next or l1.val or l2.val or carry
            if crit:
                resTracker.next = ListNode()
                resTracker = resTracker.next

        return resHead


import logging
from pytube import YouTube

def ytpytubeStreamObject(yt):
    ytStream=yt.streams
    cnt=0
    for stream in ytStream:
        print(stream)
        if not stream.is_adaptive :

            cnt+=1
    print(cnt)
if __name__ == '__main__':
    path = "C:\\users\\cg398\\Desktop"
    yt = YouTube("https://www.youtube.com/watch?v=IKfkSHpkBpw&feature=youtu.be")


import solution
import unittest
from ddt import ddt, data, unpack

@ddt
class CakeTestCase(unittest.TestCase):

    @unpack
    @data(
        ("abc", 1),
        ("abcdefabc", 1),
        ("abccbaabccba", 2),
        ("abcabcabcabc", 4)
    )
    def test_answer(self, input_string, expected):
        self.assertEquals(expected, solution.answer(input_string))

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


# What you want to update? (seperate them with comma, if all then *)
def option_validator(option, updatables, separator=","):
    '''
        while asking user to update column, this fucntion confirms if the inserted columns are valid or not
    '''
    confirmed_updates = []
    if option == "*":
        return updatables, False  # False means option is validated and can proceed futher
    else:
        sep_options = option.split(separator)
        for op in sep_options:
            if op.strip() in updatables:
                confirmed_updates.append(op.strip())
            else:
                print("Wrong updatable selected")
                return None, True  # True means try again - wrong updatable option selected

        return confirmed_updates, False


class VectorClock:
    """Classic vector clock"""
    def __init__(self, d=dict()):
        if d:
            newd = dict()
            for proc, value in d.iteritems():
                if value < 0:
                    raise ValueError('clock values must be non negative')
                if value == 0:
                    continue
                newd[proc] = value
            d = newd
        self._clocks = dict(d)

    def __getitem__(self, proc):
        try:
            return self._clocks[proc]
        except KeyError:
            return 0

    def tick(self, proc):
        vc_new = VectorClock(self._clocks)
        try:
            vc_new._clocks[proc] += 1
        except KeyError:
            vc_new._clocks[proc] = 1
        return vc_new

    def __eq__(self, vc):
        if not isinstance(vc, VectorClock):
            return False
        return self._clocks == vc._clocks

    def __lt__(self, vc):
        return self.before(vc)

    def merge(self, vc):
        # we can do such things because VectorClock() is immutable
        assert isinstance(vc, VectorClock)
        if not self._clocks:
            return vc
        if not vc._clocks:
            return self

        vc_new = VectorClock(self._clocks)
        for proc, value in vc._clocks.iteritems():
            vc_new._clocks[proc] = max([value, vc_new[proc]])
        return vc_new

    def before(self, vc):
        for proc in set(self._clocks.keys() + vc._clocks.keys()):
            if self[proc] > vc[proc]:
                return False
        return True

    def race(self, vc):
        return not (self.before(vc) or vc.before(self))

    def __str__(self):
        return str(self._clocks)

    def __repr__(self):
        return "VectorClock(%s)" % str(self._clocks)


import matplotlib.pyplot as plt

from Network import Network
from random import shuffle
import numpy as np
import copy
from Connection import Connection
import itertools
import random

#this main is used for simulating 100 random connections using all transciever technologies

def main():
    network_flex_rate = Network('../Resources/263697.json','flex_rate')
    node_labels = list(network_flex_rate.nodes.keys())

    """
    #100 random connections
    connections = []

    for i in range(100):
        shuffle(node_labels)
        connection = Connection(node_labels[0],node_labels[-1],1e-3)
        connections.append(connection)

    connections1 = copy.deepcopy(connections)
    """
    n_node = len(network_flex_rate.nodes.keys())
    t_mtx = np.ones((n_node, n_node)) * 100
    for i in range(n_node):
        t_mtx[i][i] = 0

    #for connection in connections1:  # remove the diagonal
    #    val = network_flex_rate.update_traffic_matrix(t_mtx,connection.input, connection.output)
    elements = list(itertools.permutations(network_flex_rate.nodes.keys(), 2))
    # tuples
    n_elem = len(elements)
    for e in elements:  # diagonal
        if e[0] == e[1]:
            elements.remove(e)
    for i in range(120):
        if len(elements) == 0:
            break
        el = random.choice(elements)
        val = network_flex_rate.update_traffic_matrix(t_mtx, el[0], el[1])
        if (val == 0) | (val == np.inf):
            elements.remove(el)

    #network_flex_rate.strong_failure("AB")

    print(network_flex_rate.logger_df())
    network_flex_rate.logger_df().to_csv("./LOGGERdf.csv")
    print(network_flex_rate.route_space)
    network_flex_rate.route_space.to_csv("./RouteSpace.csv")
    print(t_mtx)

if __name__ == '__main__':
    main()


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

from . import constants

class AttackEffect:
    """
    Every AttackEffect instance have: a target_pattern attribute, that shows where attacker may target,
    affected_pattern attirbute, that shows what entities will be be affected on attack,
    and perform method, where goes all the code related to decreasing hp, pushing enemies around etc.

    Parameters (built by by builders):
    ----------------------------------
    target_positions
        List of coords that attacker may target (in other words, "where player can click to attack"). Represented
        by list of tuples. Attacker position is represented by (0, 0) and the coords are relative to its position.
        Attacker may choose only one tile to perform an attack.

    attack_pattern
        List of coords that will be attacked. Coords position are relative to the target_position. Multiple tiles
        may be affected.

    Methods:
    --------
    build_target_positions
        Assigns available target_positions to the AttackEffect.

    build_attack_pattern
        Assings list of coordinates that will be attacked in relation to selected target position.

    perform
        There goes all the code related to the actually performing an attack, so decreasing hp, pushing enemies, etc.
    """

    def __init__(self):
        self.build_target_positions()
        self.build_attack_pattern()

    def build_target_positions(self):
        raise NotImplementedError

    def build_attack_pattern(self):
        raise NotImplementedError

class PunchLeftAttackEffect(AttackEffect):
    def build_target_positions(self):
        self.target_positions = [
            (-1, 0),
        ]

    def build_attack_pattern(self):
        """
        T
        """
        self.attack_pattern = [
            (0, 0),
        ]

    def perform(self, beings, map_objects, x, y):
        for cell in self.attack_pattern:
            nx = x + cell[0]
            ny = y + cell[1]
            try:
                beings.find_being_by_cell_position(
                    nx,
                    ny,
                ).hp -= 1
            except AttributeError:
                pass  # Do not act if being is not found.
            try:
                predecessor = map_objects.find_map_object_by_cell_position(nx, ny)
                successor = predecessor.destroy()
                if successor:
                    map_objects.replace_map_object(predecessor, successor)
            except AttributeError:
                pass

class PunchRightAttackEffect(PunchLeftAttackEffect):
    def build_target_positions(self):
        self.target_positions = [
            (1, 0),
        ]

class PunchTopAttackEffect(PunchLeftAttackEffect):
    def build_target_positions(self):
        self.target_positions = [
            (0, 1),
        ]

class PunchBottomAttackEffect(PunchLeftAttackEffect):
    def build_target_positions(self):
        self.target_positions = [
            (0, -1),
        ]

class SidePunchLeftAttackEffect(PunchLeftAttackEffect):
    def build_attack_pattern(self):
        self.attack_pattern = [
            (0, -1),
            (0, 1),
        ]

class SidePunchRightAttackEffect(PunchRightAttackEffect):
    def build_attack_pattern(self):
        self.attack_pattern = [
            (0, -1),
            (0, 1),
        ]

class SidePunchTopAttackEffect(PunchTopAttackEffect):
    def build_attack_pattern(self):
        self.attack_pattern = [
            (-1, 0),
            (1, 0),
        ]

class SidePunchBottomAttackEffect(PunchBottomAttackEffect):
    def build_attack_pattern(self):
        self.attack_pattern = [
            (-1, 0),
            (1, 0),
        ]

class WallPunchLeftAttackEffect(SidePunchLeftAttackEffect):
    def build_attack_pattern(self):
        self.attack_pattern = [
            (0, -1),
            (0, 0),
            (0, 1),
        ]

class WallPunchRightAttackEffect(SidePunchRightAttackEffect):
    def build_attack_pattern(self):
        self.attack_pattern = [
            (0, -1),
            (0, 0),
            (0, 1),
        ]

class WallPunchTopAttackEffect(SidePunchTopAttackEffect):
    def build_attack_pattern(self):
        self.attack_pattern = [
            (-1, 0),
            (0, 0),
            (1, 0),
        ]

class WallPunchBottomAttackEffect(SidePunchBottomAttackEffect):
    def build_attack_pattern(self):
        self.attack_pattern = [
            (-1, 0),
            (0, 0),
            (1, 0),
        ]

def construct_attack_effects(cls):
    attack_effect = cls()
    attack_effect.build_target_positions()
    attack_effect.build_attack_pattern()
    return attack_effect


# collatz.py

# In this program the user inputs any positive integer
# and outputs the successive values of the following calculation:
# At each step calculate the next value by taking the current value and,
# if it is even, divide it by two, but if it is odd,
# multiply it by three and add one.

#Authour: Dorina Agache

number = int(input("Please enter a positive number: "))
sequence = [number] # creating a list

while number != 1:
    if number % 2 == 0: #checking if number is even
            number = number // 2 #dividing by 2

    else: #if number not even
            number = number * 3 + 1 # multiplying by 3 and adding 1
    sequence.append(number)

print(sequence)


intcisla= [int(i) for i in input().split()]

vysledok=0
for m in range(len(intcisla)):
    c= intcisla[m]
    vysledok=0
    for b in range(2,c+1):

        for a in range(1,b+1):

            if (a*a + b*b) == c*c:
                vysledok+=1

            else:
                a+=1
    print(c,vysledok)


from django.test import TestCase

from server.forms.random_item_form import RandomItemDrawForm

class RandomItemDrawFormTest(TestCase):
    def valid_ok_test(self):
        """RandomItemDrawForm: Correct draw is valid"""
        form_data = {'number_of_results': 1, 'items': ['a', 'b', 'c']}
        form = RandomItemDrawForm(data=form_data)
        self.assertTrue(form.is_valid())

    def not_enough_items_ko_test(self):
        """RandomItemDrawForm: Not enough items is not valid"""
        form_data = {'number_of_results': 1, 'items': []}
        form = RandomItemDrawForm(data=form_data)
        self.assertFalse(form.is_valid())

    def not_enough_results_ko_test(self):
        """RandomItemDrawForm: Number of items > 0 """
        form_data = {'number_of_results': 0}
        form = RandomItemDrawForm(data=form_data)
        self.assertFalse(form.is_valid())


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

#load the data
data = pd.read_csv('blocktimes_raw.csv')
data['timestamp'] = pd.to_datetime(data['timestamp'])
data['blocktime'] = data['timestamp'].diff()

#convert blocktime to seconds
data['blocktime'] = data['blocktime'].dt.total_seconds()

#drop data for blocks before 15050001
data = data.loc[data['blocknumber'] >= 15050001]

#group the data by every 1000 blocks and calculate the mean of dif
data_1000 = data.groupby(data['blocknumber']//1000).blocktime.mean()
#calculate the standard deviation of dif every 1000 blocks
data_1000_sd = data.groupby(data['blocknumber']//1000).blocktime.std()

#create a scatter plot of blocktime on the y-axis and number on the x-axis

plt.scatter(data_1000.index/1000, data_1000.values, s = 0.75, c='black')
plt.axvline(x = 15.537393, color = 'b')
plt.text(15.4, 15.7, 'Ethereum Merge', verticalalignment = 'center_baseline', c='b')
plt.xlabel('Block Number (in millions)')
plt.ylabel('Average Block Time (1000 block increments)')
#add a regression line if blockgroup is less than 15.537 and greater than or equal to 15.537

x = data_1000.index/1000
y = data_1000.values

mask = x < 15.537393
x1 = x[mask]
y1 = y[mask]
m1, b1 = np.polyfit(x1, y1, 1)
print(m1, b1)
x2 = x[~mask]
y2 = y[~mask]
m2, b2 = np.polyfit(x2, y2, 1)
print(m2, b2)
plt.plot(x1, m1*x1 + b1, color = 'r', label = 'blockgroup < 15.537')
plt.plot(x2, m2*x2 + b2, color = 'g', label = 'blockgroup >= 15.537')

#save figure
plt.savefig('blocktimeavg.png', dpi = 300)
plt.show()

#create a scatter plot of moving standard deviation of blocktime on the y-axis and number on the x-axis
#do not include if the standard deviation is NaN
data_1000_sd = data_1000_sd.dropna()

plt.scatter(data_1000_sd.index/1000, data_1000_sd.values, s = 0.75, c='black')
plt.axvline(x = 15.537, color = 'b')
plt.text(15.4, 16.7, 'Ethereum Merge', verticalalignment = 'center_baseline', c='b')
plt.xlabel('Block Number (in millions)')
plt.ylabel('Standard Deviation of Block Time (1000 block increments)')
#add a regression line if blockgroup is less than 15.537 and greater than or equal to 15.537
import numpy as np
import matplotlib.pyplot as plt

x = data_1000_sd.index/1000
y = data_1000_sd.values

mask = x < 15.537
x1 = x[mask]
y1 = y[mask]
m1, b1 = np.polyfit(x1, y1, 1)
print(m1, b1)
x2 = x[~mask]
y2 = y[~mask]
m2, b2 = np.polyfit(x2, y2, 1)
print(m2, b2)
plt.plot(x1, m1*x1 + b1, color = 'r', label = 'blockgroup < 15.537')
plt.plot(x2, m2*x2 + b2, color = 'g', label = 'blockgroup >= 15.537')

# save figure so it can be used in latex
plt.savefig('blocktimestd.png', dpi=300)
plt.show()


import boto3
import pickle

from flask import Flask, request, json
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.externals import joblib

MODEL_FILE_NAME = 'model.pkl'

app = Flask(__name__)

@app.route('/', methods=['POST'])
def index():
    # Parse request body for model input
    body_dict = request.get_json(silent=True)
    data = body_dict['data']

    # Load model
    model = joblib.load(MODEL_FILE_NAME)
    # Make prediction
    prediction = model.predict(data).tolist()
    # Respond with prediction result
    result = {'prediction': prediction}
    return json.dumps(result)

if __name__ == '__main__':
    # listen on all IPs
    app.run(host='0.0.0.0')


# Permet de tester les expressions régulières de la base de données
import re

def teste(regexp, phrase):
    prog = re.compile(regexp)
    if prog.match(phrase):
        print("MATCH")
    else:
        print("NOPE")

if __name__ == "__main__":
    teste(input("REGEXP > "), input("TEST > "))


'''
Created on Apr 10, 2012

@organization: cert.org
'''
import unittest
from certfuzz.fuzztools import text
import math
import tempfile
import shutil
import os
import random

class Test(unittest.TestCase):

    def setUp(self):
        self.tempdir = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tempdir)

    def test__pattern(self):
        iterables = ['ABC', 'abc', '012']
        for length in range(3, 1000):
            pat = text._pattern(iterables, length)
            self.assertEqual(length, len(pat))
            self.assertTrue(pat.startswith('Aa0'))
            if length > 100:
                self.assertTrue('Cc2' in pat)

        # make sure it rolls over
        # each iterable has 3 possible values
        # and there are 3 iterables thus 3 chars per token
        rollover_pos = 3 * 3 * 3 * 3
        # so we want to overshoot by one token
        # to ensure that we rollover to the start token Aa0 again
        rollover_str = text._pattern(iterables, rollover_pos + 3)
        self.assertTrue(rollover_str.endswith('Cc2Aa0'))

    def test_metasploit_pattern_orig(self):
        for length in range(3, 1000):
            pat = text.metasploit_pattern_orig(length)
            self.assertEqual(length, len(pat))
            self.assertTrue(pat.startswith('Aa0'))
            if length > 101:
                self.assertEqual('Ad3', pat[99:102])

    def test_metasploit_pattern_extended(self):
        for length in range(6, 1000):
            pat = text.metasploit_pattern_extended(length)
            self.assertEqual(length, len(pat))
            self.assertTrue(pat.startswith('AAaa00'))
            if length > 101:
                self.assertEqual('AAaa16', pat[96:102])

    def test__enumerate_string(self):
        s = 'x____' * 1000

        occurrences = sorted(random.sample(population=range(0, len(s), 5), k=102))
        result = text._enumerate_string(s, occurrences)
        # length should be unchanged
        self.assertEqual(len(s), len(result))

        # convert result to string
        result = str(result)
        self.assertNotEqual(s, result)
        # check 1 digit
        self.assertTrue('____1____' in result)
        # check 2 digit
        self.assertTrue('___10___' in result)
        # check 3 digit
        self.assertTrue('__100__' in result)

    def test_enumerate_string(self):
        (fd, f) = tempfile.mkstemp(suffix='.foo', dir=self.tempdir)
        os.write(fd, 'AAAAxxxAAAAxxxxxAAAAxAAAA')
        os.close(fd)
        root, ext = os.path.splitext(f)
        expected_newpath = '{}-enum{}'.format(root, ext)

        newpath = text.enumerate_string(f, 'AAAA')
        self.assertTrue(newpath.endswith('-enum.foo'))

        self.assertEqual(expected_newpath, newpath)
        self.assertTrue(os.path.exists(expected_newpath))

        with open(newpath, 'rb') as fp:
            content = fp.read()
            self.assertEqual('0AAAxxx1AAAxxxxx2AAAx3AAA', content)
        os.remove(newpath)
        os.remove(f)

if __name__ == "__main__":
    # import sys;sys.argv = ['', 'Test.testName']
    unittest.main()


import logging, requests
from fake_useragent import UserAgent

class Http(object):

    log = logging.getLogger(__name__)

    def session(self, proxies={}, cookies=None):

        headers = {'User-Agent': UserAgent(verify_ssl=False).chrome}

        session = requests.session()

        session.headers.update(headers)

        session.proxies=proxies

        if cookies: session.cookies=cookies

        return session

    def client(self, session, url, method='GET', data=None):

        try:

            result = session.request(method, url, data=data)

            code = result.status_code

            if code in [200, 201]: return result.text

            self.log.warning('HTTP状态:[{}], {}'.format(code, url))

        except Exception as e: self.log.warning('错误信息:',e)

        return ''


import re
from enum import Enum
from typing import Counter, Dict, Iterator, List

class Emotions(Enum):
    ANGER = 1 << 0
    ANTICIPATION = 1 << 1
    DISGUST = 1 << 2
    FEAR = 1 << 3
    JOY = 1 << 4
    NEGATIVE = 1 << 5
    POSITIVE = 1 << 6
    SADNESS = 1 << 7
    SURPRISE = 1 << 8
    TRUST = 1 << 9
    ANY = 1 << 10
    def __int__(self):
        return self.value

dic: Dict[str, List[Emotions]] = {}
dicBitmap: Dict[str, int] = {}

def getEmotionName(emotion: Emotions) -> str:
    if emotion == Emotions.ANGER:
        return "anger"
    if emotion == Emotions.ANTICIPATION:
        return "anticipation"
    if emotion == Emotions.DISGUST:
        return "disgust"
    if emotion == Emotions.FEAR:
        return "fear"
    if emotion == Emotions.JOY:
        return "joy"
    if emotion == Emotions.NEGATIVE:
        return "negative"
    if emotion == Emotions.POSITIVE:
        return "positive"
    if emotion == Emotions.SADNESS:
        return "sadness"
    if emotion == Emotions.SURPRISE:
        return "surprise"
    if emotion == Emotions.TRUST:
        return "trust"
    if emotion == Emotions.ANY:
        return "analized"
    return "unknown"

def initEmotionLexicon(lang = 'en'):
    # # English
    # emotionOrder = [
    #     Emotions.ANGER, Emotions.ANTICIPATION, Emotions.DISGUST, Emotions.FEAR, Emotions.JOY,
    #     Emotions.NEGATIVE, Emotions.POSITIVE,Emotions.SADNESS, Emotions.SURPRISE, Emotions.TRUST
    # ]
    # path = './assets/NRC-Emotion-Lexicon-Wordlevel-v0.92.txt'
    # with open(path) as file:
    #     lines = [l for l in file]
    #     for i in range(0, len(lines), 10):
    #         wordLine = [l for l in lines[i:i + 10]]
    #         term = wordLine[0].split('\t')[0]
    #         emotions = [Emotions.ANY]
    #         for j in range(10):
    #             if int(wordLine[j].split('\t')[2][0]) == 1:
    #                 emotions.append(emotionOrder[j])
    #         dic[term] = emotions
    #         # bitmap = 1 << 10
    #         # for j in range(10):
    #         #     bitmap += int(wordLine[j].split('\t')[2][0]) << j
    #         # dic[term] = bitmap

    # Other languages
    emotionOrder = [
        Emotions.POSITIVE, Emotions.NEGATIVE, Emotions.ANGER, Emotions.ANTICIPATION, Emotions.DISGUST,
        Emotions.FEAR, Emotions.JOY, Emotions.SADNESS, Emotions.SURPRISE, Emotions.TRUST
    ]
    path = './assets/NRC-Emotion-Lexicon-v0.92-In105Languages-Nov2017Translations.csv'
    with open(path) as file:
        lines = [l for l in file]
        # find header column
        header = lines[0].strip('\n').split(',')[:-10]
        langCol = -1
        for i, langHeader in enumerate(header):
            if langHeader.split('(')[1].split(')')[0] == lang:
                print(langHeader)
                langCol = i
                break
        try:
            if langCol < 0:
                raise Exception('Lang not found')
        except Exception as ex:
            print(ex)
            exit(1)

        for l in lines[1:]:
            d = l.strip('\n').split(',')
            term = d[langCol]
            if lang == 'it' and (term == 'mar' or term == 'ago'):
                continue
            emotions = [Emotions.ANY]
            for i, x in enumerate(d[-10:]):
                if x == "1":
                    emotions.append(emotionOrder[i])
            bits = 0
            for e in emotions:
                bits |= e.value
            dic[term] = emotions
            dicBitmap[term] = bits

def tokenize(text: str) -> Iterator[str]:
    for match in re.finditer(r'\w+', text, re.UNICODE):
        yield match.group(0)

def isWordOfEmotion(word: str, emotion: Emotions) -> bool:
    if word in dic:
        return (dicBitmap[word] & emotion.value) != 0
    return False

def getEmotionsOfWord(word: str) -> List[Emotions]:
    if word not in dic:
        return []
    return dic[word]
    # d = dic[word]
    # for e in Emotions:
    #     if d & e.value != 0:
    #         yield e

def countEmotionsOfWords(words: Iterator[str]) -> Counter[Emotions]:
    c = Counter()
    for w in words:
        c.update(getEmotionsOfWord(w))
    return c

def countEmotionsOfText(text: str) -> Counter[Emotions]:
    return countEmotionsOfWords(tokenize(text))

def separateWordsByEmotion(text: str, dictToUpdate: Dict[Emotions, List[str]] = None) -> Dict[Emotions, List[str]]:
    if dictToUpdate is None:
        dictToUpdate = {}
        for e in Emotions:
            dictToUpdate[e] = []

    words = tokenize(text)
    for w in words:
        if w in dic:
            for e in dic[w]:
                dictToUpdate[e].append(w)

    return dictToUpdate


"""
evolving! ! !
"""

def verification(question_text):
    while True:

        answer = input(question_text).lower()
        if answer == "yes" or answer == "y":
            answer = "Yes"
            return answer

        elif answer == "no" or answer == "n":
            answer = "No"
            return answer

        else:
            print("Please enter valid answer. (yes/no)")

# Main routine
question = input("Have you played this game before? (yes/no): ")
print(f"You have chosen {question}.")
print()
chill = verification("Are you having fun? ")
print(f"You entered {chill}")


from logAnalyzer.boonsAndHexesAndStates import getBoonOrHexOrState
from logAnalyzer.logParser.strings import *  # all prefixed with s_ or r_
from logAnalyzer.logParser.cardNameFilter import getFilteredCardName
from logAnalyzer.game import Game, Player
from logAnalyzer.utils.logger import logErrorAndRaise
from logAnalyzer.utils.pythonUtils import removeItemsFromList

# Takes in 2 lists of words (str/regexp) and returns T/F if matching
# Works on both strings and regexps
# ignores trailing commas or periods

def validateWordSequence(testWords, referenceWords):
    for wordIndex in range(len(testWords)):
        testString = testWords[wordIndex]
        if testString[-1] == '.' or testString[-1] == ',':
            testString = testString[0:-1]
        if callable(getattr(referenceWords[wordIndex], 'match', None)):
            # Regular Experession
            if not referenceWords[wordIndex].match(testString):
                return False
        else:
            # String
            if testString != referenceWords[wordIndex]:
                return False
    return len(testWords) == len(referenceWords)

# Looks for an exact match with the words given.
# This only adds spaces and removes commas/periods

def parseSingleCardFromStrings(words):
    nameString = " ".join(words)
    if nameString[-1] == '.' or nameString[-1] == ',':
        nameString = nameString[0:-1]
    return getFilteredCardName(nameString)

def parseBoonOrHexOrStateFromStrings(words):
    nameString = " ".join(words)
    if nameString[-1] == '.' or nameString[-1] == ',':
        nameString = nameString[0:-1]
    return getBoonOrHexOrState(nameString)

def parseMultipleCardsFromStrings(words, firstWordIndex, lastWordIndex=99999, stopWords=[]):
    if lastWordIndex < len(words):
        words = words[firstWordIndex:lastWordIndex+1]
    else:
        words = words[firstWordIndex:]
    listToReturn = []
    "2 Coppers, a Bridge, a Bridge Troll, an Estate, and a Jack of All Trades."
    loopIndex = 0
    while loopIndex < len(words):

        if words[loopIndex] in stopWords:
            return listToReturn

        if parseBoonOrHexOrStateFromStrings(words[loopIndex:len(words)]) is not None:
            return listToReturn

        # Skip 'and'
        if words[loopIndex] == s_and:
            loopIndex += 1

        # Determine quantity
        qtyString = words[loopIndex]
        if r_number.match(qtyString):
            cardQuantity = int(qtyString)
        elif qtyString == s_a or qtyString == s_an:
            cardQuantity = 1
        # Sirs and Dames don't have quantity words (e.g.) "buys and gains Sir Michael"
        elif qtyString == s_Sir or qtyString == s_Dame:
            cardQuantity = 1
            loopIndex -= 1  # this is sort of hacky, but we want to just skip quantity
        else:
            logErrorAndRaise(
                'Couldn\'t determine quantity: ' + qtyString)
        loopIndex += 1  # processed quantity

        # check for stop words again, sometimes they come after 'a'
        # e.g. J sets a card aside with Library
        if words[loopIndex] in stopWords:
            return listToReturn

        # loop, adding words until we know we can't
        nameBeginIndex = loopIndex
        while(loopIndex < len(words)):
            if parseSingleCardFromStrings(words[nameBeginIndex:loopIndex+1]) is not None\
                    and not (loopIndex + 1 < len(words) and parseSingleCardFromStrings(words[nameBeginIndex:loopIndex+2]) is not None):
                break
            loopIndex += 1

        cardName = parseSingleCardFromStrings(
            words[nameBeginIndex:loopIndex+1])
        if (cardName is None):
            logErrorAndRaise('Could not find card name: ' +
                             " ".join(words[nameBeginIndex:loopIndex+1]))
        listToReturn += ([cardName] * cardQuantity)
        loopIndex += 1
    return listToReturn

def logToGame(logString):

    game = Game()

    lines = logString.split('\n')
    for line in lines:
        words = line.split()
        functionToCall = getFunctionForLine(words, game)
        if functionToCall is not None:
            functionToCall(words, game)  # get & execute function

    return game

def getFunctionForLine(words, game):
    if len(words) >= 2 and validateWordSequence(words[0:2], [s_intro_game, r_gameNum]):
        return None
    if len(words) >= 3 and validateWordSequence(words[0:3], [s_turn, r_number, s_hyphen]):
        return parseTurnLine
    if len(words) >= 3 and validateWordSequence(words[0:3], [r_playerLetter, s_intro_starts, s_intro_with]):
        return parseDeckStartLine
    if len(words) >= 4 and validateWordSequence(words[0:4], [r_playerLetter, s_buys, s_and, s_gains]):
        return parseBuyLine
    if len(words) >= 2 and validateWordSequence(words[0:2], [r_playerLetter, s_gains]):
        return parseGainLine
    if len(words) >= 2 and validateWordSequence(words[0:2], [r_playerLetter, s_trashes]):
        return parseTrashLine
    if len(words) >= 2 and validateWordSequence(words[0:2], [r_playerLetter, s_receives]):
        return parseReceivesLine
    if len(words) >= 2 and validateWordSequence(words[0:2], [r_playerLetter, s_returns]):
        return parseReturnsLine
    if len(words) >= 2 and validateWordSequence(words[0:2], [r_playerLetter, s_exiles]):
        return parseExileLine
    if len(words) >= 4 and validateWordSequence(words[0:2], [r_playerLetter, s_discards])\
            and validateWordSequence(words[-2:], [s_from, s_Exile]):
        return parseDiscardFromExileLine
    if len(words) >= 6 and validateWordSequence(words[0:2], [r_playerLetter, s_sets]):
        return parseSetsLine
    if len(words) >= 2 and validateWordSequence(words[0:2], [r_playerLetter, s_puts]):
        return parsePutsLine
    if len(words) >= 2 and validateWordSequence(words[0:2], [r_playerLetter, s_calls]):
        return parseCallsLine
    else:
        return None

def parseDeckStartLine(words, game):
    if game.getPlayerByInitial(words[0]) is None:
        player = Player()
        player.initial = words[0]
        game.players.append(player)
    game.getPlayerByInitial(
        words[0]).totalDeckCardNames += (parseMultipleCardsFromStrings(words, 3))

def parseTurnLine(words, game):
    if words[1] == '1':
        for i in range(len(game.players)):
            if words[3].startswith(game.players[i].initial):
                game.players[i].name = ' '.join(words[3:])
                break

def parseBuyLine(words, game):
    game.getPlayerByInitial(
        words[0]).totalDeckCardNames += parseMultipleCardsFromStrings(words, 4)

# "from trash", "onto their draw pile"
def parseGainLine(words, game):
    game.getPlayerByInitial(
        words[0]).totalDeckCardNames += parseMultipleCardsFromStrings(words, 2, stopWords=[s_from, s_onto])

# J trashes an Estate. (Cathedral)
# J trashes an Estate. (Sewers)
def parseTrashLine(words, game):
    removeItemsFromList(game.getPlayerByInitial(
        words[0]).totalDeckCardNames, parseMultipleCardsFromStrings(words, 2, stopWords=[s_CathedralBrackets, s_SewersBrackets]))

def parseExileLine(words, game):
    removeItemsFromList(game.getPlayerByInitial(
        words[0]).totalDeckCardNames, parseMultipleCardsFromStrings(words, 2))

def parseDiscardFromExileLine(words, game):
    game.getPlayerByInitial(
        words[0]).totalDeckCardNames += parseMultipleCardsFromStrings(words, 2, stopWords=[s_from])

# "to the Horse pile", "-Coin token ..."
def parseReturnsLine(words, game):
    removeItemsFromList(game.getPlayerByInitial(
        words[0]).totalDeckCardNames, parseMultipleCardsFromStrings(words, 2, stopWords=[s_to, s_minus_Coin]))

def parseReceivesLine(words, game):
    game.getPlayerByInitial(
        words[0]).totalDeckCardNames += parseMultipleCardsFromStrings(words, 2)

# "aside with Native Village"
# "a card aside with Library"
# "Druid sets {Boon} aside."
# "sets 2 Coppers aside."
# "sets nothing aside with Church"
def parseSetsLine(words, game):
    if validateWordSequence(words[-2:], [s_Native, s_Village]):
        removeItemsFromList(game.getPlayerByInitial(
            words[0]).totalDeckCardNames, parseMultipleCardsFromStrings(words, 2, stopWords=[s_aside, s_card, s_nothing]))
    else:
        return

# "into their hand"
# "on their Island mat"
# "on their Tavern mat"
# "puts a Gold in hand (Crypt)."
# "puts a Magpie back onto their deck."
# "puts a card in hand (Haven)."
# "puts a card on the bottom of their deck" (?)
# "puts a card on the bottom of Draw Pile" (Pearl Diver)
def parsePutsLine(words, game):
    if validateWordSequence(words[-3:], [s_into, s_their, s_hand])\
            or validateWordSequence(words[-1:], [s_CryptBrackets])\
            or validateWordSequence(words[-1:], [s_HavenBrackets])\
            or validateWordSequence(words[-1:], [s_ChurchBrackets])\
            or validateWordSequence(words[-1:], [s_GearBrackets])\
            or validateWordSequence(words[-2:], [s_CargoLeftBracket, s_ShipRightBracket])\
            or validateWordSequence(words[-4:], [s_back, s_onto, s_their, s_deck])\
            or validateWordSequence(words[-6:], [s_on, s_the, s_bottom, s_of, s_their, s_deck])\
            or validateWordSequence(words[-6:], [s_on, s_the, s_bottom, s_of, s_Draw, s_Pile]):
        return
    removeItemsFromList(game.getPlayerByInitial(
        words[0]).totalDeckCardNames, parseMultipleCardsFromStrings(words, 2, stopWords=[s_on]))

def parseCallsLine(words, game):
    game.getPlayerByInitial(
        words[0]).totalDeckCardNames += parseMultipleCardsFromStrings(words, 2)


from selenium import webdriver
import unittest

class OpenTest(unittest.TestCase):
    def setUp(self):
        self.browser = webdriver.Safari()

    def testOpen(self):
        self.browser.get('http://127.0.0.1:8000/fitness')
        self.assertIn('Ты лучше', self.browser.title)

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