# 手动制表
tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

def print_table(tableData):
    x = len(tableData)          # 获取多少行
    y = len(tableData[0])       # 获取多少列

    column = []                 # 获取每一列的最大长度
    for i in range(y):                 # 0             1             2 3 4
        max_length = 0
        for j in range(x):             # 0,1,2,3,4     0,1,2,3,4
            if max_length < len(tableData[j][i]):
                max_length = len(tableData[j][i])
        column.append(max_length)

    print(column)
    # 打印阶段
    for i in range(x):
        for j in range(y):
            if j == 0:
                print(tableData[i][j].rjust(column[j]), end='\t')
            else:
                print(tableData[i][j].ljust(column[j]), end='\t')
        print("")

print_table(tableData)


"""Plotting the 9 KNN accuracy plots"""
from utils.plots import load_data_from_csv_wrapper, add_subplot_axes
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
import os
import json

plt.rcParams['interactive'] = False
fig = plt.figure(figsize=(10.0, 8.0))
subpos = [0.55, 0.3, 0.5, 0.4]

# wrn, cifar10
root_dir = '/data/gilad/logs/metrics/wrn/cifar10/log_1405_230818_metrics_w_confidence-SUPERSEED=23081800'
json_file = os.path.join(root_dir, 'data_for_figures', 'data.json')
with open(json_file) as f:
    data = json.load(f)
ax2 = fig.add_subplot(321)
ax2.plot(data['test']['regular']['dnn_score']['steps'], [v * 100 for v in data['test']['regular']['dnn_score']['values']], 'k')
ax2.plot(data['test']['regular']['knn_score']['steps'], [v * 100 for v in data['test']['regular']['knn_score']['values']], 'r')
ax2.plot(data['test']['regular']['svm_score']['steps'], [v * 100 for v in data['test']['regular']['svm_score']['values']], 'b')
ax2.plot(data['test']['regular']['lr_score']['steps'] , [v * 100 for v in data['test']['regular']['lr_score']['values']] , 'g')

ax2.set_ylim(bottom=0, top=110)
ax2.set_title('CIFAR-10', fontdict={'fontsize': 15})
# ax2.text(-15000, 52, 'Wide ResNet 28-10', va='center', rotation='vertical', fontdict={'fontsize': 15})
ax2.yaxis.grid()
ax2.set_ylabel('accuracy (%)', labelpad=0.5, fontdict={'fontsize': 15})
ax2.get_xaxis().set_visible(False)
ax2.tick_params(labelsize=13)

# ax2.add_patch(patches.Polygon(xy=np.array([[40000, 99], [27513.4, 65.6], [50000, 65.6], [50000, 32.2], [50000, 90]]), closed=True, color='silver'))
# ax2.add_patch(patches.Rectangle(xy=(40000, 90), width=10000, height=10, facecolor='moccasin'))

# wrn, cifar100
root_dir = '/data/gilad/logs/metrics/wrn/cifar100/log_1405_230818_metrics_w_confidence-SUPERSEED=23081800'
json_file = os.path.join(root_dir, 'data_for_figures', 'data.json')
with open(json_file) as f:
    data = json.load(f)
ax3 = fig.add_subplot(322)
ax3.plot(data['test']['regular']['dnn_score']['steps'], [v * 100 for v in data['test']['regular']['dnn_score']['values']], 'k')
ax3.plot(data['test']['regular']['knn_score']['steps'], [v * 100 for v in data['test']['regular']['knn_score']['values']], 'r')
ax3.plot(data['test']['regular']['svm_score']['steps'], [v * 100 for v in data['test']['regular']['svm_score']['values']], 'b')
ax3.plot(data['test']['regular']['lr_score']['steps'] , [v * 100 for v in data['test']['regular']['lr_score']['values']] , 'g')

ax3.set_ylim(bottom=0, top=85)
ax3.set_title('CIFAR-100', fontdict={'fontsize': 15})
ax3.yaxis.grid()
ax3.get_xaxis().set_visible(False)
ax3.tick_params(labelsize=13)
# ax3.add_patch(patches.Polygon(xy=np.array([[40000, 83.1], [27700, 50.75], [50000, 50.75], [50000, 25], [50000, 75]]), closed=True, color='silver'))
# ax3.add_patch(patches.Rectangle(xy=(40000, 75), width=10000, height=8, facecolor='moccasin'))

# lenet, cifar10
root_dir = '/data/gilad/logs/metrics/lenet/cifar10/log_1319_120918_metrics-SUPERSEED=12091800'
json_file = os.path.join(root_dir, 'data_for_figures', 'data.json')
with open(json_file) as f:
    data = json.load(f)
ax5 = fig.add_subplot(323)
ax5.plot(data['test']['regular']['dnn_score']['steps'], [v * 100 for v in data['test']['regular']['dnn_score']['values']], 'k')
ax5.plot(data['test']['regular']['knn_score']['steps'], [v * 100 for v in data['test']['regular']['knn_score']['values']], 'r')
ax5.plot(data['test']['regular']['svm_score']['steps'], [v * 100 for v in data['test']['regular']['svm_score']['values']], 'b')
ax5.plot(data['test']['regular']['lr_score']['steps'] , [v * 100 for v in data['test']['regular']['lr_score']['values']] , 'g')

ax5.set_ylim(bottom=0, top=110)
# ax5.text(-12000, 52, 'LeNet', va='center', rotation='vertical', fontdict={'fontsize': 13})
ax5.yaxis.grid()
ax5.set_ylabel('accuracy (%)', labelpad=0.5, fontdict={'fontsize': 15})
ax5.get_xaxis().set_visible(False)
ax5.tick_params(labelsize=13)
# ax5.add_patch(patches.Polygon(xy=np.array([[40000, 87.8], [27800, 66.5], [50000, 66.5], [50000, 33.1], [50000, 78.7]]), closed=True, color='silver'))
# ax5.add_patch(patches.Rectangle(xy=(40000, 78), width=10000, height=10, facecolor='moccasin'))

# lenet, cifar100
root_dir = '/data/gilad/logs/metrics/lenet/cifar100/log_1319_120918_metrics-SUPERSEED=12091800'
json_file = os.path.join(root_dir, 'data_for_figures', 'data.json')
with open(json_file) as f:
    data = json.load(f)
ax6 = fig.add_subplot(324)
ax6.plot(data['test']['regular']['dnn_score']['steps'], [v * 100 for v in data['test']['regular']['dnn_score']['values']], 'k')
ax6.plot(data['test']['regular']['knn_score']['steps'], [v * 100 for v in data['test']['regular']['knn_score']['values']], 'r')
ax6.plot(data['test']['regular']['svm_score']['steps'], [v * 100 for v in data['test']['regular']['svm_score']['values']], 'b')
ax6.plot(data['test']['regular']['lr_score']['steps'] , [v * 100 for v in data['test']['regular']['lr_score']['values']] , 'g')

ax6.set_ylim(bottom=0, top=60)
ax6.yaxis.grid()
ax6.get_xaxis().set_visible(False)
ax6.tick_params(labelsize=13)
# ax6.add_patch(patches.Polygon(xy=np.array([[40000, 56.2], [27800, 35.6], [50000, 35.6], [50000, 18], [50000, 50]]), closed=True, color='silver'))
# ax6.add_patch(patches.Rectangle(xy=(40000, 50), width=10000, height=6, facecolor='moccasin'))

# fc2net, cifar10
root_dir = '/data/gilad/logs/metrics/fc2net/cifar10/log_1025_150918_metrics-SUPERSEED=15091800'
json_file = os.path.join(root_dir, 'data_for_figures', 'data.json')
with open(json_file) as f:
    data = json.load(f)
ax8 = fig.add_subplot(325)
ax8.plot(data['test']['regular']['dnn_score']['steps'], [v * 100 for v in data['test']['regular']['dnn_score']['values']], 'k')
ax8.plot(data['test']['regular']['knn_score']['steps'], [v * 100 for v in data['test']['regular']['knn_score']['values']], 'r')
ax8.plot(data['test']['regular']['svm_score']['steps'], [v * 100 for v in data['test']['regular']['svm_score']['values']], 'b')
ax8.plot(data['test']['regular']['lr_score']['steps'] , [v * 100 for v in data['test']['regular']['lr_score']['values']] , 'g')

ax8.set_ylim(bottom=0, top=65)
# ax8.text(-12000, 30, 'MLP-640', va='center', rotation='vertical', fontdict={'fontsize': 13})
ax8.set_ylabel('accuracy (%)', labelpad=6, fontdict={'fontsize': 15})
ax8.yaxis.grid()
ax8.tick_params(labelsize=13)

# ax8.add_patch(patches.Polygon(xy=np.array([[40000, 87.8], [27800, 66.5], [50000, 66.5], [50000, 33.1], [50000, 78.7]]), closed=True, color='silver'))
# ax8.add_patch(patches.Rectangle(xy=(40000, 78), width=10000, height=10, facecolor='moccasin'))

# fc2net, cifar100
root_dir = '/data/gilad/logs/metrics/fc2net/cifar100/log_1025_150918_metrics-SUPERSEED=15091800'
json_file = os.path.join(root_dir, 'data_for_figures', 'data.json')
with open(json_file) as f:
    data = json.load(f)
ax9 = fig.add_subplot(326)
ax9.plot(data['test']['regular']['dnn_score']['steps'], [v * 100 for v in data['test']['regular']['dnn_score']['values']], 'k')
ax9.plot(data['test']['regular']['knn_score']['steps'], [v * 100 for v in data['test']['regular']['knn_score']['values']], 'r')
ax9.plot(data['test']['regular']['svm_score']['steps'], [v * 100 for v in data['test']['regular']['svm_score']['values']], 'b')
ax9.plot(data['test']['regular']['lr_score']['steps'] , [v * 100 for v in data['test']['regular']['lr_score']['values']] , 'g')

ax9.set_ylim(bottom=0, top=30)
ax9.yaxis.grid()
ax9.tick_params(labelsize=13)
# ax9.add_patch(patches.Polygon(xy=np.array([[40000, 25], [27800, 18], [50000, 18], [50000, 9.1], [50000, 22.2]]), closed=True, color='silver'))
# ax9.add_patch(patches.Rectangle(xy=(40000, 22), width=10000, height=3, facecolor='moccasin'))

