#! /usr/bin/env python3

import socket
import random
import time
import sys
import json
import os

def sendTCP():
    # Define the IP address and port of the destination server.
    ip_address = "sender"
    port = 8000
    # Create a socket object.
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Connect to the destination server.
    sock.connect((ip_address, port))
    print(f"Addr = {ip_address}:{port}")
    # Define the data to be sent.
    data = f""
    for i in range(5):
        data += (f"id{str(i).zfill(2)}")
        data += (f"type{str(2).zfill(2)}")
        number = i + 1.1
        if len(str(number)) < 5:
            data += (f"data{str(number).zfill(4)}" + "0")
            # print(f"data{str(number).zfill(4)}" + "0")
        else:
            data += (f"data{str(number).zfill(4)}")
            # print(f"data{str(number).zfill(4)}")

    # Send the data.
    data = f"{len(data)}".zfill(4) + data
    bytes = data.encode(sys.getdefaultencoding())
    sock.sendall(bytes)
    print(f"Msg Send: {data}\t{bytes}")

    # Close the socket.
    sock.close()

def getData():
    # Define the data to be sent.
    data = f""
    for i in range(5):
        data += (f"id{str(i).zfill(2)}")
        data += (f"type{str(2).zfill(2)}")
        number = round(i * 1.1, 2)
        if len(str(number)) < 5:
            data += (f"data{str(number).zfill(4)}" + "0")
            # print(f"data{str(number).zfill(4)}" + "0")
        else:
            data += (f"data{str(number).zfill(4)}")
            # print(f"data{str(number).zfill(4)}")

    data = f"{len(data)}".zfill(4) + data
    # Get data in bytes.
    bytes = data.encode(sys.getdefaultencoding())

    return bytes

def test_sendTCP():

    # Define the IP address and port of the destination server.
    ip_address = "sender"
    port = 8000
    # Create a socket object.
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Connect to the destination server.
    sock.connect((ip_address, port))
    # print(f"Addr = {ip_address}:{port}")

    # Get the absolute path of the test script directory
    current_directory = os.path.dirname(os.path.abspath(__file__))
    data_file_path = os.path.join(current_directory, 'payload_tcp.json')

    # Send the data.
    payload = getData()
    # print (payload)
    sock.sendall(payload)

    # Close the socket.
    sock.close()

if __name__ == "__main__":
    test_sendTCP()


import pandas as pd
import pytest
from fluids.numerics import assert_close

from chemicals.acentric import LK_omega, Stiel_polar_factor, omega, omega_definition, omega_methods
from chemicals.critical import ACENTRIC_DEFINITION, critical_data_PassutDanner, critical_data_PSRKR4, critical_data_Yaws
from chemicals.identifiers import int_to_CAS
from chemicals.miscdata import heos_data

@pytest.mark.fuzz
@pytest.mark.slow
def test_acentric_fuzz():
    sources = [critical_data_PSRKR4, critical_data_PassutDanner, critical_data_Yaws, heos_data]
    CASs = set()
    for k in sources:
        for i in k.index:
            if pd.notnull(k.at[i, 'omega']):
                CASs.add(i if type(i) is str else int_to_CAS(i))

    # Use the default method for each chemical in this file
    omegas = [omega(i) for i in CASs] # This is quite slow
    assert len([i for i in omegas if i is not None]) == 6319

    omegas_default_sum = sum(abs(i) for i in omegas if i is not None)
    assert_close(omegas_default_sum, 3251.3456239999887)

def test_acentric_main():
    omega_calc = omega('629-92-5', method='PSRK')
    assert_close(omega_calc, 0.8486, rtol=1e-13)
    assert_close(omega('629-92-5'), 0.8486, rtol=1e-13)

    omega_calc = omega('629-92-5', method='PD')
    assert_close(omega_calc, 0.8271, rtol=1e-13)

    omega_calc = omega('629-92-5', method='YAWS')
    assert_close(omega_calc, 0.852, rtol=1e-13)

    methods = omega_methods('74-98-6')
    assert methods == ['HEOS', 'PSRK', 'PD', 'YAWS', ACENTRIC_DEFINITION]

    # Error handling
    assert None is omega(CASRN='BADCAS')

@pytest.mark.skip_types
def test_acentric_main_bad_methods():
    with pytest.raises(ValueError):
        omega(CASRN='98-01-1', method='BADMETHOD')
    with pytest.raises(ValueError):
        omega(CASRN='98-01-1', method=1)
    with pytest.raises(ValueError):
        omega(CASRN='98-01-1', method=omega)

def test_acentric_correlation():
    omega = LK_omega(425.6, 631.1, 32.1E5)
    assert_close(omega, 0.32544249926397856)

def test_omega_definition():
    omega = omega_definition(999542.0, 22048320.0)
    assert_close(omega, 0.3435744558761711, rtol=1e-12)

def test_Stiel_polar_factor():
    factor = Stiel_polar_factor(Psat=169745.0, Pc=22048321.0, omega=0.344)
    assert_close(0.02322146744772713, factor)


"""
week3_forloop_graphpaper.py

Graph Paper assignment using for loop.
"""

import sys

def getInt(ask):
    assert isinstance(ask, str)
    while True:
        try:
            inputvalue = input(ask)
        except EOFError:
            sys.exit(0)

        try:
            i = int(inputvalue)
        except ValueError:
            print("Sorry,", inputvalue, "is not an integer.")
            continue #Go back up to the word "while"

        return i

r = getInt("How many rows of boxes?\t")
c = getInt("How many columns of boxes?\t")
rb = getInt("How many rows of blanks in each boxes?\t")
cb = getInt("How many columns of blanks in each boxes?\t")

plus = ("+")
dash = ("-")
bar = ("|")
space = (" ")

for k in range(r):

    #Plus and Dash
    for h in range(c):
        print(plus, end="")
        for j in range(cb):
            print(dash, end="")
    print(plus)

    #Bar and Spaces
    for n in range(rb):
        for l in range(c):
            print(bar, end="")
            for m in range(cb):
                print(space, end="")
        print(bar)

#Last Line
for o in range(c):
    print(plus, end="")
    for p in range(cb):
        print(dash, end="")
print(plus)

sys.exit(0)


from flask import Flask,request,jsonify,redirect,render_template
import requests
webui=Flask(__name__)
@webui.route("/graph",methods=["GET","POST"])
def create():
    if request.method=="POST":
        if request.form["submit"]=="find_graph":
            response=requests.get("http://91e18b01665c.ngrok.io/display")
            data=response.json()
            return render_template("results.html",list=data)
        elif request.form["submit"]=="create":
            name=request.form["name"]
            id=request.form["empid"]
            if(name=="" or id==""):
                return("Please enter the values for employee id or name")
            else:
             response=requests.get("http://91e18b01665c.ngrok.io/create/"+name+"&"+id)
             return(response.text)

    else:
     return render_template("graph.html")

if __name__=="__main__":
    webui.run(port=5002)


import week2Base

#========内容=========
#・継承・overrideを使って書いた。
#・基底クラスで大まかな関数の実行順序を記述。
#・派生クラスで細かい関数の中身を実装している。

class Sample(week2Base.SampleBase):
    def __init__(self):
        super().__init__()

        self.FileEditer = FileEditer(self)
        self.main = self.FileEditer.Start

