# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import django.db.models.deletion
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('auth', '0006_require_contenttypes_0002'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('Users', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='UserProfile',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('phone', models.CharField(max_length=32, verbose_name=b'\xe6\xb3\xa8\xe5\x86\x8c\xe7\x94\xb5\xe8\xaf\x9d')),
                ('photo', models.ImageField(upload_to=b'uploadImg', null=True, verbose_name=b'\xe7\x94\xa8\xe6\x88\xb7\xe5\xa4\xb4\xe5\x83\x8f', blank=True)),
                ('birthday', models.CharField(max_length=32, verbose_name=b'\xe7\x94\xa8\xe6\x88\xb7\xe7\x94\x9f\xe6\x97\xa5')),
                ('email', models.EmailField(max_length=254, null=True, verbose_name=b'\xe9\x82\xae\xe7\xae\xb1', blank=True)),
                ('groups', models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name=b'\xe4\xb8\x9a\xe5\x8a\xa1\xe7\xbb\x84', to='auth.Group', null=True)),
                ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'db_table': 'UserProfile',
                'verbose_name': '\u5e73\u53f0\u7528\u6237\u8868',
                'verbose_name_plural': '\u5e73\u53f0\u7528\u6237\u8868',
            },
        ),
        migrations.DeleteModel(
            name='Authority',
        ),
        migrations.DeleteModel(
            name='Groups',
        ),
        migrations.DeleteModel(
            name='Users',
        ),
    ]


import csv
import matplotlib.pyplot as plt
import tkinter
from tkinter import *
from PIL import ImageTk, Image
import sv_ttk

'''This is the function for when the "ENTER" button
is clicked on the GUI.
-When the button is clicked, the state name that
the user has entered is compared against a file that
contains state names.
-A graph of all of the states' average monthly electricity
usage (also, within its own respective file)
is then pulled up with the user's state highlighted
on the graph.'''
def btn_clicked(): #all of btn_clicked() by Carly
    global stateName
    stateName = name.get() #retrieves the user's input of their state
    #read states file:
    legalNameStates = open('states.csv')
    avg_list_maker3 = csv.reader(legalNameStates) #converts States File into list of states
    for row in avg_list_maker3: #checking if the state input is in our States File
        if stateName not in row:
            stateInputLabel['text'] = 'Please input a valid state with the format: "State"'
            enterButton() #resets the ENTER button for a new state input if need be
        position = row.index(stateName)
        '''saves the index position of the entered state so that the
        correct state electricity usage can be pulled from the
        Usage File'''

    #formats State Electricity Usage File into list:
    usageList = open('newUsage.csv')
    avg_list_maker = csv.reader(usageList)
    usageList = []

    for row in avg_list_maker:  #ensures the data correctly gets put in list
        usage = row
        for num in row:
            finalNum = int(num)
            usageList.append(finalNum)

    '''Imports a file of state abbreviations and converts it
    to a list in order to later use the abbreviations as
    the labels for the x-axis on the graph of States' Monthly
    Avg Electricity Usage:'''
    statesList = open("stateAbbreviations.csv")
    avg_list_maker2 = csv.reader(statesList)

    for row in avg_list_maker2:  #ensures the data correctly gets put in list
        states = row

    '''Graphing the States' Monthly Avg Electricity Usage using
    state abbreviations list (states) as the x-axis values
    and the states' electricity usage (usageList) as the
    y-values'''
    plt.plot(states, usageList, 'c', alpha=0.5)

    global avgStateEnergy
    avgStateEnergy = usageList[position]
    #x,y, and title labels on the graph:
    plt.xlabel('States')
    plt.ylabel(f'Monthly Avg Electricity\n Usage per Household (kWh)')
    plt.title("States' Monthly Average Electricity Usage")

    #point on graph that highlights the user's state and its
    #electricity usage:
    plt.annotate(f'{stateName}: {usageList[position]} kWh',
                 xy=(states[position], usageList[position]),
                 xytext=(states[position + 1], usageList[position])) #labels the dot
    plt.plot(states[position], usageList[position], 'mo') #makes the dot on the state usage

    plt.show() #function that actually displays the graph

    #Label on GUI that prints the user's state's avg electricity usage:
    avgStateUsage['text'] = f"{stateName}'s average monthly electricity usage is {usageList[position]} kWh."

    #Label on GUI that prints a statement prepping the user to enter their own electricity usage
    label("ask4yours", root, f"Let's see how your electricity usage compares!", 35, 750, 460)

    '''Calls the NEXT button function so that the button
    appears and operates on the GUI; button opens new frame
    asking for user's personal energy usage'''
    next1Button()

#window 2: comparing user's electricity usage to state average
#base code by Nathan, GUI implementation by Carly
def next_clicked():
    global framePersonalUsage
    framePersonalUsage = Frame(root, width=1500, height=800)
    framePersonalUsage.grid()
    personalEnergy = tkinter.StringVar(framePersonalUsage)

    # main title
    mainTitle(framePersonalUsage)

    # Carly: GUI entry box that asks for user input:
    # the question:
    label("userEnergyLabel", framePersonalUsage, "What was your energy usage for this month?", 35, 750, 150)
    # the box itself:
    userEnergyInput = Entry(framePersonalUsage, textvariable=personalEnergy, bd=5, width=50, relief="sunken", font=("sylfaen"))
    userEnergyInput.grid(column=1, row=1)
    userEnergyInput.place(x=750, y=220, anchor="center", height=50)
    #energy units:
    label("units", framePersonalUsage, "kWh", 20, 1050, 220)

    #ENTER button that pulls up the comparison of the user's personal energy
    # usage to that of their state's:
    def enterButtonUserEnergy():
        btn3 = tkinter.Button(text='ENTER', bd=5, command=(lambda: PowerBill(stateName)))
        btn3.place(x=750, y=280, anchor='center')

    ''' written by Nathan = compares the user's personal energy usage
     to that of their state's so that they can get feedback on
     if they need to reduce their carbon footprint more'''
    def PowerBill(stateIn):
        #defining variables in function by different titles, so we could work
        #on code separately
        power1 = personalEnergy.get()
        power = int(power1)
        state = stateIn
        average = avgStateEnergy

        #reprinting label for state's energy use
        label("stateAvgUsageLabel", framePersonalUsage, (f"{state}'s Average Energy Usage: {average}kWh"), 35, 750, 350)

        #label for user's energy usage
        label("userUsageLabel", framePersonalUsage, (f"Your Average Energy Usage: {power}kWh"), 35, 750, 420)

        #comparing the user's personal energy usage to the state
        if power < average:
            label("comparisonLabel", framePersonalUsage, (f"Monthly Energy Usage of {power}kWh is lower than state average."), 30, 750, 490)
            label("congratsLabel", framePersonalUsage, (f"Good job! You are limiting CO2 output!"), 30, 750, 560)

        elif power > average:
            label("comparisonLabel", framePersonalUsage, (f"Caution! Monthly Power Usage of {power}kWh is higher than state average."), 30, 750, 490)
            label("fixLabel", framePersonalUsage, (f"Let's see what we can do to lower that usage!"), 30, 750, 560)

        else:
            label("comparisonLabel", framePersonalUsage, (f"Monthly Power Usage of {power}kWh is equal to state average."), 30, 750, 490)

        next2Button()
        framePersonalUsage.pack()

    enterButtonUserEnergy()

#Window 3: checkboxes of user's habits that provide carbon reducing feedback
#base code by Julia, GUI implementation by Carly
def next2_clicked():
    framePersonalUsage.destroy()
    frameHabits = Frame(root, width=1500, height=800)
    frameHabits.grid()
    frameHabits.tkraise()

    # main title
    mainTitle(frameHabits)

    # instructions for the checkboxes
    label("instructionsLabel", frameHabits, "Check the boxes of habits that you do!", 35, 750, 150)
    label("basedLabel", frameHabits, "We'll give you some feedback on how to reduce your energy usage based on your answers.", 25, 750, 220)
    frameHabits.pack()

    #empty foot as base image
    foot(r'IMG_1041.PNG', frameHabits)

    #checkbox feedback
    def c1_On(xValue, yValue, button, feedbackPhrase):
        global footFill
        global c1Text
        habit1feedback = Label(frameHabits,
                               text="",
                               font=("sylfaen", 14))
        habit1feedback.grid()
        habit1feedback.place(x=xValue+400, y=yValue)

        '''based on how many checkboxes are checked,
        the foot is filled accordingly (trying to reduce carbon footprint)'''
        def footfill():
            if footFill == 0:
                foot(r'IMG_1041.PNG', frameHabits)
            elif footFill == 1:
                foot(r'IMG_1042.PNG', frameHabits)
            elif footFill == 2:
                foot(r'IMG_1043.PNG', frameHabits)
            elif footFill == 3:
                foot(r'IMG_1044.PNG', frameHabits)
            else:
                foot(r'IMG_1045.PNG', frameHabits)

        '''tkinter doesn't allow size changes of traditional checkboxes,
        so I had to make them out of regular buttons with labels'''
        if button['text']=='x':
            footFill -= 1
            button['text']=''
            habit1feedback['text'] = "  " * len(feedbackPhrase)
            footfill()

        else:
            footFill += 1
            button['text']='x'
            habit1feedback['text'] = feedbackPhrase
            footfill()

    #1st checkbox
    global c1Text
    c1 = tkinter.Button(text=c1Text, font = tkinter.font.Font(size=15), bd=5, command=(lambda: c1_On(10,325,c1,'- Remember to shut your lights off when you '
                                                                             'leave that room or your house.')), height = 1, width = 3)
    c1.place(x=300, y=300, anchor='center')
    label("c1QuestionLabel", frameHabits, 'Do you always leave your lights on?', 25, 595, 295)

    #2nd checkbox
    global c2Text
    c2 = tkinter.Button(text=c2Text, font = tkinter.font.Font(size=15), bd=5, command=(lambda: c1_On(10, 425, c2,'- Try shutting them off when you leave the'
                                                                              ' room; open a window instead for a breeze;'
                                                                              ' close your curtains to block heat from sun.')), height=1, width=3)
    c2.place(x=300, y=400, anchor='center')
    label("c2QuestionLabel", frameHabits, 'Do you keep fans running?', 25, 535, 395)

    # 3nd checkbox
    global c3Text
    c3 = tkinter.Button(text=c3Text, font = tkinter.font.Font(size=15), bd=5, command=(lambda: c1_On(10, 525, c3, '- Make sure your faucets are turned all '
                                                                               'the way off after you use them; turn your water off when you '
                                                                                'brush your teeth.')), height=1, width=3)
    c3.place(x=300, y=500, anchor='center')
    label("c3QuestionLabel", frameHabits, 'Do you leave your water running?', 25, 585, 495)

    # 4th checkbox
    global c4Text
    c4 = tkinter.Button(text=c4Text, font = tkinter.font.Font(size=15), bd=5, command=(lambda: c1_On(10, 625, c4, '- When not using appliances, shut them off'
                                                                               ' instead of letting them run all day for convenience.')), height=1, width=3)
    c4.place(x=300, y=600, anchor='center')
    label("c4QuestionLabel", frameHabits, 'Do you leave nonessential appliances on (coffee maker, lamps, etc.)?', 25, 815, 595)
    frameHabits.pack()

    '''Carly: the function for the NEXT button that will
    pull up the final summary window'''
    def finishedButton():
        btn4 = tkinter.Button(text='DONE', bd=5, command=(lambda: finished_clicked()))
        btn4.place(x=750, y=700, anchor='center')

    #Carly: window 4: summary of carbon reduction message
    def finished_clicked():
        frameHabits.destroy()
        finishFrame = Frame(root, width=1500, height=800)
        finishFrame.grid()
        finishFrame.tkraise()

        # main title
        mainTitle(finishFrame)

        # summary:
        label("thankYouLabel", finishFrame, "Thank you for seeing what you can "
                                                "\ndo to reduce your carbon footprint!", 40, 750, 200)
        finishFrame.pack()

        label("awarenessLabel", finishFrame, "Awareness through small adjustments "
                                                 "\nis the first step to greater change!", 30, 750, 365)
        finishFrame.pack()

        #feet pics
        foot(r'IMG_1045.PNG', finishFrame, 500, 600)
        foot(r'IMG_1041.PNG', finishFrame, 1000, 600)

        arrow = Label(finishFrame, text="--->", font=("sylfaen", 35), fg="grey")
        arrow.grid()
        arrow.place(x=750, y=600, anchor="center")

        rect = Canvas(finishFrame, width=250, height=200)
        rect.create_rectangle(500, 500, 800, 800, fill='grey', outline='grey')

    finishedButton()