ax2.legend(['DNN', '$k$-NN', 'SVM', 'LR'], loc=(0.65, 0.1), fontsize=15)
ax3.legend(['DNN', '$k$-NN', 'SVM', 'LR'], loc=(0.65, 0.1), fontsize=15)
ax5.legend(['DNN', '$k$-NN', 'SVM', 'LR'], loc=(0.65, 0.1), fontsize=15)
ax6.legend(['DNN', '$k$-NN', 'SVM', 'LR'], loc=(0.65, 0.1), fontsize=15)
ax8.legend(['DNN', '$k$-NN', 'SVM', 'LR'], loc=(0.65, 0.1), fontsize=15)
ax9.legend(['DNN', '$k$-NN', 'SVM', 'LR'], loc=(0.65, 0.1), fontsize=15)

# fix subax position
# pos11 = subax1.get_position() # [[0.250367647059, 0.721470588235], [0.341544117647, 0.789411764706]]
# pos12 = [pos11.x0-0.052, pos11.y0+0.05, pos11.width, pos11.height]
# subax1.set_position(pos12)
# pos41 = subax4.get_position() # [[0.250367647059, 0.449705882353], [0.364338235294, 0.540294117647]]
# pos42 = [pos41.x0-0.052, pos41.y0, pos41.width, pos41.height]
# subax4.set_position(pos42)
plt.tight_layout()
plt.savefig('test_acc_vs_iter.png', dpi=350)


class Session:
    """
    isi session adalah berupa dictionary (tipe key : value)
    contoh _session = {
    "muzaki" : {
        "is_visit_input": True,
        "is_photo_input": False,
        "fullname": fullname,
        "nip": nip,
        "date": date,
        "voc_code": voc_code,
        "voc_state": voc_state,
        "result_voc": result_voc,
        "other_desc": other_desc,
        "photo": []
    }
    }
    """

    def __init__(self):
        self._session = {}
        self.input_vs = "input_visit"

    def is_user_active(self, user_id):
        return True if user_id in self._session.keys() else False

    def remove_user(self, user_id):
        if self.is_user_active(user_id):
            del self._session[user_id]
            return True
        return False

    def add_user(self, user_id, fullname, nip, date, voc_code ,voc_state, voc_category, result_voc, other_desc, idx_visit_code):
        self._session[user_id] = {
            "is_visit_input": True,
            "is_photo_input": False,
            "fullname": fullname,
            "nip": nip,
            "date": date,
            "voc_code" : voc_code,
            "voc_state": voc_state,
            "voc_category": voc_category,
            "result_voc": result_voc,
            "other_desc": other_desc,
            "photo": [],
            "idx_visit_code": idx_visit_code,
        }
        print(self._session)

    def add_photo(self, user_id, photo_id):
        self._session[user_id]["photo"].append(photo_id)
        self._session[user_id]["is_photo_input"] = True
        return True

    def is_visited(self, user_id):
        return self._session[user_id]["is_visit_input"]

    def get_desc_user(self, user_id):
        user = self._session[user_id]
        fullname = user["fullname"]
        nip = user["nip"]
        date = user["date"]
        voc_code = user["voc_code"]
        voc_state = user["voc_state"]
        voc_category = user["voc_category"]
        result_voc = user["result_voc"]
        other_desc = user["other_desc"]
        msg = "nama penginput : {}" \
              "\nnomor internet pelanggan : {}" \
              "\ntanggal input : {}" \
              "\nkode visit : {}" \
              "\nstatus visit : {}" \
              "\nkategori visit: {}" \
              "\nhasil visit : {}" \
              "\nketerangan lain : {}" \
              "\njangan lupa untuk mengupload foto visit dan melakukan /submit_visit".format(fullname, nip, date,
                                                                                voc_code, voc_state,
                                                                                voc_category,
                                                                                result_voc, other_desc)
        return msg

    def get_photo(self, user_id):
        """
        :param user_id:
        :return list [] : List of photo url from user
        """
        return self._session[user_id]["photo"]

    def is_submitted_photo(self, user_id):
        return self._session[user_id]["is_photo_input"]

    def get_session(self, user_id):
        return self._session[user_id]


from flask import Flask, Response, request, jsonify, abort
import json
import requests

URL = "http://web2:5000/"

application = Flask(__name__)

books = [
    {"id" : 1,
    "author" : "J. K. Rowling",
    "title" : "Harry Potter and the Philosopher's stone",
    "year" : 1997,
    "isbn" : 9780590353403,
    "part" : 3
    },
    {"id" : 2,
    "author" : "J. K. Rowling",
    "title" : "Harry Potter and the Chamber of secrets",
    "year" : 1998,
    "isbn" : 9788498387650,
    "part" : 2
    },
    {"id" : 3,
    "author" : "Charles Dickens",
    "title" : "A tale of Two Cities",
    "year" : 1859,
    "isbn" : 9780721407104,
    "part" : 2
    },
    {"id" : 4,
    "author" : "Antoine de Saint-Exupery",
    "title" : "The Little Prince",
    "year" : 1943,
    "isbn" : 9788854172388,
    "part" : 1
    }]

@application.route("/")
def homePage():
    return "
Welcome to virtual library!
To see all books"

@application.route("/api/books", methods = ["GET"])
def getBookList():

    booksToReturn = []

    args = request.args
    expand = args.get('expand')

    if (expand == "part"):
        for book in books:
            booksWithPart = book.copy()
            try:
                get = requests.get(URL + "api/parts/" + str(book["part"]))
                getPart = {
                    "manufacturer" : get.json()[0]["manufacturer"],
                    "name" : get.json()[0]["name"],
                    "type" : get.json()[0]["type"],
                    "price" : get.json()[0]["price"]
                }
                booksWithPart["part"] = getPart

            except requests.exceptions.RequestException as ex:
                print(ex)
            booksToReturn.append(booksWithPart)
        return Response(json.dumps(booksToReturn),status=200,mimetype="application/json")

    else:
        return Response(json.dumps(books),status=200,mimetype="application/json")

@application.route("/api/books", methods = ["POST"])
def postBookList():
    newRecord = request.get_json("force: True")

    if ("expand" in request.args):
        if ("author" in newRecord) and ("title" in newRecord) and ("year" in newRecord) and ("isbn" in newRecord) and ("part" in newRecord):
            if type(newRecord["part"]) == type(0):
                return Response(json.dumps({"Failure" : "Request expects json type part"}),status=400,mimetype="application/json")
            if ("manufacturer" in newRecord["part"]) and ("name" in newRecord["part"]) and ("price" in newRecord["part"]) and ("type" in newRecord["part"]):
                postPart = {
                    "manufacturer" : newRecord["part"]["manufacturer"],
                    "name" : newRecord["part"]["name"],
                    "price" : newRecord["part"]["price"],
                    "type" : newRecord["part"]["type"]
                }
                try:
                    post = requests.post(URL + "api/parts", json = postPart)
                    getPart = requests.get(URL + "/api/parts")
                    returnPart = {
                        "id" : getPart.json()[len(getPart.json())-1]["id"],
                        "manufacturer" : getPart.json()[len(getPart.json())-1]["manufacturer"],
                        "name" : getPart.json()[len(getPart.json())-1]["name"],
                        "price" : getPart.json()[len(getPart.json())-1]["price"],
                        "type" : getPart.json()[len(getPart.json())-1]["type"]
                    }
                except requests.exceptions.RequestException as ex:
                    return Response(json.dumps({"Failure" : "Can not connect to the server"}),status="503",mimetype="application/json")

                if(str(post.status_code) == "400" or str(post.status_code) == "404"):
                    return Response(json.dumps({"Failure" : "error code: " +str(post.status_code)}),status=post.status_code,mimetype="application/json")

                else:
                    newBook = {
                        "id" : books[len(books)-1]["id"] + 1,
                        "author" : newRecord["author"],
                        "title" : newRecord["title"],
                        "year" : newRecord["year"],
                        "isbn" : newRecord["isbn"],
                        "part" : getPart.json()[len(getPart.json())-1]["id"]
                    }

                    returnBook = newBook.copy()
                    returnBook["part"] = returnPart

                    books.append(newBook)
                    bookID = returnBook["id"]
                    return Response((json.dumps({"Success":"Book was added; "})+json.dumps(returnBook)), status=201, headers={"location": "/api/extendedBookList/"+str(bookID)},mimetype="application/json")

            else:
                error = "This data has not been given: "
                if "manufacturer" not in newRecord["part"]:
                    error += "manufacturer; "
                if "name" not in newRecord["part"]:
                    error += "name; "
                if "price" not in newRecord["part"]:
                    error += "price; "
                if "type" not in newRecord["part"]:
                    error += "type."
                return Response(json.dumps({"Failure" : error}),status=400,mimetype="application/json")

        else:
            error = "This data has not been given: "
            if "author" not in newRecord:
                error += "author; "
            if "title" not in newRecord:
                error += "title; "
            if "year" not in newRecord:
                error += "year; "
            if "isbn" not in newRecord:
                error += "isbn;"
            if "part" not in newRecord:
                error += "part."
            return Response(json.dumps({"Failure" : error}),status=400,mimetype="application/json")

    else:
        if ("author" in newRecord) and ("title" in newRecord) and ("year" in newRecord) and ("isbn" in newRecord) and ("part" in newRecord):
            if type(newRecord["part"]) == type(0):
                newBook = {
                    "id" : books[len(books)-1]["id"] + 1,
                    "author" : newRecord["author"],
                    "title" : newRecord["title"],
                    "year" : newRecord["year"],
                    "isbn" : newRecord["isbn"],
                    "part" : newRecord["part"]
                }
                books.append(newBook)

                return Response((json.dumps({"Success":"Book was added; "})+json.dumps(newBook)), status=201, headers={"location": "/api/bookList/"+str(books[len(books)-1]["id"])}, mimetype="application/json")
            error = "Request expects part id"
            return Response(json.dumps({"Failure" : error}),status=400,mimetype="application/json")

        else:
            error = "This data has not been given: "
            if "author" not in newRecord:
                error += "author; "
            if "title" not in newRecord:
                error += "title; "
            if "year" not in newRecord:
                error += "year; "
            if "isbn" not in newRecord:
                error += "isbn;"
            if "part" not in newRecord:
                error += "part."
            return Response(json.dumps({"Failure" : error}),status=400,mimetype="application/json")

# ---------------------------------------------------------------------------------------------------------------------------------------