class FileEditer(week2Base.FileEditer):
    def __init__(self, MainClass):
        super().__init__(MainClass)

    #load
    def Load(self):
        self.file = open(self.fileName, "r")

        allCollectionsText = self.file.readlines()
        allCollectionsText = list(map(lambda collection:collection.replace("\n", ""), allCollectionsText))
        allCollectionsText = list(map(lambda collectionText:collectionText.split(","), allCollectionsText))

        allCollections = []
        for collection in allCollectionsText:
            allCollections.append([])
            for data in collection:
                try:
                    allCollections[-1].append(int(data))
                except ValueError:
                    allCollections[-1].append(data)
        self.allCollections = allCollections

        self.file.close()

    #select menu
    def SelectFirstCollection(self):
        if self.targetCollection == None:
            self.targetCollection = self.defaultCollection
    def SelectMenu(self):
        commandIndex = int(input("{targetCollection} >> ".format(targetCollection=self.targetCollection[0])))
        if commandIndex == 0:
            self.command = self.StartSave
        elif commandIndex == 1:
            self.command = self.StartWrite
        elif commandIndex == 2:
            self.command = self.StartDelete
        elif commandIndex == 3:
            self.command = self.StartShow
        elif commandIndex == 4:
            self.command = self.StartSelect
        elif commandIndex == 5:
            self.command = self.StartNewCollection

    #save
    def MakeSentenceForSave(self):
        alldataText = ""
        for collection in self.allCollections:
            collectionText = [str(i) for i in collection]
            alldataText += ",".join(collectionText)+"\n"
        return alldataText
    def WriteInFileForSave(self, alldataText):
        self.file.write(alldataText)
    def ReflectData(self):
        collectionNameList = list(map(lambda collection : collection[0], self.allCollections))
        try:
            dataIndex = collectionNameList.index(self.targetCollection[0])
            self.allCollections[dataIndex] = self.targetCollection
        except ValueError:
            self.allCollections.append(self.targetCollection)

    #write
    def InputKey(self):
        self.writeCommand = input("{targetCollection} No.{index} >> ".format(targetCollection=self.targetCollection[0], index=len(self.targetCollection)))
        self.MainClass.delRecOutSwitch = True
    def CommandAction(self):
        if self.writeCommand == "save":
            self.Save()
            self.MainClass.previousCommand = "保存が完了しました。"
        elif self.writeCommand == "back":
            if len(self.targetCollection) >1:
                del self.targetCollection[-1]
    def Adddata(self):
        try:
            self.targetCollection.append(float(self.writeCommand))
        except ValueError:
            pass
    def ShowEnrouteData(self):
        collectionText = [str(i) for i in self.targetCollection]
        text = "{collectionName} : {data}".format(collectionName=collectionText[0], data=", ".join(collectionText[1:]))
        self.MainClass.windowText = self.writeTextBase.format(action=text)

    #delete
    def DeleteAction(self):
        collectionNameList = list(map(lambda collection : collection[0], self.allCollections))
        try:
            dataIndex = collectionNameList.index(self.targetCollection[0])
            del self.allCollections[dataIndex]
        except ValueError:
            pass

        self.targetCollection = self.defaultCollection
    def CheckMessage(self):
        answer = input("本当に削除しますか(yes or no) >> ")
        if answer == "yes":
            return True
        elif answer == "no":
            return False
        else:
            return False

    #show
    def Show(self):
        collectionText = [str(data) for data in self.targetCollection]
        text="{collectionName} : {data}".format(collectionName=self.targetCollection[0], data=", ".join(collectionText[1:]))
        self.selectMenuActionText = text

    #select
    def ShowAllCollection(self):
        collectionNameList = list(map(lambda collection : collection[0], self.allCollections))
        text = ""
        for i in range(len(collectionNameList)):
            text += "{index} : {data}\n".format(index=i, data=collectionNameList[i])
        self.MainClass.windowText = text
    def InputCollectionIndex(self):
        index = int(input("Collection Number : "))
        return index

    #new collection
    def InputForNewCollection(self):
        name = input("new name >> ")
        return name
    def ReflectToNewCollection(self, name):
        self.targetCollection = [name]
#===================実行部分===================
Sample().Main()


from app import app

import os
import re
import cv2 as cv
import numpy as np
from werkzeug.utils import secure_filename
from flask import request, render_template, url_for, jsonify, redirect, session

from ..model.UserDB import UserDB
from .SystemController import SystemController
from .HomeController import get_images_path_per_page, count_total_images

@app.route("/admin/home/page/<int:page_index>", endpoint='admin_home_page')
@SystemController.login_required
@SystemController.check_acl
def show_image_page_admin(page_index):
    if page_index == 1:
        return redirect("/")
    no_images_per_page = 200
    total_no_images = count_total_images()[0][0]
    total_no_pages = int(np.ceil(total_no_images / no_images_per_page))
    current_page = page_index

    if current_page > total_no_pages:
        return redirect(f"admin/home/page/{total_no_pages}")

    start = (current_page - 1) * no_images_per_page
    images = get_images_path_per_page(start, no_images_per_page)
    db_images = []
    for info in images:
        image_class = info[1]
        image_name = info[2]
        image_info = {
            "class": image_class,
            "name": image_name
        }
        db_images.append(image_info)
    return render_template('logedview/ACLview/adminview/admin_home.html', db_images=db_images)

@app.route("/admin/home", endpoint='admin_home', methods=['GET'])
@SystemController.login_required
@SystemController.check_acl
def admin_home():
    # if logged in before
    images = get_images_path_per_page(0, 200)
    db_images = []
    for info in images:
        image_class = info[1]
        image_name = info[2]
        image_info = {
            "class": image_class,
            "name": image_name
        }
        db_images.append(image_info)
    return render_template('logedview/ACLview/adminview/admin_home.html', db_images=db_images)


import numpy as np
import torch
import seaborn as sns
from PIL import Image
from rearrangement.evaluation.utils import coord_matching, GRIP_WIDTH, GRIP_FINGER_WIDTH, is_grasp_success
import matplotlib.pyplot as plt

DPI = 96

def aabbs_from_centers(centers, sizes):
    N = len(centers)
    aabbs = np.zeros((N, 2, 2))
    centers = np.array(centers).reshape(N, 2)
    sizes = np.array(sizes).reshape(N, 1)
    aabbs[:, 0] = centers - sizes / 2
    aabbs[:, 1] = centers + sizes / 2
    return aabbs

def plot_workspace(ax, plot_limits=False):
    ax.grid()
    xmin, xmax = 0.25, 0.75
    ymin, ymax = -0.25, 0.25
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    ax.set_xticks(np.arange(0.25, 0.75, 0.05))
    ax.set_yticks(np.arange(-0.25, 0.25, 0.05))
    if plot_limits:
        ax.add_artist(plt.Rectangle((0.3, -0.2), 0.4, 0.4, color='black', fill=False,
                                    linestyle='--', linewidth=2.0))
    return ax

def plot_gt_objects(ax, aabbs, plot_center=False,
                    target_box=False, alpha=0.1,
                    collision_radius=None,
                    plot_collision_radius=False,
                    collision_alpha=0.1):
    aabbs = np.array(aabbs)
    for aabb, color in zip(aabbs, sns.color_palette() * 2):
        d = aabb[1] - aabb[0]
        center = (aabb[1] + aabb[0]) / 2
        if target_box:
            alpha = 1.0
        r = plt.Rectangle(aabb[0], d[0], d[1], color=color, alpha=alpha)

        if plot_collision_radius:
            ax.add_artist(plt.Circle(center, collision_radius, color='black', fill=True, alpha=collision_alpha))

        ax.add_artist(r)
        if plot_center:
            ax.scatter(center[0], center[1], color=color, marker='x', s=50*2)