#label function to reduce code for GUI text:
def label(labelTitle, frame, text, fontSize, x, y, font="sylfaen"):
    labelTitle = Label(frame, text=text, font=(font, fontSize))
    labelTitle.grid()
    labelTitle.place(x=x, y=y, anchor="center")

#label fuction for main title specifically:
def mainTitle(frame):
    label("underline", frame, "_____________________________________________", 45, 750, 70, "Castellar")
    label("titleLabel", frame, "Let's reduce your carbon footprint!", 45, 750, 50, "Castellar")

#function for opening and resizing the feet pics:
def foot(image, frame, x=150, y=450):
    img = Image.open(image)
    imageResize = img.resize((300, 300), Image.ANTIALIAS)
    image = ImageTk.PhotoImage(imageResize)

    imageLabel = Label(frame, image=image)
    imageLabel.image = image
    imageLabel.place(x=x, y=y, anchor="center")

#function for the ENTER button to submit state name!
def enterButton():
    btn = tkinter.Button(text = 'ENTER', bd = 5, command=(lambda: btn_clicked()))
    btn.place(x = 750, y = 330, anchor = 'center')

#the function for the NEXT button that will
#pull up a request for the user's own electricity usage
def next1Button():
    btn2 = tkinter.Button(text = 'NEXT', bd = 5, command=(lambda: next_clicked()))
    btn2.place(x = 750, y = 535, anchor = 'center')

#the function for the NEXT button that will
#pull up the checkboxes for user's habits
def next2Button():
    btn3 = tkinter.Button(text = 'NEXT', bd = 5, command=(lambda: next2_clicked()))
    btn3.place(x = 750, y = 620, anchor = 'center')

#GUI base
root = tkinter.Tk()
sv_ttk.set_theme('dark')
root.title('GUI')
root.geometry('1500x800')

#GUI intro title --> tells the user what the program is going to do:
mainTitle(root)

'''Empty GUI label for the print statement of the state energy usage.
I made this so that if the user wants to try to input different states,
the print statement saying the energy usage will actually change rather
than printing another label on top.'''
avgStateUsage = Label(root, text=f"", font=("sylfaen", 35))
avgStateUsage.grid()
avgStateUsage.place(x=750, y=390, anchor="center")

#declaring string variable for storing stateName
name = tkinter.StringVar(root)
avgStateEnergy = None
stateName = None
framePersonalUsage = None
value = 0
c1Text = ""
c2Text = ""
c3Text = ""
c4Text = ""
footFill = 0

#GUI entry box that asks for user input:
    #the question:
stateInputLabel = Label(root, text = "What state do you live in?", font=("sylfaen", 35))
stateInputLabel.grid()
stateInputLabel.place(x = 750, y = 200, anchor="center")
    #the box itself:
stateNameInput = Entry(root, textvariable = name, bd = 5, width=50, relief="sunken", font=("sylfaen"))
stateNameInput.grid(column =1, row =1)
stateNameInput.place(x = 750, y = 270, anchor = "center", height= 50)

#calls the ENTER button function so that the button
# appears and operates on the GUI to submit state name
enterButton()

#makes sure the window displays in an infinite loop
# until closed out by user
root.mainloop()


EXAMPLE_DATA = """NNCB

CH -> B
HH -> N
CB -> H
NH -> C
HB -> C
HC -> B
HN -> C
NN -> C
BH -> H
NC -> B
NB -> B
BN -> B
BB -> N
BC -> B
CC -> N
CN -> C"""

def insert(msg, pattern, char_counts):
    new_msg = {}
    for sub_pattern, count in msg.items():
        if sub_pattern in pattern:
            insert_char = pattern[sub_pattern]
            char_counts.setdefault(insert_char, 0)
            char_counts[insert_char] += count
            new_msg.setdefault(sub_pattern[0] + insert_char, 0)
            new_msg[sub_pattern[0] + insert_char] += count
            new_msg.setdefault(insert_char + sub_pattern[1], 0)
            new_msg[insert_char + sub_pattern[1]] += count
        else:
            new_msg.setdefault(sub_pattern, 0)
            new_msg[sub_pattern] += count
    return new_msg

def main():
    with open('input.txt', 'r') as f:
        data = f.read()
    data = EXAMPLE_DATA

    origin_msg = data.splitlines()[0]
    char_counts = {}
    for c in origin_msg:
        if c not in char_counts:
            char_counts[c] = origin_msg.count(c)
    msg = {}
    for i in range(1, len(origin_msg)):
        msg.setdefault(origin_msg[i - 1:i + 1], 0)
        msg[origin_msg[i - 1:i + 1]] += 1

    origin_pattern = data.splitlines()[2:]
    pattern = {}
    for line in origin_pattern:
        a, b = line.split('->')
        pattern[a.strip()] = b.strip()

    for _ in range(40):
        msg = insert(msg, pattern, char_counts)
        # print(msg)

    char_count_items = sorted(char_counts.items(), key=lambda item: item[1])
    print(char_count_items[-1][1] - char_count_items[0][1])

if __name__ == '__main__':
    main()


# import cv2
import numpy as np
import os

from PIL import Image

from hf.core import obj_utils

from hf.core import box_3d_encoder

class LabelSegPreprocessor(object):
    def __init__(self, dataset, label_seg_dir, expand_gt_size):
        """Preprocesses label segs and saves to files for RPN-seg training

        Args:
            dataset: Dataset object
            label_seg_dir: directory to save the info
        """

        self._dataset = dataset
        self.label_seg_utils = self._dataset.kitti_utils.label_seg_utils

        self._label_seg_dir = label_seg_dir

        self._expand_gt_size = expand_gt_size

    def preprocess(self, indices):
        """Preprocesses label seg info and saves info to files

        Args:
            indices (int array): sample indices to process.
                If None, processes all samples
        """
        expand_gt_size = self._expand_gt_size

        dataset = self._dataset
        dataset_utils = self._dataset.kitti_utils
        classes_name = dataset.classes_name

        # Make folder if it doesn't exist yet
        output_dir = self.label_seg_utils.get_file_path(
            classes_name, expand_gt_size, sample_name=None
        )
        os.makedirs(output_dir, exist_ok=True)

        # Load indices of data_split
        all_samples = dataset.sample_list

        if indices is None:
            indices = np.arange(len(all_samples))
        num_samples = len(indices)

        # For each image in the dataset, save info on the segs
        for sample_idx in indices:
            # Get image name for given cluster
            sample_name = all_samples[sample_idx].name
            img_idx = int(sample_name)

            # Check for existing files and skip to the next
            if self._check_for_existing(classes_name, expand_gt_size, sample_name):
                print(
                    "{} / {}: Sample already preprocessed".format(
                        sample_idx + 1, num_samples, sample_name
                    )
                )
                continue

            # Get ground truth and filter based on difficulty
            obj_labels = obj_utils.read_labels(dataset.label_dir, img_idx)

            # Filter objects to dataset classes
            obj_labels = dataset_utils.filter_labels(obj_labels)

            image = Image.open(dataset.get_rgb_image_path(sample_name))
            image_shape = [image.size[1], image.size[0]]
            point_cloud, _ = dataset_utils.get_point_cloud(img_idx, image_shape)
            # Filtering by class has no valid ground truth, skip this image
            if len(obj_labels) == 0:
                print(
                    "{} / {} No {}s for sample {} "
                    "(Ground Truth Filter)".format(
                        sample_idx + 1, num_samples, classes_name, sample_name
                    )
                )
                label_seg = np.zeros((point_cloud.shape[0], 8), dtype=np.float32)
                self._save_to_file(classes_name, expand_gt_size, sample_name, label_seg)
                continue

            label_boxes_3d = np.asarray(
                [
                    box_3d_encoder.object_label_to_box_3d(obj_label)
                    for obj_label in obj_labels
                ]
            )

            label_classes = [
                dataset_utils.class_str_to_index(obj_label.type)
                for obj_label in obj_labels
            ]
            label_classes = np.asarray(label_classes, dtype=np.int32)

            label_seg = self.label_seg_utils.label_point_cloud(
                point_cloud, label_boxes_3d, label_classes, expand_gt_size
            )
            foreground_points = label_seg[label_seg[:, 0] > 0]
            print(
                "{} / {}:"
                "{:>6} foreground points, "
                "for {:>3} {}(s) for sample {}".format(
                    sample_idx + 1,
                    num_samples,
                    foreground_points.shape[0],
                    len(obj_labels),
                    classes_name,
                    sample_name,
                )
            )

            # Save label segs
            self._save_to_file(classes_name, expand_gt_size, sample_name, label_seg)

    def _check_for_existing(self, classes_name, expand_gt_size, sample_name):
        """
        Checks if a label seg file exists already

        Args:
            classes_name (str): classes name, e.g. 'Car', 'Pedestrian',
                'Cyclist', 'People'
            sample_name (str): sample name from dataset, e.g. '000123'

        Returns:
            True if the label seg file already exists
        """

        file_name = self.label_seg_utils.get_file_path(
            classes_name, expand_gt_size, sample_name
        )
        if os.path.exists(file_name):
            return True

        return False

    def _save_to_file(
        self, classes_name, expand_gt_size, sample_name, label_seg=np.array([])
    ):
        """
        Saves the label seg info to a file

        Args:
            classes_name (str): classes name, e.g. 'Car', 'Pedestrian',
                'Cyclist', 'People'
            sample_name (str): name of sample, e.g. '000123'
            label_seg: ndarray of label seg of shape (N, 8)
                defaults to an empty array
        """

        file_name = self.label_seg_utils.get_file_path(
            classes_name, expand_gt_size, sample_name
        )

        # Save to npy file
        label_seg = np.asarray(label_seg, dtype=np.float32)
        np.save(file_name, label_seg)


import os
import argparse
import torch
import pickle
import torch.utils.data as utils
import torch.optim as optim
from torch.distributions import Normal
import time
import numpy as np

from graph import Graph
from model import ReconstructionNet
from pool import FeaturePooling
from metrics import loss_function
from data import CustomDatasetFolder