@application.route("/api/books/<int:bookID>", methods = ["GET"])
def getBookByID(bookID):

    book = [book for book in books if book["id"] == bookID]

    if len(book) != 1:
        abort(404)

    args = request.args
    expand = args.get('expand')

    if (expand == "part"):
        returnBook = {
            "author" : book[0]["author"],
            "title" : book[0]["title"],
            "year" : book[0]["year"],
            "isbn" : book[0]["isbn"],
            "part" : book[0]["part"]
        }
        try:
            get = requests.get(URL + "api/parts/" + str(book[0]["part"]))
            getPart = {
            "manufacturer" : get.json()[0]["manufacturer"],
            "name" : get.json()[0]["name"],
            "type" : get.json()[0]["type"],
            "price" : get.json()[0]["price"]
            }
            returnBook["part"] = getPart
        except requests.exceptions.RequestException as ex:
            print(ex)

        return Response(json.dumps(returnBook), status=200,mimetype="application/json")

    else:
        returnBook = {
            "author" : book[0]["author"],
            "title" : book[0]["title"],
            "year" : book[0]["year"],
            "isbn" : book[0]["isbn"],
            "part" : book[0]["part"]
        }
        return Response((json.dumps(returnBook)), status=200,mimetype="application/json")

@application.route("/api/books/<int:bookID>", methods = ["PUT"])
def putBookByID(bookID):
    book = [book for book in books if book["id"] == bookID]

    if len(book) != 1:
        abort(404)

    updateBook = request.get_json("force: True")

    if ("author" not in updateBook) and ("title" not in updateBook) and ("year" not in updateBook) and ("isbn" not in updateBook) and ("part" not in updateBook):
        return Response(json.dumps({"Failure" : "No data is given for update"}),status=400,mimetype="application/json")

    update = "This data have been changed: "

    if ("expand" in request.args):
        if type(updateBook["part"]) == type(0):
            return Response(json.dumps({"Failure" : "Request expects json type part"}),status=400,mimetype="application/json")

        if ("manufacturer" not in updateBook["part"]) and ("name" not in updateBook["part"]) and ("price" not in updateBook["part"]) and ("type" not in updateBook["part"]):
            return Response(json.dumps({"Failure" : "No data is given for book part"}),status=400,mimetype="application/json")

        if "author" in updateBook:
            book[0]["author"] = updateBook["author"]
            update += "author; "
        if "title" in updateBook:
            book[0]["title"] = updateBook["title"]
            update += "title; "
        if "year" in updateBook:
            book[0]["year"] = updateBook["year"]
            update += "year; "
        if "isbn" in updateBook:
            book[0]["isbn"] = updateBook["isbn"]
            update += "isbn; "
        if "part" in updateBook:

            returnBook = {
                "author" : book[0]["author"],
                "title" : book[0]["title"],
                "year" : book[0]["year"],
                "isbn" : book[0]["isbn"],
                "part" :  book[0]["part"]
            }
            try:
                put = requests.put(URL + "api/parts/" + str(book[0]["part"]), json = updateBook["part"])
                update += "part; "
                get = requests.get(URL + "api/parts/" + str(book[0]["part"]))
                getPart = {
                    "manufacturer" : get.json()[0]["manufacturer"],
                    "name" : get.json()[0]["name"],
                    "type" : get.json()[0]["type"],
                    "price" : get.json()[0]["price"]
                }
                returnBook["part"] = getPart
            except requests.exceptions.RequestException as ex:
                update += "(part could not be changed because of connection error)"

        return Response(json.dumps({"Success" : str(update)})+json.dumps(returnBook),status="200",mimetype="application/json")

    else:
        if type(updateBook["part"]) == type(0):
            if "author" in updateBook:
                book[0]["author"] = updateBook["author"]
                update += "author; "
            if "title" in updateBook:
                book[0]["title"] = updateBook["title"]
                update += "title; "
            if "year" in updateBook:
                book[0]["year"] = updateBook["year"]
                update += "year; "
            if "isbn" in updateBook:
                book[0]["isbn"] = updateBook["isbn"]
                update += "isbn; "
            if "part" in updateBook:
                book[0]["part"] = updateBook["part"]

            returnBook = {
                "author" : book[0]["author"],
                "title" : book[0]["title"],
                "year" : book[0]["year"],
                "isbn" : book[0]["isbn"],
                "part" : book[0]["part"]
            }

            return Response(json.dumps({"Success" : update})+json.dumps(returnBook),status="200",mimetype="application/json")

        error = "Request expects part id"
        return Response(json.dumps({"Failure" : error}),status=400,mimetype="application/json")

@application.route("/api/books/<int:bookID>", methods = ["DELETE"])
def deleteBookByID(bookID):

    for bookDEL in books:
        if bookDEL["id"] == bookID:
            books.remove(bookDEL)
            return Response(json.dumps({"Success" : "Book with id "+str(bookID)+" have been deleted"}),status=200,mimetype="application/json")

# ---------------------------------------------------------------------------------------------------------------------------------------

@application.route("/api/books/<int:bookID>/part", methods = ["GET"])
def getBooksPartByID(bookID):
    book = [book for book in books if book["id"] == bookID]

    if len(book) == 0:
        abort(404)

    get = requests.get(URL + "/api/parts/" + str(book[0]["part"]))
    part = {
        "manufacturer" : get.json()[0]["manufacturer"],
        "name" : get.json()[0]["name"],
        "type" : get.json()[0]["type"],
        "price" : get.json()[0]["price"]
    }
    return Response(json.dumps(part),status="200",mimetype="application/json")

if __name__ == "__main__":
    application.run(host = "0.0.0.0", port = 80, debug = True)


#
# @lc app=leetcode id=19 lang=python3
#
# [19] Remove Nth Node From End of List
#
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
#
# algorithms
# Medium (33.90%)
# Total Accepted:    358.8K
# Total Submissions: 1.1M
# Testcase Example:  '[1,2,3,4,5]\n2'
#
# Given a linked list, remove the n-th node from the end of list and return its
# head.
#
# Example:
#
#
# Given linked list: 1->2->3->4->5, and n = 2.
#
# After removing the second node from the end, the linked list becomes
# 1->2->3->5.
#
#
# Note:
#
# Given n will always be valid.
#
# Follow up:
#
# Could you do this in one pass?
#
#
# Definition for singly-linked list.

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def to_list(python_list):
    tail = head = None

    for val in python_list:
        if head is None:
            tail = head = ListNode(val)
        else:
            tail.next = ListNode(val)
            tail = tail.next

    return head

def from_list(list_node):
    python_list = []

    while list_node:
        python_list.append(list_node.val)
        list_node = list_node.next

    return python_list

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if head is None:
            return None

        right = head
        for i in range(n):
            right = right.next
        if right is None:
            head = head.next
            return head

        left = head
        while right.next is not None:
            right = right.next
            left = left.next
        left.next = left.next.next
        return head

def assert_eq(actual, expected):
    if actual != expected:
        raise AssertionError('expected: %s, actual: %s' % (expected, actual))

def test(input_, output):
    result = Solution().removeNthFromEnd(*input_)
    assert_eq(from_list(result), output)

if __name__ == '__main__':
    assert_eq(from_list(to_list([1, 3, 2, 5])), [1, 3, 2, 5])
    assert_eq(from_list(to_list([])), [])
    assert_eq(from_list(to_list([3])), [3])

    test((to_list([1, 3, 2, 5]), 1), [1, 3, 2])
    test((to_list([1, 3, 2, 5]), 2), [1, 3, 5])
    test((to_list([1, 3, 2, 5]), 3), [1, 2, 5])
    test((to_list([1, 3, 2, 5]), 4), [3, 2, 5])
    test((to_list([]), 4), [])
    test((to_list([1]), 1), [])
    test((to_list([2, 1]), 1), [2])
    test((to_list([2, 1]), 2), [1])


from django.urls import re_path
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from channels.auth import AuthMiddlewareStack

from .consumers import ChatConsumer

application = ProtocolTypeRouter(
    {
        "http": get_asgi_application(),
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(
                URLRouter(
                    [
                        re_path(r"^ws/chat/(?P<room_name>\w+)/$", ChatConsumer.as_asgi()),
                    ]
                )
            )
        ),
    }
)


from django.contrib import admin
from django.urls import path
from cbview import views
from django.views.generic.base import RedirectView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('func/', views.my_fview, name="funcview"), # for function based view

    path('class/', views.my_cview.as_view(), name="classview" ), # for class based views

    path('home/', views.Home.as_view(), name="template"), # for template class view

    path('extrahome/', views.Home.as_view(extra_context = {'subject': 'Python Django Developer'}), name="template"), # for template class view with extra context

    path('redirect/', views.RedirectView.as_view(), name = "redirect_View"), # for redirect view

    path('google/', views.RedirectView.as_view(url = "https://google.com"), name="google"),

    path('pattern/', views.RedirectView.as_view(pattern_name = "funcview"), name="pattern"),
]


import torch.nn as nn
from torchtext import data
import copy
import layers as layers

#class Embedder(nn.Module):
#    def __init__(self, vocab_size, d_model):
#        super().__init__()
#        self.vocab_size = vocab_size
#        self.d_model = d_model
#
#        self.embed = nn.Embedding(vocab_size, d_model)
#
#    def forward(self, x):
#        return self.embed(x)

class EncoderLayer(nn.Module):
    def __init__(self, d_model, heads, dropout=0.1):
        """An layer of the encoder. Contain a self-attention accepting padding mask
        Args:
            d_model: the inner dimension size of the layer
            heads: number of heads used in the attention
            dropout: applied dropout value during training
            """
        super().__init__()
        self.norm_1 = layers.Norm(d_model)
        self.norm_2 = layers.Norm(d_model)
        self.attn = layers.MultiHeadAttention(heads, d_model, dropout=dropout)
        self.ff = layers.FeedForward(d_model, dropout=dropout)
        self.dropout_1 = nn.Dropout(dropout)
        self.dropout_2 = nn.Dropout(dropout)

    def forward(self, x, src_mask):
        """Run the encoding layer
        Args:
            x: the input (either embedding values or previous layer output), should be in shape [batch_size, src_len, d_model]
            src_mask: the padding mask, should be [batch_size, 1, src_len]
        Return:
            an output that have the same shape as input, [batch_size, src_len, d_model]
            the attention used [batch_size, src_len, src_len]
        """
        x2 = self.norm_1(x)
        # Self attention only
        x_sa, sa = self.attn(x2, x2, x2, src_mask)
        x = x + self.dropout_1(x_sa)
        x2 = self.norm_2(x)
        x = x + self.dropout_2(self.ff(x2))
        return x, sa

