import logging
from collections import OrderedDict
from typing import Any, Dict, Optional

from pythonjsonlogger.jsonlogger import JsonFormatter

class LogsFormatter(JsonFormatter):
    """``LogsFormatter`` defines the logs formatter class."""

    def __init__(self, request_id: Optional[str] = None) -> None:
        """Instantiates `LogsFormatter`.

        Args:
            request_id: Trigger message ID.
        """
        fmt = "%(asctime)s %(levelname)s %(run_id)s %(lineno)d %(message)s"
        if not request_id:
            fmt = "%(asctime)s %(levelname)s %(request_id)s %(run_id)s %(lineno)d %(message)s"

        super().__init__(fmt=fmt, datefmt="%Y-%m-%d %H:%M:%S")

        self.request_id = request_id

    def add_fields(
        self, log_record: OrderedDict, record: logging.LogRecord, message_dict: Dict[str, Any]
    ) -> None:
        super().add_fields(log_record, record, message_dict)

        log_record["request_id"] = self.request_id

        if isinstance(message_dict.get("message"), dict):
            log_record.pop("message")
            log_record.update(message_dict)

        if not message_dict.get("run_id"):
            log_record.pop("run_id")

def get_logger(name: Optional[str] = __name__, request_id: Optional[str] = None) -> logging.Logger:
    """Sets up the logger.

    Args:
        name: Logger instance name.
        request_id: Trigger message ID.

    Returns:
        Logger.
    """
    json_handler = logging.StreamHandler()
    json_handler.setFormatter(LogsFormatter(request_id=request_id))
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)

    for hdl in logger.handlers:
        logger.removeHandler(hdl)

    logger.addHandler(json_handler)
    return logger


from flask import Blueprint, jsonify

from app import db
from app.helpers import validate_input, token_required
from app.models.items import ItemModel
from app.models.categories import CategoryModel
from app.schemas.items import ItemSchema, UpdateItem

items_blueprint = Blueprint("items", __name__)

@items_blueprint.route("/categories/<int:category_id>/items", methods=["GET"])
def get_items(category_id):
    """
    input: category id (int)
    output: show all items in that category
        - each item: name of item
    """
    category = db.session.query(CategoryModel).filter(CategoryModel.id == category_id).first()
    if not category:
        return jsonify({"message": "Category not found"}), 404

    list_items = db.session.query(ItemModel).filter(ItemModel.category_id == category_id).all()

    return jsonify(ItemSchema(many=True).dump(list_items)), 200

@items_blueprint.route("/categories/<int:category_id>/items", methods=["POST"])
@token_required
@validate_input(schema=ItemSchema)
def create_item(category_id, user_id, data):
    """
    input:
        - category_id (int)
        - new item information
            - item name (str)
            - item description (str)
    output:
        - add new item to the category successfully
        - raise error for existed item
    """
    category = db.session.query(CategoryModel).filter(CategoryModel.id == category_id).first()
    if not category:
        return jsonify({"message": "Category not found"}), 404
    name = data["name"]
    description = data["description"]

    item = db.session.query(ItemModel).filter(ItemModel.category_id == category_id)\
        .filter(ItemModel.name == name).first()

    if item:
        return jsonify({"message": "Existed item"}), 400

    new_item = ItemModel(name=name, description=description, category_id=category_id, user_id=user_id)
    db.session.add(new_item)
    db.session.commit()

    return jsonify({"message": "Created item successfully"}), 201

@items_blueprint.route("/categories/<int:category_id>/items/<int:item_id>", methods=["GET"])
def get_item(item_id, category_id):
    """
    input:
        - category_id (int)
        - item_id (int)
    output:
    - item id and description (if found)
    - return error if not
    """
    category = db.session.query(CategoryModel).filter(CategoryModel.id == category_id).first()
    if not category:
        return jsonify({"message": "Category not found"}), 404

    item = db.session.query(ItemModel).filter(ItemModel.category_id == category_id) \
        .filter(ItemModel.id == item_id).first()

    if not item:
        return jsonify({"message": "Item not found"}), 404
    return jsonify(ItemSchema().dump(item)), 200

@items_blueprint.route("/categories/<int:category_id>/items/<int:item_id>", methods=["DELETE"])
@token_required
def delete_item(item_id, user_id, category_id):
    """
    input: item_id, category_id
    output: delete from item list
    """
    category = db.session.query(CategoryModel).filter(CategoryModel.id == category_id).first()
    if not category:
        return jsonify({"message": "Category not found"}), 404

    item = db.session.query(ItemModel).filter(ItemModel.category_id == category_id) \
        .filter(ItemModel.id == item_id).first()

    if not item:
        return jsonify({"message": "Item not found"}), 404

    if item.user_id != user_id:
        return jsonify({"message": "Unauthorized"}), 403

    db.session.delete(item)
    db.session.commit()

    return jsonify({"message": "Deleted item successfully"}), 200

@items_blueprint.route("/categories/<int:category_id>/items/<int:item_id>", methods=["PUT"])
@token_required
@validate_input(schema=UpdateItem)
def edit_item(item_id, user_id, data, category_id):
    """
    input: item_id
    output:
        - updated description (if existed)
        - raise error if not existed
    """
    category = db.session.query(CategoryModel).filter(CategoryModel.id == category_id).first()
    if not category:
        return jsonify({"message": "Category not found"}), 404

    description = data["description"]

    item = db.session.query(ItemModel).filter(ItemModel.category_id == category_id) \
        .filter(ItemModel.id == item_id).first()

    if not item:
        return jsonify({"message": "Item not found"}), 404

    if item.user_id != user_id:
        return jsonify({"message": "Unauthorized"}), 403

    item.description = description
    db.session.commit()

    return jsonify(ItemSchema().dump(item)), 200


#!/usr/bin/python3
"""
    Send request to a url and ndisplay value of X-Request-Id variable
    in the response header
"""
import sys
import urllib.request

if __name__ == "__main__":
    url = sys.argv[1]
    with urllib.request.urlopen(url) as response:
        id = response.headers.get('X-Request-Id')
        print(id)


#! /usr/bin/env python

import sys
import os
import argparse
import time
from math import exp, log
import random
from treeswift import *
import treeswift
import json
import numpy as np
from tripVote.placement_lib import complete_gene_trees

def __label_tree__(tree_obj):
	is_labeled = True
	i = 0
	labels = set()
	for node in tree_obj.traverse_preorder():
		if node.is_leaf():
			continue
		if not node.label or node.label in labels or node.label[0] != 'I':
			is_labeled = False
			node.label = 'I' + str(i)
			i += 1
		labels.add(node.label)
	return is_labeled

def get_clade_leaves(clade_dict, node):
	if node.is_leaf():
		if node.label not in clade_dict:
			clade_dict[node.label] = [node.label]
		return

	leaves = []
	for child in node.child_nodes():
		if child.label in clade_dict:
			leaves += clade_dict[child.label]
		else:
			get_clade_leaves(clade_dict, child)
			leaves += clade_dict[child.label]
	clade_dict[node.label] = leaves

def cal_nodal_dist(u, v, branch_length = False):
	u_ancestors = {}
	v_ancestors = {}
	u_ancestors[u.label] = 0
	v_ancestors[v.label] = 0

	node = u
	while not node.is_root():
		parent = node.parent
		d = 1
		if branch_length:
			d = node.get_edge_length()
		u_ancestors[parent.label] = u_ancestors[node.label] + d
		node = parent

	node = v
	while node.label not in u_ancestors:
		parent = node.parent
		d = 1
		if branch_length:
			d = node.get_edge_length()
		v_ancestors[parent.label] = v_ancestors[node.label] + d
		node = parent

	lca = node
	dist = u_ancestors[lca.label] + v_ancestors[lca.label]
	return dist

def main():
	parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
	parser.add_argument('-i', '--input', required=True, help="Input tree to be completed")
	parser.add_argument('-r', '--refs', required=True, help="Reference trees that are used to complete input trees.")
	parser.add_argument('-o', '--output_file', required=True, help="Output file")

	args = parser.parse_args()

	random.seed(a=1105)

	start = time.time()

	with open(args.input,'r') as f:
		inputTree = f.read().strip().split("\n")[0]

	with open(args.refs,'r') as f:
		refTrees = f.read().strip().split("\n")

	inputTree_obj = read_tree_newick(inputTree)
	is_labeled = __label_tree__(inputTree_obj)
	# print(inputTree_obj.newick())
	# for node in inputTree_obj.traverse_preorder():
	# 	node.edge_length = None
	print(inputTree_obj.newick())

	dataset = []
	qspr_input_list = []
	# num_leaves = inputTree_obj.num_nodes(leaves=True, internal=False)
	all_leaves = inputTree_obj.traverse_leaves()
	all_leaves = [l.label for l in all_leaves]

	bl_heights = inputTree_obj.distances_from_root(leaves=True, internal=False, unlabeled=False, weighted=True)
	bl_heights = [b[1] for b in bl_heights]
	bl_avg_height = np.mean(bl_heights)
	bl_std_height = np.std(bl_heights)

	nodal_heights = inputTree_obj.distances_from_root(leaves=True, internal=False, unlabeled=False, weighted=False)
	nodal_heights = [b[1] for b in nodal_heights]
	nodal_avg_height = np.mean(nodal_heights)
	nodal_std_height = np.std(nodal_heights)

	nodes = []
	tree_root = None
	for node in inputTree_obj.traverse_preorder():
		if node.is_root():
			tree_root = node
		nodes.append(node)

	clade_dict = {}
	get_clade_leaves(clade_dict, tree_root)

	for n in nodes:
		label = n.label
		for child in n.child_nodes():
			new_tree = treeswift.read_tree_newick(inputTree_obj.newick())
			clade_root = new_tree.label_to_node([child.label])[child.label]
			parent = clade_root.parent
			grand_parent = parent.parent

			parent.remove_child(clade_root)
			before_placement = parent.child_nodes()[0].label

			if grand_parent is None:
				if len(parent.child_nodes()) == 1:
					other_child = parent.child_nodes()[0]
					other_child.parent = None
					new_tree.root = other_child
			else:
				grand_parent.remove_child(parent)
				for c in parent.child_nodes():
					grand_parent.add_child(c)

			if new_tree.num_nodes(internal = False) < 3:
				continue

			placement_set = clade_dict[child.label]
			qspr_input_list.append((clade_root.label, placement_set, new_tree.newick(), before_placement))

		if not n.is_root():
			if len(clade_dict[n.label]) >= 3:
				new_tree = treeswift.read_tree_newick(inputTree_obj.newick())
				new_root = new_tree.label_to_node([n.label])[n.label]
				before_placement = new_root.label

				new_root.parent = None
				new_tree.root = new_root
				placement_set = list(set(all_leaves) - set(clade_dict[n.label]))
				qspr_input_list.append((clade_root.label, placement_set, new_tree.newick(), before_placement))

	for record in qspr_input_list:
		label = record[0]
		placement_set = record[1]
		input_tree_str = record[2]
		before_placement = record[3]

		outputTrees, total_scores, _ = complete_gene_trees([input_tree_str], refTrees=refTrees , placement_taxa=placement_set, sample_size =0 ,nsample = 0)
		after_placement = max(total_scores, key=total_scores.get)
		if total_scores[before_placement] == total_scores[after_placement]:
			after_placement = before_placement

		before_node = inputTree_obj.label_to_node([before_placement])[before_placement]
		after_node = inputTree_obj.label_to_node([after_placement])[after_placement]
		nodal_dist = cal_nodal_dist(before_node, after_node)
		branch_dist = cal_nodal_dist(before_node, after_node, branch_length = True)
		# print("branch dist: ", branch_dist)
		before_root_dist = cal_nodal_dist(before_node, tree_root)
		after_root_dist = cal_nodal_dist(after_node, tree_root)

		quartet_dist = total_scores[after_placement] - total_scores[before_placement]

		spr_record = []

		#clade taxa
		placement_string = ",".join(placement_set)
		spr_record.append(placement_string)

		#label
		if is_labeled:
			spr_record.append(label)
		else:
			spr_record.append("-")

		#placement label
		if is_labeled:
			spr_record.append(after_placement)
		else:
			spr_record.append("-")

		# nodal dist
		spr_record.append(str(nodal_dist))

		#avg nodal height
		spr_record.append(str(nodal_avg_height))

		#std nodal height
		spr_record.append(str(nodal_std_height))

		# branch dist
		spr_record.append(str(branch_dist))

		#avg bl height
		spr_record.append(str(bl_avg_height))

		#std bl height
		spr_record.append(str(bl_std_height))

		# dist to root (before)
		spr_record.append(str(before_root_dist))

		# dist to root (after)
		spr_record.append(str(after_root_dist))

		#quartet score diff
		spr_record.append(str(quartet_dist))

		n = len(all_leaves) - len(placement_set)
		n_choose_three = (n * (n-1) * (n-2)) / 6
		spr_record.append(str(n_choose_three * len(placement_set) * len(refTrees)))
		dataset.append(spr_record)

	with open(args.output_file, 'w') as f:
		f.write("clade taxa" + "\t" + "label" + "\t" + "placement label" + "\t" + "nodal dist" + "\t" + "avg nodal height" + "\t" + "nodal height std" + "\t" + "branch dist" + "\t" + "avg branch height" + "\t" + "branch height std" + "\t" + "dist to root (before)" + "\t" + "dist to root (after)" + "\t"
			+ "quartet score diff" + "\t" + "n-m choose 3 * m" + "\n")
		for r in dataset:
			f.write("\t".join(r) + "\n")

	end = time.time()
	print("Runtime: ", end - start)