class Annealer(object):
    def __init__(self, init, delta, steps):
        self.init = init
        self.delta = delta
        self.steps = steps
        self.s = 0
        self.data = self.__repr__()
        self.recent = init

    def __repr__(self):
        return {"init": self.init, "delta": self.delta, "steps": self.steps, "s": self.s}

    def __iter__(self):
        return self

    def __next__(self):
        self.s += 1
        value = max(self.delta + (self.init - self.delta) * (1 - self.s / self.steps), self.delta)
        self.recent = value
        return value

    def state_dict(self):
        return {'init': self.init, 'delta': self.delta, 'steps': self.steps, 's': self.s, 'data': self.data, 'recent': self.recent}

    def load_state_dict(self, state_dict):
        self.init = state_dict['init']
        self.delta = state_dict['delta']
        self.steps = state_dict['steps']
        self.s = state_dict['s']
        self.data = state_dict['data']
        self.recent = state_dict['recent']

# Args
parser = argparse.ArgumentParser(description='Pixel2Mesh training script')
parser.add_argument('--data', type=str, default=None, metavar='D',
                    help="folder where data is located.")
parser.add_argument('--epochs', type=int, default=100, metavar='E',
                    help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=3e-5, metavar='LR',
                    help='learning rate (default: 3e-5)')
parser.add_argument('--log_step', type=int, default=100, metavar='LS',
                    help='how many batches to wait before logging training status (default: 100)')
parser.add_argument('--saving_step', type=int, default=100, metavar='S',
                    help='how many batches to wait before saving model (default: 1000)')
parser.add_argument('--experiment', type=str, default='./model/', metavar='E',
                    help='folder where model and optimizer are saved.')
parser.add_argument('--load_model', type=str, default=None, metavar='M',
                    help='model file to load to continue training.')
parser.add_argument('--load_optimizer', type=str, default=None, metavar='O',
                    help='model file to load to continue training.')
args = parser.parse_args()

# Cuda
use_cuda = torch.cuda.is_available()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

# Model
nIms = 5
if args.load_model is not None: # Continue training
    state_dict = torch.load(args.load_model, map_location=device)
    model_gcn = ReconstructionNet(x_dim=3, v_dim=7, r_dim=256, h_dim=128, z_dim=64, i_dim=nIms, L=8)
    model_gcn.load_state_dict(state_dict)
else:
    model_gcn = ReconstructionNet(x_dim=3, v_dim=7, r_dim=256, h_dim=128, z_dim=64, i_dim=nIms, L=8)

# Optimizer
if args.load_optimizer is not None:
    state_dict_opt = torch.load(args.load_optimizer, map_location=device)
    optimizer = optim.Adam(model_gcn.parameters(), lr=args.lr)
    optimizer.load_state_dict(state_dict_opt)
else:
    optimizer = optim.Adam(model_gcn.parameters(), lr=args.lr)
model_gcn.train()

# Graph
graph = Graph("./ellipsoid/init_info.pickle")

# Data Loader
folder = CustomDatasetFolder(args.data, extensions = ["png"], dimension=nIms)
train_loader = torch.utils.data.DataLoader(folder, batch_size=1, shuffle=True)

# Param
nb_epochs = args.epochs
log_step = args.log_step
saving_step = args.saving_step
curr_loss = 0

# To GPU
if use_cuda:
    print('Using GPU', flush=True)
    model_gcn.cuda()
    for state in optimizer.state.values():
        for k, v in state.items():
            if torch.is_tensor(v):
                state[k] = v.cuda()
else:
    print('Using CPU', flush=True)

print("nb trainable param", model_gcn.get_nb_trainable_params(), flush=True)

sigma_scheme = Annealer(2.0, 0.7, 80000)

# Train
for epoch in range(1, nb_epochs+1):
    for n, data in enumerate(train_loader):
        ims, viewpoints, gt_points, gt_normals = data
        ims = np.transpose(ims, (1, 0, 2, 3, 4))
        viewpoints = np.transpose(viewpoints, (1, 0, 2, 3))

        m, b, *x_dims = ims.shape
        indices = np.arange(m)
        np.random.shuffle(indices)
        context_idx, query_idx = indices[:-1], indices[-1]
        context_ims = ims[context_idx]
        context_viewpoints = viewpoints[context_idx]
        query_ims = ims[query_idx]
        query_viewpoints = viewpoints[query_idx]

        context_ims = np.transpose(context_ims, (1, 0, 2, 3, 4))
        context_viewpoints = np.transpose(context_viewpoints, (1, 0, 2, 3))

        if use_cuda:
            context_ims = context_ims.cuda()
            context_viewpoints = context_viewpoints.cuda()
            query_ims = query_ims.cuda()
            query_viewpoints = query_viewpoints.cuda()
            gt_points = gt_points.cuda()
            gt_normals = gt_normals.cuda()

        # Forward
        graph.reset()
        optimizer.zero_grad()
        pred_points, x_mu, kl = model_gcn(context_ims, context_viewpoints, query_ims, query_viewpoints, graph)

        # Loss
        loss = loss_function(pred_points, gt_points.squeeze(),
                                          gt_normals.squeeze(), graph)

        sigma = next(sigma_scheme)
        ll = Normal(x_mu, sigma).log_prob(query_ims)

        likelihood     = torch.mean(torch.sum(ll, dim=[1, 2, 3]))
        kl_divergence  = torch.mean(torch.sum(kl, dim=[1, 2, 3]))
        elbo = likelihood - kl_divergence
        loss = loss - elbo * 1e-4

        # Backward
        loss.backward()
        optimizer.step()

        curr_loss += loss

        # Log
        if (n+1)%log_step == 0:
            print("Epoch", epoch, flush=True)
            print("Batch", n+1, flush=True)
            print(" Loss:", curr_loss.data.item()/log_step, flush=True)
            curr_loss = 0

        # Save
        if (n+1)%saving_step == 0:
            model_file = args.experiment + "model_" + str(n+1) + ".pth"
            optimizer_file = args.experiment + "optimizer_" + str(n+1) + ".pth"
            torch.save(model_gcn.state_dict(), model_file)
            torch.save(optimizer.state_dict(), optimizer_file)
            print("Saved model to " + model_file, flush=True)


from tkinter import *
from tkinter.filedialog import *

class notepad:
    def new(self):
        self.l1.config(text="")
        try:
            self.text.delete(1.0, END)
            self.l1.config(text="")
        except:
            pass

    def open(self):
        try:
            self.l1.config(text="")

            self.file = askopenfile(
                filetypes=(("Text files", "*.txt"), ("All files", "*.*"))
            ).name
            self.text.delete(1.0, END)
            with open(self.file, "r") as f:
                str = f.read()
                self.text.insert("1.0", str)
            self.l1.config(text="Opened from:\n" + self.file)
        except:
            pass

    def save(self):
        # try:
        try:
            with open(self.file, "w") as f:
                f.write(self.text.get("1.0", END))
            self.l1.config(text="Saved at: \n" + self.file)
        except:
            self.file = open("write.txt", "w")
            self.file.write(self.text.get(1.0, END))
            self.file.close()
            self.l1.config(text="Saved at: \nDesktop\gui\write.txt ")

    # except:

    def saveas(self):
        files = [
            ("All Files", "*.*"),
            ("Python Files", "*.py"),
            ("Text Document", "*.txt"),
        ]
        try:
            self.file = asksaveasfile(filetypes=files, defaultextension=files).name
            with open(self.file, "w") as f:
                f.write(self.text.get("1.0", END))
            self.l1.config(text="Saved at:\n" + self.file)
        except:
            pass

    def __init__(self):
        self.window = Tk()
        self.window.config(bg="#2b2d42")
        self.window.geometry("1000x600")
        self.window.title("Notepad")
        self.create_frame1()
        self.create_text()

    def create_text(self):
        self.text = Text(
            self.window, width=400, height=24, font=("Times New Roman", 15)
        )
        self.text.pack(side=BOTTOM, padx=20, pady=5)
        self.l1 = Label(
            self.window, text="", fg="white", font=("Arial", "15"), bg="#2b2d42"
        )
        self.l1.place(x=400, y=10)

    def create_frame1(self):
        self.frame = Frame(self.window, width=205, height=1000, bg="#6096ba")
        self.frame.pack(side=LEFT, padx=10, pady=10)
        btn1 = Button(
            self.frame,
            text="Save",
            padx=50,
            pady=10,
            font=("Bahma", "20"),
            fg="#f1faee",
            bg="#e63946",
            command=lambda: self.save(),
        )
        btn1.place(x=10, y=100)
        btn1 = Button(
            self.frame,
            text="Open",
            padx=47,
            pady=10,
            font=("Bahma", "20"),
            fg="#caf0f8",
            bg="#03045e",
            command=lambda: self.open(),
        )
        btn1.place(x=10, y=200)
        btn1 = Button(
            self.frame,
            text="New",
            padx=54,
            pady=10,
            font=("Bahma", "20"),
            fg="#e0aaff",
            bg="#3c096c",
            command=lambda: self.new(),
        )
        btn1.place(x=10, y=300)
        btn1 = Button(
            self.frame,
            text="Save As",
            padx=30,
            pady=10,
            font=("Bahma", "20"),
            fg="#ffffff",
            bg="#ff9f1c",
            command=lambda: self.saveas(),
        )
        btn1.place(x=10, y=400)

root = notepad()
root.window.mainloop()


from texttable import Texttable
import random

class BoardException(Exception):
    def __init__(self, message):
        self._message = message

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

class Snake:
    def __init__(self):
        self._direction = 'up'
        self._head = [0, 0]
        self._body_coords = []

    @property
    def direction(self):
        return self._direction

    @direction.setter
    def direction(self, value):
        self._direction = value

    @property
    def head(self):
        return self._head

    @head.setter
    def head(self, value):
        self._head = value

    @property
    def body_coords(self):
        return self._body_coords

    @body_coords.setter
    def body_coords(self, key, value):
        self.body_coords[key] = value

    def remove_last_position(self):
        del self._body_coords[len(self._body_coords) - 1]