class DecoderLayer(nn.Module):
    def __init__(self, d_model, heads, dropout=0.1):
        """An layer of the decoder. Contain a self-attention that accept no-peeking mask and a normal attention tha t accept padding mask
        Args:
            d_model: the inner dimension size of the layer
            heads: number of heads used in the attention
            dropout: applied dropout value during training
            """
        super().__init__()
        self.norm_1 = layers.Norm(d_model)
        self.norm_2 = layers.Norm(d_model)
        self.norm_3 = layers.Norm(d_model)

        self.dropout_1 = nn.Dropout(dropout)
        self.dropout_2 = nn.Dropout(dropout)
        self.dropout_3 = nn.Dropout(dropout)

        self.attn_1 = layers.MultiHeadAttention(heads, d_model, dropout=dropout)
        self.attn_2 = layers.MultiHeadAttention(heads, d_model, dropout=dropout)
        self.ff = layers.FeedForward(d_model, dropout=dropout)

    def forward(self, x, memory, src_mask, trg_mask):
        """Run the decoding layer
        Args:
            x: the input (either embedding values or previous layer output), should be in shape [batch_size, tgt_len, d_model]
            memory: the outputs of the encoding section, used for normal attention. [batch_size, src_len, d_model]
            src_mask: the padding mask for the memory, [batch_size, 1, src_len]
            tgt_mask: the no-peeking mask for the decoder, [batch_size, tgt_len, tgt_len]
        Return:
            an output that have the same shape as input, [batch_size, tgt_len, d_model]
            the self-attention and normal attention received [batch_size, head, tgt_len, tgt_len] & [batch_size, head, tgt_len, src_len]
        """
        x2 = self.norm_1(x)
        # Self-attention
        x_sa, sa = self.attn_1(x2, x2, x2, trg_mask)
        x = x + self.dropout_1(x_sa)
        x2 = self.norm_2(x)
        # Normal multi-head attention
        x_na, na = self.attn_2(x2, memory, memory, src_mask)
        x = x + self.dropout_2(x_na)
        x2 = self.norm_3(x)
        x = x + self.dropout_3(self.ff(x2))
        return x, (sa, na)

def get_clones(module, N, keep_module=True):
    if(keep_module and N >= 1):
        # create N-1 copies in addition to the original
        return nn.ModuleList([module] + [copy.deepcopy(module) for i in range(N-1)])
    else:
        # create N new copy
        return nn.ModuleList([copy.deepcopy(module) for i in range(N)])

class Encoder(nn.Module):
    """A wrapper that embed, positional encode, and self-attention encode the inputs.
    Args:
        vocab_size: the size of the vocab. Used for embedding
        d_model: the inner dim of the module
        N: number of layers used
        heads: number of heads used in the attention
        dropout: applied dropout value during training
        max_seq_length: the maximum length value used for this encoder. Needed for PositionalEncoder, due to caching
    """
    def __init__(self, vocab_size, d_model, N, heads, dropout, max_seq_length=200):
        super().__init__()
        self.N = N
        self.embed = nn.Embedding(vocab_size, d_model)
        self.pe = layers.PositionalEncoder(d_model, dropout=dropout, max_seq_length=max_seq_length)
        self.layers = get_clones(EncoderLayer(d_model, heads, dropout), N)
        self.norm = layers.Norm(d_model)

        self._max_seq_length = max_seq_length

    def forward(self, src, src_mask, output_attention=False, seq_length_check=False):
        """Accepts a batch of indexed tokens, return the encoded values.
        Args:
            src: int Tensor of [batch_size, src_len]
            src_mask: the padding mask, [batch_size, 1, src_len]
            output_attention: if set, output a list containing used attention
            seq_length_check: if set, automatically trim the input if it goes past the expected sequence length.
        Returns:
            the encoded values [batch_size, src_len, d_model]
            if available, list of N (self-attention) calculated. They are in form of [batch_size, heads, src_len, src_len]
        """
        if(seq_length_check and src.shape[1] > self._max_seq_length):
            src = src[:, :self._max_seq_length]
            src_mask = src_mask[:, :, :self._max_seq_length]
        x = self.embed(src)
        x = self.pe(x)
        attentions = [None] * self.N
        for i in range(self.N):
            x, attn = self.layers[i](x, src_mask)
            attentions[i] = attn
        x = self.norm(x)
        return x if(not output_attention) else (x, attentions)

class Decoder(nn.Module):
    """A wrapper that receive the encoder outputs, run through the decoder process for a determined input
    Args:
        vocab_size: the size of the vocab. Used for embedding
        d_model: the inner dim of the module
        N: number of layers used
        heads: number of heads used in the attention
        dropout: applied dropout value during training
        max_seq_length: the maximum length value used for this encoder. Needed for PositionalEncoder, due to caching
    """
    def __init__(self, vocab_size, d_model, N, heads, dropout, max_seq_length=200):
        super().__init__()
        self.N = N
        self.embed = nn.Embedding(vocab_size, d_model)
        self.pe = layers.PositionalEncoder(d_model, dropout=dropout, max_seq_length=max_seq_length)
        self.layers = get_clones(DecoderLayer(d_model, heads, dropout), N)
        self.norm = layers.Norm(d_model)

        self._max_seq_length = max_seq_length

    def forward(self, trg, memory, src_mask, trg_mask, output_attention=False):
        """Accepts a batch of indexed tokens and the encoding outputs, return the decoded values.
        Args:
            trg: input Tensor of [batch_size, trg_len]
            memory: output of Encoder [batch_size, src_len, d_model]
            src_mask: the padding mask, [batch_size, 1, src_len]
            trg_mask: the no-peeking mask, [batch_size, tgt_len, tgt_len]
            output_attention: if set, output a list containing used attention
        Returns:
            the decoded values [batch_size, tgt_len, d_model]
            if available, list of N (self-attention, attention) calculated. They are in form of [batch_size, heads, tgt_len, tgt/src_len]
        """
        x = self.embed(trg)
        x = self.pe(x)

        attentions = [None] * self.N
        for i in range(self.N):
            x, attn = self.layers[i](x, memory, src_mask, trg_mask)
            attentions[i] = attn
        x = self.norm(x)
        return x if(not output_attention) else (x, attentions)

class Config:
    """Deprecated"""
    def __init__(self):
        self.opt = {
            'train_src_data':'/workspace/khoai23/opennmt/data/iwslt_en_vi/train.en',
            'train_trg_data':'/workspace/khoai23/opennmt/data/iwslt_en_vi/train.vi',
            'valid_src_data':'/workspace/khoai23/opennmt/data/iwslt_en_vi/tst2013.en',
            'valid_trg_data':'/workspace/khoai23/opennmt/data/iwslt_en_vi/tst2013.vi',
            'src_lang':'en', # useless atm
            'trg_lang':'en',#'vi_spacy_model', # useless atm
            'max_strlen':160,
            'batchsize':1500,
            'device':'cuda',
            'd_model': 512,
            'n_layers': 6,
            'heads': 8,
            'dropout': 0.1,
            'lr':0.0001,
            'epochs':30,
            'printevery': 200,
            'k':5,
        }


from django import forms

class SearchForm(forms.Form):
    """
    This is the basic form for the user where he/she will search for his required articles/research Papers.
    """
    # Here we are defining the type of the fields
    article = forms.CharField(
        max_length=100, required=True, label="Enter article Name:",
        widget=forms.TextInput(attrs={'placeholder': "Enter subject title or Name",
                                    'autofocus': 'autofocus'}))


#!/usr/bin/env python
#-*-coding: utf-8-*-
#
# Rosalind Intro problem:
#  Print all even-numbered lines from 'poem.txt', assuming 1-based
#  numbering of lines
#
from __future__ import print_function

poem_file = open("poem.txt", "r")
new_poem_file = open("poem2.txt", "w")

for index, line in enumerate(poem_file):
    line_number = index + 1
    if (line_number % 2 == 0):
        new_poem_file.write(line)


from django.urls import reverse
from rest_framework import status

from api.tests.test_setup import TestSetUp
from api.models import List

class TestLists(TestSetUp):
    def test_create_list(self):
        self.user_data = {'title': 'my_list', 'owner': self.super_user.id}
        response = self.client.post(reverse('api:list-lists'), data=self.user_data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(self.user_data['title'], str(List.objects.filter(owner=self.super_user).latest('title')))

    def test_get_all_lists(self):
        response = self.client.get(reverse('api:list-lists'))
        self.assertEqual((len(response.data)), self.list_count)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_get_single_list(self):
        self.obj = List.objects.get(pk=self.list_pk)
        response = self.client.get(reverse('api:list-single-list', kwargs={'pk': self.obj.pk}))
        self.assertEqual(response.data['id'], self.obj.pk)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_single_list(self):
        self.obj = List.objects.get(pk=self.list_pk)
        new_title = 'Updated Content'
        response = self.client.put(reverse('api:list-single-list', kwargs={'pk': self.obj.pk}), data={
            'title': new_title,
            'owner': self.super_user.id})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['title'], new_title)

    def test_delete_single_list(self):
        self.obj = List.objects.get(pk=self.list_pk)
        response = self.client.delete(reverse('api:list-single-list', kwargs={'pk': self.obj.pk}))
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    def test_if_test_user_can_get_all_lists(self):
        self.client.force_login(self.test_user)
        lists = List.objects.all().count()
        response = self.client.get(reverse('api:list-lists'))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertNotEqual(lists, len(response.data))


import requests
import pandas as pd
from flask import Flask
import financialanalysis as fa
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
from sklearn.model_selection import train_test_split
import pickle

app =Flask(__name__)
def train():
    url="https://edonations.000webhostapp.com/api-last-day-donation.php"
    headers = {'Content-Type': 'application/json' }
    response = requests.get(url=url,headers=headers)
    df = pd.read_json(response.text)
    if df.empty:
        pass
    else:
        df.drop([u'name',u'donationId',u'name'],inplace=True,axis=1)
        X = df["date"].to_list() # convert Series to list
        X = fa.datetimeToFloatyear(X) # for example, 2020-07-01 becomes 2020.49589041
        # [2020.0054794520547, 2020.0082191780823, 2020.01643835616, ...]
        df["date"] = X
        # separate the independent and target variable
        train_X = df.drop(columns=['quantity'])
        train_Y = df['quantity']
        # randomly split the data
        train_x, test_x, train_y, test_y = train_test_split(train_X, train_Y,test_size=0.25,random_state=0)
        # create an object of the LinearRegression Model
        model1 = pickle.load(open('lassoModel.pkl', 'rb'))
        model2 = pickle.load(open('linearModel.pkl', 'rb'))
        model3 = pickle.load(open('ridgeModel.pkl', 'rb'))
        # fit the model with the training data
        model1.fit(train_x, train_y)
        model2.fit(train_x, train_y)
        model3.fit(train_x, train_y)
        #save traning
        pickle.dump(model1,open('lassoModel.pkl', 'rb'))
        pickle.dump(model2, open('linearModel.pkl', 'rb'))
        pickle.dump(model3,open('ridgeModel.pkl', 'rb'))