if __name__ == "__main__":
	main()


from torchvision import datasets, transforms
from torch.utils.data.dataset import Dataset
import glob, os
from skimage import io
import torch
import numpy as np

class SingleTaskCovidDataset(Dataset):
    def __init__(self, split_name, opts, transform=None):
        super(SingleTaskCovidDataset, self).__init__()
        assert split_name in ["train", "val"]
        assert opts.dataset.lower() == "covid_ct"
        self.slice_files = []
        self.folder_path = None

        if split_name == "train":
            self.folder_path = os.path.join(opts.data_dir, opts.dataset + "/train/")
        elif split_name == "val":
            self.folder_path = os.path.join(opts.data_dir, opts.dataset + "/val/")

        assert os.path.exists(self.folder_path)
        for dir in os.listdir(self.folder_path):
            self.slice_files.extend(glob.glob(os.path.join(self.folder_path, dir + '/images','*.png')))

        self.transform = transform
        self.label = []
        for slice_path in self.slice_files[:]:
            path = ''
            if opts.task == "lung":
                path = os.path.join(os.path.dirname(slice_path),'../masks/lung_field', os.path.basename(slice_path))
            elif opts.task == "ground_glass":
                path = os.path.join(os.path.dirname(slice_path),'../masks/ground_glass_shadow', os.path.basename(slice_path))
            elif opts.task == "consolidation":
                path = os.path.join(os.path.dirname(slice_path),'../masks/consolidation', os.path.basename(slice_path))
            elif opts.task == "fibrosis":
                path = os.path.join(os.path.dirname(slice_path),'../masks/fibrosis', os.path.basename(slice_path))
            elif opts.task == "effusion":
                path = os.path.join(os.path.dirname(slice_path),'../masks/pleural_effusion', os.path.basename(slice_path))
            elif opts.task == "thickening":
                path = os.path.join(os.path.dirname(slice_path),'../masks/thickening', os.path.basename(slice_path))
            else:
                print("Task {} not supported. Available options: lung, ground_glass, fibrosis, effusion, thickening".format(opts.task))
                raise NotImplementedError

            if np.count_nonzero(io.imread(path)) > 0:
                self.label.append(path)
            else:
                self.slice_files.remove(slice_path)

    def __getitem__(self, index):
        img = (io.imread(self.slice_files[index])/255).astype(np.float32)
        label = io.imread(self.label[index])
        if self.transform is not None:
            img = self.transform(img)
        return (img, label)

    def __len__(self):
        return len(self.slice_files)


import argparse
import os
files_removed = 0
i = 0
parser = argparse.ArgumentParser()
parser.add_argument("path", help="File path for players folder")
parser.add_argument("initial_items", type=int, help="Number of inventory slots to be igonred, as in initial items")
args = parser.parse_args()
directory = args.path
initialItems = args.initial_items
for filename in os.listdir(directory):
    fullPath = directory + '/' + filename
    file = open(fullPath, "r")
    while(1):
        test = file.read(i)
        if test == "Empty":
            i += 1
        else:
            print("Player", file, "not cleared")

        file.close()
        if i == 43:
            print("Player", file, "deleted")
            os.remove(fullPath)
            files_removed += 1

            break

print("Player clearing process completed.", files_removed, "players deleted.")


from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.status import HTTP_201_CREATED, HTTP_400_BAD_REQUEST,HTTP_200_OK
from .serializers import AdocaoSerializer
from .email_service import send_email_confirmation
from .models import Adocao

class AdocaoList(APIView):

    def get(self, request, format=None):
        adoptions = Adocao.objects.all()
        serializer = AdocaoSerializer(adoptions, many=True)
        return Response(serializer.data, status=HTTP_200_OK)

    def post(self, request, format=None):
        serializer = AdocaoSerializer(data=request.data)
        if serializer.is_valid():
            adoption = serializer.save()
            send_email_confirmation(adoption)
            return Response(serializer.data, status=HTTP_201_CREATED)
        return Response(
            {
                "errors": serializer.errors,
                "message": "Houveram erros de validacao",
            },
            status=HTTP_400_BAD_REQUEST,
        )


# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from keras.datasets import mnist
from matplotlib import pyplot
import matplotlib.pyplot as plt

size = 28
numLabels = 10
pixels = size*numLabels

train = np.loadtxt('mnist_train_6000.csv', delimiter= ',')
test = np.loadtxt('mnist_test_1000.csv', delimiter=',')

no_of_different_labels = 10
test[test==255]
test.shape
fac = 0.99 / 255
train_imgs = np.asfarray(train[:, 1:]) * fac + 0.01
test_imgs = np.asfarray(test[:, 1:]) * fac + 0.01
train_labels = np.asfarray(train[:, :1])
test_labels = np.asfarray(test[:, :1])
lr = np.arange(10)

for label in range(10):
    one_hot = (lr==label).astype(np.int)
    print("label: ", label, " in one-hot representation: ", one_hot)

lr = np.arange(no_of_different_labels)

# transform labels into one hot representation
train_labels_one_hot = (lr==train_labels).astype(np.float)
test_labels_one_hot = (lr==test_labels).astype(np.float)

# we don't want zeroes and ones in the labels neither:
train_labels_one_hot[train_labels_one_hot==0] = 0.01
train_labels_one_hot[train_labels_one_hot==1] = 0.99
test_labels_one_hot[test_labels_one_hot==0] = 0.01
test_labels_one_hot[test_labels_one_hot==1] = 0.99

for i in range(10):
    img = train_imgs[i].reshape((28,28))
    plt.imshow(img, cmap="Greys")
    plt.show()


import this
list_1 = ["a", "b", "c"]
list_2 = ["boy", "4.8", "True", "boy"]

print(list_2[0])
list_3 = ["a", "b", "c", "d", "e", "f", "g"]

print(list_3[: : 2])
## Checking the presence of an element in a link
print('A' in list_3)
# Changing elements in a list
list_3 = ["a", "b", "c", "d", "e", "f", "g"]
list_3[4:7] = 1, 2, 3
print(list_3)


#!/usr/bin/env python
# encoding: utf-8

from distutils.core import setup

import py2exe

options = {"py2exe":
                {"compressed": 1,
                 "optimize": 2,
                 "bundle_files": 1, # 表示把所有文件打包进exe可执行程序
                 # "packages": extra_modules,
                 #"includes": extra_modules
                }
          }
setup(
    version = "1.0.0",
    description = "test for py2exe",
    name = "Py2exeTest",
    options = options,
    zipfile = None,
    console = [{"script": "wdf.py"}]
)


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pika
import json

msg = json.dumps({"message":"hello,word"})
parameters = pika.URLParameters('amqp://guest:guest@172.17.0.2:5672')
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
for i in range(10000):
    channel.basic_publish(
        'test_exchange',
        'test',
        msg)
channel.close()


from googlesearch import search
from newspaper import Article
from newspaper.article import ArticleException
import streamlit as st
import nltk

nltk.download('punkt')
st.title("Trustee Recruitment")

def article_content(url):
    article = Article(url)

    try:
        article.download()
        article.parse()
        article.nlp()
        st.write(article.summary)
    except ArticleException as e:
        print("Error while processing article:", e)

def search_and_extract(query):
    search_results = search(query)
    for i, result in enumerate(search_results, start=1):
        if result in visited_links:
            continue
        visited_links.add(result)
        st.subheader(result)
        article_content(result)

if __name__ == "__main__":
    visited_links = set()
    search_queries = ['Charity trustee recruitment UK', 'Effective ways to recruit a trustee', 'Points to remember while finding charity trustees']
    for search_query in search_queries:
        st.header(search_query.upper(), divider = "rainbow")
        search_and_extract(search_query)


""" 1978 소수 찾기 """
test = int(input())
num = list(map(int, input().split()))
cnt2 = 0  #  소수의 개수

for i in num:
    cnt = 0  #  약수의 개수
    if i == 1:
        continue
    for j in range(1, i):
        if i % j == 0:
            cnt += 1
    if cnt == 1:
        cnt2 += 1
print(cnt2)


'''
1202. Smallest String With Swaps

You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b]
indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smallest string that s can be changed to after using the swaps.

Example 1:
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"

Example 2:
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"

Example 3:
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explaination:
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"

Constraints:
1 <= s.length <= 10^5
0 <= pairs.length <= 10^5
0 <= pairs[i][0], pairs[i][1] < s.length
s only contains lower case English letters.
'''

# make parent union of all the indexes
# you should get an arr p where each index has its parent as element
# create a dict like 0-> 0,3 where 0 is the parent of the list in its value
# then for each key of the dict sort the corresponding characters in its value list
# then swap the s[ind] with the sorted list of the character

from collections import defaultdict

class Solution:
    def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:

        p = [i for i in range(len(s))]

        def find(x):
            if p[x] != x:
                p[x] = find(p[x])

            return p[x]

        def union(x, y):
            px = find(x)
            py = find(y)

            if px != py:
                p[py] = px

        for x, y in pairs:
            union(x,y)

        dic = defaultdict(list)
        res = list(s)

        for ind, ele in enumerate(p):
            dic[find(ele)].append(ind)

        for key in dic.keys():
            ind_list = dic[key]
            char_list = [s[i] for i in ind_list]
            char_list.sort()

            for ind, char in zip(ind_list, char_list):
                res[ind] = char

        return "".join(res)

# time (n log n)
# space O(n)


from retrieveRedditPost import getPost
from videoMaker import makeVideo
import time

def main():
    #timer
    start_time = time.time()

    print("WELCOME TO THE SUBREDDIT VIDEO MAKER!")

    #retrieve a  post (question and comments) from the subreddit (there is an option to manually select a post from a given list)
    reddit_post = getPost(subreddit = "askreddit", manual_selection = False, console_output = True)
    #make video
    makeVideo(reddit_post, console_output = True)

    #print total time taken for this video
    print(f"\nTime taken to make video: {round(time.time() - start_time, 2)} seconds")

if __name__ == '__main__':
    main()