class Board:
    def __init__(self, DIM, apple_count, snake):
        self._DIM = DIM
        self._apple_count = apple_count
        self._data =[[0 for column in range(self._DIM)] for row in range(self._DIM)]
        self._snake = snake
        self.place_snake()
        self.place_apples()

    @property
    def dimension(self):
        return self._DIM

    @property
    def apple_count(self):
        return self._apple_count

    def get(self, row, column):
        return self._data[row][column]

    def is_free(self, row, column):
        return self.get(row, column) == 0

    def not_adjacent_apples(self, row, column):
        sem1 = 0
        sem2 = 0

        if row !=0 and row != self._DIM - 1 and column != 0 and column != self._DIM - 1:
            if self._data[row + 1][column] == -1 or self._data[row - 1][column] == -1 or self._data[row][column - 1] == -1 or self._data[row][column + 1] == -1:
                return False
        else:
            if row == 0 and column == 0:
                sem1 = 1
                if self._data[row + 1][column] == -1 or self._data[row][column + 1] == -1:
                    return False
            if row == 0 and column == self._DIM - 1:
                sem1 = 1
                if self._data[row + 1][column] == -1 or self._data[row][column - 1] == -1:
                    return False
            if row == self._DIM - 1 and column == 0:
                sem2 = 1
                if self._data[row - 1][column] == -1 or self._data[row][column + 1] == -1:
                    return False
            if row == self._DIM - 1 and column == self._DIM - 1:
                sem2 = 1
                if self._data[row - 1][column] == -1 or self._data[row][column - 1] == -1:
                    return False
            if row == 0 and sem1 == 0:
                if self._data[row + 1][column] == -1 or self._data[row][column - 1] == -1 or self._data[row][column + 1] == -1:
                    return False
            elif row == self._DIM - 1 and sem2 == 0:
                if self._data[row - 1][column] == -1 or self._data[row][column - 1] == -1 or self._data[row][column + 1] == -1:
                    return False
            elif column == 0 and sem1 == 0 and row != self._DIM - 1:
                if self._data[row + 1][column] == -1 or self._data[row - 1][column] == -1 or self._data[row][column + 1] == -1:
                    return False
            elif column == self._DIM - 1 and sem2 == 0:
                if self._data[row + 1][column] == -1 or self._data[row - 1][column] == -1 or self._data[row][column - 1] == -1:
                    return False

        return True

    def place_snake(self):
        middle = self._DIM // 2
        self._data[middle - 2][middle] = 1              #1 = head
        self._snake.head = [middle - 2, middle]
        self._data[middle - 1][middle] = 2          #2 = body
        self._snake.body_coords.append([middle - 1, middle])
        self._data[middle][middle] = 2
        self._snake.body_coords.append([middle, middle])

    def place_new_snake(self):
        self._data[self._snake.head[0]][self._snake.head[1]] = 1
        for index in range(len(self._snake.body_coords)):
            if index == len(self._snake.body_coords) - 1:
                self._data[self._snake.body_coords[index][0]][self._snake.body_coords[index][1]] = 0
                #self._snake.remove_last_position()
            else:
                self._data[self._snake.body_coords[index][0]][self._snake.body_coords[index][1]] = 2

    def place_apples(self):
        emptyLocations = []
        for row in range(self._DIM):
            for column in range(self._DIM):
                if self.is_free(row, column):
                    emptyLocations.append((row, column))

        apples = self._apple_count
        while apples > 0:
            randomLocation = random.choice(emptyLocations)
            row = randomLocation[0]
            column = randomLocation[1]
            emptyLocations.remove(randomLocation)
            if self.not_adjacent_apples(row, column):
                self._data[row][column] = -1            #-1 = apple
                apples -= 1

    def __str__(self):
        table = Texttable()
        for row in range(self._DIM):
            rowData = []
            for index in self._data[row]:
                if index == 0:
                    rowData.append(' ')
                elif index == 1:
                    rowData.append('*')
                elif index == 2:
                    rowData.append('+')
                elif index == -1:
                    rowData.append('.')
            table.add_row(rowData)

        return table.draw()


# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

from django.conf.urls import url

from . import views

urlpatterns = [
    # URL pattern for the url_encode view
    url(
        regex=r'^encode$',
        view=views.url_encode,
        name='encode'
    ),
    # URL pattern for the url_decode view
    url(
        regex=r'^(?P<pattern>.*)$',
        view=views.url_decode,
        name='decode'
    )
]


import collections
import datetime
import getpass
import grp
import io
import itertools
import logging
import operator
import os
import os.path
import pathlib
import shutil
import stat
import sys
import typing
from functools import partial
from typing import Optional, Union, Iterable, Iterator, TextIO, Tuple

import jinja2
import netaddr
from jinja2.exceptions import FilterArgumentError
try:
    from jinja2.filters import pass_environment
except ImportError:
    # Jinja2 <3
    # noinspection PyUnresolvedReferences
    from jinja2.filters import environmentfilter as pass_environment

from hades import constants

logger = logging.getLogger(__name__)

template_filters: dict[str, typing.Callable] = {}

def template_filter(name):
    def decorator(f):
        template_filters[name] = f
        return f

    return decorator

@template_filter('unique')
def do_unique(a):
    return set(a)

@template_filter('intersection')
def do_intersection(a, b):
    return set(a).intersection(set(b))

@template_filter('difference')
def do_difference(a, b):
    return set(a).difference(set(b))

@template_filter('symmetric_difference')
def do_symmetric_difference(a, b):
    return set(a).symmetric_difference(set(b))

@template_filter('union')
def do_union(a, b):
    return set(a).union(set(b))

@template_filter('min')
def do_min(a):
    return min(a)

@template_filter('max')
def do_max(a):
    return max(a)

@template_filter('sorted')
@pass_environment
def do_sorted(env, iterable, *, attribute=None, item=None, reverse=False):
    if attribute is None and item is None:
        key = None
    elif attribute is not None and item is not None:
        raise FilterArgumentError("Only one of attribute and item may be"
                                  "specified")
    elif attribute is not None:
        key = partial(env.getattr, attribute=attribute)
    elif item is not None:
        key = partial(env.getitem, argument=item)
    return sorted(iterable, key=key, reverse=reverse)

@template_filter('zip')
def do_zip(*iterables):
    return zip(*iterables)

@template_filter('zip_longest')
def do_zip_longest(*iterables, fillvalue=None):
    return itertools.zip_longest(*iterables, fillvalue=fillvalue)

@template_filter('dirname')
def do_dirname(a):
    return os.path.dirname(a)

PathArg = Union[str, pathlib.PurePath]

def yield_all_sources(
    *search_path: pathlib.Path,
) -> Iterator[Tuple[pathlib.Path, pathlib.Path]]:
    """Find all files in the directories on ``search_path``.

    The algorithm is similar to systemd's unit search or the shell's ``PATH``
    search algorithm.

    The directories on the search path are recursively walked in parallel.
    Directories at the beginning of ``search_path`` take precedence over later
    directories, thus for files with the same name, the version in the
    leftmost directory that contains the file is selected. The content of
    directories is merged.

    Symbolic links are never followed and the path of symbolic link is returned
    instead of the path of its target.

    Symbolic links to ``/dev/null`` are handled specially and denote a
    *deletion marker*, that indicates that a file or directory should not be
    included. For directories this means that no directories and their contents
    to the right of the respective directory in the search path should be
    included. Version of the directory and their contents that are on the search
    path to the left of the deletion marker are still included.

    The kind of paths that are returned depend on the kind of paths, that are
    passed as ``search_path``. Relative search path components will yield
    relative paths and absolute components absolute paths.

    :param search_path: A list of paths to directories
    :return: An iterator that yields pairs, where the first element is the
     component of ``search_path``, where the file was found and the second
     element is the path of the file.
    """
    if logger.isEnabledFor(logging.DEBUG):
        logger.debug("Searching for all sources in %s",
                     ', '.join(map(str, search_path)))
    # Perform a bread-first search via a queue.
    # The queue contains a sequence of (search-path, file) pairs for each
    # version of a file on the search path
    queue: typing.Deque[
        typing.Sequence[typing.Tuple[
            pathlib.Path,  # base
            pathlib.Path,  # children
        ]]
    ] = collections.deque()
    queue.appendleft(tuple(zip(search_path, search_path)))
    while queue:
        sources = queue.pop()
        if not sources:
            raise ValueError("No search paths")
        else:
            relative_source = sources[0][1].relative_to(sources[0][0])

        # If the current file is a directory, we collect all versions of it in
        # a list, for all other elements we break the loop and continue with the
        # next element. If an error occurs we continue with the next version of
        # the file instead.
        directories: typing.List[
            typing.Tuple[
                pathlib.Path,  # base
                pathlib.Path,  # source
                typing.Dict[
                    str,  # child.name
                    pathlib.Path  # child
                ]
            ]
        ] = []
        for base, source in sources:
            if source.is_symlink():
                target = os.readlink(str(source))
                # Check for deletion marker
                if target != os.path.devnull:
                    if directories:
                        logger.error("%s is a symlink, while %s is a directory",
                                     source, directories[-1][1])
                        continue
                    else:
                        logger.debug("Found symlink %s to %s in %s",
                                     relative_source, target, base)
                        yield base, source
                else:
                    logging.debug("Skipping %s due to deletion marker in %s",
                                  relative_source, base)
                break
            elif source.is_dir():
                logger.debug("Found directory %s in %s", relative_source, base)
                directories.append(
                    (base, source, {
                        child.name: child
                        for child in source.iterdir()
                    })
                )
            elif source.is_file():
                logger.debug("Found file %s in %s", relative_source, base)
                if directories:
                    logger.error("%s is not a directory, while %s is",
                                 source, directories[-1])
                    continue
                yield base, source
                break
            else:
                logger.error("%s must be a regular file, directory, or symlink",
                             source)
                continue

        if directories:
            if logger.isEnabledFor(logging.DEBUG):
                dir_names = ', '.join(
                    str(base) for base, directory, children in directories)
                logger.debug("Descending into %s in %s",
                             relative_source, dir_names)
            # Merge all names of children
            names = set(itertools.chain(*(
                children.keys()
                for base, directory, children in directories
            )))
            for name in names:
                queue.appendleft(tuple(
                    (base, children[name])
                    for base, directory, children in directories
                    if name in children
                ))
            yield directories[0][:2]

def yield_all_versions(
    name: pathlib.PurePath,
    *search_path: pathlib.Path,
) -> Iterator[Tuple[pathlib.Path, pathlib.Path]]:
    """Find all versions of `name` on `search_path`.

    The principle behind the search algorithm are the same as
    :func:`yield_all_sources`. This function however will search for a single
    file or directory named ``name`` and return all versions of ``name`` that
    can be found on the ``search_path``. The version with the highest precedence
    (i.e. from the leftmost component of ``search_path`` that contains a version
    of ``name``) will be returned first.

    :param name: The name of the file or directory
    :param search_path: A list of of paths to directories
    :return: An iterator that yields pairs, where the first element is the
     component of ``search_path``, where the file was found and the second
     element is the path of the file.
    """
    if logger.isEnabledFor(logging.DEBUG):
        logger.debug("Searching for versions of %s in %s", name,
                     ', '.join(map(str, search_path)))
    if not search_path:
        raise ValueError("Empty search path")

    for directory in search_path:
        filename = directory
        # Check for invalid components and /dev/null deletion markers in all
        # components of the path
        for idx, part in enumerate(name.parts):
            if filename.is_symlink():
                raise ValueError("Intermediate components can't be symbolic "
                                 "links")
            if part == os.path.pardir or part == os.path.sep:
                raise ValueError("Illegal component {!r} at index {} of path {}"
                                 .format(part, idx, name))
            filename = filename / part
            # Abort search if deletion marker found
            if (filename.is_symlink() and
                    os.readlink(str(filename)) == os.path.devnull):
                logger.debug("Skipping %s due to deletion marker at %s",
                             directory, filename)
                return
            if not filename.exists() and not filename.is_symlink():
                break
        # Yield if no break occurred
        else:
            logger.debug("Found version of %s in %s at %s",
                         name, directory, filename)
            yield directory, filename

class OverridableFileSystemLoader(jinja2.BaseLoader):
    """A Jinja2 loader that loads templates with the :func:`yield_all_sources`
    algorithm, if the template name is a relative.

    The loader accepts :class:`pathlib.PurePath` objects in addition to strings
    to identify templates.
    """

    def __init__(self, search_paths, encoding='utf-8', template_suffix='.j2'):
        self.search_paths = search_paths
        self.encoding = encoding
        self.template_suffix = template_suffix

    def get_source(self, environment: jinja2.Environment,
                   template: str):
        path_template = pathlib.Path(template)
        if not path_template.is_absolute():
            try:
                base, path_template = next(yield_all_versions(path_template,
                                                         *self.search_paths))
            except StopIteration:
                raise jinja2.TemplateNotFound(path_template.name) from None
        try:
            with path_template.open('r', encoding=self.encoding) as f:
                contents = f.read()
        except (FileNotFoundError, IsADirectoryError):
            raise jinja2.TemplateNotFound(path_template.name)

        mtime = path_template.stat().st_mtime

        def has_changed():
            """Checks whether the template loaded via
            :class:`OverridableFileSystemLoader` has changed.

            This function won't detect new versions of the template in other
            search paths with higher precedence or new deletion markers in other
            search paths. We would additionally need a list of all parent
            directories in the other search paths and check all of them."""
            try:
                return path_template.stat().st_mtime == mtime
            except OSError:
                return False

        return contents, str(path_template), has_changed

    def list_templates(self):
        return set(str(path.relative_to(base))
                   for base, path in yield_all_sources(*self.search_paths)
                   if not path.is_symlink() and path.is_file()
                   and path.suffix == self.template_suffix)