if __name__ == '__main__':
    scheduler = BackgroundScheduler({'apscheduler.timezone': 'UTC'}, daemon=True)
    scheduler.add_job(func=train, trigger='interval',hour = 24 )
    scheduler.start()
#Exit on app exit
    atexit.register(lambda: scheduler.shutdown())
    app.run(debug = False)


# UI MODULE #

from tkinter import *

class UI:
    """Class to set up and manage the user interface"""

    def __init__(self, app):
        """Initialize attributes"""

        self.settings = app.settings
        self.app = app
        self.set_window()
        self.create_images()
        self.set_canvas()
        self.set_buttons()

    def set_window(self):
        """Set up the window"""

        self.window = Tk()
        self.window.title(self.settings.app_title)
        self.window.config(padx=30, pady=30, bg=self.settings.GREEN)

    def create_images(self):
        """Assign images to class"""

        self.flashcard_back = PhotoImage(file=self.settings.card_back)
        self.flashcard_front = PhotoImage(file=self.settings.card_front)
        self.tick = PhotoImage(file=self.settings.tick_image)
        self.cross = PhotoImage(file=self.settings.cross_image)
        self.start_image = PhotoImage(file=self.settings.start_image)
        self.flip_image = PhotoImage(file=self.settings.flip_image)

    def set_canvas(self):
        """Set up any canvas classes"""

        self.canvas = Canvas(width=self.settings.canvas_width,
                             height=self.settings.canvas_height,
                             highlightthickness=0,
                             bg=self.settings.GREEN
                             )

        self.card = self.canvas.create_image(self.settings.canvas_width/2,
                                             self.settings.canvas_height/2,
                                             image=self.flashcard_back)

        self.language = self.canvas.create_text(400, 150,
                                                text=self.settings.lan_welcome,
                                                font=('Arial', 30),
                                                fill='white',
                                                )

        self.word = self.canvas.create_text(400, 300,
                                            text=self.settings.welcome,
                                            font=('Arial', 30),
                                            fill='white',
                                            )

        self.canvas.grid(column=1, row=1, columnspan=3)

    def set_buttons(self):
        """Set up any button classes"""

        self.tick_button = Button(image=self.tick,
                                  border=0,
                                  highlightthickness=0,
                                  bg=self.settings.GREEN,
                                  command=self.app.store_info
                                  )

        self.cross_button = Button(image=self.cross,
                                   border=0,
                                   highlightthickness=0,
                                   bg=self.settings.GREEN,
                                   command=self.app.get_word,
                                   )

        self.centre_button = Button(image=self.start_image,
                                    border=0,
                                    highlightthickness=0,
                                    bg=self.settings.GREEN,
                                    command=self.app.start_cards
                                    )

        self.tick_button.grid(column=1, row=2)
        self.centre_button.grid(column=2, row=2)
        self.cross_button.grid(column=3, row=2)

    def flip_card_front(self):
        """Flip the flash card to English"""

        self.canvas.itemconfig(self.language,
                               text='English',
                               fill='black',
                               font=('Arial', 30, 'italic'),
                               )

        self.canvas.itemconfig(self.word,
                               text=self.app.word_data.translation,
                               fill='black',
                               font=('Arial', 45, 'bold'),
                               )

        self.canvas.itemconfig(self.card,
                               image=self.flashcard_front)

    def flip_card_back(self):
        """Flip the flash card to Polish"""

        self.canvas.itemconfig(self.language,
                               text='Polish',
                               fill='white',
                               font=('Arial', 30, 'italic'),
                               )

        self.canvas.itemconfig(self.word,
                               text=self.app.word_data.new_word,
                               fill='white',
                               font=('Arial', 45, 'bold'),
                               )

        self.canvas.itemconfig(self.card,
                               image=self.flashcard_back)

    def change_centre_button(self):
        """Change centre button each time it is pressed"""

        self.centre_button.config(image=self.flip_image,
                                  command=self.app.switch_card,
                                  )


from collect_training_data import CollectImageData
from train_model import TrainingModel
from utils import *
import cv2

if(yes_or_no("Do you want to collect training data?")):
    fc = CollectImageData()

    fc.ExtractAndSaveFacesFromCamera('dataset')

if(yes_or_no('Do you want to retrain the model?')):
    tm = TrainingModel()

    tm.TrainingModel('dataset')

if(yes_or_no('Is it ready to recognize faces?')):
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer.read('Trained_Models/face_trainer.yml')

    cascadePath = 'DATA/haarcascades/haarcascade_frontalface_default.xml'
    faceCascade = cv2.CascadeClassifier(cascadePath)
    font = cv2.FONT_HERSHEY_SIMPLEX

    names = ['unkown','Jin']

    cam = cv2.VideoCapture(0+cv2.CAP_DSHOW)
    cam.set(3, 640)
    cam.set(4, 480)

    minW = 0.1*cam.get(3)
    minH = 0.1*cam.get(4)

    while True:
        ret, img = cam.read()

        gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        faces = faceCascade.detectMultiScale(gray_img,
                                            scaleFactor=1.2,
                                            minNeighbors=15,
                                            minSize=(int(minW), int(minH)))
        for (x, y, w, h) in faces:
            cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)

            id, confidence = recognizer.predict(gray_img[y:y+h, x:x+w])

            if(confidence < 50):
                id = names[id]
                confidence = " {0}%".format(round(100.0-confidence))
            else:
                id = 'unknown'
                confidence = " {0}%".format(round(100.0-confidence))
            cv2.putText(
                img,
                str(id),
                (x+5, y-5),
                font,
                1,
                (255, 255, 255),
                2,
            )

            cv2.putText(
                img,
                str(confidence),
                (x+5, y+h-5),
                font,
                1,
                (255, 255, 0),
                1,
            )
        cv2.imshow('camera', img)
        k = cv2.waitKey(1) & 0Xff
        if k == 27:
            break
    cam.release()
    cv2.destroyAllWindows()


"""
Testing KNN on the Iris Dataset
"""
import numpy as np

from k_nearest_neighbor import KNearestNeighbor
from utilities.evaluation_utils import (
    create_confusion_matrix,
    display_confusion_matrix,
    display_eval_metrics,
    eval_metrics_from_confusion_matrix,
)
from utilities.read_data import get_numerical_features, get_numerical_labels, read_data

if __name__ == "__main__":
    NUM_NEIGHBORS = 3
    NUM_CLASSES = 3

    train_set = read_data("iris_dataset/train.csv")
    train_set_labels = np.array(get_numerical_labels(train_set, data_type=int))
    train_set_features = np.array(get_numerical_features(train_set, data_type=float))

    validation_set = read_data("iris_dataset/valid.csv")
    validation_set_labels = np.array(
        get_numerical_labels(validation_set, data_type=int)
    )
    validation_set_features = np.array(
        get_numerical_features(validation_set, data_type=float)
    )

    print("--- Testing KNNs on Iris ---\n")
    knearest = KNearestNeighbor(NUM_NEIGHBORS, "mode")
    knearest.fit(train_set_features, train_set_labels)
    predicted_labels = knearest.predict(validation_set_features)

    confusion_matrix = create_confusion_matrix(
        NUM_CLASSES, validation_set_labels, predicted_labels
    )
    display_confusion_matrix(confusion_matrix)
    eval_metrics = eval_metrics_from_confusion_matrix(confusion_matrix)
    display_eval_metrics(eval_metrics)


"""
This is a module used for doing grid searches using python
"""
import math
import sys
import numpy as np
from sklearn import preprocessing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
import mlflow
import mlflow.sklearn
from pyspark.sql import SparkSession
from hyperopt import fmin, tpe, hp, SparkTrials, STATUS_OK
from sklearn.model_selection import cross_val_score

def main():
    """
    This is the entry point for the application
    :return:
    """
    spark = SparkSession \
        .builder \
        .appName("MLops_search_python") \
        .getOrCreate()
    uid = "testing123" if sys.argv[1] == "" else sys.argv[1]
    spark.conf.set("spark.sql.execution.arrow.enabled", True)
    print(f"reading delta table: dbfs:/datalake/stocks_{uid}/data")
    try:
        df = spark.read.format("delta").load(f"dbfs:/datalake/stocks_{uid}/data")
    except Exception as e:
        print(f"There was an error loading the delta stock table, : error:{e}")
    pdf = df.select("*").toPandas()
    df_2 = pdf.loc[:, ["AdjClose", "Volume"]]
    df_2["High_Low_Pert"] = (pdf["High"] - pdf["Low"]) / pdf["Close"] * 100.0
    df_2["Pert_change"] = (pdf["Close"] - pdf["Open"]) / pdf["Open"] * 100.0
    df_2.fillna(value=-99999, inplace=True)
    forecast_out = int(math.ceil(0.01 * len(df_2)))
    forecast_col = "AdjClose"
    df_2['label'] = df_2[forecast_col].shift(-forecast_out)
    X = np.array(df_2.drop(['label'], 1))
    X = preprocessing.scale(X)
    X = X[:-forecast_out]
    y = np.array(df_2['label'])
    y = y[:-forecast_out]
    X_train, _, y_train, _ = train_test_split(X, y, test_size=0.33, random_state=42)
    print("creating MLflow project")
    mlflow.set_experiment(f"/Users/bclipp770@yandex.com/datalake/stocks/experiments/cluster_{uid}")
    print("building our model")
    algo = tpe.suggest

    def objective(hypers):
        regr = RandomForestRegressor(max_depth=hypers["max_depth"],
                                     max_features=hypers["max_features"],
                                     min_samples_leaf=hypers["min_samples_leaf"],
                                     min_samples_split=hypers["min_samples_split"],
                                     n_estimators=hypers["n_estimators"]
                                     )
        accuracy = cross_val_score(regr, X_train, y_train).mean()
        return {'loss': -accuracy, 'status': STATUS_OK}

    search_space = {
        'max_depth': hp.choice('max_depth', range(1, 110)),
        'max_features': hp.choice('max_features', np.arange(0.1, 1.0, 0.1)),
        "min_samples_leaf": hp.choice('min_samples_leaf', range(3, 5)),
        "min_samples_split": hp.choice("min_samples_split", range(8, 12)),
        'n_estimators': hp.choice('n_estimators', range(100, 500))}

    spark_trials = SparkTrials()

    with mlflow.start_run():
        argmin = fmin(
            fn=objective,
            space=search_space,
            algo=algo,
            max_evals=16,
            trials=spark_trials)

    print("Best value found: ", argmin)

if __name__ == "__main__":
    main()


import json
import os

class ConfigException(Exception):
    pass