# lesson 2
# 1)
a = ["dog", 43, 34.8]
for word in a:
    print(type(word))

# 2)
li = input("введите несколько слов: ").split()
for i in range(0, len(li) - 1, 2):
    li[i], li[i - 1] = li[i - 1], li[i]
print(li)
# 3)
d = {"зима": [12, 1, 2], "весна": [3, 4, 5], "лето": [6, 7, 8], "осень": [9, 10, 11]}
m = int(input("введите номер: "))
for el in d:
    if m in d[el]:
        break
print(m)
# второй вариант
m = int(input("введите номер месяца: "))
if (m == 12) or (m <= 2):
    print("зима")
elif (m == 3) or (m <= 5):
    print("весна")
elif (m == 6) or (m <= 8):
    print("лето")
elif (m == 9) or (m <= 11):
    print("осень")
if m < 1 or m > 12:
    print("погугли сколько месяцев в году")

# 4
word = input("введите слова:").split()
for i, el in enumerate(word, 1):
    print(i, el[0:10])
# 5
li = [7, 5, 3, 3, 2]
n = int(input("enter new score: "))
i = 0
for el in li:
    if n <= el:
        i += 1
li.insert(i, n)
print(li)


# Import Libraries
import sys # Use system services
from  tkinter import * # Tkinter is for GUI
import time # Match system time

# Function for time format
def times():
	current_time=time.strftime("%H:%M:%S")
	clock.config(text=current_time)
	clock.after(1000,times)

# Initialize Tkinter and create format
root=Tk()
root.geometry("500x200") # Size of GUI
clock=Label(root,font=("helvetica",50,"bold"),bg="gold") # Label() = the name for the GUI along with design.
clock.grid(row=2,column=2,pady=25,padx=100) # Grid() allows for the layout of the time format
times() # Calling the times() function

digi=Label(root,text="Digital Clock",font="helvetica 24 bold") # Label() = the name for the GUI along with design.
digi.grid(row=0,column=2) # Grid() allows for the layout of the time format

nota=Label(root,text="Hours   Minutes   Seconds   ",font="helvetica 15 bold") # Label() = the name for the GUI along with design.
nota.grid(row=3,column=2) # Grid() allows for the layout of the time format

root.mainloop() # Mainloop() is the end function for Tk()


import pytest

from dolfin import *
from dolfin_adjoint import *
import moola

import numpy as np

set_log_level(30)

def convergence_rates(E_values, eps_values, show=True):
	"""
	Source https://github.com/dolfin-adjoint/pyadjoint/blob/master/pyadjoint/verification.py
	"""
	from numpy import log
	r = []
	for i in range(1, len(eps_values)):
		r.append(log(E_values[i] / E_values[i - 1])
		/ log(eps_values[i] / eps_values[i - 1]))
	if show:
		print("Computed convergence rates: {}".format(r))
	return r

def random_optimal_poisson(n, ydm=1.0, k=2, alpha=1e-3, samples=np.ones(1), gtol=1e-9):
	"""Defines a simple risk-neutral optimal control problem.

	The diffusion coefficient is a random scalar. The SAA solution for the infinite
	dimensional control problem is known (called u_analytic below).

	The problem is partly based on that considered in
	http://www.dolfin-adjoint.org/en/latest/documentation/poisson-mother/poisson-mother.html
	"""
	set_working_tape(Tape())

	mesh = UnitSquareMesh(n, n)

	V = FunctionSpace(mesh, "CG", 1)
	W = FunctionSpace(mesh, "DG", 0)
	bc = DirichletBC(V, 0.0, "on_boundary")

	yd = Expression("m*sin(k*pi*x[0])*sin(k*pi*x[1])", degree = 3, m = ydm, k=k)
	u = Function(W)
	y = Function(V)
	v = TestFunction(V)

	m1 = np.mean(1/samples)
	m2 = np.mean(1/samples**2)

	um = (2.0*k**2*np.pi**2*ydm*m1) / (4.0*k**4*np.pi**4*alpha+m2)

	u_analytic = Expression("m*sin(k*pi*x[0])*sin(k*pi*x[1])", degree = 3, m = um, k=k)

	# compute sample average
	J = 0.
	for i in range(len(samples)):

		F = Constant(samples[i])*inner(grad(y), grad(v))*dx - u * v * dx
		solve(F == 0, y, bc)

		j = assemble(0.5 * inner(y - yd, y - yd) * dx + .5*Constant(alpha)*u**2*dx)
		J += 1.0/(i+1.0)*(j-J)

	rf = ReducedFunctional(J, Control(u))
	problem = MoolaOptimizationProblem(rf)
	u_moola = moola.DolfinPrimalVector(u)

	solver = moola.NewtonCG(problem, u_moola, options={'gtol': gtol,
                                                   'maxiter': 20,
                                                   'display': 3,
                                                   'ncg_hesstol': 0})

	sol = solver.solve()
	u_opt = sol['control'].data

	control_error = errornorm(u_analytic, u_opt, degree_rise=3)

	return control_error

def test_random_optimal_poisson_convergence_rates():
	"""Checks if the theoretical convergence rate equals the empirical rate.

	The theoretical convergence rate is O(h^2). We observe a first oder convergence.
	"""
	# problem data

	ydm = 1.0/(2*np.pi**2)
	k = 2
	alpha = 1e-3

	N = 10
	np.random.seed(1234)
	samples = np.exp(np.random.randn(N))
	gtol = 1e-9

	errors = []
	values = []

	for n in [8, 16, 32, 64, 128]:

		error = random_optimal_poisson(n, ydm=ydm, k=k, alpha=alpha, samples=samples, gtol=gtol)
		errors.append(error)
		values.append(1.0/n)

	rate = np.median(convergence_rates(errors, values))
	assert rate > 1.0


from typing import Iterable, List

import torch
from pykeen.triples.instances import SubGraphSLCWAInstances, BaseBatchedSLCWAInstances
from pykeen.triples.utils import compute_compressed_adjacency_list

class LinearSubGraphSLCWAInstances(BaseBatchedSLCWAInstances):
    """Pre-batched training instances for SLCWA of linear chains."""

    def __init__(self, **kwargs):
        """
        Initialize the instances.

        :param kwargs:
            keyword-based parameters passed to :meth:`BaseBatchedSLCWAInstances.__init__`
        """
        super().__init__(**kwargs)
        # indexing
        self.degrees, self.offset, self.neighbors = compute_compressed_adjacency_list(
            mapped_triples=self.mapped_triples
        )

    def subgraph_sample(self) -> List[int]:
        """sample a single linear chain with disjoint vertices and self.batch_size edges"""
        node_weights = self.degrees.detach().clone()
        # edge_picked = torch.zeros(self.mapped_triples.shape[0], dtype=torch.bool)
        # node_picked = torch.zeros(self.degrees.shape[0], dtype=torch.bool)

        redo = True

        while redo:
            edge_picked = torch.zeros(self.mapped_triples.shape[0], dtype=torch.bool)
            node_picked = torch.zeros(self.degrees.shape[0], dtype=torch.bool)
            redo = False
            result = []
            # choose a random vertex to start
            current_head = torch.randint(node_picked.numel(), size=tuple())

            while node_weights[current_head] == 0:
                current_head = torch.randint(node_picked.numel(), size=tuple())

            node_picked[current_head] = True
            for _ in range(self.batch_size):
                start = self.offset[current_head]
                current_head_degree = self.degrees[current_head].item()
                if current_head_degree == 0:
                    redo = True
                    # start over
                    break

                stop = start + current_head_degree
                adj_list = self.neighbors[start:stop, :]

                # check that there is at least one valid edge to pick.
                invalid_edges = edge_picked[adj_list[:,0]] | node_picked[adj_list[:,1]]
                # probably node_picked is sufficient, huh?
                if torch.all(invalid_edges):
                    redo = True
                    break

                chosen_edge_index = torch.randint(current_head_degree, size=tuple())
                chosen_edge = adj_list[chosen_edge_index]
                edge_number = chosen_edge[0]
                # find an edge which has not been picked and whose tail vertex also has not been picked
                while invalid_edges[chosen_edge_index]:
                    chosen_edge_index = torch.randint(current_head_degree, size=tuple())
                    chosen_edge = adj_list[chosen_edge_index]
                    edge_number = chosen_edge[0]

                result.append(edge_number.item())

                edge_picked[edge_number] = True
                current_head = chosen_edge[1]
                node_picked[current_head] = True

        return result

    # docstr-coverage: inherited
    def iter_triple_ids(self) -> Iterable[List[int]]:  # noqa: D102
        yield from (self.subgraph_sample() for _ in self.split_workload(n=len(self)))


import py_trees

from pytwb.common import behavior

#
## decide visit points based on information from vector map
#
@behavior
class SetLocations(py_trees.behaviour.Behaviour):
    desc = 'create candidates of visit locations by vector map'

    def __init__(self, name):
        super(SetLocations, self).__init__(name)

    def initialise(self) -> None:
        bb = py_trees.blackboard.Blackboard()
        self.bb = bb

        world = bb.get('geometric_map')
        r = world.get_root_region()
        self.region = r
        pose_list = []
        for sr in r.get_subregions():
            c = sr.get_weight_center()
            pose_list.append([float(c.x), float(c.y), 0])
        bb.set("pose_list", pose_list)

    def update(self):
        return py_trees.common.Status.SUCCESS


import pygame

class PlayerCharge(pygame.sprite.Sprite):

    size = (45, 35)

    """Creating class of player attacking charge."""

    def __init__(self, start_pos, delta_cords, enemies_group, player, *groups):
        super().__init__(*groups)

        self.image = pygame.transform.scale(pygame.image.load('static/player_charge.png'), PlayerCharge.size)
        self.rect = self.image.get_rect()
        self.rect.center = start_pos
        self.mask = pygame.mask.from_surface(self.image)

        self.delta_cords = delta_cords
        self.enemies_group = enemies_group

        self.counter = round(3 / 0.033)

        self.player = player

    def move(self):
        for enemy in self.enemies_group:
            if pygame.sprite.collide_mask(self, enemy):
                enemy.get_damage(10, self.player)
                self.kill()
                break
        self.rect.x += self.delta_cords[0]
        self.rect.y += self.delta_cords[1]

    def update(self, *args):
        self.counter -= 1
        if self.counter <= 0:
            self.kill()
        self.move()


import boto3
from common.Logger import Logger

class BookmarksTableManager:
    def __init__(self, table_name):
        self.dynamodb = boto3.resource('dynamodb')
        self.table_name = table_name
        self.table = self.dynamodb.Table(table_name)
        self.logging_instance = Logger()

    def remove_item(self, key):
        try:
            self.table.delete_item(Key=key)
            return True
        except Exception as e:
            self.logging_instance.log_exception(e, 'remove_item')
            return False

    def update_user_data(self, email, config_json=None, last_modified=None):
        ## If email does not exists, this function will create a new record.
        try:
            update_expression = "SET"
            expression_attribute_values = {}
            expression_attribute_names = {}

            if config_json is not None:
                # No need to enumerate over each config item, as the compressed json is a single string
                update_expression += " #F = :f,"
                expression_attribute_values[":f"] = config_json
                expression_attribute_names["#F"] = "config_json"

            if last_modified is not None:
                update_expression += " #L1 = :l1,"
                expression_attribute_values[":l1"] = last_modified
                expression_attribute_names["#L1"] = "last_modified"

            if update_expression == "SET":
                # No fields provided for update
                return False

            # Remove the trailing comma from the update expression
            update_expression = update_expression.rstrip(",")

            self.table.update_item(
                Key={'email': email},
                UpdateExpression=update_expression,
                ExpressionAttributeValues=expression_attribute_values,
                ExpressionAttributeNames=expression_attribute_names
            )

            return True
        except Exception as e:
            self.logging_instance.log_exception(e, 'update_user_data')
            raise

    def get_user_data(self, email):
        try:
            response = self.table.get_item(
                Key={'email': email},
                AttributesToGet=[
                    'config_json',
                ]
            )

            if 'Item' in response:
                return response['Item']['config_json']
            else:
                print(f"No data found for email: {email}")
                return None

        except Exception as e:
            self.logging_instance.log_exception(e, 'get_user_data')
            raise