class GeneratorError(Exception):
    pass

class ConfigGenerator:
    DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S%z"
    """Format string for producing RFC3339-compatible datetime strings"""
    TEMPLATE_SUFFIX = ".j2"

    def __init__(self, template_dirs: Union[PathArg, Iterable[PathArg]],
                 config, mode: int = 0o0750,
                 group: Optional[grp.struct_group] = None):
        self._current_user = getpass.getuser()
        self.group = group
        mode = stat.S_IMODE(mode)
        # The mode could be masked with much less characters.
        # The verbosity of these statements is for clarity and documentation.
        # Allow only read, write, sticky, and setgid for directories
        self.dir_mode = mode & (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                                stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH |
                                stat.S_ISVTX | stat.S_ISGID)
        # Set execution bits if corresponding read bits are set
        self.dir_mode |= stat.S_IXUSR if stat.S_IRUSR else 0
        self.dir_mode |= stat.S_IXGRP if stat.S_IRGRP else 0
        self.dir_mode |= stat.S_IXOTH if stat.S_IROTH else 0
        # Allow only read, write, and sticky for files
        self.file_mode = mode & (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                                 stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH |
                                 stat.S_ISVTX)
        self.config = config
        if isinstance(template_dirs, (pathlib.PurePath, str)):
            template_dirs = (template_dirs, )
        self.template_dirs = tuple(pathlib.Path(template_dir).resolve()
                                   for template_dir in template_dirs)
        self.env = jinja2.Environment(
            loader=OverridableFileSystemLoader(
                self.template_dirs,
                template_suffix=self.TEMPLATE_SUFFIX
            ),
            auto_reload=False, autoescape=False, keep_trailing_newline=True,
            undefined=jinja2.StrictUndefined,
            extensions=['jinja2.ext.do', 'jinja2.ext.loopcontrols',
                        'jinja2.ext.with_'],
            trim_blocks=True, lstrip_blocks=True,
        )
        self.env.globals.update({
            'collections': collections,
            'itertools': itertools,
            'netaddr': netaddr,
            'dirname': os.path.dirname,
            'constants': constants,
        })
        self.env.filters.update(template_filters)

    def _format_search_path(self):
        return ':'.join(map(str, self.template_dirs))

    def _setgroup(self, destination: pathlib.Path):
        if self.group is not None:
            os.chown(str(destination), -1, self.group.gr_gid,
                     follow_symlinks=False)

    def _setstat(self, destination: pathlib.Path, mode: int):
        destination.chmod(mode)
        self._setgroup(destination)

    def generate(self, source: PathArg, destination: Optional[PathArg]):
        source = pathlib.PurePath(source)
        sources = tuple(yield_all_versions(source, *self.template_dirs))
        if not sources:
            raise GeneratorError(
                "No file or directory named {} found (search path: {})".format(
                    str(source), self._format_search_path()
                )
            ) from None
        base, source = sources[0]
        if source.is_dir():
            if destination is None:
                raise GeneratorError(
                    "Destination can't be stdout, if source is a directory"
                )
            destination = pathlib.Path(destination)
            search_path = tuple(map(operator.itemgetter(1), sources))
            self._do_generate_directory(search_path, destination)
        else:
            self._do_generate_file(base, source, destination)

    def generate_directory(self, source: PathArg, destination: PathArg):
        source = pathlib.PurePath(source)
        if source.is_absolute():
            raise GeneratorError("Source {} must be a relative path"
                                 .format(source))
        sources = tuple(map(operator.itemgetter(1), yield_all_versions(source)))
        if not sources:
            raise GeneratorError("No directory named {} found (search path {})"
                                 .format(source, self._format_search_path()))
        destination = pathlib.Path(destination)
        self._do_generate_directory(sources, destination)

    def _do_generate_directory(self, sources: Tuple[pathlib.Path, ...],
                               destination: pathlib.Path):
        destination_base = destination
        logger.info("Generating %s from %s", destination,
                    ', '.join(map(str, sources)))
        for base, source in yield_all_sources(*sources):
            destination = destination_base / source.relative_to(base)
            if source.is_symlink():
                self._create_symlink(source, destination)
            elif source.is_dir():
                if destination.exists():
                    logger.debug("Clearing directory %s", destination)
                    # Clear destination directory contents
                    if destination.is_symlink() or not destination.is_dir():
                        raise GeneratorError("Destination {} is not a directory"
                                             .format(destination))
                    for path in destination.iterdir():
                        if path.is_dir():
                            shutil.rmtree(str(path))
                        else:
                            path.unlink()
                else:
                    logger.debug("Creating directory %s", destination)
                    destination.mkdir(self.dir_mode, exist_ok=True)
                shutil.copystat(str(source), str(destination),
                                follow_symlinks=False)
                self._setstat(destination, self.dir_mode)
            else:
                if source.suffix == self.TEMPLATE_SUFFIX:
                    destination = destination.with_name(destination.stem)
                    self._generate_template_to_file(base, source, destination)
                else:
                    self._copy_to_file(source, destination)

    def generate_file(self, source: PathArg, destination: Optional[PathArg]):
        source = pathlib.PurePath(source)
        try:
            base, source = next(yield_all_versions(source, *self.template_dirs))
        except StopIteration:
            raise GeneratorError("File {} not found (search path {})"
                                 .format(source, self._format_search_path())
                                 ) from None
        if not source.is_file() and not source.is_symlink():
            raise GeneratorError("{} is not a file".format(source))
        destination = pathlib.Path(destination)
        self._do_generate_file(base, source, destination)

    def _do_generate_file(self, base: pathlib.Path, source: pathlib.Path,
                          destination: Optional[PathArg]):
        if destination is None:
            if source.suffix == self.TEMPLATE_SUFFIX:
                self._generate_template_to_stdout(base, source)
            else:
                self._copy_to_stdout(source)
        else:
            destination = pathlib.Path(destination)
            if source.is_symlink():
                self._create_symlink(source, destination)
            elif source.suffix == self.TEMPLATE_SUFFIX:
                if destination.is_dir():
                    destination = destination / source.stem
                self._generate_template_to_file(base, source, destination)
            else:
                if destination.is_dir():
                    destination = destination / source.name
                self._copy_to_file(source, destination)

    def _create_symlink(self, source: pathlib.Path, destination: pathlib.Path):
        target = pathlib.Path(os.readlink(str(source)))
        logger.debug("Creating symlink %s to %s", destination, target)
        destination.symlink_to(target)
        self._setgroup(destination)

    def _copy_to_file(self, source: pathlib.Path, destination: pathlib.Path):
        logger.debug("Copying %s to %s", source, destination)
        shutil.copy2(str(source), str(destination), follow_symlinks=False)
        self._setstat(destination, self.file_mode)

    def _copy_to_stdout(self, source: pathlib.Path):
        logger.debug("Copying %s to stdout", source)
        self._copy_to_fd(source, sys.stdout.fileno())

    def _copy_to_fd(self, source: pathlib.Path, fd: int):
        with source.open('r') as file:
            end = file.seek(0, io.SEEK_END)
            os.sendfile(fd, file.fileno(), 0, end)

    def _create_file(self, name: pathlib.Path) -> int:
        flags = os.O_WRONLY | os.O_CLOEXEC | os.O_EXCL | os.O_CREAT
        return os.open(str(name), flags, mode=self.file_mode)

    def _generate_template_to_file(self, base: pathlib.Path,
                                   source: pathlib.Path,
                                   destination: pathlib.Path):
        destination = pathlib.Path(destination)
        # Safely create file:
        # 1. Create with O_CREAT | O_EXCL
        # 2. Unlink if fails
        # 3. Try again
        logger.info("Creating %s from template %s", destination, source)
        try:
            fd = self._create_file(destination)
        except FileExistsError:
            destination.unlink()
            fd = self._create_file(destination)
        self._setgroup(destination)
        with os.fdopen(fd, mode='w', encoding='utf-8') as writer:
            self._generate_template_to_writer(
                base, source, writer,
                destination_dir=destination.parent,
                destination=destination)

    def _generate_template_to_stdout(self, base: pathlib.Path,
                                     source: pathlib.Path):
        logger.info("Instantiating template %s", source)
        self._generate_template_to_writer(base, source, sys.stdout)

    def _generate_template_to_writer(self, base: pathlib.Path,
                                     source: pathlib.Path,
                                     writer: TextIO, **extra_variables):
        try:
            template = self.env.get_template(str(source))
        except jinja2.TemplateNotFound as e:
            raise GeneratorError("Template {} not found (search path {})"
                                 .format(source,
                                         self._format_search_path())
                                 ) from e
        now = datetime.datetime.now(datetime.timezone.utc).astimezone()
        comment = ("Generated on {} from {} by {}"
                   .format(now.strftime(self.DATETIME_FORMAT), source,
                           self._current_user))
        relative_source = source.relative_to(base)
        stream = template.stream(**self.config, **extra_variables,
                                 comment=comment,
                                 source_base=base,
                                 source=relative_source,
                                 source_dir=relative_source.parent)
        writer.writelines(stream)


from pathlib import Path
ROOT = Path(__file__).absolute().parent.parent
import sys
sys.path.append(str(ROOT))
from easydict import EasyDict
from tqdm import tqdm
from visualizer import draw, Visualizer, Camera
from utils.tools import *

nusc_map = ['car', 'truck', 'construction_vehicle', 'bus', 'trailer',
            'barrier', 'motorcycle', 'bicycle', 'pedestrian', 'traffic_cone']

def demo_draw_single(datas):
    for data in tqdm(datas):
        data = EasyDict(data)
        points = data.points
        gt_boxes = data.gt_boxes
        gt_names = data.gt_names
        pred_boxes = data.pred_boxes
        pred_scores = data.pred_scores
        pred_labels = data.pred_labels
        pred_names = data.pred_names
        draw(points, gtBoxes=gt_boxes, gtNames=gt_names, refBoxes=pred_boxes, refLabels=pred_labels,
             refScores=pred_scores, refNames=pred_names, labelName=nusc_map, backgroundColor='black')

def demo_draw_sequence(datas):
    points = []
    gt_boxes = []
    gt_names = []
    pred_boxes = []
    pred_scores = []
    pred_labels = []
    pred_names = []
    for data in datas:
        data = EasyDict(data)
        points.append(data.points)
        gt_boxes.append(data.gt_boxes)
        gt_names.append(data.gt_names)
        pred_boxes.append(data.pred_boxes)
        pred_scores.append(data.pred_scores)
        pred_labels.append(data.pred_labels)
        pred_names.append(data.pred_names)
    draw(points, gtBoxes=gt_boxes, gtNames=gt_names, refBoxes=pred_boxes, refLabels=pred_labels,
         refScores=pred_scores, refNames=pred_names, labelName=nusc_map, backgroundColor='black', camera3dLock=True, showProgressBar=True, scoreThresh=0.3)