class Config:
    """Configuration class, load from filename, file or python dictionary. Environment variable aware."""

    def __init__(self, filename=None, file=None, config=None):
        if config is not None:
            self.config = config
        elif file is not None:
            self.config = json.load(file)
        elif filename is not None:
            with open(filename) as f:
                self.config = json.load(f)
        else:
            raise ConfigException("No configuration specified")

    def __getitem__(self, key):
        config = self.config
        for subkey in key.split('.'):
            config = config[subkey]
        if type(config) is str and config.startswith("ENV{") and config.endswith("}"):
            config = os.environ[config[len("ENV{"):-1]]
        return config


import torch
from omegaconf import DictConfig
from torch import nn

from modules.graph_encoder import GraphEncoder, GraphEncoderSequential
from utils.torch.models.mlp import MLP

class GlobalCritic(nn.Module):
    def __init__(self,
                 graph_size: int,
                 n_actions: int,
                 n_agents: int,
                 input_dim: int,
                 node_dim: int,
                 config: DictConfig):
        super().__init__()
        self.n_actions = n_actions
        self.n_agents = n_agents

        self.embed_dim = config.embed_dim
        self.node_dim = node_dim  # number of features per node
        self.other_dim = input_dim - graph_size
        self.graph_size = graph_size  # number of nodes * node_dim
        self.number_of_nodes = int(self.graph_size / self.node_dim)
        graph_encoder_layers = [GraphEncoder(self.embed_dim, config) for _ in range(config.number_graph_encoder_layers)]
        self.graph_encoder = GraphEncoderSequential(graph_encoder_layers, self.node_dim, self.embed_dim)

        self.q_dim = self.embed_dim + self.other_dim  # graph dim + other input
        self.q_net = MLP(input_size=self.q_dim, output_size=self.n_actions, **config.q_layer)

    def forward(self, x):
        # split in graph specific part and agent specific part
        batch_shape = x.shape[:-1]
        agent_specific = x[:, :, :, self.graph_size:]
        nodes = x[:, :, :, :self.graph_size].reshape(-1, self.number_of_nodes, self.node_dim)
        _, graph_embedding = self.graph_encoder.forward(nodes)

        agent_specific = agent_specific.reshape(-1, self.other_dim)
        output = self.q_net(torch.cat([graph_embedding, agent_specific], dim=-1))
        output = output.view(*batch_shape, -1)

        return output


import json

from telegram.ext import Updater, CommandHandler

def start(update, context):
    """Команда подключения к боту."""
    user_list = {}
    with open("users.json", "r") as users:
        try:
            user_list = json.load(users)
        except:
            pass
    user_list[update.message.chat.username] = update.message.chat.to_dict()
    with open("users.json", "w") as users:
        users.write(json.dumps(user_list))
    context.bot.send_message(
        chat_id = update.effective_chat.id,
        text = "Привет!"
    )

def help(update, context):
    """Стандартная команда подсказки по использованию бота."""
    context.bot.send_message(
        chat_id = update.effective_chat.id,
        text = "Это учебный бот, он собирает данные о пользователях!"
    )

def stop(update, context):
    """Команда отключения от бота."""
    user_list = {}
    with open("users.json", "r") as users:
        user_list = json.load(users)
    user_list.pop(update.message.chat.username, None)
    with open("users.json", "w") as users:
        users.write(json.dumps(user_list))
    context.bot.send_message(
        chat_id = update.effective_chat.id,
        text = f'Прощай, {update.message.chat.first_name}! :('
    )

def user_count(update, context):
    """Команда выводящая количество подключенных пользователей."""
    user_list = {}
    with open("users.json", "r") as users:
        user_list = json.load(users)
    context.bot.send_message(
        chat_id = update.effective_chat.id,
        text = f'Пользователей подключено: {len(user_list)}'
    )

def describe_me(update, context):
    """Команда выводящая информацию о пользователе."""
    user_list = {}
    with open("users.json", "r") as users:
        user_list = json.load(users)
    me = user_list.get(update.message.chat.username)
    context.bot.send_message(
        chat_id = update.effective_chat.id,
        text = f'Ваш айди - {me.get("id")}, ваш ник - {me.get("username")}, ваше имя = {me.get("first_name")}!'
    )

def main():
    updater = Updater("") # сюда нужно вставить токен бота
    updater.dispatcher.add_handler(CommandHandler('start', start))
    updater.dispatcher.add_handler(CommandHandler('help', help))
    updater.dispatcher.add_handler(CommandHandler('stop', stop))
    updater.dispatcher.add_handler(CommandHandler('count', user_count))
    updater.dispatcher.add_handler(CommandHandler('describe', describe_me))
    updater.start_polling(poll_interval=10.0)

if __name__ == "__main__":
    main()


import sys
from collections import deque
dx = [0, -1, 0, 1]
dy = [-1, 0, 1, 0]
N, M = map(int, sys.stdin.readline().split())
MAP = [list(map(int, sys.stdin.readline().rstrip())) for _ in range(N)]

result = []
isflag = 0

def bfs(x, y):
    global count
    global isflag
    queue = deque()
    queue.append([x, y, 1])
    visit = [[[0] * 2 for _ in range(M)] for _ in range(N)]
    visit[x][y][1] = 1
    while queue:
        cx, cy, cw = queue.popleft()
        if cx == N-1 and cy == M-1:
            return visit[cx][cy][cw]
        for d in range(4):
            nx = cx + dx[d]
            ny = cy + dy[d]
            if 0 <= nx < N and 0 <= ny < M:
                if MAP[nx][ny] == 1 and cw ==1:
                    visit[nx][ny][0] = visit[cx][cy][1] + 1
                    queue.append([nx, ny, 0])
                elif MAP[nx][ny] == 0 and visit[nx][ny][cw] == 0:
                    visit[nx][ny][cw] = visit[cx][cy][cw] + 1
                    queue.append([nx,ny,cw])
    return - 1
print(bfs(0,0))        # 다  0일수도 있음

daily_PS_Baekjoon/dfs,bfs/백준 2206 벽 부수고 이동하기.py

백준 2206 벽 부수고 이동하기.py


import cv2, os
import random
import numpy as np

import torch
from torch.utils.data import Dataset
import torchvision.transforms as tfms