def plot_grasp_positions(ax, coords, colors=None):
    if colors is None:
        colors = sns.color_palette() * 2

    for center_n, color_n in zip(coords, colors):
        center_n = np.array(center_n).tolist()
        ax.plot(center_n[0] + np.array([-GRIP_FINGER_WIDTH / 2, GRIP_FINGER_WIDTH / 2]),
                np.full(2, center_n[1] - GRIP_WIDTH / 2), color=color_n)
        ax.plot(center_n[0] + np.array([-GRIP_FINGER_WIDTH, GRIP_FINGER_WIDTH]),
                np.full(2, center_n[1] + GRIP_WIDTH / 2), color=color_n)
        ax.plot(np.full(2, center_n[0]),
                center_n[1] + np.array([-GRIP_WIDTH / 2, GRIP_WIDTH / 2]), color=color_n)

def plot_centers(ax, centers, color=None, plot_gripper=True):
    colors = sns.color_palette() * 2 if color is None else np.full(len(centers), color)
    for center_n, color in zip(centers, colors):
        ax.scatter(center_n[0], center_n[1], color=color, marker='x', s=150*2)

def plot_pc(ax, pc, color=None):
    colors = sns.color_palette() * 2 if color is None else np.full(len(pc), color)
    for pc_n, color in zip(pc, colors):
        ax.scatter(pc_n[0], pc_n[1], color=color, marker='x', s=10*2)

def resize(im, size=(320, 240)):
    return np.array(Image.fromarray(np.array(im)).resize(size))

def make_rgba_instance_segm(instance_segm, colors):
    rgba = np.zeros((*instance_segm.shape, 4), dtype=np.uint8)
    for uniq, color in zip(np.unique(instance_segm[instance_segm > 0]), colors):
        rgba[instance_segm == uniq, :3] = np.array(color) * 255
        rgba[instance_segm == uniq, -1] = 255
    return rgba

def plot_instance_segm_overlay(im, instance_segm, ax,
                               alpha=0.6, show_id=True,
                               show_box=True, plot_im=True):
    instance_segm = resize(instance_segm, tuple(reversed(im.shape[:2])))
    uniqs = np.unique(instance_segm[instance_segm > 0])
    if plot_im:
        ax.imshow(im)
    ax.imshow(make_rgba_instance_segm(instance_segm, sns.color_palette() * 2), alpha=alpha)

    for n, (color, uniq) in enumerate(zip(sns.color_palette() * 2, uniqs)):
        ids = np.transpose(np.nonzero(instance_segm == uniq))

        if show_box:
            topleft = ids.min(axis=0)
            bottomright = ids.max(axis=0)
            wh = bottomright - topleft
            rect = plt.Rectangle((topleft[1], topleft[0]), wh[1], wh[0],
                                 color=color, fill=False, linewidth=1.0, linestyle='--')
            ax.add_artist(rect)
            string = f'{n + 1}' if show_id else ''
            ax.text(topleft[1], topleft[0] - 4, string, color='black')
    return ax

def plot_src_tgt(src_im, src_aabbs, src_pc, src_coord, src_inst_segm,
                 tgt_im, tgt_aabbs, tgt_pc, tgt_coord, tgt_inst_segm,
                 plot_gripper=True, collision_radius=None,
                 plot_im_matching=False, plot_workspace_matching=False,
                 planned_action=None, axs=None):
    if axs is None:
        n_rows = 2
        n_cols = 3
        ax_size = np.array([300, 300]) * (4/3) / DPI
        f, axs = plt.subplots(n_rows, n_cols, figsize=(ax_size[0] * (n_cols + 1), ax_size[1] * n_rows))

    plot_predictions(axs[0], src_im, src_aabbs, src_coord, src_pc, src_inst_segm,
                     plot_mask=False, plot_class_mask=False, show_id=True)

    plot_predictions(axs[1], tgt_im, tgt_aabbs, tgt_coord, tgt_pc, tgt_inst_segm,
                     plot_mask=False, plot_class_mask=False, show_id=True)

    if collision_radius is not None:
        for coord_n in src_coord:
            axs[0, -1].add_artist(plt.Circle(coord_n, collision_radius, color='black', fill=True, alpha=0.1))

    plot_gt_objects(axs[0, -1], tgt_aabbs, plot_center=False, target_box=True)
    return axs

def plot_src_tgt_patches(src_patches, tgt_patches, matching, axs=None):
    if axs is None:
        n_rows = 2
        n_cols = len(tgt_patches.images)
        ax_size = np.array([100, 100]) * (4/3) / DPI
        f, axs = plt.subplots(n_rows, n_cols, figsize=(ax_size[0] * (n_cols + 1), ax_size[1] * n_rows))

    n_plots = max(len(src_patches.images), len(tgt_patches.images))
    n_plots = min(n_plots, len(axs[0]))

    for n in range(n_plots):
        if n < len(src_patches.images):
            axs[0, n].imshow(src_patches.images[n].permute(1, 2, 0))
            axs[0, n].axis('off')
        if n < len(tgt_patches.images):
            axs[1, n].imshow(tgt_patches.images[matching][n].permute(1, 2, 0))
            axs[1, n].axis('off')
    return axs

def plot_predictions(axs, rgb, aabbs, coord, pc, instance_segm,
                     field=None, mask=None, class_mask=None,
                     plot_field=False, plot_instance_segm=True,
                     plot_mask=False, plot_class_mask=False,
                     show_id=True, alpha=0.6, collision_radius=None, plot_grasp=False):
    m = 0

    aabbs = torch.tensor(aabbs)
    if len(aabbs) > 0:
        centers = (aabbs[:, 1] + aabbs[:, 0]) / 2
        success_matching, matching = coord_matching(coord, centers[..., :2].float())
        aabbs = aabbs[matching] if success_matching else aabbs
        success_grasps = [is_grasp_success(aabb, coord_i) for aabb, coord_i in zip(aabbs, coord)]
    else:
        success_grasps = []
        success_matching = False

    if success_matching:
        errors = torch.norm(centers[matching][..., :2].float() - coord.float(), dim=1)
    else:
        errors = None

    axs[m].imshow(rgb)
    axs[m].axis('off')
    m += 1

    if plot_field:
        axs[m].imshow(field[0])
        m += 1
        axs[m].imshow(field[1])
        m += 1

    if plot_instance_segm:
        plot_instance_segm_overlay(rgb, instance_segm, axs[m],
                                   alpha=0.6, show_id=show_id)
        axs[m].axis('off')
        sem_segm = class_mask.argmax(dim=0).type(torch.uint8)
        sem_segm[sem_segm < 4] = 0
        plot_instance_segm_overlay(rgb, sem_segm, axs[m], alpha=0.6, show_box=False)
        m += 1

    if plot_mask:
        axs[m].imshow(mask[0])
        m += 1

    if plot_class_mask:
        axs[m].imshow(class_mask.argmax(dim=0))
        m += 1

    ax = axs[m]
    avg_error = f'{errors.mean(0).item():.4f}' if errors is not None else 'None'
    max_error = f'{errors.max(0)[0]:.4f}' if errors is not None else 'None'
    ax.set_title(
        f'identification: {success_matching}, avg: {avg_error}, max: {max_error}, grasp {sum(success_grasps)}/{len(coord)}')  # noqa
    color = 'black' if (not success_matching and len(aabbs) > 0) else None
    plot_workspace(ax)
    plot_gt_objects(ax, aabbs)
    # plot_pc(ax, pc, color=color)
    plot_centers(ax, coord, color=color)
    if plot_grasp:
        plot_grasp_positions(ax, coord, colors=[('black' if succ else 'red') for succ in success_grasps])