def demo_draw_sequence_update(datas):
    V=Visualizer()
    V.labelName=nusc_map
    V.backgroundColor='black'
    V.camera3dLock=True
    V.showProgressBar=True
    V.scoreThresh=0.3
    V.labelStartFromZero=False
    V.segPointsBylabel=True
    V.pointSize=2.0
    V.workDir="./temptest"
    for data in datas:
        data = EasyDict(data)
        points = data.points
        point_labels = data.point_labels
        gt_boxes = data.gt_boxes
        gt_names = data.gt_names
        pred_boxes = data.pred_boxes
        pred_scores = data.pred_scores
        pred_labels = data.pred_labels
        pred_names = data.pred_names
        V.draw3d(points[:,:3], pointLabels=point_labels,gtBoxes=gt_boxes, gtNames=gt_names, refBoxes=pred_boxes, refLabels=pred_labels,
             refScores=pred_scores, refNames=pred_names)
    V.saveVideo()
    V.saveLastCameraParam()
    V.saveConfig()

def demo_draw_2d(datas):
    V=Visualizer()
    V.labelName=nusc_map
    V.camera3dLock=True
    V.labelStartFromZero=False
    V.workDir="./temptest"
    V.scoreThresh=0.5
    V.imagesLayout=[
        [None, 0, 'front'],
        [-1, '3d', -1]
    ]
    V.draw2dWith3d=True
    V.saveOnly2d=False
    V.boxType2d='2d'
    cameraFront=Camera('front')
    cameraFront.extrinsic.addTranslation(0,-1,0.5)
    cameraFront.extrinsic.addRotation(rx=np.pi/2)
    cameraFront.intrinsic.matrix=[
     [1950, 0, 1950],
     [0, 1950, 1150],
     [0, 0, 1]
    ]
    cameraFront.width=3840
    cameraFront.height=2160
    cameraFront.viewangle=120
    V.addCamera2d(cameraFront)
    for data in tqdm(datas):
        data = EasyDict(data)
        points = data.points
        point_labels = data.point_labels
        gt_boxes = data.gt_boxes
        gt_names = data.gt_names
        pred_boxes = data.pred_boxes
        pred_scores = data.pred_scores
        pred_labels = data.pred_labels
        pred_names = data.pred_names
        V.draw2d(points,
         pointLabels=point_labels,gtBoxes=gt_boxes, gtNames=gt_names, refBoxes=pred_boxes, refLabels=pred_labels,refScores=pred_scores, refNames=pred_names,
         )
    V.saveVideo()
    V.saveConfig()

def main():
    datapath = ROOT / 'data' / 'demo.pkl'
    datas = loadPickle(datapath)[:5]
    demo_draw_single(datas)
    demo_draw_sequence(datas)
    demo_draw_sequence_update(datas)
    demo_draw_2d(datas)

if __name__ == "__main__":
    main()


import sys
import os
import subprocess

mac_build = "clang++ -dynamiclib -L/usr/local/lib -lsndfile -logg -lvorbis -lvorbisfile -lvorbisenc -F/usr/local/opt/qt/lib -framework QtCore -framework QtXml -std=c++11 interface.cpp -o sfont.dylib"
linux_build = "gcc -shared -lsndfile -logg -lvorbis -lvorbisfile -lvorbisenc -o sfont.so -fPIC interface.cpp"
win_build = "cl.exe /D_USRDLL /D_WINDLL interface.cpp sfont.h sfont.cpp /link /DLL /OUT:sfont.dll"

if sys.platform == "darwin":
    if os.path.exists("/usr/local/opt/qt/lib"):
        subprocess.run(mac_build.split(" "))
    else:
        raise RuntimeError("Please install qt under /usr/local/opt/qt via homebrew")
elif sys.platform == "linux":
    subprocess.run(linux_build.split(" "))
elif sys.platform == "win32":
    subprocess.run(win_build.split(" "))
else:
    subprocess.run(linux_build.split(" "))


###############################
#   Authors
###############################
#   André Mourato nmec 84745
#   Gonçalo Marques nmec 80327
###############################
# Benchmarking
import tracemalloc
import time
# Necessary imports
import sys
import math
import Stemmer
import operator
import csv
# File imports
from utils import *

def indexer(filename):
    '''An improved tokenizer that replaces all non-alphabetic characters by a space, lowercases
    tokens, splits on whitespace, and ignores all tokens with less than 3 characters. This tokenizer
    also uses the Porter stemmer and applies a stopword filter
    ----------
    filename : string
        File containing the dataset

    Returns
    -------
    term_index : dict
        Dictionary that contains the token as the key and the number of occurences as the value.
        Example: {
            "9dj07sac": {
                "incub": 4,
                "period": 4,
                "epidemiolog": 2,
                "characterist": 1,
                "novel": 2
            }
        }

    document_length_index : dict
        Dictionary that contains the number of terms of each document, i.e., the document length
        Example: {
            "vho70jcx": 124,
            "i9tbix2v": 92,
            "62gfisc6": 147,
            "058r9486": 153,
            "wich35l7": 161,
            "z3tgnzth": 88,
            "1xxrnpg3": 127,
        }
    '''
    term_index = {}
    document_length_index = {}
    with open(filename) as csvfile:
        # Iterate over the CSV file ignoring entries without an abstract
        # and joining the title and abstract fields into a single string
        for idx,row in enumerate(csv.DictReader(csvfile)):
            if len(row['abstract']) > 0:
                string =  row['title'] + ' ' + row['abstract']
                # Removes non-alphabetic characters by a space, lowercases
                # tokens, splits on whitespace, and ignores all tokens with less than 3 characters.
                # This tokenizer also uses the Porter stemmer and applies a stopword filter
                for tok in Stemmer.Stemmer('porter').stemWords([token \
                    for token in (remove_non_alpha(string)) \
                        if len(token) >= 3 and token not in stopwords]):

                    # Indexes all the input tokens into one dictionaries
                    # the term_index dict which registers the total number of occurrences
                    # of a token in each document
                    # Counts the number of tokens in each document
                    if row['cord_uid'] not in document_length_index:
                        document_length_index[row['cord_uid']] = 0
                    # Counts the number of terms in each document
                    document_length_index[row['cord_uid']] += 1
                    # Counts the term frequency
                    if row['cord_uid'] not in term_index:
                        term_index[row['cord_uid']] = {}
                    if tok not in term_index[row['cord_uid']]:
                        term_index[row['cord_uid']][tok] = 1
                    else:
                        term_index[row['cord_uid']][tok] += 1

    return term_index, document_length_index

def lnc_calculation(term_index,document_length_index):
    '''Normalized lnc weight and idf calculator for all terms in dataset
    ----------
    term_index : dict
        Dictionary that contains the token as the key and the number of occurences as the value

    document_length_index : dict
        Dictionary that contains the number of terms of each document, i.e., the document length

    Returns
    -------
    term_document_weights : dict
        Dictionary of dictionaries that associates the lnc normalized weight of all
        documents that contain each term
        Example: {
            "siann": {
                "vho70jcx": 0.1646582242160933
            },
            "strain": {
                "vho70jcx": 0.1431574201623654,
                "nljskxut": 0.1081438046556659,
                "lcpp5fim": 0.17536757263696706,
                "gjxumrmm": 0.1248067511230974
                }
            }

    idf_list : dict
        Dictionary that contains the token as the key and the idf as the value.
        Example: {
            "siann": 4.578776695691345,
            "strain": 0.9240227624384145,
            "identif": 1.2125405719730515,
            "align": 2.012928877017827
            }
    '''
    term_document_weights = {}
    idf_list = {}
    for docID in term_index:
        # 1 - NON-NORMALIZED WEIGHT CALCULATION
        document_term_weights = {}
        for token in term_index[docID]:
            document_term_weights[token] = 1 + math.log10(term_index[docID][token])
            if token not in term_document_weights:
                term_document_weights[token] = {}
            term_document_weights[token][docID] = 1 + math.log10(term_index[docID][token])

        # 2 - CALCULATION OF THE NORM FACTOR
        norm_factor = 1/math.sqrt(sum([w**2 for w in document_term_weights.values()]))

        # 3 - NORMALIZED WEIGHT CALCULATION
        for token in document_term_weights:
            term_document_weights[token][docID] *= norm_factor
            # 4 - Calculating IDF
            N = len(document_length_index)
            dft = len(term_document_weights[token])
            idf_list[token] = math.log10(N/dft)

    return term_document_weights, idf_list

def bm25_avdl(document_length_index):
    '''Calculates average document length of the dataset, used for bm25
    ----------
    document_length_index : dict
        Dictionary that contains the token as the key and the number of terms as the value.

    Returns
    -------
    avdl : float
        Average document length
    '''
    avdl = sum(v for v in document_length_index.values())
    return avdl / len(document_length_index)

def bm25_weighting(N, k, b, avdl, document_term_index, document_length_index, idf_list):
    '''Calculates bm25 weights for each token
    ----------
    N : int
        Total number of documents

    k : double
        Term frequency saturation value

    b : double
        Document length normalization factor

    avdl : float
        Average document length

    document_term_index : dict
        Dictionary that contains the token as the key and the number of occurences as the value.

    document_length_index : dict
        Dictionary that contains the token as the key and the number of terms as the value.

    idf_list : dict
        Dictionary that contains the token as the key and the idf as the value.

    Returns
    -------
        weights : dict
            Dictionary of dictionaries that contains the term as the key
            and a dictionary with the docIDs in which the term exists and corresponding lnc normalized weight,
            as the value.
        Example :{
            "siann": {
                "vho70jcx": 8.205306314501156
            },
            "strain": {
                "vho70jcx": 1.4736887259523785,
                "nljskxut": 1.050309414805419,
                "lcpp5fim": 1.4952129090104211,
                "gjxumrmm": 1.2983115687733342
                }
            }
    '''
    weights = {}
    for docID in document_term_index:
        for token in document_term_index[docID]:
            if token not in weights:
                weights[token] = {}
            # Calculates the weight of term token in docID
            first = idf_list[token]
            second = (k+1) * document_term_index[docID][token]
            third = 1 / ( k*((1-b) + (b*document_length_index[docID] / avdl)) + document_term_index[docID][token])
            weights[token][docID] = first*second*third
    return weights