class VOC_Dataset(Dataset):
    def __init__(self, image_dir, label_txt, image_size=448, grid_size=7, num_bboxes=2, num_classes=20, train=True, debug=False):

        self._train = train
        self._debug = debug
        self.image_size = image_size

        self.S, self.B, self.C = grid_size, num_bboxes, num_classes
        self.mean_rgb = np.array([122.6791434, 116.66876762, 104.00698793], dtype=np.float32)
        self.to_tensor = tfms.Compose([
            tfms.ToTensor(),
            # tfms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
            tfms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
        ])

        self.paths, self.bboxes, self.labels = [], [], []
        with open(label_txt) as f:
            lines = f.readlines()

        for line in lines:
            attrs = line.strip().split()

            img_name = attrs[0]
            path = os.path.join(image_dir, img_name)
            self.paths.append(path)

            num_bboxes = (len(attrs)-1)//5
            bbox, label = [], []

            for n in range(num_bboxes):
                x1         = float(attrs[5*n + 1])
                y1         = float(attrs[5*n + 2])
                x2         = float(attrs[5*n + 3])
                y2         = float(attrs[5*n + 4])
                confidence = int(attrs[5*n + 5])
                bbox.append([x1, y1, x2, y2])
                label.append(confidence)
            self.bboxes.append(torch.Tensor(bbox))
            self.labels.append(torch.LongTensor(label))

        self.length = len(self.paths)

    def __getitem__(self, index):
        path = self.paths[index]
        img = cv2.imread(path)
        if self._debug:
            original_img = img.copy()

        boxes = self.bboxes[index].clone()
        labels = self.labels[index].clone()

        if self._train:
            img, boxes = self.lr_flip(img, boxes)
            img, boxes = self.ud_flip(img, boxes)
            img, boxes = self.width_scale(img, boxes)
            img, boxes = self.height_scale(img, boxes)
            img = self.blur(img)
            img = self.brightness(img)
            img = self.hue(img)
            img = self.saturation(img)
            img, boxes, labels = self.shift(img, boxes, labels)

        if self._debug:
            debug_dir = './debug'
            os.makedirs(debug_dir, exist_ok=True)

            img_show = img.copy()
            box_show = boxes.numpy().reshape(-1)
            n = len(box_show) // 4

            for b in range(n):
                pt1 = (int(box_show[4*b + 0]), int(box_show[4*b + 1]))
                pt2 = (int(box_show[4*b + 2]), int(box_show[4*b + 3]))
                cv2.rectangle(img_show, pt1=pt1, pt2=pt2, color=(0,255,0), thickness=2)

                cv2.imwrite(os.path.join(debug_dir, './train_valid/debug_{}.jpg'.format(index+1)), img_show)
                # cv2.imwrite(os.path.join(debug_dir, './train_valid/original_{}.jpg'.format(index+1)), original_img)

        h, w, _ = img.shape
        boxes /= torch.Tensor([[w, h, w, h]]).expand_as(boxes) # normalize (x1, y1, x2, y2) w.r.t. image width/height.
        target = self.to_target(boxes, labels) # [S, S, 5 x B + C]

        img = cv2.resize(img, dsize=(self.image_size, self.image_size), interpolation=cv2.INTER_LINEAR)
        # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img = self.to_tensor(img)
        return img, target

    def __len__(self):
            return self.length

    def to_target(self, bboxes, labels):
        S, B, C = self.S, self.B, self.C
        N = 5 * B + C

        target = torch.zeros(S, S, N)
        cell_size = 1.0 / float(S)
        bboxes_wh = bboxes[:, 2:] - bboxes[:, :2] # width and height for each box, [n, 2]
        bboxes_ct = (bboxes[:, 2:] + bboxes[:, :2]) / 2.0 # center x & y for each box, [n, 2]

        for b in range(bboxes.size(0)):
            ct, wh, label = bboxes_ct[b], bboxes_wh[b], int(labels[b])

            ij = (ct / cell_size).ceil() - 1.0
            i, j = int(ij[0]), int(ij[1])
            base_xy = ij * cell_size # x & y of the cell left-top corner.
            offset_xy = (ct - base_xy) / cell_size # x & y of the box on the cell, normalized from 0.0 to 1.0.

            # TBM, remove redundant dimensions from target tensor.
            # To remove these, loss implementation also has to be modified.
            for k in range(B):
                s = 5 * k
                target[j, i, s  :s+2] = offset_xy
                target[j, i, s+2:s+4] = wh
                target[j, i, s+4    ] = 1.0
            target[j, i, 5*B + label] = 1.0

        return target

    def lr_flip(self, img, bboxes):
        if random.random() < 0.5:
            return img, bboxes

        h, w, _ = img.shape
        img = np.fliplr(img)

        x1, x2 = bboxes[:, 0], bboxes[:, 2]
        new_x1 = w - x2
        new_x2 = w - x1
        bboxes[:, 0], bboxes[:, 2] = new_x1, new_x2

        return img, bboxes

    def ud_flip(self, img, bboxes):
        if random.random() < 0.5:
            return img, bboxes

        h, w, _ = img.shape
        img = np.flipud(img)

        y1, y2 = bboxes[:, 1], bboxes[:, 3]
        new_y1 = h - y2
        new_y2 = h - y1
        bboxes[:, 1], bboxes[:, 3] = new_y1, new_y2

        return img, bboxes

    def width_scale(self, img, bboxes):
        if random.random() < 0.5:
            return img, bboxes

        scale = random.uniform(0.8, 1.2)
        h, w, _ = img.shape
        img = cv2.resize(img, dsize=(int(w*scale), h), interpolation=cv2.INTER_LINEAR)

        scale_tensor = torch.FloatTensor([[scale, 1.0, scale, 1.0]]).expand_as(bboxes)
        bboxes *= scale_tensor

        return img, bboxes

    def height_scale(self, img, bboxes):
        if random.random() < 0.5:
            return img, bboxes

        scale = random.uniform(0.8, 1.2)
        h, w, _ = img.shape
        img = cv2.resize(img, dsize=(w, int(h*scale)), interpolation=cv2.INTER_LINEAR)

        scale_tensor = torch.FloatTensor([[1.0, scale, 1.0, scale]]).expand_as(bboxes)
        bboxes *= scale_tensor

        return img, bboxes

    def blur(self, img):
        if random.random() < 0.5:
            return img

        ksize = random.choice([2, 3, 4, 5])
        img = cv2.blur(img, (ksize, ksize))
        return img

    def brightness(self, img):
        if random.random() < 0.5:
            return img

        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        h, s, v = cv2.split(img)
        adjust = random.uniform(0.6, 1.0)
        v = v * adjust
        v = np.clip(v, 0, 255).astype(hsv.dtype)
        hsv = cv2.merge((h, s, v))
        img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

        return img

    def hue(self, img):
        if random.random() < 0.5:
            return img

        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        h, s, v = cv2.split(hsv)
        adjust = random.uniform(1.0, 1.5)
        h = h * adjust
        h = np.clip(h, 0, 255).astype(hsv.dtype)
        hsv = cv2.merge((h, s, v))
        img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

        return img

    def saturation(self, img):
        if random.random() < 0.5:
            return img

        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        h, s, v = cv2.split(hsv)
        adjust = random.uniform(1.0, 1.5)
        s = s * adjust
        s = np.clip(s, 0, 255).astype(hsv.dtype)
        hsv = cv2.merge((h, s, v))
        img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

        return img

    def shift(self, img, boxes, labels):
        if random.random() < 0.5:
            return img, boxes, labels

        centre = (boxes[:, 2:] + boxes[:, :2]) / 2.0

        h, w, c = img.shape
        img_out = np.zeros((h, w, c), dtype=img.dtype)
        # mean_bgr = self.mean_rgb[::-1]
        # img_out[:, :] = mean_bgr

        dx = random.uniform(-w*0.2, w*0.2)
        dy = random.uniform(-h*0.2, h*0.2)
        dx, dy = int(dx), int(dy)

        if dx >= 0 and dy >= 0:
            img_out[dy:, dx:] = img[:h-dy, :w-dx]
        elif dx >= 0 and dy < 0:
            img_out[:h+dy, dx:] = img[-dy:, :w-dx]
        elif dx < 0 and dy >= 0:
            img_out[dy:, :w+dx] = img[:h-dy, -dx:]
        elif dx < 0 and dy < 0:
            img_out[:h+dy, :w+dx] = img[-dy:, -dx:]

        centre = centre + torch.FloatTensor([[dx, dy]]).expand_as(centre) # [n, 2]
        mask_x = (centre[:, 0] >= 0) & (centre[:, 0] < w) # [n,]
        mask_y = (centre[:, 1] >= 0) & (centre[:, 1] < h) # [n,]
        mask = (mask_x & mask_y).view(-1, 1) # [n, 1], mask for the boxes within the image after shift.

        boxes_out = boxes[mask.expand_as(boxes)].view(-1, 4) # [m, 4]
        if len(boxes_out) == 0:
            return img, boxes, labels
        shift = torch.FloatTensor([[dx, dy, dx, dy]]).expand_as(boxes_out) # [m, 4]

        boxes_out = boxes_out + shift
        boxes_out[:, 0] = boxes_out[:, 0].clamp_(min=0, max=w)
        boxes_out[:, 2] = boxes_out[:, 2].clamp_(min=0, max=w)
        boxes_out[:, 1] = boxes_out[:, 1].clamp_(min=0, max=h)
        boxes_out[:, 3] = boxes_out[:, 3].clamp_(min=0, max=h)

        labels_out = labels[mask.view(-1)]

        return img_out, boxes_out, labels_out

def test():
    from torch.utils.data import DataLoader
    from torch.utils.data import random_split

    image_dir = './data/VOC2012'
    label_txt = './data/voc2012.txt'

    dataset = VOC_Dataset(image_dir, label_txt, debug=True)

    valid_ratio = .2
    dataset_size = len(dataset)
    valid_size = int(valid_ratio * dataset_size)

    train_set, valid_set = random_split(dataset, [dataset_size-valid_size, valid_size])
    valid_set._train = False

    train_loader = DataLoader(train_set, batch_size=1, shuffle=False, num_workers=0)
    valid_loader = DataLoader(valid_set, batch_size=1, num_workers=0)

    data_iter = iter(train_loader)
    for i in range(5):
        img, target = next(data_iter)
        print(img.size(), target.size())

    data_iter = iter(valid_loader)
    for i in range(5):
        img, target = next(data_iter)
        print(img.size(), target.size())

if __name__ == "__main__":
    test()


# Ejercicio 10

# Escribir un programa que solicite al usuario que ingrese cuántos shows musicales ha visto en el último año y almacene ese número en una variable.
# A continuación mostrar en pantalla un valor de verdad (True o False) que indique si el usuario ha visto más de 3 shows.

showsMusicales = int(input("A cuantos shows has asistido durante el último año?: "))
if (showsMusicales >= 3):
    print("Has asistido a muchos shows este año (True)")
else:
    print("Debes asistir a más shows (False)")


from typing import Union
from mltk.core.tflite_model.tflite_schema import BuiltinOperator
from .layer import Layer, flat_size, KerasLayer, TfliteLayer

class Quantize(Layer):

    def __init__(self):
        Layer.__init__(self, ('Quantize', BuiltinOperator.QUANTIZE))

    def process(self, layer:Union[TfliteLayer,KerasLayer]):
        self.name = layer.name
        self.macs = 0
        # https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/kernels/internal/reference/quantize.h#L31
        # 1 divide
        # 1 add
        # 1 min
        # 1 max
        if isinstance(layer, KerasLayer):
            input_shape = layer.input_shape
        else:
            input_shape = layer.inputs[0].shape

        self.ops = flat_size(input_shape[1:]) * 4

class Dequantize(Layer):

    def __init__(self):
        Layer.__init__(self, ('Dequantize', BuiltinOperator.DEQUANTIZE))

    def process(self, layer:Union[TfliteLayer,KerasLayer]):
        self.name = layer.name
        self.macs = 0
        # https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/kernels/internal/reference/dequantize.h
        # 1 multiply
        # 1 substract

        if isinstance(layer, KerasLayer):
            input_shape = layer.input_shape
        else:
            input_shape = layer.inputs[0].shape

        self.ops = flat_size(input_shape[1:]) * 2

Quantize()
Dequantize()


import sys, getopt
from cligen import *

def hello(cgen, vars, arg):
    'This callback just prints the function argument'

    cgen.output(sys.stdout, "{:s}\n".format(str(arg)))
    return 0

def cb(cgen, vars, arg):
    'This is a generic callback printing the variable vector and argument'

    cgen.output(sys.stdout, 'variables:\n');
    for i, cv in enumerate(vars):
        name = cv.name_get()
        if name is None:
            name = "(null)"
        cgen.output(sys.stdout, '\t{:d} name:{:s} type:{:s} value:{:s}\n'.format(
                i,
                name,
                cv.type2str(),
                str(cv)))

    if arg is not None:
        cgen.output(sys.stdout, '\targument: {:s}\n'.format(str(arg)))

    return 0

def letters(cgen, vars, arg):
    'An example of a callback handling a complex syntax'

    if 'ca' in vars:
        cgen.output(sys.stdout, "{:s}\n".format(str(vars['ca'])))
    if 'int' in vars:
        cgen.output(sys.stdout, "{:s}\n".format(str(vars['int'])))
    if 'cb' in vars:
        cgen.output(sys.stdout, "{:s}\n".format(str(vars['cb'])))
    if 'dd' in vars:
        cgen.output(sys.stdout, "{:s}\n".format(str(vars['dd'])))
    if 'ee' in vars:
        cgen.output(sys.stdout, "{:s}\n".format(str(vars['ee'])))

    return 0

def secret(cgen, vars, arg):
    'This callback changes the prompt to the variable setting'

    cgen.output(sys.stdout, 'This is a hidden command: {:s}\n'.format(str(arg)))
    return 0;

def setprompt(cgen, vars, arg):
    'This callback changes the prompt to the variable setting'

    if 'new' in vars:
        cgen.prompt_set(str(vars['new']))

    return 0;

def Quit(cgen, vars, arg):
    'request quitting the CLI'

    cgen.exiting_set(1);
    return 0

def unknown(cgen, vars, arg):
    'Command without assigned callback'

    cgen.output(sys.stdout,
                'The command has no assigned callback: {:d}\n'.format(vars[0]))
    return 0;

def interface(cgen, func, cvec, arg):
    return [ { 'command':'eth0', 'help':'Interface eth0' },
             { 'command':'eth1', 'help':'Interface eth1' }
           ]

def usage(cgen, argv):
    cgen.output(sys.stdout, 'Usage: {:s} [-h][-f <filename>][-s <syntax>]\n'.format(sys.argv[0]))
    sys.exit(2)