#!/usr/bin/python
# -*- coding: UTF-8 -*-

import configparser
import smtplib
import socket
import datetime
from email.mime.text import MIMEText
from email.header import Header

conf = configparser.ConfigParser()

conf.read("../../rule.ini", encoding="utf-8")
def  send_mail(type):
    # 获取当前时间
    datetime.datetime.now()
    time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    # 获取计算机信息
    def func( ):
        s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.connect(('8.8.8.8',80))
        ip = s.getsockname( )[0]
        return ip
    mail_body=func( )

    html ="send_info:"+"    "+ "IP:"+mail_body+"    "+"TYPE:"+type+"    "+"TIME:"+time

    # 第三方 SMTP 服务
    mail_host = conf.get("default","mail_host")
    mail_user = conf.get("default","mail_user")
    mail_pass = conf.get("default","mail_pass")
    sender = conf.get("default","sender")
    receivers = conf.get("default","receivers")
    port = conf.get("default","port")
    subject_content = conf.get("default","subject_content")

    message =MIMEText(html, 'html', 'utf-8')
    message['From'] = Header("send from", 'utf-8')
    message['To'] =  Header("send to", 'utf-8')
    subject = subject_content+mail_body
    message['Subject'] = Header(subject,  'utf-8')

    try:
        smtpObj = smtplib.SMTP(host=mail_host )
        smtpObj.connect(mail_host, port)    # 25 为 SMTP 端口号
        smtpObj.ehlo()
        smtpObj.starttls()
        smtpObj.login(mail_user,mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("邮件发送成功")
    except Exception as err:
        print("邮件发送失败")
        print(err)


from copy import deepcopy
import os
from sched import scheduler
import time
from datetime import datetime
from tkinter.tix import Tree
import numpy as np
from PPO.PPO import PPO
from config import Machine_State, config
from plot import plot_cluster_with_scheduled_jobs
from simanneal.anneal import Annealer
from hpc.HPCEnv import HPCEnv
from multiprocessing import Pool, Manager

class Instance:
    def __init__(self) -> None:
        self.scheduled_dic = []
        self.cost = []
    def reset(self, scheduled_dic, cost):
        self.scheduled_dic = scheduled_dic
        self.cost = cost

class HPCScheduler(Annealer):
    def __init__(self):
        env_name = "jobscheduling"
        action_std = 0.1            # set same std for action distribution which was used while saving
        K_epochs = 80               # update policy for K epochs
        eps_clip = 0.2              # clip parameter for PPO
        gamma = 0.99                # discount factor

        lr_actor = 0.0003           # learning rate for actor
        lr_critic = 0.001           # learning rate for critic

        #####################################################

        self.env = HPCEnv()

        random_seed = 0             #### set this to load a particular checkpoint trained on random seed
        run_num_pretrained = 0      #### set this to load a particular checkpoint num
        checkpoint_path = config.checkpoint_path
        # state space dimension
        state_dim = self.env.observation_space.shape[0]

        action_dim = self.env.action_space.n

        # initialize a PPO agent
        self.ppo_agent = PPO(state_dim, action_dim, lr_actor, lr_critic, gamma, K_epochs, eps_clip, False, action_std)
        self.ppo_agent.load(checkpoint_path)
        self.need_schedule_by_RL_jobs_before_move = []
        self.current_solution_cost = 0

    def move(self):
        initial_reward = self.E # or initial energy

        assert len(self.need_schedule_by_RL_jobs_before_move) == len(self.env.scheduled_rl.keys())
        self.env.need_schedule_by_RL_jobs = deepcopy(self.need_schedule_by_RL_jobs_before_move)
        # random remove a certain number of jobs
        scheduling_job_num = len(self.env.scheduled_rl.keys())
        need_remove_num = self.env.np_random.randint(1, 3)
        # need_remove_num = 2

        all_schedule_job_ids = list(self.env.best_scheduled_rl.keys())

        if scheduling_job_num <= need_remove_num:
            random_select_job_ids = all_schedule_job_ids
        else:
            random_select_job_ids = np.random.choice(all_schedule_job_ids, need_remove_num, replace=False) # replace element into set is false

        # for job_id in self.need_schedule_by_RL_jobs:
        #     if not job_id in random_select_job_ids:
        #         self.cluster.allocate_in_Batch(self.scheduled_rl[job_id])
        for job_id in random_select_job_ids:
            self.env.cluster.release(self.env.scheduled_rl[job_id])

        # modify state
        self.env.current_scheduling_job_index_in_need_schedule = 0

        # update self.env.need_schedule_by_RL and self.env.scheduled_rl
        self.env.need_schedule_by_RL_jobs = []
        for job in self.need_schedule_by_RL_jobs_before_move:
            if job.id in random_select_job_ids:
                self.env.scheduled_rl.pop(job.id)
                self.env.need_schedule_by_RL_jobs.append(job)

        self.env.update_state(before_step=False)

        # use rl to re-insert
        scheduled_dic, reward = self.find_one_solution(with_RL=True)
        self.state = scheduled_dic
        self.E = -reward
        assert -reward == self.current_solution_cost
        return self.energy() - initial_reward

    def energy(self):
        # calculate_cost = 0
        # for job_id in self.state.keys():
        #     calculate_cost += self.env.cluster.calculate_total_distance_nodes(self.state[job_id])
        # assert abs(calculate_cost - self.E) < 1
        # assert calculate_cost == self.E
        return self.current_solution_cost

    # def insert(self):
    #     action = self.ppo_agent.select_action(self.env.mask_for_invalid_action)
    #     self.env.step(action)

    def find_one_solution(self, with_RL):
        # use rl to re-insert
        while(True):
            if with_RL and config.SA_with_RL:
                # action = self.ppo_agent.select_action(state=self.env.state, mask=self.env.mask_for_invalid_action)
                if config.re_scale_state:
                    state, idle_node_ids_in_line= self.env.re_scale_state()
                else:
                    state = self.env.state
                if config.re_scale_state:
                    action_in_idle_index = self.ppo_agent.select_action(state, self.env.mask_for_invalid_action)
                    action = idle_node_ids_in_line[action_in_idle_index]
                else:
                    action = self.ppo_agent.select_action(state, self.env.mask_for_invalid_action)
            else:
                idle_node_ids_in_line = self.env.obtain_all_idles_node_ids_before_step()
                # action_in_idle_index = self.env.np_random.randint(0, len(idle_node_ids_in_line))
                action_in_idle_index = self.env.np_random.randint(0, min(len(idle_node_ids_in_line), config.max_nodes_for_drl))
                action = idle_node_ids_in_line[action_in_idle_index]

            reward, done, skip = self.env.step(action)
            if done:
                self.current_solution_cost = -reward
                break
        return self.env.scheduled_rl, reward

    def find_initial_solution(self):
        cost = 0
        schedule_initial = {}
        total_allocated_node_ids = []
        for job in self.need_schedule_by_RL_jobs_before_move:
            select_node_ids = self.env.cluster.find_idle_nodes_by_seq(job.request_number_of_nodes, total_allocated_node_ids)
            assert len(select_node_ids) == job.request_number_of_nodes
            # if len(self.need_schedule_by_RL_jobs_before_move) >= 2:
            #     for node_id in select_node_ids:
            #         assert not total_allocated_node_ids.__contains__(node_id)
            #         total_allocated_node_ids.append(node_id)
            self.env.cluster.allocate_in_Batch(select_node_ids)
            cost += self.env.cluster.calculate_total_distance_nodes(select_node_ids)
            assert not cost == 0
            schedule_initial[job.id] = select_node_ids
        self.env.scheduled_rl = deepcopy(schedule_initial)
        self.env.best_scheduled_rl = deepcopy(self.env.scheduled_rl)
        self.env.best_cost = cost
        self.current_solution_cost = cost
        return schedule_initial, -cost

#################################### Testing ###################################
def test():
    print("============================================================================================")
    total_test_episodes = 10   # total num of testing episodes
    max_ep_len = 100           # max timesteps in one episode

    scheduler = HPCScheduler()

    save_file_name = 'simanneal/compare_test{}_layer{}_index{}_method{}_rescale{}_step{}.txt'.format(config.test_name, config.layer_type, config.layer_index,
                                                                                config.method_find_nodes, config.re_scale_state*1, config.stepsforsa)
    f = open(save_file_name, mode='w')
    f.write('epoch, avg. cost for seq, avg. cost for model(notimelimit), avg. time for model(notimelimit),'+
         'avg. cost for model(timelimit), avg. canceled job num(timelimit), avg. time for model(timelimit),'+
         'avg. cost for SA, avg. time for SA, avg. cost for SA+model, avg. time for SA+model\n' +
         'avg. cost for NSA, avg. time for NSA, avg. cost for NSA+model, avg. time for NSA+model\n')
    f2 = open('simanneal/SCIP_time_NSA_steps_{}_layer{}_index{}_method{}_rescale{}_step{}.txt'.format(config.test_name, config.layer_type, config.layer_index, config.method_find_nodes, config.re_scale_state*1, config.stepsforsa), mode = 'w')
    f2.write('idle node num, schedule job num, required num nodes, solving_time, optimal_steps\n')
    f3 = open('simanneal/solving_log_time_obj_{}_layer{}_index{}_method{}_rescale{}_step{}.txt'.format(config.test_name, config.layer_type, config.layer_index, config.method_find_nodes, config.re_scale_state*1, config.stepsforsa), mode = 'w')

    for ep in range(1, total_test_episodes+1):
        cumulative_cost_nsa = 0
        cumulative_cost_sa_step500 = 0
        cumulative_cost_sa_step1000 = 0
        cumulative_cost_model_notimelimit = 0
        cumulative_cost_model = 0
        cumulative_cost_seq = 0
        cumulative_cost_nsa_model = 0
        cumulative_solving_time_nsa = 0

        cumulative_solving_time_sa_step500 = 0
        cumulative_solving_time_sa_step1000 = 0
        cumulative_solving_time_model = 0
        cumulative_solving_time_model_notimelimit = 0
        cumulative_solving_time_nsa_model = 0
        cumulative_cancel_job_number_model_timelimit = 0
        cumulative_cancel_job_number_model_notimelimit = 0
        cumulative_schedule_job_num = 0

        scheduler.env.reset()
        for t in range(1, max_ep_len+1):
            need_to_process = scheduler.env.need_proceed_by_RL()
            if not need_to_process:
                continue
            f3.write('---------------------------------------------------------------------\n')
            f3.write('ep: {}, instance: {}, idle num: {}, job num: {}, total request node: {}\n'.format(ep, t, scheduler.env.cluster.idle_node_num,
            len(scheduler.env.need_schedule_by_RL_jobs), scheduler.env.obtain_total_request_node()))
            start_time = time.time()
            scheduler.need_schedule_by_RL_jobs_before_move = deepcopy(scheduler.env.need_schedule_by_RL_jobs)
            scheduled_dic, reward = scheduler.find_initial_solution()

            super(HPCScheduler, scheduler).__init__(scheduled_dic, -reward, config.stepsforsa)  # important!
            config.SA_with_RL = True
            best_scheduled_dic_NSA, best_cost_NSA, optimal_steps_NSA = scheduler.anneal(ep, t, f3)
            assert abs(best_cost_NSA-scheduler.env.best_cost) <= 1
            duration_nsa = round(time.time() - start_time, 3)
            # scheduler.env.schedule_finish_assign_best_solution(refill_with_best_scheduled=True, duration = duration)

            # for SA steps=500
            config.SA_with_RL = False
            scheduler.env.remove_current_schedule()
            best_solution_for_NSA = scheduler.env.best_scheduled_rl     # record best solution for NSA
            scheduler.env.reset_for_next_time_step(update_timestamp=False)
            start_time = time.time()
            scheduler.env.need_schedule_by_RL_jobs = scheduler.need_schedule_by_RL_jobs_before_move
            scheduled_dic_1, reward_1 = scheduler.find_initial_solution()
            assert reward_1 == reward
            super(HPCScheduler, scheduler).__init__(scheduled_dic_1, -reward_1, config.stepsforsa)
            best_scheduled_dic_SA_step500, best_cost_SA_step500, optimal_steps_SA_step500 = scheduler.anneal(ep, t, f3)
            duration_sa_step500 = round(time.time() - start_time, 3)

            # for SA steps=1000
            scheduler.env.remove_current_schedule()
            scheduler.env.reset_for_next_time_step(update_timestamp=False)
            start_time = time.time()
            scheduler.env.need_schedule_by_RL_jobs = scheduler.need_schedule_by_RL_jobs_before_move
            scheduled_dic_1, reward_1 = scheduler.find_initial_solution()
            assert reward_1 == reward
            super(HPCScheduler, scheduler).__init__(scheduled_dic_1, -reward_1, config.stepsforsa*2)
            best_scheduled_dic_SA_step1000, best_cost_SA_step1000, optimal_steps_SA_step1000 = scheduler.anneal(ep, t, f3)
            duration_sa_step1000 = round(time.time() - start_time, 3)

            scheduler.env.need_schedule_by_RL_jobs = scheduler.need_schedule_by_RL_jobs_before_move
            scheduler.env.remove_current_schedule()
            cumulative_schedule_job_num += len(scheduler.need_schedule_by_RL_jobs_before_move)
            # scheduler.env.plot_cluster()
            if config.plot_cluster:
                scheduler.env.plot_cluster()
            if config.compare_with_model:
                all_job_assign_nodes_dic_1, cost_seq_2, cost_model, solving_time, cancled_job_num, is_optimal = scheduler.env.compare_with_other_policy(duration_NSA = duration_nsa, duration_SA = duration_sa_step500, best_cost_NSA = best_cost_NSA, best_cost_SA
                =best_cost_SA_step500, f_write = f2, optimal_steps = optimal_steps_NSA, enableoutput = False, with_timelimit_scip = True)
                scheduler.env.cost_model = 0
                scheduler.env.cost_seq = 0
                enableoutput = False
                # if ep == total_test_episodes and solving_time > duration and cancled_job_num == 0 and cost_model >= best_cost:
                #     enableoutput = True
                if not is_optimal:
                    all_job_assign_nodes_dic_2, cost_seq_1, cost_model_notimelimit, solving_time_notimelimit, cancled_job_num_notimelimit, is_optimal_notimelimit = scheduler.env.compare_with_other_policy(duration_NSA = duration_nsa, duration_SA = duration_sa_step500, best_cost_NSA = best_cost_NSA, best_cost_SA
                =best_cost_SA_step500, f_write = f2, optimal_steps = optimal_steps_NSA, enableoutput = False, with_timelimit_scip = False)
                    assert is_optimal_notimelimit
                    if config.method_find_nodes == 1:
                        assert cancled_job_num_notimelimit == 0
                    cumulative_cancel_job_number_model_notimelimit += cancled_job_num_notimelimit
                else:
                    all_job_assign_nodes_dic_2 = all_job_assign_nodes_dic_1
                    cost_seq_1 = cost_seq_2
                    cost_model_notimelimit = cost_model
                    solving_time_notimelimit = solving_time
                    assert cancled_job_num == 0
                # if cost_model_notimelimit - 10000 > best_cost:
                #     scheduler.env.plot_cluster()

                assert cost_seq_1 == cost_seq_2

                cumulative_cost_seq += cost_seq_1
                cumulative_cost_model_notimelimit += cost_model_notimelimit
                cumulative_cost_model += cost_model

                cumulative_solving_time_model_notimelimit += solving_time_notimelimit
                cumulative_solving_time_model += solving_time
                cumulative_cancel_job_number_model_timelimit += cancled_job_num

                if cost_model < best_cost_NSA and cancled_job_num == 0:
                    cumulative_cost_nsa_model += cost_model
                    cumulative_solving_time_nsa_model += solving_time
                    scheduler.env.schedule_finish_assign_best_solution(all_job_assign_nodes_dic_1, duration_nsa)
                else:
                    cumulative_cost_nsa_model += best_cost_NSA
                    cumulative_solving_time_nsa_model += duration_nsa
                    scheduler.env.schedule_finish_assign_best_solution(best_solution_for_NSA, duration_nsa)
            else:
                scheduler.env.calculate_cost_by_seq_allocate()
                scheduler.env.schedule_finish_assign_best_solution(best_solution_for_NSA, duration_nsa)
                print('\nSeq:{}, SA time step 500:{}, SA cost step 500:{}, SA time step 1000:{}, SA cost step 1000:{}, NSA time:{}, NSA cost:{}'.format(scheduler.env.cost_seq,
                    duration_sa_step500, best_cost_SA_step500, duration_sa_step1000, best_cost_SA_step1000, duration_nsa, best_cost_NSA))

            cumulative_cost_nsa += best_cost_NSA
            cumulative_solving_time_nsa += duration_nsa

            cumulative_cost_sa_step500 += best_cost_SA_step500
            cumulative_solving_time_sa_step500 += duration_sa_step500

            cumulative_cost_sa_step1000 += best_cost_SA_step1000
            cumulative_solving_time_sa_step1000 += duration_sa_step1000

            scheduler.env.reset_for_next_time_step()

        f.write('{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}\n'.format(ep, cumulative_cost_seq//max_ep_len,
        cumulative_cost_model_notimelimit//max_ep_len, round(cumulative_cancel_job_number_model_notimelimit/cumulative_schedule_job_num,2), round(cumulative_solving_time_model_notimelimit/max_ep_len, 1),
        cumulative_cost_model//max_ep_len, round(cumulative_cancel_job_number_model_timelimit/cumulative_schedule_job_num,2), round(cumulative_solving_time_model/max_ep_len,1),
        cumulative_cost_sa_step500//max_ep_len, round(cumulative_solving_time_sa_step500/max_ep_len, 1),
        cumulative_cost_sa_step1000//max_ep_len, round(cumulative_solving_time_sa_step1000/max_ep_len, 1),
        cumulative_cost_nsa//max_ep_len, round(cumulative_solving_time_nsa/max_ep_len, 1),
        cumulative_cost_nsa_model//max_ep_len, round(cumulative_solving_time_nsa_model/max_ep_len, 1)))
        f.flush()
        f2.flush()
        f3.flush()
    f.close()
    f2.close()
    f3.close()

def test2(max_ep, max_time_steps):
    print("============================================================================================")
    scheduler = HPCScheduler()
    start_time_step = 0
    fw = open('simanneal/comm_wait_cost_{}.txt'.format(config.time_slot), 'w')
    for ep in range(1, max_ep + 1):
        scheduler.env.reset()
        scheduler.env.start_index = start_time_step
        scheduler.env.current_timestamp = scheduler.env.all_jobs[start_time_step].submit_time + config.time_slot
        max_job_number = start_time_step + max_time_steps
        scheduler.env.job_number = max_job_number
        while(True):
            if scheduler.env.start_index >= max_job_number and len(scheduler.env.job_queue) == 0:
                break
            need_to_process = scheduler.env.need_proceed_by_RL()
            if not need_to_process:
                continue
            start_time = time.time()
            scheduler.need_schedule_by_RL_jobs_before_move = deepcopy(scheduler.env.need_schedule_by_RL_jobs)
            scheduled_dic, reward = scheduler.find_initial_solution()
            super(HPCScheduler, scheduler).__init__(scheduled_dic, -reward, config.stepsforsa)  # important!
            best_scheduled_dic, best_cost, obtain_optimal_steps = scheduler.anneal(ep, scheduler.env.start_index, None)
            assert abs(best_cost-scheduler.env.best_cost) <= 1
            scheduler.env.need_schedule_by_RL_jobs = scheduler.need_schedule_by_RL_jobs_before_move
            duration = time.time() - start_time
            scheduler.env.remove_current_schedule()
            scheduler.env.schedule_finish_assign_best_solution(best_scheduled=best_scheduled_dic, duration = duration)
            scheduler.env.reset_for_next_time_step()

        avg_comm_cost, avg_wait_time = scheduler.env.get_comm_cost_wait_time()
        # assert len(scheduler.env.scheduled_logs.values()) == max_time_steps
        # print('\navg. comm. cost,', avg_comm_cost, ', avg. waiting time, ', avg_wait_time)
        fw.write('ep:{}, comm. cost: {}, waiting. cost: {}\n'.format(ep, avg_comm_cost, avg_wait_time))
        fw.flush()
        start_time_step += max_time_steps
    fw.close()

if __name__ == '__main__':
    test()


# Comparison is a way to test items agains each other

a = 5
b = 22
c = 21
d = c
# Nesting is method to show which statement belong to what function
# indented block

# if (a > b){
# 	print('A is less than B', a)

# print('This statement does not have any indentation')

# if(True):
# 	print('This statement HAS indentation')

# # Less Than
# if (a < b):
# 	print('A is Greater than B')
# # Greater than
# elif (c > b):
# 	print('C is Greater than B')

# # Greater than or Equal to
# elif (b >= a):
# 	print('B is Greater than A')

# # If all other cases Fail
# else:
# 	print('All others Failed')

# Inequality
# if (d != a):
# 	print('D is not equal A')
# else:
# 	print('D is equal A')

# if (a < b) and (c < b):
# 	print('this is an example of multiple options')

# if (a > b) or (c > b):
# 	print('if both statements are True this is Printed')

# True and True = True
# True and False = False
# False and False = False

# True or True = True
# True or False = True
# False or False = False

# string_one = 'This is a String'
# string_two = 'this is a string'

# if (string_one == string_two):
# 	print('both Strings are equal')
# elif (string_one.lower() == string_two.lower()):
# 	print('both lowercase strings are equal')
# else:
# 	print('neither is equal')

# IN Operator can test whether items are in the list or not
# my_list = [12,45,34,56,123,12,3,2,4]
# num = 12

# if num in my_list:
# 	print(num)

while True:
	import random

	options = ['rock', 'paper', 'scissors']
	choice = input('Enter your Choice: ')
	choice = choice.lower()
	computer = random.choice(options)

	print(f'You chose {choice} and the computer chose {computer}')

	if (choice == 'rock') and (computer == 'paper'):
		print('Computer Wins')
	elif (choice == 'rock') and (computer == 'scissors'):
		print('You Wins')
	elif (choice == 'scissors') and (computer == 'rock'):
		print('Computer Wins')
	elif (choice == 'scissors') and (computer == 'paper'):
		print('You Wins')
	elif (choice == 'paper') and (computer == 'scissors'):
		print('Computer Wins')
	elif (choice == 'paper') and (computer == 'rock'):
		print('You Wins')
	else:
		print("It's a tie!!")

# For Loops do something for each value
# ForEach loop

items = [12,45,34,56,123,12,3,2,4]

# Enumerate
# for item in items:
# 	# Don't have a way to increment without index number

# for item in items:
# 	if(item >= 21):
# 		print(f'You are {item} years old, You can enter')
# 	else:
# 		print(f'You are only {item} years old and cannot enter')

# Print Index
# for index, item in enumerate(items):
# 	print(index, item)

# print('After the For Loop is done', index, item)

# List Comprehension - Python Specific Feature
# result = [[index, item] for index, item in enumerate(items)]
# print(result)
# print('After the For Loop is done', index, item)

# Generators / List Comprehension
# people_over_21 = [age for age in items if age >= 21]
# print(people_over_21)
# for item in people_over_21:
# 	print(item)

# While - Repeat until a parameter is met

# i = 10
# counter = 0
# while counter <= 10:
# 	print("Only run for a little bit", counter)

# 	# Break Case for Loop
# 	counter += 1
# print('While loop is finised!!!!')

# If / Elif / Else / For Loop / While Loop

# Conditional run 1 Time
# If / elif / else Run only 1 Time

# Loops Run until the Break Case
# For Break Case (python For is really forEach)
# - For loops run until the end of the list/dictionary

# While Loops - Will repeat until a break case is met

# Conditional can be put inside a loop


from typing import List, Tuple

# simufml
from simufml.secureprotol.encrypt import PaillierEncrypt
from simufml.utils.util import Role
from simufml.common.comm.communication import Communicator

class CipherSynchronizer(Communicator):
    cipher_class: callable = None

    def __init__(
        self,
        role: str,
        roles: List[str],
        key_length: int=1024
    ):
        super().__init__(
            role=role,
            variables=[(f'{r}_pubkey', r, Role.broadcast) for r in roles]
        )
        self.roles = roles
        self.key_length = key_length

    async def sync(self):
        cipher = self.cipher_class()
        cipher.generate_key(self.key_length)
        pubkey = cipher.get_public_key()
        await self.send(f'{self.role}_pubkey', pubkey)
        ciphers = {self.role: cipher}
        for peer in self.roles:
            if peer==self.role:
                continue
            ciphers[peer] = self.cipher_class()
            pubkey = await self.get(f'{peer}_pubkey')
            ciphers[peer].set_public_key(pubkey)
        return ciphers

class PaillierSynchronizer(CipherSynchronizer):
    cipher_class = PaillierEncrypt


from flask import request, url_for
from flask_restful import Resource
from http import HTTPStatus
from utils import hash_password
from models.user import User
from flask_jwt_extended import jwt_required, get_jwt_identity
from schemas.user import UserSchema
from schemas.recipe import RecipeSchema, RecipePaginationSchema
from models.recipe import Recipe
from webargs import fields
from webargs.flaskparser import use_kwargs
from extensions import mail, image_set
from utils import generate_token, verify_token, save_image
from flask_mail import Message
import os
# globals
user_schema = UserSchema()
user_public_schema = UserSchema(exclude=('email',))
recipe_list_schema = RecipeSchema(many=True)
user_avatar_schema = UserSchema(only=('avatar_url',))
recipe_pagination_schema = RecipePaginationSchema()

class MeResource(Resource):
    @jwt_required(optional=True)
    def get(self):
        current_user = get_jwt_identity()
        user = User.get_by_id(id=current_user)
        return user_schema.dump(user), HTTPStatus.OK

class UserResource(Resource):
    @jwt_required(optional=True)
    def get(self, username):
        user = User.get_by_username(username=username)
        if user is None:
            return {'message': 'user not found'}, HTTPStatus.NOT_FOUND
        current_user = get_jwt_identity()
        if current_user == user.id:
            return user_schema.dump(user), HTTPStatus.OK
        else:
            return user_public_schema.dump(user), HTTPStatus.OK

class UserListResource(Resource):
    def post(self):
        json_data = request.get_json()
        data = user_schema.load(data=json_data)

        username = data.get('username')
        email = data.get('email')

        if User.get_by_username(username):
            return {'message': 'username already exists'}, HTTPStatus.BAD_REQUEST
        if User.get_by_email(email):
            return {'message': 'email already exists'}, HTTPStatus.BAD_REQUEST

        user = User(**data)
        user.save()
        token = generate_token(user.email, salt='activate')
        subject = 'Please confirm your registration.'
        link = url_for('useractivateresource',
                       token=token,
                       _external=True)
        body = 'Hi, Thanks for using SmileCook! Please confirm your registration by clicking on the link: {}'.format(
            link)
        msg = Message(recipients=[user.email],
                      body=body,
                      subject=subject)
        mail.send(msg)
        return user_schema.dump(user), HTTPStatus.CREATED

class UserRecipeListResource(Resource):
    @jwt_required(optional=True)
    @use_kwargs({'page': fields.Int(missing=1), 'per_page': fields.Int(missing=10), 'visibility': fields.Str(missing='public')}, location='query')
    def get(self, username, page, per_page, visibility):
        user = User.get_by_username(username=username)
        if user == None:
            return {'message': 'No such user'}, HTTPStatus.NOT_FOUND
        current_user = get_jwt_identity()
        if current_user == user.id and visibility in ['all', 'private']:
            pass
        else:
            visibility = 'public'

        paginated_recipes = Recipe.get_all_by_user(
            user_id=user.id, page=page, per_page=per_page, visibility=visibility)
        return recipe_pagination_schema.dump(paginated_recipes), HTTPStatus.OK

class UserActivateResource(Resource):
    def get(self, token):
        email = verify_token(token, salt='activate')
        if email is False:
            return {'message': 'Invalid tooken or token expired'}, HTTPStatus.BAD_REQUEST
        user = User.get_by_email(email)
        if not user:
            return {'message': 'Invalid user'}, HTTPStatus.NOT_FOUND
        if user.is_active == True:
            return {'message': 'user already active'}, HTTPStatus.BAD_REQUEST
        user.is_active = True
        user.save()
        return {'message': 'User activated'}, HTTPStatus.NO_CONTENT

class UserAvatarUploadResource(Resource):
    @jwt_required()
    def put(self):
        file = request.files.get('avatar')
        if not file:
            return {'message': 'Not a valid image'}, HTTPStatus.BAD_REQUEST
        if not image_set.file_allowed(file, file.filename):
            return {'message': 'File type not allowed'}, HTTPStatus.BAD_REQUEST
        user = User.get_by_id(id=get_jwt_identity())
        if user.avatar_image:
            avatar_path = image_set.path(
                folder='avatars', filename=user.avatar_image)
            if os.path.exists(avatar_path):
                os.remove(avatar_path)
        filename = save_image(image=file, folder='avatars')
        user.avatar_image = filename
        user.save()
        return user_avatar_schema.dump(user), HTTPStatus.OK


def GL_ANZ():
    master = Tk()
    p = Canvas(master, width=400, height=400)
    p.grid(row=400, column=200)
    p.create_line(200, 0, 200, 400)
    p.create_line(0, 200, 400, 200)

    def bruch(s):
        try:
            t = ''
            m = ''
            trigger = ''
            for i in range(0, len(s), 1):
                hilf = s[i]
                if hilf == '/':
                    trigger = 'aktiv'
                elif trigger == 'aktiv':
                    m = m + hilf
                else:
                    t = t + hilf
            ausgabe = int(t) / int(m)
        except ValueError:
            ausgabe = float(s)
        return ausgabe

    print('y=cx^2+bx+a')
    c = bruch(input('c='))  # n
    b = bruch(input('b='))  # x
    a = bruch(input('a='))  # x^2

    if c == 0:  # linear
        d = abs(b)

        if d < 1 / 10000:
            print('Das ist zu niedrig')
        elif d >= 1 / 10000 and d <= 1 / 1000:
            lx = 1 / 100
            ly = d / (lx)
        elif d > 1 / 1000 and d < 1 / 100:
            lx = 1 / 10
            ly = d / (lx)
        elif d >= 1 / 100 and d < 33:
            lx = 1
            ly = d
        elif d >= 33 and d < 3333:
            lx = 10
            ly = d / (lx)
        elif d >= 3333 and d <= 33333:
            lx = 100
            ly = round(d / (lx))
        else:
            print('Das ist zu hoch')

        # Beschriftung:
        for i in range(200, 410, 10):  # x-Achse(rechts)
            p.create_line(i, 200, i, 205)
        for i in range(200, -20, -10):  # x-Achse(links)
            p.create_line(i, 200, i, 205)
        for i in range(200, 410, 10):  # y-Achse(unten)
            p.create_line(200, i, 195, i)
        for i in range(200, -20, -10):  # y-Achse(oben)
            p.create_line(200, i, 195, i)
        # große Markierungen
        for i in range(200, 450, 50):
            p.create_line(i, 200, i, 210)
        for i in range(200, -100, -50):
            p.create_line(i, 200, i, 210)
        for i in range(200, 450, 50):
            p.create_line(200, i, 190, i)
        for i in range(200, -100, -50):
            p.create_line(200, i, 190, i)

        skalierung = input('Geben sie ein, ob die Skalierung automatisch(1) oder manuell(2) erfolgen soll: ')
        if skalierung != '1' and skalierung != '2':
            print('ENTWEDER 1 ODER 2 SCHREIBEN!!! SO SCHWER IST DAS NICHT!!!')
            pm = 0
            ln = 0
        elif skalierung == '1':
            e = abs(a)
            if e > 30 * d:
                print('a darf höchstens 30 mal so groß, wie b sein, um eine optimale Skallierung zu erreichen')
            elif e == 0:
                lx = lx
                ly = ly
                ln = 0
            elif e == d:
                lx = lx
                ly = ly
                if a >= 0:
                    ln = 50
                else:
                    ln = -50
            elif e > d and e <= 30 * d:
                lx = lx / 10
                ly = 10 * ly
                if a >= 0:
                    ln = 50 // ((10 * d) / e)
                else:
                    ln = -(50 // ((10 * d) / e))
            elif e < d and e > d / 10:
                lx = lx
                ly = ly
                if a >= 0:
                    ln = 50 // (d / e)
                else:
                    ln = -(50 // (d / e))
            else:
                print('a muss min. 1/10 von b betragen, um eine optimale Skallierung zu erreichen')

            for i in range(5, 20, 5):
                try:
                    hilfx = (i / 5) / lx
                    if abs(hilfx) >= 1:
                        hilfx = int(hilfx)
                    else:
                        hilfx = round(hilfx, 2)
                    hilfy = (i / 5) * ly
                except NameError:
                    hilfx = 0
                    hilfy = 0
                    print('Kein x vorhanden')
                # print(round(hilfe+0.01))
                # hilfe=int(hilfe)
                # print(hilfe)
                p.create_text(200 + 10 * i, 215, text=abs(hilfx))  # text(breite,höhe,text='text')  #rechts
                p.create_text(200 - 10 * i, 215, text=-abs(hilfx))  # links
                p.create_text(180, 200 - 10 * i, text=round(abs(hilfy), 2))  # oben
                p.create_text(178, 200 + 10 * i, text=round(-abs(hilfy), 2))  # unten
                if b >= 0:
                    pm = 1
                else:
                    pm = -1

        else:
            bx = int(input('Geben sie das maximale x im intervall an (positiv und ganzzahlig): '))
            by = int(input('Geben sie das maximale y im intervall an (positiv und ganzzahlig): '))
            for i in range(5, 20, 5):
                hilfx = (i / 5) * (bx / 4)
                hilfy = (i / 5) * (by / 4)
                p.create_text(200 + 10 * i, 215, text=round(abs(hilfx), 2))  # text(breite,höhe,text='text')  #rechts
                p.create_text(200 - 10 * i, 215, text=round(-abs(hilfx), 2))  # links
                p.create_text(180, 200 - 10 * i, text=round(abs(hilfy), 2))  # oben
                p.create_text(178, 200 + 10 * i, text=round(-abs(hilfy), 2))  # unten
            pm = (bx / by) * b
            ln = a / ((by / 4) / 50)

        if round(a + b) == a + b:
            for x in range(-2000, 2001, 1):
                e = ((x - 1) + 200)
                f = 400 - ((x - 1) * pm + 200) - ln
                g = (x + 200)
                h = 400 - (x * pm + 200) - ln
                p.create_line(e, f, g, h, fill='red')

        elif round(a + b, 1) == a + b:
            for x in range(-2000, 2001, 1):
                e = (((x - 1) + 200))
                f = (400 - ((x - 1) * pm + 200) - ln)
                g = ((x + 200))
                h = (400 - (x + 200) * pm - ln)
                p.create_line(e, f, g, h, fill='yellow')
        else:
            for x in range(-2000, 2001, 1):
                e = round((((x - 1) + 200)), 2)
                f = round((400 - ((x - 1) * pm + 200) - ln), 2)
                g = round(((x + 200)), 2)
                h = round((400 - (x * pm + 200) - ln), 2)
                p.create_line(e, f, g, h, fill='blue')

    else:
        mc = c / 10
        d = abs(c)
        e = abs(b)
        f = abs(a)
        # Beschriftung:
        for i in range(200, 410, 10):  # x-Achse(rechts)
            p.create_line(i, 200, i, 205)
        for i in range(200, -20, -10):  # x-Achse(links)
            p.create_line(i, 200, i, 205)
        for i in range(200, 410, 10):  # y-Achse(unten)
            p.create_line(200, i, 195, i)
        for i in range(200, -20, -10):  # y-Achse(oben)
            p.create_line(200, i, 195, i)
        # große Markierungen
        for i in range(200, 450, 50):
            p.create_line(i, 200, i, 210)
        for i in range(200, -100, -50):
            p.create_line(i, 200, i, 210)
        for i in range(200, 450, 50):
            p.create_line(200, i, 190, i)
        for i in range(200, -100, -50):
            p.create_line(200, i, 190, i)
        skalierung = input('Geben sie ein, ob die Skalierung automatisch(1) oder manuell(2) erfolgen soll: ')
        if skalierung != '1' and skalierung != '2':
            print('ENTWEDER 1 ODER 2 SCHREIBEN!!! SO SCHWER IST DAS NICHT!!!')
            pm = 0
            ln = 0
        elif skalierung == '1':
            hil = 1
            if d >= 1000:
                print('Das ist zu hoch! Nicht optimale Skalierung möglich')
            elif d >= 100:
                qx = 1 / 100
                qy = 1 / 100
                mc = mc / 100
            elif d < 100 and d >= 10:
                qx = 1 / 10
                qy = 1 / 10
                mc = mc / 10
            elif d < 10 and d >= 1 / 10:
                qx = 1
                qy = 1
                mc = mc
            elif d < 1 / 10 and d >= 1 / 100:
                qx = 10
                qy = 10
                mc = 10 * mc
            elif d <= 1 / 1000:
                print('Das ist zu niedrig! Keine optimale Skalierung möglich')
            else:
                qx = 100
                qy = 100
                mc = 100 * mc
            for x in range(-200, 201, 1):
                # print(x*x,'x^2')
                e = ((x - 1) + 200)
                f = 400 - (mc * (x - 1) * (x - 1) + b * (x - 1) / qx + 200) - a * 10 / qx
                g = (x + 200)
                h = 400 - (mc * x * x + b * x / qx + 200) - a * 10 / qx
                # print(e,f,g,h)
                p.create_line(e, f, g, h, fill='red')

        else:
            bx = int(input('Geben sie das maximale x im intervall an (positiv und ganzzahlig): '))
            by = int(input('Geben sie das maximale y im intervall an (positiv und ganzzahlig): '))
            qx = bx / 4 / 5
            qy = by / 4 / 5
            mc = c / 10
            hil = bx / by
            if c == 1:
                hil = 2
            else:
                hil = hil
            for x in range(-200, 201, 1):
                # print(x*x,'x^2')
                e = ((50 / (bx / 4)) * (x - 1) + 200)
                f = 400 - (c * (50 / (by / 4)) * (x - 1) * (x - 1) + b * (50 / (by / 4)) * (x - 1) + 200) - a * (
                200 / by)
                g = ((50 / (bx / 4)) * x + 200)
                h = 400 - (c * (50 / (by / 4)) * x * x + b * (50 / (by / 4)) * x + 200) - a * (200 / by)
                # print(e,f,g,h)
                p.create_line(e, f, g, h, fill='red')

        for i in range(5, 20, 5):
            p.create_text(200 + 10 * i, 215, text=i * qx)
            p.create_text(200 - 10 * i, 215, text=-i * qx)
            p.create_text(175, 200 - 10 * i, text=i * qy)
            p.create_text(175, 200 + 10 * i, text=-i * qy)

    master.mainloop()


# pip install streamlit
# pip install numpy
# pip install joblib
# pip install openpyxl

# from tkinter import X
import streamlit as st
import pandas as pd
import os
import pandas as pd
import MC_status
import MC_Graph
import model_predict
import glob
import openpyxl
import csv
# from streamlitapp.Data_Input import data_input

st.set_page_config(
    page_title="Swtich Gear Prediction Main Page",
    layout="wide"
)
def get_csv(df):

    csv = df.to_csv(index=False)

    return csv
def get_data1(dtfile):
    dtfile.to_csv (r'Temp/temp.csv', index = False, header=True)

def form_callback():
    st.write(st.session_state.my_option)
    st.write(st.session_state.my_checkbox)

def listmodel(path):
    # return os.urllib(path)

    return os.listdir(path)

def listmachine(path):
    return os.listdir(path)

def st_header(data):
    st.title("Switch Gear Status Classification App")

    with st.container():

        col1, col2, col3 = st.columns([1,10,1])

        with col2 :
            # st.markdown("{}".format(str(word)))
            uploaded_file = st.file_uploader("Choose a A1-A16 file")

            # st.markdown("{}".format(str(word)))
            uploaded_file2 = st.file_uploader("Choose a A18-A31 file")

            if uploaded_file is not None and uploaded_file2 is not None:
                import data_split
                data_split.Data_Split.split(uploaded_file)
                data_split.Data_Split.split(uploaded_file2)
                data = True

                # st.write(data.head())

                # get_data1(data)
                # st.table(data)
                # import Data_split
                # Data_split.data_input(data)
    return data

def st_body():

    # url = 'https://raw.githubusercontent.com/mullermu/SWG_Streamlit/tree/main/streamlitapp/model/'
    lstmodel = listmodel('model/')
    # st.write(lstmodel)
    tmp = [i.split('.')[0] for i in lstmodel]
    col1, col2, col3 = st.columns([1,10,1])
    with col2 :
        with st.form(key='my_form'):
            option = st.selectbox('Select Model:',tmp,key="my_option")
            submitted = st.form_submit_button('selected model and predict')
            if submitted:
                st.write('You selected model: {}'.format(str(option)))
            return lstmodel[tmp.index(option)]

    # import requests
    # from bs4 import BeautifulSoup

    # # URL on the Github where the csv files are stored
    # github_url = 'https://https://github.com/mullermu/SWG_Streamlit_2/tree/master/model'  # change USERNAME, REPOSITORY and FOLDER with actual name

    # result = requests.get(github_url)

    # soup = BeautifulSoup(database.text, 'html.parser')
    # csvfiles = soup.find_all(title=result.compile("\.csv$"))

    # filename = [ ]
    # for i in csvfiles:
    #         filename.append(i.extract().get_text())

def st_result(clf, df, sim = False):
    if clf is not None:
        if sim is not True:
            df = None
            model_predict.get_predict_result.getResult(clf, df, False)
            download_results()
        else:
            model_predict.get_predict_result.getResult(clf, df, True)
        # model = joblib.load(os.path.join("../model/",clf))
        # z = model.predict(X)
        # res = pd.concat([data,pd.DataFrame(z,columns=['Status'])],axis=1)
        # col1, col2, col3 = st.columns([1,1,1])
        # with col2 :
        #     st.download_button("Download Classification File",get_csv(res),"../output/result_app.csv")
def create_last_results():
    files = [os.path.split(filename) for filename in glob.glob("output/Predicted Results/*.csv")]
    wb = openpyxl.Workbook()
    del wb[wb.sheetnames[0]]        # Remove the default 'Sheet1'
    for f_path, f_name in files:
        (f_short_name, f_extension) = os.path.splitext(f_name)
        with open(os.path.join(f_path, f_name)) as f_input:
            # st.write(f_short_name)
            ws = wb.create_sheet(title=os.path.basename(f_short_name))
            for row in csv.reader(f_input):
                ws.append(row)
    wb.save('output/Predicted Results/Last_Results.xlsx')
def download_results():

    files = [os.path.split(filename) for filename in glob.glob("output/Predicted Results/*.csv")]
    st.write("Data Predicted")

    saveToDB = st.radio(
    "Do you want to save data to database?",
    ('Yes, This is new data.', 'No, Data was the same as the old one.','Replace all with the new one.'))
    saveBT = st.button('Save to Database')
    if saveToDB == 'Yes, This is new data.' and saveBT == True:
        wb = openpyxl.load_workbook('output/Predicted Results/Results.xlsx')
        for f_path, f_name in files:
            (f_short_name, f_extension) = os.path.splitext(f_name)
            with open(os.path.join(f_path, f_name)) as f_input:
                ws = wb[f_short_name]
                csv_reader = csv.reader(f_input)
                first_line = next(csv_reader)
                # st.write(first_line)
                for row in csv.reader(f_input):
                    if row != first_line:
                        ws.append(row)
        wb.save('output/Predicted Results/Results.xlsx')
        create_last_results()
        st.write("Added to Database")

    elif saveToDB == 'No, Data was the same as the old one.' and saveBT == True:
        st.write("Nothing saved")
        create_last_results()
    elif saveToDB == 'Replace all with the new one.' and saveBT == True:
        wb = openpyxl.Workbook()
        del wb[wb.sheetnames[0]]        # Remove the default 'Sheet1'
        for f_path, f_name in files:
            (f_short_name, f_extension) = os.path.splitext(f_name)
            with open(os.path.join(f_path, f_name)) as f_input:
                # st.write(f_short_name)
                ws = wb.create_sheet(title=os.path.basename(f_short_name))
                for row in csv.reader(f_input):
                    ws.append(row)
        wb.save('output/Predicted Results/Results.xlsx')
        st.write("Replaced to Database")
        create_last_results()

    downloadResults = st.radio(
    "Which file do you would like to download?",
    ('Download last results.', 'Download all database results.'))
    if downloadResults == 'Download last results.':
        my_file = open('output/Predicted Results/Last_Results.xlsx', 'rb')
        fileName = 'Last_Results.xlsx'
    elif downloadResults == 'Download all database results.':
        my_file = open('output/Predicted Results/Results.xlsx', 'rb')
        fileName = 'Database_Results.xlsx'

    st.download_button(label = 'Download Results', data = my_file, file_name = fileName, mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

def status_body():
    status = MC_status.MC_status.st_status()
    return status

def summary_chart():
    st.header("Summary Chart")
    chart_data = pd.DataFrame(
    MC_status.MC_status.sum_status(),
    columns=['Summary'],
    index=['Stage A', 'Stage B', 'Stage C','Stage D'])
    st.bar_chart(chart_data)

def history_chart():
    MC_Graph.mc_graph.get_mc_graph()

def simulation_app():
    st.write("""
    # Simulation Prediction App
    """)
    def user_input_features():

        col1, col2 = st.columns([1,1])
        with col1 :
            from datetime import date
            Start_Time = date.today()
            End_Time = date.today()
            UPPER_BUS_PHASE_A = st.slider('UPPER BUS PHASE A Temperature', 0.00, 100.00, 50.00)
            UPPER_BUS_PHASE_B = st.slider('UPPER BUS PHASE B Temperature', 0.00, 100.00, 50.00)
            UPPER_BUS_PHASE_C = st.slider('UPPER BUS PHASE C Temperature', 0.00, 100.00, 50.00)
            LOWER_BUS_PHASE_A = st.slider('LOWER BUS PHASE A Temperature', 0.00, 100.00, 50.00)
            LOWER_BUS_PHASE_B = st.slider('LOWER BUS PHASE B Temperature', 0.00, 100.00, 50.00)
            LOWER_BUS_PHASE_C = st.slider('LOWER BUS PHASE C Temperature', 0.00, 100.00, 50.00)
        with col2:
            OUTGOING_PHASE_A = st.slider('OUTGOING PHASE A Temperature', 0.00, 100.00, 50.00)
            OUTGOING_PHASE_B = st.slider('OUTGOING PHASE B Temperature', 0.00, 100.00, 50.00)
            OUTGOING_PHASE_C = st.slider('OUTGOING PHASE C Temperature', 0.00, 100.00, 50.00)
            UPPER_BUS_PD = st.slider('UPPER BUS PD', 0.00, 10000.00, 100.00)
            LOWER_BUS_PD = st.slider('LOWER BUS PD', 0.00, 10000.00, 100.00)
            SPOUT_PD = st.slider('SPOUT PD', 0.00, 10000.00, 100.00)
            OUTGOING_PD = st.slider('OUTGOING PD', 0.00, 10000.00, 100.00)
        data = {
                'Start' : Start_Time,
                'End' : End_Time,
                'UPPER_BUS_PHASE_A': UPPER_BUS_PHASE_A,
                'UPPER_BUS_PHASE_B': UPPER_BUS_PHASE_B,
                'UPPER_BUS_PHASE_C': UPPER_BUS_PHASE_C,
                'LOWER_BUS_PHASE_A': LOWER_BUS_PHASE_A,
                'LOWER_BUS_PHASE_B': LOWER_BUS_PHASE_B,
                'LOWER_BUS_PHASE_C': LOWER_BUS_PHASE_C,
                'OUTGOING_PHASE_A' : OUTGOING_PHASE_A,
                'OUTGOING_PHASE_B' : OUTGOING_PHASE_B,
                'OUTGOING_PHASE_C' : OUTGOING_PHASE_C,
                'UPPER_BUS_PD': UPPER_BUS_PD,
                'LOWER_BUS_PD' : LOWER_BUS_PD,
                'SPOUT_PD' : SPOUT_PD,
                'OUTGOING_PD': OUTGOING_PD
                }

        features = pd.DataFrame(data, index=[0])
        return features
    input_df = user_input_features()
    # df = input_df.iloc[:]
    # Displays the user input features
    st.subheader('User Input features')

    st.write('Awaiting CSV file to be uploaded. Currently using example input parameters (shown below).')
    st.write(input_df.iloc[:1])

    if input_df is not None:
        # Reads in saved classification model
        lstmodel = listmodel('model/')
        # st.write(lstmodel)
        tmp = [i.split('.')[0] for i in lstmodel]
        col1, col2, col3 = st.columns([1,5,1])
        with col2 :
            option = st.selectbox('Select Model:',tmp)
            st.write('You selected model: {}'.format(str(option)))
            lstmodel[tmp.index(option)]
        st_result(lstmodel[tmp.index(option)], input_df, True)

def main():
    with st.sidebar:
            data = None
            data = st_header(data)
            clf = st_body()
            if clf is not None and data is True:
                df = None
                st_result(clf, df, False)
            else:
                st.write('Please upload files and select predection model!')

    tab1, tab2, tab3 = st.tabs(["Summary", "Details", "Simulation"])
    with tab1:
        st.header("Summary")
        status_body()
        summary_chart()
    with tab2:
        history_chart()
    with tab3:
        simulation_app()

main()


import json
# it is almost like python dictionary
# there is some converts from json to python like {none:None},{true:True}
# dumps - convert dict to the string
# loads - by reverse ==>
# when we create json(string) it is mandatory to use double quatation mark

# d = {
#       'name': 'Jones',
#       'age': 17,
#       'id': '21B30819'
# }

# data = json.dumps(d)
# print(type(data))

# d2 = json.loads(data)
# print(type(d2), d2['name'], d2['age'], d2['id'])
# print(d==d2)

######################################################################################

# f = open('input.txt','r')
# info = f.read()
# d = json.loads(info)
# print(d['name'], d['surname'])

######################################################################################

game_state = {
      'position':{
            'x': 100,
            'y': 200
      },
      'full_name':'Hello_World',
      'enemy':{
            'x': 300,
            'y': 300
      }
}
with open('output.','w') as f:
      f.write(json.dumps(game_state))

d = {
      'Almat': 3.9,
      'Dima': 3.1,
      'So on': 45
}

with open ('exam.json', 'w') as f:
      f.write(json.dumps(d))


#
# @lc app=leetcode id=1110 lang=python3
#
# [1110] Delete Nodes And Return Forest
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
from collections import deque

class Solution:
    def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:
        res = []
        to_delete = set(to_delete)
        q = deque([(root, True, root.val in to_delete)])

        while q:
            node, is_root, marked = q.popleft()
            if is_root and (not marked):
                res.append(node)
            if node.left:
                is_deleted = node.left.val in to_delete
                q.append((node.left, marked, is_deleted))
                if is_deleted:
                    node.left = None
            if node.right:
                is_deleted= node.right.val in to_delete
                q.append((node.right, marked, is_deleted))
                if is_deleted:
                    node.right = None

        return res

        # def dfs(node, is_root, marked):
        #     if is_root and (not marked):
        #         res.append(node)
        #     if node.left:
        #         is_deleted = node.left.val in to_delete
        #         dfs(node.left, marked, is_deleted)
        #         if is_deleted:
        #             node.left = None
        #     if node.right:
        #         is_deleted= node.right.val in to_delete
        #         dfs(node.right, marked, is_deleted)
        #         if is_deleted:
        #             node.right = None

        # dfs(root, True, root.val in to_delete)

# @lc code=end


# Exercise 9.4: Thermal diffusion in the Earth's crust
# Ryan Hennessey

from math import sin,pi
from numpy import empty
from pylab import plot,title,xlabel,ylabel,show

# Constants
L = 20.0      # Depth below surface in meters
D = 0.1       # Thermal diffusivity (m^2/day)
N = 100       # Number of divisions in grid
a = L/N       # Grid spacing
h = .1        # Time-step
epsilon = h

A = 10.0      # Constant in Celsius
B = 12.0      # Constant in Celsius
tau = 365.0   # Period in days

Tmid = 10.0   # Intermediate temperature in Celsius
T20 = 11.0    # Temperature at 20 m below surface

t1 = 9.25*tau
t2 = 9.5*tau
t3 = 9.75*tau
t4 = 10.0*tau
tend = t4 + epsilon

# Create arrays
T = empty(N+1,float)
T[N] = T20
T[1:N] = Tmid
Tp = empty(N+1,float)
Tp[N] = T20

# Main loop
t = 0.0
c = h*D/(a*a)
while t<tend:

    # Calculate the new surface temperature values
    T0 = A + B*sin(2*pi*t/tau)
    T[0] = T0
    Tp[0] = T0

    # Calculate the new values of T
    Tp[1:N] = T[1:N] + c*(T[0:N-1]+T[2:N+1]-2*T[1:N])
    T,Tp = Tp,T
    t += h

    # Make plots at the given times
    if abs(t-t1)<epsilon:
        plot(T)
    if abs(t-t2)<epsilon:
        plot(T)
    if abs(t-t3)<epsilon:
        plot(T)
    if abs(t-t4)<epsilon:
        plot(T)

xlabel("x")
ylabel("T")
show()


from PIL import Image, ImageEnhance, ImageFilter

import os
from tqdm import tqdm

# folder path
dir_path = r"./data/coco"
readpath = dir_path+"/val2014/"
writepath = dir_path+"/val2014(1)/"
# list to store files
res = []
# Iterate directory
for file in os.listdir(readpath):
    # check only text files
    if file.endswith('.jpg'):
        res.append(file)

for file in tqdm(res):
    img = Image.open(readpath + file)
    filter = ImageEnhance.Brightness(img)
    img2 = filter.enhance(1.5)
    name = file.split(".jpg")
    name = name[0]
    img2.save(writepath + name + "_bright.jpg")
    img2 = filter.enhance(0.5)
    img2.save(writepath + name + "_dark.jpg")
    img2 = img.rotate(45)
    img2.save(writepath + name + "_rotated1.jpg")
    img2 = img.rotate(315)
    img2.save(writepath + name + "_rotated2.jpg")
    img.save(writepath + name + '.jpg')

# rotate image
# img2 = img.rotate(45)
# img2.save("rotate.jpg")

#img2.show()


from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from drf_yasg import openapi
from drf_yasg.views import get_schema_view

schema_view = get_schema_view(openapi.Info(
    title='Документация для проекта "Туристические путешествия"',
    description='Сайт "Туристические путешествия"',
    default_version='v1'
), public=True)

urlpatterns = [
    path('grappelli/', include('grappelli.urls')),
    path('admin/', admin.site.urls),
    path('docs/', schema_view.with_ui('swagger')),
    path('api/v1/', include('account.urls')),
    path('api/v1/', include('Packets.urls')),
    path('api/v1/', include('Reviews.urls')),
]

"""Подключение media и static"""
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


class Vehicle:
    __reg: str
    __model: int
    __prod_year: int

    def __init__(self, reg: str = None, model: int = 0, prod_year: int = 2022) -> None:
        self.__reg = reg
        self.__model = model
        self.__prod_year = prod_year
        if self.__model < 0:
            self.__model = 0
        if self.__prod_year < 1900 or self.__prod_year > 2022:
            self.__prod_year = 2022

    @property
    def reg(self) -> str:
        return self.__reg

    @property
    def model(self) -> int:
        return self.__model

    @property
    def prod_year(self) -> int:
        return self.__prod_year

    @reg.setter
    def reg(self, value: str) -> None:
        self.__reg = value

    @model.setter
    def model(self, value: int) -> None:
        if value < 0:
            print("zla wartosc")
            return
        else:
            self.__model = value

    @prod_year.setter
    def prod_year(self, value: int) -> None:
        if value < 1900 or value > 2022:
            print("zla wartosc")
            return
        else:
            self.__prod_year = value

    def brake(self) -> str:
        return "Zatrzymuję się"

    def drive(self) -> str:
        return f"Jadę świetnym pojazdem z roku {self.__prod_year}"

    def __repr__(self) -> str:
        if self.__reg is None:
            return f'Pojazd wyprodukowany w roku: {self.__prod_year}\nModel: {self.__model}'
        else:
            return f'Pojazd wyprodukowany w roku: {self.__prod_year}\nModel: {self.__model}\nRejestracja: {self.__reg}'

    def __eq__(self, other) -> bool:
        if self.__model == other.__model:
            if self.__prod_year == other.__prod_year:
                return True
            else:
                return False
        else:
            return False

    def __ne__(self, other) -> bool:
        if self.__model == other.__model:
            if self.__prod_year != other.__prod_year:
                return True
            else:
                return False
        else:
            return True


numero_alto = numero_baixo = altura_maior = altura_menor = 0
for i in range(10):
    numero_alunos = int(input(f'Código do aluno {i+1}: '))
    altura = float(input(f'Altura do aluno {i+1}: '))
    if i == 0:
        numero_alto = numero_baixo = numero_alunos
        altura_maior = altura_menor = altura
    else:
        if altura > altura_maior:
            altura_maior = altura
            numero_alto = numero_alunos
        elif altura < altura_menor:
            altura_menor = altura
            numero_baixo = numero_alunos
print('-=' * 20)
print(f'O aluno de número {numero_alto} possui a maior altura da turma, {altura_maior} m')
print(f'O aluno de número {numero_baixo} possui a menor altura da turma, {altura_menor} m')