def bmc_pre_calculation(term_index, document_length_index, idf_list):
    '''Uses parameter values required for bm25 weighting and then calculates bm25 weights for each token
    ----------
    term_index : dict
        Dictionary that contains the token as the key and the number of occurences as the value.

    document_length_index : dict
        Dictionary that contains the token as the key and the number of terms as the value.

    idf_list : dict
        Dictionary that contains the token as the key and the idf as the value.

    Returns
    -------
        weights : dict
            Dictionary of dictionaries that contains the term as the key
            and a dictionary with the docIDs in which the term exists and the corresponding lnc normalized weight,
            as the value.
        Example :{
            "siann": {
                "vho70jcx": 8.205306314501156
            },
            "strain": {
                "vho70jcx": 1.4736887259523785,
                "nljskxut": 1.050309414805419,
                "lcpp5fim": 1.4952129090104211,
                "gjxumrmm": 1.2983115687733342
                }
            }
    '''
    avdl = bm25_avdl(document_length_index)
    N = len(document_length_index)
    k = 1.2
    b = 0.75
    return bm25_weighting(N, k, b, avdl, term_index, document_length_index, idf_list)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        filename = 'datasets/metadata_2020-03-27.csv'
    else:
        filename = sys.argv[1]
    print('Reading dataset from file',filename)
    print('------------------------------------------------------------')
    print('STARTING INDEXING...')
    print('------------------------------------------------------------')

    # Trace used memory and time for the
    # indexing process using the improved tokenizer
    tracemalloc.start()
    time_start = time.process_time()

    #########################################################
    # LOADING INFORMATION FROM A FILE
    #########################################################
    stopwords = load_stop_words('resources/stopwords.txt')

    current, peak = tracemalloc.get_traced_memory()
    print(f"Memory usage when loading stopwords was {current / 10**6}MB; Peak was {peak / 10**6}MB")

    #########################################################
    # INDEXER
    #########################################################
    # 1 - Indexing
    term_index, document_length_index = indexer(filename)
    current, peak = tracemalloc.get_traced_memory()
    print(f"Memory usage when indexing was {current / 10**6}MB; Peak was {peak / 10**6}MB")

    # 2 - TF-IDF
    term_document_weights, idf_list = lnc_calculation(term_index,document_length_index)
    dump_weights(term_document_weights, idf_list, 'tf_idf_weights.csv')
    current, peak = tracemalloc.get_traced_memory()
    print(f"Memory usage when calculating lnc was {current / 10**6}MB; Peak was {peak / 10**6}MB")

    # 3 - BMC
    bmc_weights = bmc_pre_calculation(term_index,document_length_index, idf_list)
    dump_weights(bmc_weights, idf_list, 'bmc_weights.csv')
    current, peak = tracemalloc.get_traced_memory()
    print(f"Memory usage when calculating bmc was {current / 10**6}MB; Peak was {peak / 10**6}MB")
    #########################################################
    # BENCHMARKING INFORMATION
    #########################################################
    print('Total indexing time:',time.process_time() - time_start,'s')
    current, peak = tracemalloc.get_traced_memory()
    print(f"FINAL MEMORY USAGE: {current / 10**6}MB; Peak was {peak / 10**6}MB")
    tracemalloc.stop()
    print('Total vocabulary size is: ',len(term_index),'words')
    print('------------------------------------------------------------')

    #########################################################
    # DUMPING DATA STRUCTURES TO A FILE
    # Used for debugging but was kept commented on purpose
    #########################################################
    # dump_to_file(term_index,'term_index.json')

    # dump_to_file(bmc_weights,'bmc_weights.json')

    # dump_to_file(document_length_index,'document_length_index.json')

    # dump_to_file(idf_list,'idf_list.json')


import pandas as pd
import numpy as np
from scipy.optimize import minimize
import time
import matplotlib.pyplot as plt

def sphere_evaluate(x):
    value = sum((x-shift[0:len(x)])**2)+bias
    converge.append(value)
    return value

def minimize_sphere(dim, shifts, biases):
    start = time.time()
    global shift, bias, converge
    shift = shifts['sphere']
    bias = biases['sphere'].values[0]
    converge = []
    x = np.zeros(dim)
    result = minimize(sphere_evaluate, x)
    print(f'done in {time.time()-start} seconds.')
    sphere_evaluate(result['x'])
    plt.plot(converge)
    plt.xlabel('# of evaluations')
    plt.ylabel('value')
    plt.title(f'Sphere convergence plot - dim {dim}')
    return result


import pygame
from bullet import Bullet
WINDOW_WIDTH = 512
WINDOW_HEIGHT = 768

class Hero(object):

    def __init__(self, win):
        self.img = pygame.image.load("res/hero.png")
        self.window = win

        # 获取图片的矩形对象
        # hero_rect = hero.get_rect()  # 获取图片的矩形对象（一个图片就会有一个矩形对象，通过这个.get_rect() 来获取矩形对象， 这个矩形对象的宽高和图片一样）
        # print(hero_rect)   # <rect(0, 0, 120, 78)>
        # print(hero_rect[2])   # 120   # hero_rect[2]获取到图片的宽度， hero_rect[3]获取到图片的高度
        # 得到矩形对象
        self.rect = self.img.get_rect()
        self.speed = 3  # 飞机的移动速度
        self.rect[0] = WINDOW_WIDTH/2-self.rect[2]/2   # 飞机矩形对象初始的x值
        self.rect[1] = 600  # 飞机矩形对象初始的y值

        self.bullets = []   # 用来存放子弹对象

    def move(self):
        # print(self.rect)
        # 长按控制飞机移动
        pressed_keys = pygame.key.get_pressed()
        if pressed_keys[pygame.K_w] or pressed_keys[pygame.K_UP]:
            if self.rect[1] > 0:            # 为了限制飞机的移动边界，下面这行代码（造成飞机的移动）在y>0的情况下才执行
                self.rect[1] -= self.speed  # 最终决定飞机位置的改变--移动，  往上移动
        if pressed_keys[pygame.K_s] or pressed_keys[pygame.K_DOWN]:
            if self.rect[1] < WINDOW_HEIGHT - self.rect[3]:
                self.rect[1] += self.speed
        if pressed_keys[pygame.K_a] or pressed_keys[pygame.K_LEFT]:
            if self.rect[0] > 0:
                self.rect[0] -= self.speed
        if pressed_keys[pygame.K_d] or pressed_keys[pygame.K_RIGHT]:
            if self.rect[0] < WINDOW_WIDTH - self.rect[2]:  # x必须小于串口宽度-飞机图片宽度，才执行下面的代码
                self.rect[0] += self.speed

    def shot(self):
        self.bullets.append(Bullet(self.window, self.rect[0], self.rect[1], self.rect[2]))

    def blited(self):
        self.window.blit(self.img, (self.rect[0], self.rect[1]))  # 设置飞机的位置和矩形对象的位置是一致的
        # 显示子弹： [Bullet(),Bullet(),Bullet()]
        for i in self.bullets:   # i就是每一个子弹对象
            if i.rect[1] < 0:
                self.bullets.remove(i)
            else:
                i.blited()


from aux import array2string, loop_minmax
from vis import ccmap
import numpy as np
import matplotlib.pyplot as plt
import itertools
import logging
import json
from netCDF4 import Dataset
log = logging.getLogger(__name__)

class DataObject:
    def __init__(self, filename, variable):
        self.fn = filename
        self.var = variable
        self.get_t_xyz_nsi()
        self.zl = None
        self.grp = {}

    def get_t_xyz_nsi(self):
        with Dataset(self.fn, "r") as data:
            self.nsip = json.loads(data.inputfile)
            self.x = data.variables['x'][:]
            self.y = data.variables['y'][:]
            self.t = t_idx(data, [])
            self.z_min, self.z_max, self.z_ae = z_mme(data, self.var, self.t)

    def set_azl(self, n_lev_auto, n_dec):
        with Dataset(self.fn, "r") as data:
            self.azl = auto_z_levels(data, self.x, self.y, self.var, self.t,
                                     n_lev_auto, n_dec)

    def set_fzl(self, z_levels, n_seg, avleng, n_frame):
        with Dataset(self.fn, "r") as data:
            n_frame = np.floor(n_frame*len(self.t)).astype(int)
            self.fzl = filter_z_levels(data, self.x, self.y, self.var, self.t,
                                       z_levels, n_seg, avleng, n_frame)

    def set_zl_indep(self, n_lev_auto, n_dec, n_seg,
                     avleng, n_frame, n_lev, symflag):
        with Dataset(self.fn, "r") as data:
            self.azl = auto_z_levels(data, self.x, self.y, self.var, self.t,
                                     n_lev_auto, n_dec)
            print("automatic:\n{}".format(self.azl))
            n_frame = np.floor(n_frame*len(self.t)).astype(int)
            self.fzl = filter_z_levels(data, self.x, self.y, self.var, self.t,
                                       self.azl, n_seg,
                                       avleng, n_frame)
            print("filtered:\n{}".format(self.fzl))
            self.zl = spread_z_levels(self.fzl, n_lev, symflag)
            print("spread:\n{}".format(self.zl))

    def set_zl(self, z_levels):
        self.zl = z_levels

    def set_grp(self, key, val):
        self.grp[key] = val

    def set_ewc(self, edge, white, color_span, color_show):
        self.edge = edge
        self.white = white
        self.color_span = color_span
        self.color_show = color_show

    def set_cmap(self, cmap_name):
        xedges = [self.z_min, self.z_max] if self.edge is None else self.grp[self.edge]
        xwhite = [self.z_min, self.z_max] if self.white is None else self.grp[self.white]
        xcolor_span = [-self.z_ae, self.z_ae] if self.color_span is None else self.grp[self.color_span]
        xcolor_show = [self.z_min, self.z_max] if self.color_show is None else self.grp[self.color_show]
        self.cmap, self.norm = ccmap(xedges, xwhite, xcolor_span,
                                     xcolor_show, cmap_str=cmap_name,
                                     n=1024, rgba_grey=[.8, .8, .8, 1.])

# operate on passed netcdf dataset --------------------------------------------
def t_idx(fid, t):
    """
    list(idx) = list_t_idx(fid, t)
                           fid ... handler to netcdf4 dataset
                                t ... (list of) indices (integer)
                                [] means all timesteps
    """
    t_idx = []
    if type(t) is int:
        t_idx.append(t)
    elif np.size(t) == 0:
        t_idx = range(len(fid.variables['time'][:]))
    else:
        t_idx = t
    return t_idx

def z_mme(fid, variable, t_idx):
    """
    float, float, float = zmme(fid, variable, t_idx)
    z_min  z_max  |z_ext|
    """
    data = fid.variables[variable][t_idx[-1]]
    z_min = np.amin(data)
    z_max = np.amax(data)
    for i in t_idx[:-1]:
        data = fid.variables[variable][i]
        data_min = np.amin(data)
        data_max = np.amax(data)
        if data_max > z_max:
            z_max = data_max
        if data_min < z_min:
            z_min = data_min
    z_ext_abs = np.amax(np.absolute((z_min, z_max)))
    return (z_min, z_max, z_ext_abs)

def auto_z_levels(fid, x, y, variable, t_idx, n_cont, n_dec):
    """
    list(float) = auto_z_levels(fid, variable, t_idx, n_cont, n_dec)
                                                      ... # contour lines
                                                              ... # post .
    """
    fig, ax = plt.subplots()
    z_levs = np.ndarray(0)
    for i in t_idx:
        data = fid.variables[variable][i]
        cp = ax.contour(x, y, data, n_cont)
        z_levs = np.concatenate((z_levs, cp.levels), axis=0)
        z_levs = np.sort(np.unique(np.around(z_levs, n_dec)))
    plt.close(fig)
    return z_levs

def filter_z_levels(fid, x, y, variable, t_idx, z_levs, n_seg_degrade,
                    avleng_degrade, n_frame_threshold):
    """
    list(float) = filter_z_levels(fid, variable, t_idx, z_levs, n_seg_degrade,
                                  avleng_degrade, n_frame_threshold)
    """
    fig, ax = plt.subplots()
    qual = np.ones((len(t_idx), len(z_levs)), dtype=np.int8)
    for i in t_idx:
        data = fid.variables[variable][i]
        cp = ax.contour(x, y, data, levels=z_levs)
        for j, level in enumerate(cp.collections):
            n_seg = len(level.get_segments())
            l = 0.
            for path in level.get_segments():
                l = l + np.sum(np.sqrt(np.sum(np.diff(path, axis=0)**2,
                                              axis=1)))   # length of contour
            # degrade ranking
            if n_seg == 0 or n_seg > n_seg_degrade or l/n_seg < avleng_degrade:
                qual[i, j] = 0
    z_levs = z_levs[np.sum(qual, axis=0) >= n_frame_threshold]
    plt.close(fig)
    return z_levs