def main(argv):
    syntax = None
    infile = None

    c = CLIgen()

    try:
        opts, args = getopt.getopt(argv,"hf:s:")
    except getopt.GetoptError:
        usage(c, argv)

    for opt, arg in opts:
      if opt == '-h':
          usage(c, argv)
          sys.exit()
      elif opt in ("-s"):
         syntax = arg
      elif opt in ("-f"):
         infile = arg

    if syntax is not None:
        pt = ParseTree(c, syntax=syntax)
    elif infile is not None:
        pt = ParseTree(c, file=infile)
    else:
        usage(c, argv)

    if 'prompt' in pt.globals():
        c.prompt_set(pt.globals()['prompt'])
    if 'comment' in pt.globals():
        c.comment_set(pt.globals()['comment'])
    if 'tabmode' in pt.globals():
        c.tabmode_set(int(pt.globals()['tabmode']))

    try:
        treename = pt.globals()['name']
    except KeyError:
        treename = 'tutorial'
    c.tree_add(treename, pt)
    c.tree_active_set(treename)

    c.output(sys.stdout, 'Syntax:\n')
    c.output(sys.stdout, pt)

    c.eval()

if __name__ == "__main__":
    main(sys.argv[1:])


# xray.py

import pandas as pd

from ..fields.xray_emissivity import get_xray_emissivity
from ..load_sim import LoadSim

class Xray:

    @LoadSim.Decorators.check_pickle
    def read_xray_all(self, nums=None, prefix='xray_all',
                      savdir=None, force_override=False):
        rr = dict()
        if nums is None:
            nums = self.nums

        print('num:', end=' ')
        for i,num in enumerate(nums):
            print(num, end=' ')
            r = self.read_xray(num=num, savdir=savdir, force_override=False)
            if i == 0:
                for k in r.keys():
                    rr[k] = []

            for k in r.keys():
                try:
                    rr[k].append(r[k].value.item())
                except:
                    rr[k].append(r[k])

        rr = pd.DataFrame(rr)
        return rr

    @LoadSim.Decorators.check_pickle
    def read_xray(self, num, Z_gas=1.0, emin_keV=0.5, emax_keV=7.0, prefix='L_X',
                  savdir=None, force_override=False):
        """
        Function to calculate x-ray luminosity of the snapshot
        """

        ds = self.load_vtk(num)
        dV = ds.domain['dx'].prod()*(self.u.length.cgs.value)**3
        d = ds.get_field(['density','temperature'])
        em = get_xray_emissivity(d['temperature'].data, Z_gas,
                                 emin_keV, emax_keV, energy=True)
        d['j_X'] = d['density']**2*em
        #dd['I_X'] = d['j_X'].sum(dim='z')*d.domain['dx'][2]*self.u.length.cgs.value

        res = dict()
        res['time'] = ds.domain['time']
        res['L_X'] = float(d['j_X'].sum()*dV)

        return res


import random
from django.core.management.base import BaseCommand
from main.models import Player

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('count', type=int, help='Total number of Players to create')
        parser.add_argument('-p', '--prefix', type=str, help='Prefix for Players to create')
        parser.add_argument('-l', '--local', action='store_true', help='Create local Players')
        parser.add_argument('-f', '--foreign', action='store_true', help='Create foreign Players')

    def handle(self, *args, **options):
        count = options.get('count')
        prefix = options.get('prefix')
        local = options.get('local')
        foreign = options.get('foreign')

        if prefix is None:
            prefix = 'Player'

        for i in range(count):
            if local:
                Player.objects.create(first_name=f'{prefix} {i}', age=random.randint(18, 40), is_local=True)
            elif foreign:
                Player.objects.create(first_name=f'{prefix} {i}', age=random.randint(18, 40), is_foreign=True)
            else:
                Player.objects.create(first_name=f'{prefix} {i}', age=random.randint(18, 40))
            self.stdout.write(f'{prefix} {i} created')


# Rezolvare Tema Lectia 4
import time

# 1. Conversia unei temperaturi din 'C in 'F:
def celsius_to_fahrenheit(celsius):
    fahrenheit = celsius * 9 / 5 + 32
    return fahrenheit

temperatura = float(input("Temperatura in grade C este: "))
print("Temperatura convertita in grade F este: ", celsius_to_fahrenheit(temperatura))
print()
print("-----------------------------Exercitiul 2 -----------------------------")
time.sleep(2)

# 2. Conversia unei temperaturi din 'F in 'C
def fahrenheit_to_celsius(fahrenheit):
    celsius = (fahrenheit - 32) * 5 / 9
    return celsius

temperatura = float(input("Temperatura in grade F este: "))
print("Temperatura convertita in grade C este: ", fahrenheit_to_celsius(temperatura))
print()
print("-----------------------------Exercitiul 3 -----------------------------")
time.sleep(2)

# 3. Produsul tuturor numerelor de la 1 pana la o valoare primita ca parametru
def produs(valoare):
    produsul = 1
    for i in range(1, valoare + 1):
        produsul = produsul * i
    return produsul

valoare = int(input("Introduceti o valoare pentru a afla produsul: "))
print("Produsul tuturor numerelor pana la valoarea introdusa este : ", produs(valoare))
print()
print("-----------------------------Exercitiul 4 -----------------------------")
time.sleep(2)

# 4. Media armonica a oricator valori primite prin parametru
def media_armonica(*args):
    numarator = len(args)
    numitor = 0
    for i in args:
        numitor += 1 / i
    return numarator / numitor

print("Media armonica este: ", media_armonica(3, 8))
print()
print("-----------------------------Exercitiul 5 -----------------------------")
time.sleep(2)

# 5. Calculul ariei unui cerc, cu raza primita prin parametru
import math

def aria(raza):
    aria_cercului = math.pi * (raza ** 2)
    return aria_cercului

raza = int(input("Introduceti raza cercului: "))
print("Aria cercului este: ", aria(raza))
print()
print("-----------------------------Exercitiul 6 -----------------------------")
time.sleep(2)

# 6. Calculul volumului unei sfere cu raza primita prin parametru
def volum(raza):
    volumul = (4 * math.pi * (raza ** 3)) / 3
    return volumul

raza = int(input("Introduceti raza sferei: "))
print("Volumul sferei este: ", volum(raza))
print()
print("-----------------------------Exercitiul 7 -----------------------------")
time.sleep(2)

# 7. Afisarea brazilor din tema de data trecuta, cu valori date ca parametri de intrare obligatorii si/sau optionali.
def bradut(baza, frunza="#", cer=" ", nor="^"):
    spatiu = baza // 2
    for index in range(1, baza + 1, 2):
        if spatiu > 1:
            print(nor * (spatiu - 1) + cer, end="")
        elif spatiu == 1:
            print(cer, end="")
        print(frunza * index, end="")
        if spatiu > 1:
            print(cer + nor * (spatiu - 1), end="")
        elif spatiu == 1:
            print(cer, end="")
        spatiu -= 1
        print()

bradut(25, nor="~")
print()
print("-----------------------------Exercitiul 8 -----------------------------")
time.sleep(2)

# 8. Conversia unui string de forma "1.234.567,89 Lei" la un float de forma 1234567.89
def conversie(numar):
    numar_float = numar.replace(".", "")
    numar_float = numar_float.replace(",", ".")
    numar_float = float(numar_float)
    return numar_float

numar = input("Introduceti un numar cu mai multe puncte si o virgula: ")
print(conversie(numar))
print()
print("-----------------------------Exercitiul 9 -----------------------------")
time.sleep(2)

# 9. Numararea aparitiilor fiecarui caracter dintr-un string primit ca parametru. Rezultatul sa fie un dictionar cu forma
#    {"a":1, "b":3, ...}
def numarare_caractere(lista):
    dictionar = {}
    for i in lista:
        count = lista.count(i)
        dictionar.update({i: count})
    return dictionar

lista = ["a", "a", "b", "b", "b", "c", "c", "c", "c", "d"]
print(numarare_caractere(lista))
print()
print("-----------------------------Exercitiul 10 -----------------------------")
time.sleep(2)

# 10. Generarea unui drepunghi in terminal cu latimea si lungimea date ca parametri.
# Aici am facut sa printeze un dreptunghi plin, alcatuit dintr-un simbol dat
def dreptunghi(coloane, randuri, symbol):
    for i in range(coloane):
        for j in range(randuri):
            print(symbol, end="")
        print()

coloane = int(input("Introduceti numarul de coloane: "))
randuri = int(input("Introduceti numarul de randuri:"))
symbol = input("Introduceti simbolul pe care doriti sa il folositi:")
dreptunghi(coloane, randuri, symbol)

print()
print("-----------------------------SAU -----------------------------")
time.sleep(2)
picture = [
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
]
for i in picture:
    print()
    for j in i:
        if j == 0:
            print("  ", end="")
        else:
            print("o", end="")
print()
print("-----------------------------Exercitiul 11 -----------------------------")
time.sleep(2)

# 11. Reducerea preciziei unui float primit ca parametru la 2 zecimale
def reducere_la_doua_zecimale(nr):
    print(round(nr, 2))

nr = float(input("Introduceti un numar cu muuulllllteeee zecimale: "))
reducere_la_doua_zecimale(nr)

# 12. Generarea unui cerc in terminal, cu raza data de la tastatura.
# Nu am idee

# 13. Sa se calculeze produsul tuturor numerelor pana la o valore data ca parametru. Sa se implementeze recursiv.
def functie_produs(valoare):
    if valoare <= 1:
        return 1
    else:
        return valoare * functie_produs(valoare - 1)

valoare = int(input("Introduceti un numar pana la care sa calculam produsul: "))
print(functie_produs(valoare))


import unittest
from collections import deque

class Solution:
    def numBusesToDestination(self, routes, S, T):
        """
        :type routes: List[List[int]]
        :type S: int
        :type T: int
        :rtype: int
        """
        if S == T:
            return 0

        if not routes or not routes[0]:
            return -1

        table = self.stopBoard(routes)
        if S not in table or T not in table:
            return -1

        ret = 0
        busTaken = set()
        queue = deque()
        queue.append(S)
        while queue:
            ret += 1

            size = len(queue)
            for _ in range(size):
                currStop = queue.popleft()
                buses = table[currStop]
                for bus in buses:
                    if bus in busTaken:
                        continue
                    busTaken.add(bus)
                    for stop in routes[bus]:
                        if stop == T:
                            return ret
                        queue.append(stop)
            ret += 1
        return -1

    def stopBoard(self, routes):
        table = dict()  # key is bus stop, value is a list of buses that go though the list
        numOfBuses = len(routes)
        for busIdx in range(numOfBuses):
            for stop in routes[busIdx]:
                if stop not in table:
                    table[stop] = list()
                table[stop].append(busIdx)
        return table

class TestSolution(unittest.TestCase):
    sol = Solution()

    def testNumBusesToDestination(self):
        routes = [[1, 2, 7], [3, 6, 7]]
        S = 1
        T = 6
        self.assertEqual(2, self.sol.numBusesToDestination(routes, S, T))

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