def plot_batch_predictions(rgb, aabbs, objects, segm, pred, N=2,
                           rand=False, plot_field=False, plot_instance_segm=True,
                           plot_mask=False, plot_class_mask=False, show_id=True, plot_grasp=False,
                           axs=None):
    if axs is None:
        n_rows = min(N, len(rgb))
        n_cols = 2 + (2 if plot_field else 0) + sum([plot_instance_segm, plot_mask, plot_class_mask])
        ax_size = np.array([299, 299]) * (4/3) / DPI
        fig, axs = plt.subplots(n_rows, n_cols, figsize=(ax_size[0] * (n_cols + 1), ax_size[1] * n_rows))
        if n_rows == 1:
            axs = axs[np.newaxis]

    indices = np.random.permutation(range(len(rgb)))[:N] if rand else range(N)
    for k, n in enumerate(indices):
        plot_predictions(axs[k], rgb=rgb[n], aabbs=aabbs[n],
                         coord=objects.coord[n], pc=objects.pc[n],
                         instance_segm=segm.instance[n], field=pred.field[n],
                         mask=pred.mask[n], class_mask=pred.class_mask[n],
                         plot_field=plot_field, plot_instance_segm=plot_instance_segm, plot_mask=plot_mask,
                         plot_class_mask=plot_class_mask, show_id=show_id)
    return axs

def plot_boxes(boxes, conf=None, ax=None, color='red', th=0.5):
    if ax is None:
        ax_size = np.array([299, 299]) * (4/3) / DPI
        _, ax = plt.subplots(1, 1, figsize=(ax_size[0] * 2, ax_size[1] * 2))

    if conf is None:
        conf = np.full(boxes.shape[0], 1.)
    else:
        conf = np.array(conf).copy().clip(0, 1)

    plot_workspace(ax)
    for box, conf in zip(boxes, conf):
        wh = box[[2, 3]] - box[[0, 1]]
        if conf > th:
            ax.add_artist(plt.Rectangle((box[0], box[1]), wh[0], wh[1], color=color, alpha=conf, fill=False))
            ax.text(box[0] + wh[0] / 2, box[1] + 0.005, str(float(conf)), color=color)
    return ax


from binascii import hexlify

import lascar
import numpy as np
from lascar.tools.aes import sbox
from rainbow.generics import rainbow_arm
from rainbow.utils import hw
from visplot import plot
from tqdm import tqdm
import trsfile as trs
from trsfile import trs_open, Trace, SampleCoding, TracePadding, Header
from trsfile.parametermap import TraceParameterMap, TraceParameterDefinitionMap
from trsfile.traceparameter import ByteArrayParameter, ParameterType, TraceParameterDefinition
from Crypto.Cipher import AES
from numba import jit
import matplotlib.pyplot as plt
import  argparse

def check_aes_ecb_enc(plaintext, key):
    if (len(plaintext) == 16 and len(key) == 16):
        cipher = AES.new(key, AES.MODE_ECB)
        ciphertext = cipher.encrypt(bytes(plaintext))
        return bytearray(ciphertext)

@jit(parallel=True)
def aes_encrypt(e ,key, plaintext):

    e.mem_trace = True
    e.trace_regs = True

    key_addr = 0xDEAD0000
    e[key_addr] = key
    rk_addr = 0xDEAD1000
    e[rk_addr] = key

    # AES_128_keyschedule(key, rk+16)
    e["r0"] = key_addr
    e["r1"] = rk_addr + 16
    e.start(e.functions["AES_128_keyschedule"] | 1, 0)

    buf_in = 0xDEAD2000
    buf_out = 0xDEAD3000
    e[buf_in] = plaintext
    e[buf_out] = b"\x00" * 16  # Need to do this so this buffer is mapped into unicorn

    # AES_128_encrypt(rk, buf_in, buf_out)
    e["r0"] = rk_addr
    e["r1"] = buf_in
    e["r2"] = buf_out
    # e.trace_reset()
    e.start(e.functions["AES_128_encrypt"] | 1, 0)

    ## Read out the ciphertext
    ciphertext = e[buf_out:buf_out+16]

    # Hamming weight + noise to pretend we're on a real target
    trace = np.array([hw(i) for i in e.sca_values_trace]) + np.random.normal(
        0, 1.0, (len(e.sca_values_trace)))
    return trace,ciphertext

def cw_in_out_convert_trs_legacy(text_in, text_out):
    dest = bytearray()
    dest.extend(text_in)
    dest.extend(text_out)
    return dest

if __name__ == "__main__":

        from random import getrandbits

        import numpy as np
        from rainbow.utils import hw

        # from visplot import plot

        e = rainbow_arm(sca_mode=True)
        e.load("aes.bin", typ=".elf")

        traces = []
        ciphertexts = []
        plaintexts = []
        N = 5000
        KEY = bytes(bytearray.fromhex("cafebabedeadbeef0001020304050607"))
        with trs_open(
                "test.trs",  # File name of the trace set
                'w',  # Mode: r, w, x, a (default to x)
                # Zero or more options can be passed (supported options depend on the storage engine)
                engine='TrsEngine',  # Optional: how the trace set is stored (defaults to TrsEngine)
                headers={  # Optional: headers (see Header class)
                    Header.TRS_VERSION: 2,
                    Header.SCALE_X: 1e-6,
                    Header.SCALE_Y: 0.1,
                    Header.DESCRIPTION: 'Exported  from CW ',
                },
                padding_mode=TracePadding.AUTO,  # Optional: padding mode (defaults to TracePadding.AUTO)
                live_update=True  # Optional: updates the TRS file for live preview (small performance hit)
        ) as traces_trs:
         for i in tqdm(range(N),desc='Capturing and save traces'):
                 plaintext = bytes([getrandbits(8) for i in range(16)])
                 trace, ciphertext = aes_encrypt(e,KEY,plaintext)
                 ciphertext_py = check_aes_ecb_enc(plaintext,KEY)
                 if ciphertext_py !=  ciphertext:
                    print("Are you have some problems!!")
                 print("Plaintext is :", hexlify(plaintext).upper())
                 print("Ciphertext is :", hexlify(ciphertext).upper())
                 traces_trs.append(Trace(SampleCoding.FLOAT, trace, TraceParameterMap(
                {'LEGACY_DATA': ByteArrayParameter(
                    cw_in_out_convert_trs_legacy(plaintext, ciphertext))})))

        traces_trs.close
        print("Convertion trace completed")
        #traces = np.array(traces)
        #plt.plot(traces[0])
        #plt.show()
        print(len(traces))
        #traces += np.random.normal(0, 1, size=traces.shape)

        #v = plot(traces, dontrun=True)
        #v.multiple_select(0)
        #v.run()


import warnings
from typing import Dict, List, Tuple, Iterable, Any

import numpy

import torch
import torch.nn.functional as F
from torch.nn.modules.linear import Linear
from torch.nn.modules.rnn import LSTMCell, LSTM