def symmetric_z_levels(z_levs):
    """
    list(float) = symmetric_z_levels(z_levs)
    """
    z_levs_abs = np.absolute(z_levs)
    z_levs_abs_unique = np.unique(z_levs_abs)
    n = np.zeros(np.size(z_levs_abs_unique), dtype=int)-1
    for i, zau in enumerate(z_levs_abs_unique):
        for za in z_levs_abs:
            if zau == za:
                n[i] += 1
    z_levs = z_levs_abs_unique[n.astype(bool)]
    return z_levs

def spread_z_levels(z_levs, n_cont, symflag):
    """
    list(float) = spread_z_levels(z_levs, n_cont, symflag)
    """
    z_levs_sets = []
    if symflag:
        z_levs_sym = symmetric_z_levels(z_levs)
        z_levs_max = z_levs_sym[-1]
        z_levs_min = -z_levs_max
        for item in z_levs_sym[0:-1]:
            z_levs_sets.append(np.array([-item, item]))
    else:
        z_levs_min = np.amin(z_levs)
        z_levs_max = np.amax(z_levs)
        for item in z_levs[1:-1]:
            z_levs_sets.append(np.array([item]))

    inner = list(itertools.combinations(z_levs_sets, n_cont))
    n = len(inner)
    inner_npa = np.sort(np.squeeze(np.array(inner)).reshape(n, -1),
                        axis=1)
    lv, rv = np.empty((n, 1)), np.empty((n, 1))
    lv.fill(z_levs_min)
    rv.fill(z_levs_max)
    z_levs_npa = np.concatenate((lv, inner_npa, rv), axis=1)
    diff = np.diff(z_levs_npa)
    std = np.std(diff, axis=1)
    z_levs = z_levs_npa[np.argmin(std)]
    return z_levs

def z_levels(fid, x, y, variable, n_levels, n_frames, t_idx,
             symflag, n_lev_auto, n_dec, n_seg, avleng):
    """
    list(float) = zlevels(fid, variable, n_levels, n_frames, t_idx,
                          symflag, n_lev_auto, n_dec, n_seg, avleng)
    """
    z_levs_auto = auto_z_levels(fid, x, y, variable, t_idx, n_lev_auto, n_dec)
    z_levs_filter = filter_z_levels(fid, x, y, variable, t_idx, z_levs_auto,
                                    n_seg, avleng, n_frames)
    z_levs = spread_z_levels(z_levs_filter, n_levels, symflag)

    log.info('z-levels, automatic: '+array2string(z_levs_auto, n_dec))
    log.info('z-levels, filtered:  '+array2string(z_levs_filter, n_dec))
    log.info('z-levels, used:      '+array2string(z_levs, n_dec))
    return z_levs


import logging
import traceback

__pubsub = {}

def subscribe(topic, callback):
    global __pubsub

    logging.debug("subscribe to %s, callback = %s" % (
        topic, str(callback) ))

    if topic not in __pubsub:
        __pubsub[topic] = []
    __pubsub[topic].append(callback)

def unsubscribe(topic, callback):
    global __pubsub

    logging.debug("unsubscribe to %s, callback = %s" % (
        topic, str(callback) ))

    if topic not in __pubsub and callback in __pubsub[topic]:
        del __pubsub[topic][ __pubsub[topic].index(callback) ]
        if len(__pubsub[topic]) == 0:
            del __pubsub[topic]

def publish(topic, *args):
    if topic in __pubsub:
        for cb in __pubsub[topic]:
            try:
                cb( *args )
            except:
                logging.error(traceback.format_exc())


#
# This is an example script to transfer peaks to all spectra
# and save peak lists
#
# Saving entities:
# ppm, Hz, intensity, S/N
#
# You can customize as you wish.
#
#
# by Woonghee Lee, Ph.D. (woonghee.lee@ucdenver.edu)
#
# To run this script:
#   In Poky Notepad,
#     File -> Run Python Module
#
#         Make sure the source spectrum is selected,

# if this is not set, files will be saved in spectrum path.
import __main__
s = __main__.main_session
output_dir = s.open_directorydialog('Select a directory to save peak lists.', '')
#output_dir = '/path/to/save/your/files'

import os.path
from sputil import parse_assignment, split_group_atom

def save_peaks(spec):
  fname = os.path.basename(spec.data_path)
  a, b = os.path.splitext(fname)
  path = a + '.list'
  if output_dir != '':
    fullpath = os.path.join(output_dir, path)
  else:
    fullpath = os.path.join(os.path.dirname(spec.data_path) +
                        path)

  f = open(fullpath, 'w')
  for peak in spec.peak_list():
    line = '%-13s %7.3f %7.3f %10.3f %10.3f %11d %5d\n' % \
        (peak.assignment, peak.frequency[0], peak.frequency[1],
        peak.frequency[0] * spec.hz_per_ppm[0],
        peak.frequency[1] * spec.hz_per_ppm[1],
        peak.data_height, int(peak.data_height / spec.noise))
    f.write(line)
  f.close()

def tga(session):
  ref_spec = session.selected_spectrum()
  save_peaks(ref_spec)
  ref_peaks = ref_spec.peak_list()
  for spec in session.project.spectrum_list():
    if ref_spec == spec:
      continue
    for peak in ref_peaks:
      peak2 = spec.place_peak(peak.frequency)
      if peak.is_assigned == 1:
        tasn = parse_assignment(peak.assignment)
        peak2.assign(0, tasn[0][0], tasn[0][1])
        peak2.assign(1, tasn[1][0], tasn[1][1])
        peak2.show_assignment_label()
    save_peaks(spec)

import __main__
s = __main__.main_session
tga(s)
print('Done.')


#基于链表实现完全 二叉树

#先构建一个链表结点
class BinTNode:
    def __init__(self,data,left=None,right=None):
        self.data = data
        self.left = left
        self.right = right
class BinaryTree:
    def __init__(self):
        self.root = None
    def is_empty(self):
        return self.root is None
    def find_none_node(self,node,way=left):
        #way的值left或right
        self.way = way
        if self.way == 'left':
            self.p = node.left
            if self.p.left is None:
                return self.p.left
        elif self.way == 'right':
            self.p = node.right
            if self.p.right is None:
                return self.p.right
        else:
            raise  TypeError
        self.find_none_node(self.p,self.way)

    def insertLeft(self,newNode):
        if self.root is not None:
            self.root = BinTNode(newNode)
        else:
            self.N = self.find_none_node(self.root,way = left)
            self.N.left = BinTNode(newNode)
    def insertright(self,newNode):
        if self.root is not None:
            self.root = BinTNode(newNode)
        else:
            self.N = self.find_none_node(self.root,way = right)
            self.N.right = BinTNode(newNode)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Fast Fourier Transformation

christoph dürr - jill-jênn vie - 2022
"""
# http://www.cs.toronto.edu/~denisp/csc373/docs/tutorial3-adv-writeup.pdf
# https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm

import math     # for pi
import cmath    # for exp

def pad(x):
    """ pad array x with zeros to make its length a power of two
    :complexity: linear
    """
    n = 1
    while n < len(x):
        n <<= 1
    x += [0] * (n - len(x))

def fft(x):
    """ Fast Fourier Transformation
    :input x: list of coefficients. Length n has to be a power of 2.
    :returns: list of sample values.
    :complexity: O(n log n).
    """
    n2 = len(x) // 2
    if n2 == 0:
        return x
    assert(2 * n2 == len(x))        # need to split evenly
    even = fft(x[0::2])
    odd  = fft(x[1::2])
    T = [cmath.exp(-1j * math.pi * k / n2) * odd[k] for k in range(n2)]
    return [even[k] + T[k] for k in range(n2)] + \
           [even[k] - T[k] for k in range(n2)]

def inv_fft(y):
    """ Inverse Fast Fourier Transformation
    :input y: list of sample values. Length n has to be a power of 2.
    :returns: list of coefficients.
    :complexity: O(n log n).
    """
    n = len(y)
    p = fft([yi.conjugate() for yi in y])
    return [pi.conjugate() / n for pi in p]

def mul_poly_fft(p, q):
    """Multiply two polynomials in integer coefficient representation
    :complexity: O(n log n)
    """
    n = (len(p) + len(q))   # make them of same and enough large size
    p += [0] * (n - len(p))
    q += [0] * (n - len(q))
    pad(p)
    y = fft(p)
    pad(q)
    z = fft(q)
    n = len(y)  # the padding might have increased the size n
    r = [y[i] * z[i] for i in range(n)]
    R = inv_fft(r)
    return [int(round(ri.real)) for ri in R]


def bank(n,p):
    credentials={"Ramesh": "12345", "Seetha": "abcde", "Abhishek": "pqrst", "Ramya": "98765", "Priya": "xyzab"}
    if credentials.get(n) is None :
        print("Your details does not match with our records")

    else :
        print(("Dear {}, you are welcome to our bank".format(n)))

bank("Ramesh","12345")
bank("Abhsk","1245")


import sys
import math
K = int(input())

#２の倍数のとき
if K % 2 == 0:
    print(-1)
    sys.exit()

if K % 7 == 0:
    K /= 7

val = 1
count = 0
pow = 10

while True:

    if val % K == 0:
        print(count)
        sys.exit()

    val += pow
    pow *= 10
    count += 1


_window_title = "RsWdolA"
_caesar_shift = 3

def caesar_cipher(text, shift):
    encrypted_text = ""
    for char in text:
        # 文字がアルファベットの場合のみ処理を行う
        if char.isalpha():
            # 大文字と小文字で処理を分ける
            if char.isupper():
                # 大文字の場合はアルファベットの範囲を超えないようにシフトする
                encrypted_text += chr((ord(char) - ord('A') + shift) % 26 + ord('A'))
            else:
                # 小文字の場合も同様にシフトする
                encrypted_text += chr((ord(char) - ord('a') + shift) % 26 + ord('a'))
        else:
            # アルファベット以外の文字はそのまま追加する
            encrypted_text += char
    return encrypted_text

def window_title():
    return caesar_cipher(_window_title, _caesar_shift * -1)


from nose.tools import eq_, ok_

from deeprank.models.variant import PdbVariantSelection
from deeprank.domain.amino_acid import alanine, valine, glutamine, glycine, methionine

def test_instance():

    pdb_ac = "1AK4"
    chain_id = "A"
    residue_number = 10
    wt_amino_acid = alanine
    var_amino_acid = glutamine

    selection = PdbVariantSelection(pdb_ac, chain_id, residue_number, wt_amino_acid, var_amino_acid)

    eq_(selection.chain_id, chain_id)

    eq_(selection.residue_number, residue_number)

    eq_(selection.pdb_ac, pdb_ac)

    eq_(selection.wild_type_amino_acid, wt_amino_acid)
    eq_(selection.variant_amino_acid, var_amino_acid)

def test_hash():
    variant1 = PdbVariantSelection("101M", "A", 10, valine, glutamine)
    variant2 = PdbVariantSelection("110M.pdb", "A", 25, glycine, methionine)

    dictionary = {variant1: 1, variant2: 2}

    eq_(dictionary[variant1], 1)
    eq_(dictionary[variant2], 2)

    ok_(hash(variant1) != hash(variant2))