from allennlp.common.util import START_SYMBOL, END_SYMBOL
from allennlp.data import TextFieldTensors, Vocabulary
from allennlp.modules import Attention, TextFieldEmbedder, Seq2SeqEncoder
from allennlp.models.model import Model
from allennlp.modules.token_embedders import Embedding
from allennlp.nn import util
from allennlp.nn.beam_search import BeamSearch
from allennlp.common.lazy import Lazy
from allennlp.training.metrics import BLEU

@Model.register("simple_seq2seq")
class SimpleSeq2Seq(Model):
    """
    This `SimpleSeq2Seq` class is a `Model` which takes a sequence, encodes it, and then
    uses the encoded representations to decode another sequence.  You can use this as the basis for
    a neural machine translation system, an abstractive summarization system, or any other common
    seq2seq problem.  The model here is simple, but should be a decent starting place for
    implementing recent models for these tasks.
    # Parameters
    vocab : `Vocabulary`, required
        Vocabulary containing source and target vocabularies. They may be under the same namespace
        (`tokens`) or the target tokens can have a different namespace, in which case it needs to
        be specified as `target_namespace`.
    source_embedder : `TextFieldEmbedder`, required
        Embedder for source side sequences
    encoder : `Seq2SeqEncoder`, required
        The encoder of the "encoder/decoder" model
    beam_search : `BeamSearch`, optional (default = `Lazy(BeamSearch)`)
        This is used to during inference to select the tokens of the decoded output sequence.
    target_namespace : `str`, optional (default = `'tokens'`)
        If the target side vocabulary is different from the source side's, you need to specify the
        target's namespace here. If not, we'll assume it is "tokens", which is also the default
        choice for the source side, and this might cause them to share vocabularies.
    target_embedding_dim : `int`, optional (default = `'source_embedding_dim'`)
        You can specify an embedding dimensionality for the target side. If not, we'll use the same
        value as the source embedder's.
    target_pretrain_file : `str`, optional (default = `None`)
        Path to target pretrain embedding files
    target_decoder_layers : `int`, optional (default = `1`)
        Nums of layer for decoder
    attention : `Attention`, optional (default = `None`)
        If you want to use attention to get a dynamic summary of the encoder outputs at each step
        of decoding, this is the function used to compute similarity between the decoder hidden
        state and encoder outputs.
    scheduled_sampling_ratio : `float`, optional (default = `0.`)
        At each timestep during training, we sample a random number between 0 and 1, and if it is
        not less than this value, we use the ground truth labels for the whole batch. Else, we use
        the predictions from the previous time step for the whole batch. If this value is 0.0
        (default), this corresponds to teacher forcing, and if it is 1.0, it corresponds to not
        using target side ground truth labels.  See the following paper for more information:
        [Scheduled Sampling for Sequence Prediction with Recurrent Neural Networks. Bengio et al.,
        2015](https://arxiv.org/abs/1506.03099).
    use_bleu : `bool`, optional (default = `True`)
        If True, the BLEU metric will be calculated during validation.
    ngram_weights : `Iterable[float]`, optional (default = `(0.25, 0.25, 0.25, 0.25)`)
        Weights to assign to scores for each ngram size.
    """

    def __init__(
        self,
        vocab: Vocabulary,
        source_embedder: TextFieldEmbedder,
        encoder: Seq2SeqEncoder,
        beam_search: Lazy[BeamSearch] = Lazy(BeamSearch),
        attention: Attention = None,
        target_namespace: str = "tokens",
        target_embedding_dim: int = None,
        scheduled_sampling_ratio: float = 0.0,
        use_bleu: bool = True,
        bleu_ngram_weights: Iterable[float] = (0.25, 0.25, 0.25, 0.25),
        target_pretrain_file: str = None,
        target_decoder_layers: int = 1,
        **kwargs
    ) -> None:
        super().__init__(vocab)
        self._target_namespace = target_namespace
        self._target_decoder_layers = target_decoder_layers
        self._scheduled_sampling_ratio = scheduled_sampling_ratio

        # We need the start symbol to provide as the input at the first timestep of decoding, and
        # end symbol as a way to indicate the end of the decoded sequence.
        self._start_index = self.vocab.get_token_index(START_SYMBOL, self._target_namespace)
        self._end_index = self.vocab.get_token_index(END_SYMBOL, self._target_namespace)

        if use_bleu:
            pad_index = self.vocab.get_token_index(
                self.vocab._padding_token, self._target_namespace
            )
            self._bleu = BLEU(
                bleu_ngram_weights,
                exclude_indices={pad_index, self._end_index, self._start_index},
            )
        else:
            self._bleu = None

        # At prediction time, we'll use a beam search to find the best target sequence.
        # For backwards compatibility, check if beam_size or max_decoding_steps were passed in as
        # kwargs. If so, update the BeamSearch object before constructing and raise a DeprecationWarning
        deprecation_warning = (
            "The parameter {} has been deprecated."
            " Provide this parameter as argument to beam_search instead."
        )
        beam_search_extras = {}
        if "beam_size" in kwargs:
            beam_search_extras["beam_size"] = kwargs["beam_size"]
            warnings.warn(deprecation_warning.format("beam_size"), DeprecationWarning)
        if "max_decoding_steps" in kwargs:
            beam_search_extras["max_steps"] = kwargs["max_decoding_steps"]
            warnings.warn(deprecation_warning.format("max_decoding_steps"), DeprecationWarning)
        self._beam_search = beam_search.construct(
            end_index=self._end_index, vocab=self.vocab, **beam_search_extras
        )

        # Dense embedding of source vocab tokens.
        self._source_embedder = source_embedder

        # Encodes the sequence of source embeddings into a sequence of hidden states.
        self._encoder = encoder

        num_classes = self.vocab.get_vocab_size(self._target_namespace)

        # Attention mechanism applied to the encoder output for each step.
        self._attention = attention

        # Dense embedding of vocab words in the target space.
        target_embedding_dim = target_embedding_dim or source_embedder.get_output_dim()
        if not target_pretrain_file:
            self._target_embedder = Embedding(
                num_embeddings=num_classes, embedding_dim=target_embedding_dim
            )
        else:
            self._target_embedder = Embedding(
                embedding_dim=target_embedding_dim,
                pretrained_file=target_pretrain_file,
                vocab_namespace=self._target_namespace,
                vocab=self.vocab,
            )

        # Decoder output dim needs to be the same as the encoder output dim since we initialize the
        # hidden state of the decoder with the final hidden state of the encoder.
        self._encoder_output_dim = self._encoder.get_output_dim()
        self._decoder_output_dim = self._encoder_output_dim

        if self._attention:
            # If using attention, a weighted average over encoder outputs will be concatenated
            # to the previous target embedding to form the input to the decoder at each
            # time step.
            self._decoder_input_dim = self._decoder_output_dim + target_embedding_dim
        else:
            # Otherwise, the input to the decoder is just the previous target embedding.
            self._decoder_input_dim = target_embedding_dim

        # We'll use an LSTM cell as the recurrent cell that produces a hidden state
        # for the decoder at each time step.
        # TODO (pradeep): Do not hardcode decoder cell type.
        if self._target_decoder_layers > 1:
            self._decoder_cell = LSTM(
                self._decoder_input_dim,
                self._decoder_output_dim,
                self._target_decoder_layers,
            )
        else:
            self._decoder_cell = LSTMCell(self._decoder_input_dim, self._decoder_output_dim)

        # We project the hidden state from the decoder into the output vocabulary space
        # in order to get log probabilities of each target token, at each time step.
        self._output_projection_layer = Linear(self._decoder_output_dim, num_classes)

    def take_step(
        self, last_predictions: torch.Tensor, state: Dict[str, torch.Tensor], step: int
    ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
        """
        Take a decoding step. This is called by the beam search class.
        # Parameters
        last_predictions : `torch.Tensor`
            A tensor of shape `(group_size,)`, which gives the indices of the predictions
            during the last time step.
        state : `Dict[str, torch.Tensor]`
            A dictionary of tensors that contain the current state information
            needed to predict the next step, which includes the encoder outputs,
            the source mask, and the decoder hidden state and context. Each of these
            tensors has shape `(group_size, *)`, where `*` can be any other number
            of dimensions.
        step : `int`
            The time step in beam search decoding.

        # Returns
        Tuple[torch.Tensor, Dict[str, torch.Tensor]]
            A tuple of `(log_probabilities, updated_state)`, where `log_probabilities`
            is a tensor of shape `(group_size, num_classes)` containing the predicted
            log probability of each class for the next step, for each item in the group,
            while `updated_state` is a dictionary of tensors containing the encoder outputs,
            source mask, and updated decoder hidden state and context.
        Notes
        -----
            We treat the inputs as a batch, even though `group_size` is not necessarily
            equal to `batch_size`, since the group may contain multiple states
            for each source sentence in the batch.
        """
        # shape: (group_size, num_classes)
        output_projections, state = self._prepare_output_projections(last_predictions, state)

        # shape: (group_size, num_classes)
        class_log_probabilities = F.log_softmax(output_projections, dim=-1)

        return class_log_probabilities, state

    def forward(
        self,  # type: ignore
        source_tokens: TextFieldTensors,
        target_tokens: TextFieldTensors = None,
    ) -> Dict[str, torch.Tensor]:

        """
        Make foward pass with decoder logic for producing the entire target sequence.
        # Parameters
        source_tokens : `TextFieldTensors`
           The output of `TextField.as_array()` applied on the source `TextField`. This will be
           passed through a `TextFieldEmbedder` and then through an encoder.
        target_tokens : `TextFieldTensors`, optional (default = `None`)
           Output of `Textfield.as_array()` applied on target `TextField`. We assume that the
           target tokens are also represented as a `TextField`.
        # Returns

        `Dict[str, torch.Tensor]`

        """
        state = self._encode(source_tokens)

        if target_tokens:
            state = self._init_decoder_state(state)
            # The `_forward_loop` decodes the input sequence and computes the loss during training
            # and validation.
            output_dict = self._forward_loop(state, target_tokens)
        else:
            output_dict = {}

        if not self.training:
            state = self._init_decoder_state(state)
            predictions = self._forward_beam_search(state)
            output_dict.update(predictions)
            if target_tokens and self._bleu:
                # shape: (batch_size, beam_size, max_sequence_length)
                top_k_predictions = output_dict["predictions"]
                # shape: (batch_size, max_predicted_sequence_length)
                best_predictions = top_k_predictions[:, 0, :]
                self._bleu(best_predictions, target_tokens["tokens"]["tokens"])

        return output_dict

    def make_output_human_readable(self, output_dict: Dict[str, Any]) -> Dict[str, Any]:
        """
        Finalize predictions.
        This method overrides `Model.make_output_human_readable`, which gets called after `Model.forward`, at test
        time, to finalize predictions. The logic for the decoder part of the encoder-decoder lives
        within the `forward` method.
        This method trims the output predictions to the first end symbol, replaces indices with
        corresponding tokens, and adds a field called `predicted_tokens` to the `output_dict`.
        """
        predicted_indices = output_dict["predictions"]
        if not isinstance(predicted_indices, numpy.ndarray):
            predicted_indices = predicted_indices.detach().cpu().numpy()
        all_predicted_tokens = []
        for top_k_predictions in predicted_indices:
            # Beam search gives us the top k results for each source sentence in the batch
            # we want top-k results.
            if len(top_k_predictions.shape) == 1:
                top_k_predictions = [top_k_predictions]

            batch_predicted_tokens = []
            for indices in top_k_predictions:
                indices = list(indices)
                # Collect indices till the first end_symbol
                if self._end_index in indices:
                    indices = indices[: indices.index(self._end_index)]
                predicted_tokens = [
                    self.vocab.get_token_from_index(x, namespace=self._target_namespace)
                    for x in indices
                ]
                batch_predicted_tokens.append(predicted_tokens)

            all_predicted_tokens.append(batch_predicted_tokens)
        output_dict["predicted_tokens"] = all_predicted_tokens
        return output_dict

    def _encode(self, source_tokens: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
        # shape: (batch_size, max_input_sequence_length, encoder_input_dim)
        embedded_input = self._source_embedder(source_tokens)
        # shape: (batch_size, max_input_sequence_length)
        source_mask = util.get_text_field_mask(source_tokens)
        # shape: (batch_size, max_input_sequence_length, encoder_output_dim)
        encoder_outputs = self._encoder(embedded_input, source_mask)
        return {"source_mask": source_mask, "encoder_outputs": encoder_outputs}

    def _init_decoder_state(self, state: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
        batch_size = state["source_mask"].size(0)
        # shape: (batch_size, encoder_output_dim)
        final_encoder_output = util.get_final_encoder_states(
            state["encoder_outputs"],
            state["source_mask"],
            self._encoder.is_bidirectional(),
        )
        # Initialize the decoder hidden state with the final output of the encoder.
        # shape: (batch_size, decoder_output_dim)
        state["decoder_hidden"] = final_encoder_output
        # shape: (batch_size, decoder_output_dim)
        state["decoder_context"] = state["encoder_outputs"].new_zeros(
            batch_size, self._decoder_output_dim
        )
        if self._target_decoder_layers > 1:
            # shape: (num_layers, batch_size, decoder_output_dim)
            state["decoder_hidden"] = (
                state["decoder_hidden"].unsqueeze(0).repeat(self._target_decoder_layers, 1, 1)
            )

            # shape: (num_layers, batch_size, decoder_output_dim)
            state["decoder_context"] = (
                state["decoder_context"].unsqueeze(0).repeat(self._target_decoder_layers, 1, 1)
            )

        return state

    def _forward_loop(
        self, state: Dict[str, torch.Tensor], target_tokens: TextFieldTensors = None
    ) -> Dict[str, torch.Tensor]:
        """
        Make forward pass during training or do greedy search during prediction.
        Notes
        -----
        We really only use the predictions from the method to test that beam search
        with a beam size of 1 gives the same results.
        """
        # shape: (batch_size, max_input_sequence_length)
        source_mask = state["source_mask"]

        batch_size = source_mask.size()[0]

        if target_tokens:
            # shape: (batch_size, max_target_sequence_length)
            targets = target_tokens["tokens"]["tokens"]

            _, target_sequence_length = targets.size()

            # The last input from the target is either padding or the end symbol.
            # Either way, we don't have to process it.
            num_decoding_steps = target_sequence_length - 1
        else:
            num_decoding_steps = self._beam_search.max_steps

        # Initialize target predictions with the start index.
        # shape: (batch_size,)
        last_predictions = source_mask.new_full(
            (batch_size,), fill_value=self._start_index, dtype=torch.long
        )

        step_logits: List[torch.Tensor] = []
        step_predictions: List[torch.Tensor] = []
        for timestep in range(num_decoding_steps):
            if (
                self.training
                and self._scheduled_sampling_ratio > 0.0
                and torch.rand(1).item() < self._scheduled_sampling_ratio
            ):
                # Use gold tokens at test time and at a rate of 1 - _scheduled_sampling_ratio
                # during training.
                # shape: (batch_size,)
                input_choices = last_predictions
            elif not target_tokens:
                # shape: (batch_size,)
                input_choices = last_predictions
            else:
                # shape: (batch_size,)
                input_choices = targets[:, timestep]

            # shape: (batch_size, num_classes)
            output_projections, state = self._prepare_output_projections(input_choices, state)

            # list of tensors, shape: (batch_size, 1, num_classes)
            step_logits.append(output_projections.unsqueeze(1))

            # shape: (batch_size, num_classes)
            class_probabilities = F.softmax(output_projections, dim=-1)

            # shape (predicted_classes): (batch_size,)
            _, predicted_classes = torch.max(class_probabilities, 1)

            # shape (predicted_classes): (batch_size,)
            last_predictions = predicted_classes

            step_predictions.append(last_predictions.unsqueeze(1))

        # shape: (batch_size, num_decoding_steps)
        predictions = torch.cat(step_predictions, 1)

        output_dict = {"predictions": predictions}

        if target_tokens:
            # shape: (batch_size, num_decoding_steps, num_classes)
            logits = torch.cat(step_logits, 1)

            # Compute loss.
            target_mask = util.get_text_field_mask(target_tokens)
            loss = self._get_loss(logits, targets, target_mask)
            output_dict["loss"] = loss

        return output_dict

    def _forward_beam_search(self, state: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
        """Make forward pass during prediction using a beam search."""
        batch_size = state["source_mask"].size()[0]
        start_predictions = state["source_mask"].new_full(
            (batch_size,), fill_value=self._start_index, dtype=torch.long
        )

        # shape (all_top_k_predictions): (batch_size, beam_size, num_decoding_steps)
        # shape (log_probabilities): (batch_size, beam_size)
        all_top_k_predictions, log_probabilities = self._beam_search.search(
            start_predictions, state, self.take_step
        )

        output_dict = {
            "class_log_probabilities": log_probabilities,
            "predictions": all_top_k_predictions,
        }
        return output_dict

    def _prepare_output_projections(
        self, last_predictions: torch.Tensor, state: Dict[str, torch.Tensor]
    ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
        """
        Decode current state and last prediction to produce produce projections
        into the target space, which can then be used to get probabilities of
        each target token for the next step.
        Inputs are the same as for `take_step()`.
        """
        # shape: (group_size, max_input_sequence_length, encoder_output_dim)
        encoder_outputs = state["encoder_outputs"]

        # shape: (group_size, max_input_sequence_length)
        source_mask = state["source_mask"]

        # shape: (num_layers, group_size, decoder_output_dim)
        decoder_hidden = state["decoder_hidden"]

        # shape: (num_layers, group_size, decoder_output_dim)
        decoder_context = state["decoder_context"]

        # shape: (group_size, target_embedding_dim)
        embedded_input = self._target_embedder(last_predictions)

        if self._attention:
            # shape: (group_size, encoder_output_dim)
            if self._target_decoder_layers > 1:
                attended_input = self._prepare_attended_input(
                    decoder_hidden[0], encoder_outputs, source_mask
                )
            else:
                attended_input = self._prepare_attended_input(
                    decoder_hidden, encoder_outputs, source_mask
                )
            # shape: (group_size, decoder_output_dim + target_embedding_dim)
            decoder_input = torch.cat((attended_input, embedded_input), -1)
        else:
            # shape: (group_size, target_embedding_dim)
            decoder_input = embedded_input

        if self._target_decoder_layers > 1:
            # shape: (1, batch_size, target_embedding_dim)
            decoder_input = decoder_input.unsqueeze(0)

            # shape (decoder_hidden): (num_layers, batch_size, decoder_output_dim)
            # shape (decoder_context): (num_layers, batch_size, decoder_output_dim)
            _, (decoder_hidden, decoder_context) = self._decoder_cell(
                decoder_input.float(), (decoder_hidden.float(), decoder_context.float())
            )
        else:
            # shape (decoder_hidden): (batch_size, decoder_output_dim)
            # shape (decoder_context): (batch_size, decoder_output_dim)
            decoder_hidden, decoder_context = self._decoder_cell(
                decoder_input.float(), (decoder_hidden.float(), decoder_context.float())
            )

        state["decoder_hidden"] = decoder_hidden
        state["decoder_context"] = decoder_context

        # shape: (group_size, num_classes)
        if self._target_decoder_layers > 1:
            output_projections = self._output_projection_layer(decoder_hidden[-1])
        else:
            output_projections = self._output_projection_layer(decoder_hidden)
        return output_projections, state

    def _prepare_attended_input(
        self,
        decoder_hidden_state: torch.LongTensor = None,
        encoder_outputs: torch.LongTensor = None,
        encoder_outputs_mask: torch.BoolTensor = None,
    ) -> torch.Tensor:
        """Apply attention over encoder outputs and decoder state."""
        # shape: (batch_size, max_input_sequence_length)
        input_weights = self._attention(decoder_hidden_state, encoder_outputs, encoder_outputs_mask)

        # shape: (batch_size, encoder_output_dim)
        attended_input = util.weighted_sum(encoder_outputs, input_weights)

        return attended_input

    @staticmethod
    def _get_loss(
        logits: torch.LongTensor,
        targets: torch.LongTensor,
        target_mask: torch.BoolTensor,
    ) -> torch.Tensor:
        """
        Compute loss.
        Takes logits (unnormalized outputs from the decoder) of size (batch_size,
        num_decoding_steps, num_classes), target indices of size (batch_size, num_decoding_steps+1)
        and corresponding masks of size (batch_size, num_decoding_steps+1) steps and computes cross
        entropy loss while taking the mask into account.
        The length of `targets` is expected to be greater than that of `logits` because the
        decoder does not need to compute the output corresponding to the last timestep of
        `targets`. This method aligns the inputs appropriately to compute the loss.
        During training, we want the logit corresponding to timestep i to be similar to the target
        token from timestep i + 1. That is, the targets should be shifted by one timestep for
        appropriate comparison.  Consider a single example where the target has 3 words, and
        padding is to 7 tokens.
           The complete sequence would correspond to <S> w1  w2  w3  <E> <P> <P>
           and the mask would be                     1   1   1   1   1   0   0
           and let the logits be                     l1  l2  l3  l4  l5  l6
        We actually need to compare:
           the sequence           w1  w2  w3  <E> <P> <P>
           with masks             1   1   1   1   0   0
           against                l1  l2  l3  l4  l5  l6
           (where the input was)  <S> w1  w2  w3  <E> <P>
        """
        # shape: (batch_size, num_decoding_steps)
        relevant_targets = targets[:, 1:].contiguous()

        # shape: (batch_size, num_decoding_steps)
        relevant_mask = target_mask[:, 1:].contiguous()

        return util.sequence_cross_entropy_with_logits(logits, relevant_targets, relevant_mask)

    def get_metrics(self, reset: bool = False) -> Dict[str, float]:
        all_metrics: Dict[str, float] = {}
        if self._bleu and not self.training:
            all_metrics.update(self._bleu.get_metric(reset=reset))
        return all_metrics

    default_predictor = "seq2seq"


import numpy as np
from matplotlib import pyplot as plt
from jdutil import *
from netCDF4 import date2num, num2date

# This is an implementation of Max Reuter's IDL code
'''
def ufunc1_2018(lats, dates, a):
    # LATS are in radians!

    jdates = np.array([date_to_jd(d.year, d.month, d.day)
                       for d in dates])
    t = (jdates - date_to_jd(2003, 1, 1)) / 365.25
    dumt1 = np.tanh(a[3] * lats + a[4])
    dumt2 = np.tanh(a[5] * lats + a[6]) + a[7]
    dumt3 = np.tanh(a[8] * lats + a[9])

    season = (
        a[11] * dumt2 * np.sin(t * 2.0 * np.pi + a[10] * dumt3) +
        a[12] * dumt2 * np.cos(t * 2.0 * np.pi + a[10] * dumt3) +
        a[13] * dumt2 * np.sin(t * 4.0 * np.pi + a[10] * dumt3) +
        a[14] * dumt2 * np.cos(t * 4.0 * np.pi + a[10] * dumt3)
        )

    f = a[0] + a[1] * t + a[2] * dumt1 + season
    return f, season

def secm_co2_2018(lats, dates):

    c = np.array([38.779246,   2.0831194])
'''

def ufunc1_2018(lats, dates, a):

    dumt2 = np.tanh(a[5] * lats + a[6]) + a[7]
    dumt3 = np.tanh(a[8] * lats + a[9])

    season = (
        a[11] * dumt2 * np.sin(t * 2.0 * np.pi + a[10] * dumt3) +
        a[12] * dumt2 * np.cos(t * 2.0 * np.pi + a[10] * dumt3) +
        a[13] * dumt2 * np.sin(t * 4.0 * np.pi + a[10] * dumt3) +
        a[14] * dumt2 * np.cos(t * 4.0 * np.pi + a[10] * dumt3)
        )

    return season

def ufunc2_2018(lats, dates, a):

    season = ufunc1_2018(lats, dates, a)

    dumt1 = np.tanh(a[3] * lats + a[4])
    return a[0] + a[1]*t + a[2] * dumt1 + season

def ufunc3_2018(lats, dates, a, c, p, pt=0.2):

    result = np.zeros((len(dates), len(p)))

    result += c[0] * (0.5 * pt * pt - pt)
    result += c[1] * (pt - 0.5 - 0.5 * pt * pt)

    print(result.shape)
    result = (result.T * ufunc1_2018(lats, dates, a)).T

    p_low = p <= pt
    p_high = p > pt

    result[:, p_low] += c[0] * p[p_low]
    result[:, p_high] += c[0] * pt + np.outer(ufunc1_2018(lats, dates, a),
                                              c[1] * (p[p_high] - pt))

    return (result.T + ufunc2_2018(lats, dates, a)).T


""" @package pydefault
Controller of a Tic Tac Toe Game
"""
from cppGame import *
import json

def index():
    """Default function which passes URLs to Python functions to index.html
    """
    return dict(
        url_move = URL('move'),
        url_reset = URL('reset'),
        url_register = URL('register'),
        url_getName = URL('getName'),
        url_getMove = URL('getMove'),
        url_unregister = URL('unregister'),
        url_getWinnerPoints = URL('getWinnerPoints')
    )

def register():
    """Function to register new player
    """
    idnum = GameList.getInstance().getNewID()
    name = str(request.post_vars.name)
    sign = GameList.getInstance().addPlayer(idnum, name)
    return json.dumps({'id' : idnum, 'sign' : sign})

def move():
    """Function to make move by a player
    Returns:
        'status' - Game result(VICTORY, DRAW, STILL_PLAYING) and 'points' - player points or False if move wasn't made
    """
    i = int(request.post_vars.x)
    j = int(request.post_vars.y)
    idnum = int(request.post_vars.id)

    ret = GameList.getInstance().makeMove(idnum, i, j)
    if ret == False :       # if False, move wasn't made
        return json.dumps({'status': "False"})
    else:
        status = getGameState(idnum)
        points = GameList.getInstance().getPlayerPoints(idnum)
        return json.dumps({'status': status, 'points': points})

def getName():
    """Returns:
        'playerName' - opponent's name
    """
    idnum = int(request.post_vars.id)
    playerName = ""
    playerName = GameList.getInstance().getOpponentsName(idnum)
    return json.dumps({'playerName' : playerName})

def getMove():
    """Returns:
        last move in a game
    """
    idnum = int(request.post_vars.id)
    hasLeft = bool(GameList.getInstance().hasOpponentLeft(idnum))
    if(hasLeft):
        return json.dumps({ "status" : "HAS_LEFT" })
    lastMove = GameList.getInstance().getLastMove(idnum)
    status = getGameState(idnum)
    points = GameList.getInstance().getOpponentsPoints(idnum)
    return json.dumps({'x' : lastMove.x, 'y' : lastMove.y, "sign" : lastMove.sign, "status" : status, 'points' : points})

def getGameState(idnum):
    """
    Args:
        idnum: player id
    Returns:
        Game result converted to string
    """
    game_state = GameList.getInstance().getResult(idnum)
    if game_state == GameResult.VICTORY :
        return "VICTORY"
    elif game_state == GameResult.DRAW :
        return "DRAW"
    else :
        return "STILL_PLAYING"

def reset():
    """ Method which resets game which has player with id passed by JSON
    """
    GameList.getInstance().resetGame(int(request.post_vars.id))

def unregister():
    """Method to unregister Player
    """
    idnum = int(request.post_vars.id)
    GameList.getInstance().unregister(idnum)

def getWinnerPoints():
    """Returns:
        Points that has resulted in a VICTORY
    """
    idnum = int(request.post_vars.id)
    struc = GameList.getInstance().getWinnerPoints(idnum)
    return json.dumps({'x1' : struc.x1, 'y1': struc.y1, 'x2' : struc.x2, 'y2': struc.y2, 'x3' : struc.x3, 'y3': struc.y3, 'x4' : struc.x4, 'y4': struc.y4, 'x5' : struc.x5, 'y5': struc.y5})


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

theta = np.linspace(0, np.pi, 100)

x = np.cos(theta)
y = -np.sin(theta)

sizes = np.linspace(100, 100, 100)

plt.scatter(x, y, s=sizes, alpha=0.5)

plt.scatter([-0.3, 0.3], [-0.2, -0.2], c='black', s=400, alpha=1)

plt.scatter([0], [-0.5], c='red', s=20, alpha=1)

plt.show()


from django.shortcuts import render, get_object_or_404, redirect
from movies.models import Movie
from cart.cart import Cart
from cart.forms import CartForm
from django.views.decorators.http import require_POST

@require_POST
def add_to_cart(request, movie_id):
    movie = get_object_or_404(Movie, id=movie_id)
    cart = Cart(request)
    form = CartForm(data=request.POST)
    if form.is_valid():
        quantity = form.cleaned_data["quantity"]
        replace = form.cleaned_data["replace"]
        cart.add(movie, quantity, replace)
    return redirect("cart_detail")

def cart_detail_view(request):
    cart = Cart(request)
    for item in cart:
        item["refresh_form"] = CartForm(initial={
            "quantity": item["quantity"],
            "replace": True,
        })
    return render(request, "cart/cart_detail.html", context={
        "cart": cart,
    })

def remove_from_cart(request, movie_id):
    movie = get_object_or_404(Movie, id=movie_id)
    cart = Cart(request)
    cart.remove(movie)
    cart.save()
    return redirect("cart_detail")

@require_POST
def clear_cart(request):
    cart = Cart(request)
    cart.clear()
    return redirect("cart_detail")