from django.urls import path
from bookstore.views import user_account_views as account
from bookstore.views import user_detail_views as detail

urlpatterns = [
    path('login/', account.MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('register/', account.register_user, name='register-user'),

    path('account/', account.get_user_account, name='get-user-account'),
    path('list/', account.get_user_list, name='get-user-list'),
    path('delete/<str:pk>/', account.delete_user, name='delete-user'),
    path('update/', account.update_user_account, name='user-account-update'),

    path('address/get/', account.get_address, name='get-address'),
    path('address/add/', account.add_address, name='add-address'),
    path('address/update/', account.update_address, name='update-address'),
    path('address/delete/<str:pk>/', account.delete_address, name='delete-address'),
    path('address/default/', account.default_address, name='change-default-address'),

    path('notifications/', account.get_unread_notifications, name='get-unread-notifications'),
    path('notifications/update/', account.update_read_notifications,
         name='update-read-notifications'),
    path('notifications/delete/<str:pk>/', account.delete_all_notifications,
         name='delete-notifications'),

    path('detail/', detail.get_user_detail, name='get-user-detail'),
    path('follow/author/', detail.follow_author, name='follow-author'),
    path('favourite/book/', detail.favourite_book, name='favourite-book'),
    path('favourite/genre/', detail.favourite_genre, name='favourite-genre'),
    path('favourite/genrelist/', detail.favourite_genrelist, name='favourite-genrelist'),
    path('favourite/series/', detail.favourite_series, name='favourite-series'),

    path('cart/', detail.get_cart_items, name='get-cart-item'),
    path('cart/add/', detail.add_cart_item, name='add-cart-item'),
    path('cart/remove/<str:pk>/', detail.remove_cart_item, name='remove-cart-item'),
    path('cart/clear/', detail.clear_cart_items, name='clear-cart-item'),

    path('wishlist/', detail.get_wishlist_items, name='get-wishlist-item'),
    path('wishlist/add/', detail.add_wishlist_item, name='add-wishlist-item'),
    path('wishlist/remove/<str:pk>/', detail.remove_wishlist_item, name='remove-wishlist-item'),
    path('wishlist/clear/', detail.clear_wishlist_items, name='clear-wishlist-item'),
]


import streamlit as st
import gdown
import pickle
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import re
from sklearn.feature_extraction.text import TfidfVectorizer

@st.cache_data
def collect():
  gdown.download(id = '1GK_KpfUVfdbdJlutyaXX_Sf0uaApqXfN')#ret data
  return

@st.cache_resource
def getdata():
  gdown.download(id = '1AFL6D6TJgqpkjNAwtNrf0j0e3GadxWp_')
  gdown.download(id = '1vLnhZi7vk0Hal45b0cdJrIaPafBFbkN_')#knn model
  with open(r'/mount/src/linkedin_deployment/knn_model_linkedin.pkl', 'rb') as file:
    model = pickle.load(file)
  return model

model = getdata()

def top_4_prediction(input_data):
    df = input_data
    del df['name']

    #------------------------------------------------------------------------------------------------------
    for column in df.columns:
      df[column] = df[column].apply(lambda x: str(x).lower().replace(r'[^\w\s]', ''))
      df[column] = df[column].str.replace(r'fulltime|selfemployed|· self-employed|· full-time', '', flags=re.IGNORECASE).str.strip()
    #------------------------------------------------------------------------------------------------------

    titlecols = [col for col in df.columns if 'title' in col]
    df['all_titles'] = df[titlecols].apply(lambda row: ' '.join(row.dropna().astype(str)), axis=1)#--------------------------------------remove punctuvation
    df.drop(columns=titlecols, inplace=True)

    org_cols = ([col for col in df.columns if 'org' in col])
    df['all_org_cols'] = df[org_cols].apply(lambda row: ','.join(row.dropna().astype(str)), axis=1)
    df.drop(columns=org_cols, inplace=True)

    job_location_cols = [col for col in df.columns if 'location' in col]
    df['all_loc_cols'] = df[job_location_cols].apply(lambda row: ' '.join(row.dropna().astype(str)), axis=1)
    df.drop(columns=job_location_cols, inplace=True)

    institute_cols = [col for col in df.columns if 'institute' in col]
    df['all_instutes'] = df[institute_cols].apply(lambda row: ','.join(row.dropna().astype(str)), axis=1)
    df.drop(columns=institute_cols, inplace=True)

    degree_cols = [col for col in df.columns if 'degree' in col and 'duration' not in col]
    df['all_degree'] = df[degree_cols].apply(lambda row: ' '.join(row.dropna().astype(str)), axis=1)
    df.drop(columns=degree_cols, inplace=True)

    comp_emp_count = [col for col in df.columns if 'company' in col and 'emp' in col]            # how big are their company exp's so we are totaling the info.
    df['all_comp_emp_count'] = df[comp_emp_count].sum(axis=1)
    df.drop(columns=comp_emp_count, inplace=True) #not enough data

    comp_ind = [col for col in df.columns if 'company' in col and 'industry' in col]
    df['all_comp_ind'] = df[comp_ind].apply(lambda row: ' '.join(row.dropna().astype(str)), axis=1)
    df.drop(columns=comp_ind, inplace=True)

    #------------------------------------------------------------------------------------------------------
    def vectorize_columns_method1(df, columns_to_vectorize):
        tfidf_vectorizer_method1 = TfidfVectorizer(tokenizer=lambda x: x.split(','))
        job_titles_method1 = df[columns_to_vectorize].apply(lambda row: ','.join(row), axis=1)
        job_title_matrix_method1 = tfidf_vectorizer_method1.fit_transform(job_titles_method1)
        job_title_vector_df_method1 = pd.DataFrame(job_title_matrix_method1.toarray(), columns=tfidf_vectorizer_method1.get_feature_names_out())
        return job_title_vector_df_method1,tfidf_vectorizer_method1

    def vectorize_columns_method2(df, columns_to_vectorize):
        tfidf_vectorizer_method2 = TfidfVectorizer()
        job_titles_method2 = df[columns_to_vectorize].apply(lambda row: ' '.join(row), axis=1)
        job_title_matrix_method2 = tfidf_vectorizer_method2.fit_transform(job_titles_method2)
        job_title_vector_df_method2 = pd.DataFrame(job_title_matrix_method2.toarray(), columns=tfidf_vectorizer_method2.get_feature_names_out())
        return job_title_vector_df_method2,tfidf_vectorizer_method2

    columns_to_vectorize_1 = ['all_org_cols','all_instutes']
    columns_to_vectorize_2 = [ 'all_titles', 'all_loc_cols', 'all_degree', 'all_comp_ind']

    vectorized_df_method1,tfidf_vectorizer_method1 = vectorize_columns_method1(df, columns_to_vectorize_1)
    vectorized_df_method2,tfidf_vectorizer_method2 = vectorize_columns_method2(df, columns_to_vectorize_2)

    # Concatenate the vectorized DataFrames horizontally
    result_df = pd.concat([df, vectorized_df_method1, vectorized_df_method2], axis=1)

    # Drop the non-vectorized columns
    result_df = result_df.drop(columns=columns_to_vectorize_1)
    result_df = result_df.drop(columns=columns_to_vectorize_2)
    #------------------------------------------------------------------------------------------------------
    colsdf = pd.read_csv(r'/mount/src/linkedin_deployment/x_train.csv')
    colsdf = pd.DataFrame(columns=colsdf.columns.to_list())

    for column in colsdf.columns:
        if column in result_df.columns:
            colsdf[column] = result_df[column]
    colsdf = colsdf.fillna(0)
    #------------------------------------------------------------------------------------------------------
    orgdf = pd.read_csv(r'/mount/src/linkedin_deployment/retrivaldata.csv')

    user_input = colsdf.iloc[0]  # Change the index (5) to any user index you want to test
    user_input = user_input.values.reshape(1, -1)  # Reshape to 2D array

    distances, indices = model.kneighbors(user_input, n_neighbors=4)

    top_4_indices = indices[0]

    top_4_profiles = orgdf.iloc[top_4_indices]

    top_4_profiles = top_4_profiles.dropna(axis=1, how='all')
    top_4_profiles = top_4_profiles.loc[:, (top_4_profiles != 0.0).any()]
    top_4_profiles = top_4_profiles.reset_index(drop=True)

    cosine_similarity_scores = [1 - distance for distance in distances]
    st.write( f'KNN Distances from profiles', distances)

    return(top_4_profiles)

def main():
    a = collect()
    st.write('Welcome to the Application, *Find Matching Founder Profiles* :sunglasses:')

    st.title('Enter your profile Details')

    main = {}
    # Basic Information
    name = st.text_input("Name")
    location = st.text_input("Location")

    main.update({
      'name':name,
      'location':location
    })

    # Previous Jobs
    num_previous_jobs = st.number_input("Number of Previous Jobs", min_value=0, max_value=15, value=0)

    for i in range(num_previous_jobs):
        st.subheader(f"Previous Job {i+1}")
        org = st.text_input(f"Organization {i+1}")
        title = st.text_input(f"Title {i+1}")
        duration = st.number_input(f"Duration {i + 1} in Months", min_value=0, max_value=999,value=0)
        job_location = st.text_input(f"Job Location {i+1}")

        main[f"org_{i}"] = org
        main[f"title_{i}"] = title
        main[f"job_{i}_duration"] = duration
        main[f"job_{i}_location"] = job_location

    # Education
    num_education_entries = st.number_input("Number of Education Entries", min_value=0, max_value=3, value=0)

    for i in range(num_education_entries):
        st.subheader(f"Education Entry {i+1}")
        institute = st.text_input(f"Institute {i+1}")
        degree = st.text_input(f"Degree {i+1}")
        degree_duration = st.number_input(f"Degree Duration {i+1} in Months", min_value=0, max_value=999, value=0)

        main[f"institute_{i}"] = institute
        main[f"degree_{i}"] = degree
        main[f"degree_{i}_duration"] = degree_duration

    # Company Information
    for i in range(num_previous_jobs):
        st.subheader(f"Company {i + 1}")
        emp_count = st.number_input(f"Employee Count {i + 1}", min_value=0)
        industry = st.text_input(f"Industry {i + 1}")

        main[f"company_{i}_emp_count"] = emp_count
        main[f"company_{i}_industry"] = industry

    user_input = pd.DataFrame(main, index=[0])

    # prediction

    top_4_profiles = pd.DataFrame()

    # button
    if st.button('Check'):
        top_4_profiles = top_4_prediction(user_input)

    st.write(top_4_profiles)

    st.download_button(
        label='Download CSV',
        data = top_4_profiles.to_csv(index=False),
        file_name='data.csv',
        mime='text/csv'
    )

if __name__ == '__main__':
    main()


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

import redis
import uuid
import time

class MyLock:

    def acquire_lock(self, conn, lockname, acquire_lock_time=10, lock_time_out=10):
        identifier = str(uuid.uuid4())
        print(identifier)

        end_time = time.time() + acquire_lock_time
        lockname = "lock:" + lockname
        print(lockname)
        while time.time() < end_time:
            if conn.setnx(lockname, identifier):
                conn.expire(lockname, lock_time_out)
                return identifier
            elif conn.ttl(lockname) == -1:
                # 如果没有设置过期时间
                conn.expire(lockname, lock_time_out)
            time.sleep(.001)
        return False

    def release_lock(self, conn, lockname, locked):
        pipe = conn.pipeline(True)
        lockname = "lock:" + lockname
        while True:
            try:
                pipe.watch(lockname)
                if pipe.get(lockname) == locked:
                    pipe.multi()
                    pipe.delete(lockname)
                    pipe.execute()
                    return True
                pipe.unwatch()
                break

            except redis.exceptions.WatchError:
                pass

        return False


import logging

from autonetkit.design.utils import filters
from autonetkit.design.utils.graph_utils import connected_components
from autonetkit.network_model.topology import Topology
from autonetkit.network_model.types import DeviceType

logger = logging.getLogger(__name__)

def check_layer2_conn(topology: Topology) -> bool:
    """

    @param topology:
    @return:
    """
    valid = True

    components = connected_components(topology)
    if len(components) > 1:
        logger.warning("Disconnected network: %s components", len(components))
        valid = False

    routers = filters.routers(topology)

    routers_present = len(routers) > 0

    if routers_present:
        # check that all hosts connect to a router
        hosts = filters.hosts(topology)
        for host in hosts:
            peers = host.peer_nodes()
            if not any(n.type == DeviceType.ROUTER for n in peers):
                logger.warning("Host %s is not connected to a router", host.label)
                valid = False

    return valid


# Representations abstraites
import matplotlib.pyplot as plt
import numpy as np
import pickle
import params

# # Ouverture des listes
# with open ('liste1', 'rb') as fp:
#     l1x = pickle.load(fp)
# with open ('liste2', 'rb') as fp:
#     l1y = pickle.load(fp)
# with open ('liste1v', 'rb') as fp:
#     l2x = pickle.load(fp)
# with open ('liste2v', 'rb') as fp:
#     l2y = pickle.load(fp)

#Affichage
def Affichage(l1x,l1y,l2x,l2y):
    color = params.color_abstr

    plt.figure()
    ax = plt.subplot()

    plt.plot(l1x, l1y, 'b'+'--')
    plt.plot(l1x, l1y, 'b'+'o',label = 'Piano')
    for i in range(len(l1x)):
        ax.annotate(' {}'.format(i+1), (l1x[i], l1y[i]), color='black')
    plt.plot(l2x, l2y, 'r'+'--')
    plt.plot(l2x, l2y, 'r'+'o', label = 'Violon')
    for i in range(len(l2x)):
        ax.annotate(' {}'.format(i+1), (l2x[i], l2y[i]), color='black')

    d1, d2 = 'diffConcordance', 'crossConcordance'
    plt.xlabel(d1[0].upper() + d1[1:])
    plt.ylabel(d2[0].upper() + d2[1:])
    plt.title('Cadence ' + ' (' + d1[0].upper() + d1[1:] + ', ' + d2[0].upper() + d2[1:] + ')')
    plt.legend(frameon=True, framealpha=0.75)
    plt.show()

pts1 = [np.array((l1x[t],l1y[t])) for t in range(len(l1x))]
pts2 = [np.array((l2x[t],l2y[t])) for t in range(len(l1x))]

# #distance euclidienne
# def dist(x,y):
#     return np.sqrt(np.sum((x-y)**2))
#
#
# def distance(pts1,pts2,type = 'diff'):
#     distance = 0
#     if type == 'stat':
#         for t in range(len(pts1)):
#             distance += dist(pts1[t], pts2[t])
#         return distance
#     else :
#         pts1_diff = [pts1[t+1]-pts1[t] for t in range(len(pts1)-1)]
#         pts2_diff = [pts2[t+1]-pts2[t] for t in range(len(pts2)-1)]
#         for t in range(len(pts1_diff)):
#             distance += dist(pts1_diff[t], pts2_diff[t])
#         return distance

# print(distance(pts1,pts2,'stat'))

points = np.asarray([pts1, pts2])

# Fonction qui calcule l'éloignement de courbes nomalisées, correspondant à différents timbres
def dispersion(points,type = 'diff'):
    if type == 'stat':
        return np.linalg.norm(np.std(points,axis = 0), axis = 1)
    else :
        points_diff = np.zeros((points.shape[0],points.shape[1]-1,points.shape[2]))
        for i in range(points.shape[1]-1):
            points_diff[:,i] = points[:,i+1]-points[:,i]
        return np.linalg.norm(np.std(points_diff,axis = 0), axis = 1)

print(dispersion(points))

# Affichage(l1x,l1y,l2x,l2y)


#coding:utf-8
"""
Created on 2018年12月25日
@author: devshilei@gmail.com
"""
import shutil
import os
from PIL import Image

def image_files_all_in_one(source_path, target_path):
    """
    Discription: 处理原始图像文件（汇总到一个文件目录下）
    @param source_path: 源目录
    @param target_path: 目标目录
    """
    for root, __, files in os.walk(source_path):
        for name in files:
            if "Thumbs.db" != name and name[0] != "X":
                full_path = os.path.join(root, name)
                rename = full_path.replace(source_path, "").replace("\\", "_")
                target_file_path = os.path.join(target_path, rename)
                print(full_path, target_file_path)
                shutil.copyfile(full_path, target_file_path)
    print("image_files_all_in_one".center(100, "-"))

def batch_image_resize(source_path, resized_file_path):
    """
    Discription: 原始文件几何变换：resize
    @param source_path: 源目录
    @param resized_file_path: 大小重置之后文件存储目录
    """
    file_name_list = os.listdir(source_path)
    for file_name in file_name_list:
        img = Image.open(os.path.join(source_path, file_name))
        (height, width) = img.size
        dst = img.resize((height, width))
        #half_height, half_width = height//2, width//2
        #print(file_name, height, width, half_height, half_width)
        #img.resize((half_height, half_width))
        dst.save(os.path.join(resized_file_path, file_name))
    print("batch_image_resize".center(100, "-"))

def image_augmentation(source_path, target_path):
    """
    Discription: 图像增广：原始文件几何变换：[包括上下、左右镜像、顺时针旋转180°]
    @param source_path: 源目录
    @param target_path: 几何变换后文件存储目录
    """
    file_name_list = os.listdir(source_path)
    for file_name in file_name_list:
        img = Image.open(os.path.join(source_path, file_name))
        dst = img.transpose(Image.FLIP_LEFT_RIGHT)  #左右互换
        dst.save(os.path.join(target_path, "FLR_" + file_name))
        dst = img.transpose(Image.FLIP_TOP_BOTTOM)  #上下互换
        dst.save(os.path.join(target_path, "FTB_" + file_name))
        dst = img.transpose(Image.ROTATE_180)       #顺时针旋转
        dst.save(os.path.join(target_path, "R180_" + file_name))
    print("image_augmentation".center(100, "-"))

def image_to_gray(source_path, target_path):
    file_name_list = os.listdir(source_path)
    for file_name in file_name_list:
        img = Image.open(os.path.join(source_path, file_name))
        gray = img.convert("L")
        gray.save(os.path.join(target_path, "G_" + file_name))
    print("image_to_gray".center(100, "-"))

def image_gray_filter():
    file_name_list = os.listdir(source_path)
    for file_name in file_name_list:
        img = Image.open(os.path.join(source_path, file_name))
        gray = img.convert("L")
        gray.save(os.path.join(target_path, "G_" + file_name))
    print("image_gray_filter".center(100, "-"))

if __name__ == '__main__':
#     # step1 将原始文件拷贝到统一文件目录下
#     source_path, target_path = "D:/Mimage/12-21", "images/step_01_all_in_one"
#     image_files_all_in_one(source_path, target_path)
#     # step2-1 原始文件重置大小
#     source_path, resized_file_path = "real/step_01_all_in_one", "real/step_02_1_resize"
#     batch_image_resize(source_path, resized_file_path)
#     # step2-2 原始文件重置大小
#     source_path, target_path = "real/step_02_1_resize", "real/step_02_2_augmentation"
#     image_augmentation(source_path, target_path)
    source_path, target_path = "real/step_02_2_augmentation", "real/step_03_1_gray"
    image_to_gray(source_path, target_path)
    print("Finished".center(100, "-"))


#!/usr/bin/sudo python

from mininet.topo import Topo
from mininet.net import Mininet
from mininet.log import setLogLevel
from mininet.node import OVSKernelSwitch, RemoteController, CPULimitedHost
from mininet.cli import CLI
from mininet.link import TCLink
import os
import threading
import numpy as np
from random import randint, choice
from time import sleep

from intent_manager import IntentManager
from link_manager import LinkManager
from settings import *
import subprocess
import socket
import re
from switch_movement import SwitchMover
from media_server import MediaServer
from energy_management import BatteryCapacityLogger
from switch_operations import SwitchOperator
import traceback
import time
import json
import shutil
import pickle
from process_cleaner import stop_children_processes

switch_mover = None
media_server = None
media_server_info = {}
drone_battery_manager = None
link_manager = None
intent_manager = None
processes = []
link_options_host2switch = dict(bw=54 / DATA_SCALING, delay='100us', loss=0.01, max_queue_size=1000, use_htb=True)
link_options_switch2switch = dict(bw=100 / DATA_SCALING, delay='100us', loss=0.01, max_queue_size=1000, use_htb=True)
# linkOptionsMediaServer2Switch = dict(bw=100, penalty='0ms', loss=0.01, max_queue_size=100000, use_htb=True)
link_options_switch_dummy_host2switch = dict(bw=1000 / DATA_SCALING, delay='0', loss=0, max_queue_size=1000,
                                             use_htb=True)
listen_host_availability_thread = None
request_file_thread = None
switch_mobility_thread = None
busy_hosts = []
switch_name_id_table = {}
switch_id_name_table = {}
links_h2s = []
links_s2s = {}
current_links = []
current_time = 0
requests_from_depleted_drones = 0
simulation_id = str(int(time.time() // 10))

simulation_snapshot = {"settings": {}}

with open('settings.py', 'r') as f:
    exec (f.read(), simulation_snapshot["settings"])
if '__builtins__' in simulation_snapshot["settings"]:
    del simulation_snapshot["settings"]['__builtins__']

def debug(msg):
    if PRINT_DUMMY_MESSAGES:
        print(msg)

def print_link_changes(message):
    if PRINT_LINK_CHANGES:
        print(message)

class InbandController(RemoteController):

    def checkListening(self):
        if self.port is None:
            self.port = 6633
        return

class DroneTopology(Topo):
    def build(self, s=NUMBER_OF_SWITCHES, n=NUMBER_OF_HOSTS_PER_SWITCH):
        global switch_name_id_table
        switches = []
        host_number = 1
        for sw in range(s):
            new_switch = self.addSwitch('s%d' % (sw + 1))
            cache_host_in_switch = self.addHost('hs%d' % (sw + 1),
                                                mac='00:00:00:00:%s:00' % hex(sw + 1).split('x')[-1].zfill(2),
                                                ip='10.0.%d.1/16' % (sw + 1),
                                                cpu=.5 / (s * n)
                                                )
            self.addLink(cache_host_in_switch, new_switch, **link_options_switch_dummy_host2switch)
            switch_name_id_table['s%d' % (sw + 1)] = sw
            switch_id_name_table[sw] = 's%d' % (sw + 1)
            for h in range(n):
                host = self.addHost('h%d' % host_number,
                                    cpu=.30 / (s * n),
                                    mac='00:00:00:00:00:' + hex(host_number).split('x')[-1].zfill(2))
                host_number += 1
                self.addLink(host, new_switch, bw=switch_mover.switch2host_link_capacities[sw] / DATA_SCALING,
                             delay='0',
                             loss=0,
                             max_queue_size=10000, use_htb=True)
            switches.append(new_switch)

        for link in switch_mover.active_link_pair_capacity_table:
            # pair = "{}-{}".format(switch_id_name_table[link[0]], switch_id_name_table[link[1]])
            self.addLink(switch_id_name_table[link[0]], switch_id_name_table[link[1]], bw=100 / DATA_SCALING,
                         delay='0ms',
                         loss=0,
                         max_queue_size=10000, use_htb=True)
        # serverNode = self.addHost('msrv', mac='00:00:00:00:00:FF', ip='10.0.200.200/8')
        # self.addLink(serverNode, switch_id_name_table[switch_mover.content_server_switch_id],
        # **linkOptionsMediaServer2Switch)

def wait_exponentially(scale_of_exponential):
    time_until_next_request = np.random.exponential(scale_of_exponential)
    sleep(time_until_next_request)

def request_file(scale_of_exponential=REQUEST_INTERVAL, host_number=NUMBER_OF_HOSTS, alpha_zipf_exponent=1.1,
                 number_of_files=NUMBER_OF_FILES):
    global requests_from_depleted_drones
    s = np.random.zipf(alpha_zipf_exponent, number_of_files * 10)
    random_file_selection_list = s[s < number_of_files + 1] - 1
    t = threading.currentThread()
    flow_id = 0
    while getattr(t, "is_running", True):
        # start = time.time()
        requesting_host_id = randint(1, host_number)
        if requesting_host_id - 1 in drone_battery_manager.depleted_battery_ids:
            requests_from_depleted_drones += 1
            wait_exponentially(scale_of_exponential)
            continue
        requested_file_id = str(choice(random_file_selection_list))
        # File request protocol message: requesting_host_ip;requested_file_id

        try:
            host = net.get("h%d" % requesting_host_id)
            host_ip = host.IP()

            if DISABLE_MULTIPLE_REQUESTS_FROM_SAME_HOST and host_ip in busy_hosts:
                debug("h%d already requested a file" % requesting_host_id)
                continue
            else:
                debug("%d: h%s requests file %s" % (flow_id, requesting_host_id, requested_file_id))
            if DISABLE_MULTIPLE_REQUESTS_FROM_SAME_HOST and GENERATE_TRAFFIC:
                busy_hosts.append(host_ip)
            request_message = "{};{}".format(host_ip, requested_file_id)
            media_source_node_ip, redirect_message = media_server.process_file_request(request_message,
                                                                                media_server_info["ip"])
            if media_source_node_ip in [SOURCE_OWN_CACHE, SOURCE_NOT_AVAILABLE]:
                if DISABLE_MULTIPLE_REQUESTS_FROM_SAME_HOST:
                    busy_hosts.remove(host_ip)
                wait_exponentially(scale_of_exponential)
                continue
            # debug(request_message)

            # host.cmd("echo '{};{}' | nc {} {} -w 0.5 &> /dev/null &".format(redirect_message, flow_id,
            # media_source_node_ip, str(FILE_REQUEST_LISTEN_PORT)))
            if ONOS_INTENT_ADD_MODE:
                intent_manager.create_host_2_host_intent(host_ip, media_source_node_ip)
            host.cmd("echo '{};{}' >/dev/tcp/{}/{} &".format(redirect_message, flow_id, media_source_node_ip,
                                                             str(FILE_REQUEST_LISTEN_PORT)))

            flow_id += 1
            # debug(result)
            # I assume request rate is Poisson Distribution so the time intervals are exponential distributions
            # end = time.time()
            # print(end - start)
            wait_exponentially(scale_of_exponential)
        except Exception as e:
            print(traceback.format_exc())
            print(e)
            print(media_server_info)

# def moveHosts(host_number=NUMBER_OF_HOSTS, switch_number=NUMBER_OF_SWITCHES, interval=MOVE_EVENT_INTERVALS):
#     while True:
#         try:
#             movingHostID = randint(1, host_number)
#             newSwitchID = randint(1, switch_number)
#             host = net.get("h%d" % movingHostID)
#             switch = net.get("s%d" % newSwitchID)
#             host.deleteIntfs()
#             print ("Host %d hand over to %d " % (movingHostID, newSwitchID))
#             sleep(interval / 2)
#             net.addLink(host, switch, **link_options_host2switch)
#             sleep(interval / 2)
#         except Exception as e:
#             print(traceback.format_exc())
#             print (e)

def update_links_h2s():
    for switchID, new_link_capacity in enumerate(switch_mover.switch2host_link_capacities):
        previous_link_capacity = links_h2s[switchID][1]
        if previous_link_capacity != new_link_capacity:
            interface = links_h2s[switchID][0]
            interface.config(bw=new_link_capacity / DATA_SCALING, smooth_change=True)
            links_h2s[switchID][1] = new_link_capacity
            print_link_changes(
                "H2S {} capacity has changed from {} to {}".format(switchID, previous_link_capacity, new_link_capacity))

def update_links_s2s():
    new_link_capacities_s2s = {}
    new_links = []
    for link in switch_mover.active_link_pair_capacity_table:
        sw1 = switch_id_name_table[link[0]]
        sw2 = switch_id_name_table[link[1]]
        new_capacity = link[2]
        pair = "{}-{}".format(sw1, sw2)
        if sw1 == sw2:
            print("Link to itself: %s" % sw1)
            print("Operating switches:")
            print(switch_mover.operating_switches)
            print("Neighbors:")
            print(switch_mover.neighbors)
            print("Active link table:")
            print(switch_mover.active_link_pair_capacity_table)
            continue
        new_link_capacities_s2s[pair] = new_capacity
        new_links.append(pair)
        # Check link exists
        if pair in links_s2s:
            if not links_s2s[pair][3]:
                # Link was down, make link up
                interface1 = links_s2s[pair][1][0]
                interface2 = links_s2s[pair][1][1]
                if links_s2s[pair][2] != new_capacity:
                    # Apply the new bw
                    interface1.config(bw=new_capacity / DATA_SCALING, smooth_change=True)
                    print_link_changes(
                        "{} capacity has changed from {} to {}".format(pair, links_s2s[pair][2], new_capacity))
                net.get(sw1).attach(interface1)
                print_link_changes("{} is up".format(pair))
                if ONOS_LINK_ADD_MODE:
                    link_manager.send_two_way_link_to_controller(interface1.sumo_id, interface2.sumo_id)
        else:
            # Create the link
            try:
                net.addLink(sw1, sw2, bw=100 / DATA_SCALING)
            except Exception as e:
                print(traceback.format_exc())
                print (e)

            interfaces = net.get(sw1).connectionsTo(net.get(sw2))[0]
            interface1 = interfaces[0]
            interface2 = interfaces[1]
            net.get(sw1).attach(interface1)
            net.get(sw2).attach(interface2)
            links_s2s[pair] = [sw1, interfaces, new_capacity, True]
            print_link_changes("{} is created.".format(pair))
            if ONOS_LINK_ADD_MODE:
                link_manager.send_two_way_link_to_controller(interface1.sumo_id, interface2.sumo_id)

    for previously_active_link in current_links:
        # From the previous time slot, check the link changes one by one
        if previously_active_link in new_link_capacities_s2s:
            # Link continues to operate
            previous_capacity = links_s2s[previously_active_link][2]
            new_capacity = new_link_capacities_s2s[previously_active_link]
            if previous_capacity != new_capacity:
                # Link capacity has changed.
                interface1 = links_s2s[previously_active_link][1][0]
                interface1.config(bw=new_capacity / DATA_SCALING, smooth_change=True)
                print_link_changes(
                    "{} capacity has changed from {} to {}".format(previously_active_link, previous_capacity,
                                                                   new_capacity))
            else:
                print_link_changes("{}-> Alles gut.".format(previously_active_link))
        else:
            # Link is down
            links_s2s[previously_active_link][3] = False
            interfaces = links_s2s[previously_active_link][1]
            interface1 = interfaces[0]
            interface2 = interfaces[1]
            if ONOS_LINK_ADD_MODE:
                link_manager.delete_two_way_link_from_controller(interface1.sumo_id, interface2.sumo_id)
            net.get(links_s2s[previously_active_link][0]).detach(interface1)
            print_link_changes("{} is down".format(previously_active_link))

    # Save the new link pairs
    current_links[:] = new_links

def update_links():
    update_links_h2s()
    update_links_s2s()

def remove_depleted_switches(depleted_batteries):
    switch_mover.number_of_switches_alive -= len(depleted_batteries)
    switch_mover.operating_switches = np.setdiff1d(switch_mover.operating_switches, depleted_batteries)
    for switch in depleted_batteries:
        net.get(switch_id_name_table[switch]).stop()
    if switch_mover.number_of_switches_alive <= 0:
        terminate_simulation()
        return
    if switch_mover.content_server_switch_id in depleted_batteries:
        print("Content server switch is depleted")
        global media_server_info
        switch_mover.get_central_node()
        media_server_dummy_host_name = "h" + switch_id_name_table[switch_mover.content_server_switch_id]
        media_server_info = {"node": net.get(media_server_dummy_host_name),
                             "ip": net.get(media_server_dummy_host_name).IP(),
                             "id": switch_mover.content_server_switch_id}

def save_simulation_snapshot_to_file(data_time, file_name=None):
    if file_name is None:
        file_name = "resultsV2/situation-%s.pkl" % simulation_id
    simulation_snapshot[data_time] = {"links": switch_mover.active_link_pair_capacity_table[:],
                                      "content_server": switch_mover.content_server_switch_id,
                                      "battery_levels": np.copy(drone_battery_manager.battery_levels),
                                      "media_server_logs": media_server.get_caching_statistics(),
                                      "requests_from_depleted_drones": requests_from_depleted_drones,
                                      "caching_switches": switch_operator.caching_switches[:],
                                      "cached_switches": switch_operator.cached_switches[:],
                                      "depleted_battery_ids": np.copy(drone_battery_manager.depleted_battery_ids),
                                      "energy_consumption_statistics": np.copy(
                                          drone_battery_manager.energy_consumption_statistics),
                                      "energy_cost_matrix": media_server.energy_cost_matrix[:],
                                      "flow_hop_matrix": media_server.flow_hop_matrix[:],
                                      }
    with open(file_name, 'wb+') as handle:
        pickle.dump(simulation_snapshot, handle, protocol=pickle.HIGHEST_PROTOCOL)

def move_switches(interval=MOVE_EVENT_INTERVALS):
    global current_time
    t = threading.currentThread()
    print("Time is %d." % (current_time / 60))
    # try:
    #     os.remove("batteryLevelsSpecific.csv")
    # except:
    #     traceback
    # drone_battery_manager.printProportionalBatteryLevelsToFile("batteryLevelsSpecific.csv", (current_time / 60))
    # switch_mover.printLinksToFile("links/links_%d" % (current_time / 60))
    save_simulation_snapshot_to_file(current_time)
    while switch_mover.number_of_switches_alive and getattr(t, "is_running", True):
        sleep(interval)
        current_time += interval
        drone_battery_manager.decrease_battery_fly()
        switch_operator.get_switch_overheads()
        depleted_batteries = drone_battery_manager.check_for_depleted_batteries()
        if depleted_batteries:
            remove_depleted_switches(depleted_batteries)
        switch_mover.move_switches_for_one_time_interval(current_time)
        switch_operator.update_device_coordinates_on_controller()
        update_links()
        if current_time % 60 == 0:
            "Caching host placement time"
            switch_operator.select_caching_nodes()
            # switch_mover.printLinksToFile("links/links_%d" % (current_time / 60))
            # drone_battery_manager.printProportionalBatteryLevelsToFile("batteryLevelsSpecific.csv",(current_time/60))
            # drone_battery_manager.printEnergyConsumptionStatisticsToFile(current_time / 60)
            save_simulation_snapshot_to_file(current_time)
            print(drone_battery_manager.battery_levels)
            print("Time is %d." % (current_time / 60))

def get_host_availability(accepted_socket):
    message = accepted_socket.recv(1024).decode()
    accepted_socket.close()
    print(message)
    if ONOS_INTENT_ADD_MODE:
        message_parsed = message.split(";", 3)
        src_ip = message_parsed[0]
        dst_ip = message_parsed[1]
        intent_manager.delete_host_2_host_intent(src_ip, dst_ip)
    if DISABLE_MULTIPLE_REQUESTS_FROM_SAME_HOST:

        try:
            busy_hosts.remove(dst_ip)
        except Exception as e:
            print(traceback.format_exc())
            print (e)

def listen_host_availability():
    t = threading.currentThread()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((MININET_IP, HOST_AVAILABILITY_LISTEN_PORT))
    s.listen(5)
    while getattr(t, "is_running", True):
        # print("...ABC...")
        accepted_socket, address = s.accept()
        try:
            if not getattr(t, "is_running", True):
                return
            get_host_availability(accepted_socket)
        except Exception as e:
            print(traceback.format_exc())
            print(e)

def get_initial_link_objects():
    global media_server_info
    print(switch_mover.active_link_pair_capacity_table)
    media_server_dummy_host_name = "h" + switch_id_name_table[switch_mover.content_server_switch_id]
    media_server_info = {"node": net.get(media_server_dummy_host_name),
                         "ip": net.get(media_server_dummy_host_name).IP(),
                         "id": switch_mover.content_server_switch_id}
    drone_battery_manager.add_extra_battery(switch_mover.content_server_switch_id)
    for switchID, linkCapacity in enumerate(switch_mover.switch2host_link_capacities):
        switch_name = switch_id_name_table[switchID]
        interface = net.get(switch_name).intf()
        links_h2s.append([interface, linkCapacity])
    for link in switch_mover.active_link_pair_capacity_table:
        sw1 = switch_id_name_table[link[0]]
        sw2 = switch_id_name_table[link[1]]
        capacity = link[2]
        interfaces = net.get(sw1).connectionsTo(net.get(sw2))[0]
        interface1 = interfaces[0]
        interface2 = interfaces[1]
        # Initialize link with high value then set one side real value which is bottleneck for the whole link
        interface1.config(bw=capacity / DATA_SCALING, smooth_change=True)
        pair = "{}-{}".format(sw1, sw2)
        links_s2s[pair] = [sw1, interfaces, capacity, True]
        current_links.append(pair)
        if ONOS_LINK_ADD_MODE:
            link_manager.send_two_way_link_to_controller(interface1.sumo_id, interface2.sumo_id)

def initialize_network():
    # Tell mininet to print information
    setLogLevel(MININET_LOG_LEVEL)
    "Create drone network"
    topology = DroneTopology()
    mininet_network = Mininet(topo=topology, controller=RemoteController('main_controller', ip='127.0.0.1', port=6653),
                              switch=OVSKernelSwitch, host=CPULimitedHost, link=TCLink)
    return mininet_network

def start_network():
    global request_file_thread, listen_host_availability_thread, switch_mobility_thread
    # c1 = network.addController('c0', controller=RemoteController, ip=CONTROLLER_IP)
    # Add internet connection
    net.addNAT().configDefault()
    net.start()

    listen_host_availability_thread = threading.Thread(target=listen_host_availability)
    listen_host_availability_thread.setDaemon(True)
    listen_host_availability_thread.start()

    # CLI(net)
    get_initial_link_objects()
    CLI(net)
    # mediaServerIP = network.get("msrv").IP()
    # debug("mediaServerIP %s" % mediaServerIP)
    for h in net.hosts:
        h.popen("ping -c 1 10.0.0.1")
        if re.match(r"h[0-9]+", h.name):
            # itg_rec_signal_port = int(h.name[1:]) + 9000
            # processes.append(h.popen('ITGRecv -Sp %d -a %s' % (itg_rec_signal_port, h.IP())))
            if GENERATE_TRAFFIC:
                processes.append(h.popen('python streamer_host.py %s %s' % (h.IP(), simulation_id)))
        elif re.match(r"hs[0-9]+", h.name):
            if GENERATE_TRAFFIC:
                processes.append(h.popen('python streamer_host.py %s %s' % (h.IP(), simulation_id)))
    CLI(net)
    # hostMobilityThread = threading.Thread(target=moveHosts, kwargs={"host_number": NUMBER_OF_HOSTS,
    #                                                                 "switch_number": NUMBER_OF_SWITCHES,
    #                                                                 "interval": MOVE_EVENT_INTERVALS})
    # hostMobilityThread.setDaemon(True)
    # hostMobilityThread.start()
    switch_mobility_thread = threading.Thread(target=move_switches)
    switch_mobility_thread.setDaemon(True)
    switch_mobility_thread.start()

    request_file_thread = threading.Thread(target=request_file,
                                           kwargs={"scale_of_exponential": REQUEST_INTERVAL,
                                                   "host_number": NUMBER_OF_HOSTS,
                                                   "alpha_zipf_exponent": ALPHA_ZIPF,
                                                   "number_of_files": NUMBER_OF_FILES})
    request_file_thread.setDaemon(True)
    request_file_thread.start()

    debug(links_s2s)
    debug(links_h2s)

def copytree(src, dst, symlinks=False, ignore=None):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            shutil.copytree(s, d, symlinks, ignore)
        else:
            shutil.copy2(s, d)

def terminate_simulation():
    print("We are done!!")
    save_simulation_snapshot_to_file(current_time)
    report = media_server.get_caching_statistics()
    report["requests_from_depleted_drones"] = requests_from_depleted_drones
    report["current_time"] = current_time
    print(report)
    results_path = "results/%s" % simulation_id
    result_file = os.path.join(results_path, "result.json")
    if not os.path.isfile(result_file):
        os.makedirs(results_path)
        with open(result_file, "w+") as outfile:
            json.dump(report, outfile)
        subprocess.call(['chmod', '-R', '777', 'results'])
    try:
        listen_host_availability_thread.is_running = False
    except Exception as e:
        print(traceback.format_exc())
        print(e)
    try:
        request_file_thread.is_running = False
    except Exception as e:
        print(traceback.format_exc())
        print(e)
    try:
        switch_mobility_thread.is_running = False
    except Exception as e:
        print(traceback.format_exc())
        print(e)

if __name__ == '__main__':
    stop_children_processes(processes)

    link_manager = LinkManager()
    intent_manager = IntentManager()
    switch_mover = SwitchMover()
    drone_battery_manager = BatteryCapacityLogger()
    switch_operator = SwitchOperator(switch_mover, drone_battery_manager)
    media_server = MediaServer(switch_operator)

    net = initialize_network()
    start_network()

    CLI(net)
    terminate_simulation()

    stop_children_processes(processes)
    net.stop()


# Exercicio - Lista de tarefas com desfazer e refazer
# todo = [] -> lista de tarefas
# todo = ['fazer café'] -> Adiciona fazer café
# todo = ['fazer café', 'caminhar'] Adiciona caminhar
# desfazer = ['fazer café',] -> Refazer ['Caminhar']
# desfazer = [] -> Refazer ['caminhar', 'fazer café']
# refazer = todo ['fazer café]
# refazer = todo ['fazer café', 'caminhar']
import os
import json

def listar(tarefas):
    contador = 1
    print()
    if not tarefas:
        print('Nenhuma tarefa para listar.')
        print()
        return

    print('Tarefas:')
    for tarefa in tarefas:
        print(f'\t{contador} - {tarefa}')
        contador += 1
    print()

def desfazer(tarefas, tarefas_refazer):
    print()
    if not tarefas:
        print('Nenhuma tarefa para desfazer.')
        return
    tarefa = tarefas.pop()
    print(f'{tarefa} desfeita com sucesso.')
    tarefas_refazer.append(tarefa)
    print()
    listar(tarefas)

def refazer(tarefas, tarefas_refazer):
    if not tarefas_refazer:
        print('Nenhuma tarefa para refazer.')
        return
    tarefa = tarefas_refazer.pop()
    print(f'{tarefa} refeita com sucesso.')
    tarefas.append(tarefa)
    print()
    listar(tarefas)

def adicionar(tarefa, tarefas):
    tarefa = tarefa.strip()
    if not tarefa:
        print('Você não digitou nenhuma tarefa.')
    tarefas.append(tarefa)
    print()
    listar(tarefas)

def ler(tarefas, caminho_arquivo):
    dados = []
    try:
        with open(caminho_arquivo, 'r', encoding='utf8') as arquivo:
            dados = json.load(arquivo)
    except FileNotFoundError:
        salvar(tarefas, caminho_arquivo)
    return dados

def salvar(tarefas, caminho_arquivo):
    dados = tarefas
    with open(caminho_arquivo, 'w', encoding='utf8') as arquivo:
        dados = json.dump(tarefas, arquivo, indent=2, ensure_ascii=False)
    return dados

CAMINHO_ARQUIVO = 'aula123.json'
tarefas = ler([], CAMINHO_ARQUIVO)
tarefas_refazer = []

print('Comandos: ')
print('\tListar - Para listar')
print('\tDesfazer - Para desfazer')
print('\tRefazer - Para refazer')
print('\tClear - Para limpar o terminal')
print('\tSair - Para sair')

while True:
    tarefa = input('Digite um comando ou uma tarefa: ').lower()

    comandos = {
        'listar': lambda: listar(tarefas),
        'desfazer': lambda: desfazer(tarefas, tarefas_refazer),
        'refazer': lambda: refazer(tarefas, tarefas_refazer),
        'clear': lambda: os.system('cls'),
        'adicionar': lambda: adicionar(tarefa, tarefas),
    }
    comando = comandos.get(tarefa) if comandos.get(tarefa) is not None else \
        comandos['adicionar']
    comando()
    if tarefa == 'sair':
        break

    salvar(tarefas, CAMINHO_ARQUIVO)

    # if tarefa == 'listar':
    #     listar(tarefas)
    #     continue

    # elif tarefa == 'desfazer':
    #     desfazer(tarefas, tarefas_refazer)
    #     listar(tarefas)
    #     continue

    # elif tarefa == 'refazer':
    #     refazer(tarefas, tarefas_refazer)
    #     listar(tarefas)
    #     continue

    # elif tarefa == 'clear':
    #     os.system('cls')

    # elif tarefa == 'sair':
    #     os.system('cls')
    #     listar(tarefas)
    #     break

    # else:
    #     adicionar(tarefa, tarefas)
    #     listar(tarefas)
    #


#!/bin/python3
# ===========================
# Ar-Ray-code 2022
# ===========================

from PySide2.QtWidgets import QApplication, QWidget, QMessageBox
import sys
import argparse

class QuestionWidget(QWidget):
    def __init__(self):
        super().__init__()

        parser = argparse.ArgumentParser(description='Select folder')
        parser.add_argument('-t', '--title', help='title of dialog', default='Choose your answer')
        parser.add_argument('-al', '--answer-list', help='list of answers', nargs='+', default=['Connect', 'Abort'])

        args = parser.parse_args()

        self.title = args.title
        self.answer_list = args.answer_list

        self.create_widgets()

    def create_widgets(self):
        msgBox = QMessageBox()
        msgBox.setText(self.title)

        ans_get = []
        for ans in self.answer_list:
            ans_get.append(msgBox.addButton(ans, QMessageBox.ActionRole))

        msgBox.exec_()

        for ans in ans_get:
            if msgBox.clickedButton() == ans:
                print(ans.text())
                sys.exit(0)

        sys.exit(1)

def entry_point():
    app = QApplication(sys.argv)
    ex = QuestionWidget()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = QuestionWidget()


import sys, os
import numpy as np
import jax
import jax.numpy as jnp
from jax import random, grad, jit, vmap, jacfwd, jacrev
from functools import partial

class NuclearPotential(object):
    def __init__(self, nwalk, pot_name, pot_3b_name):
        self.nwalk=nwalk
        self.hc = 197.327053
        self.alpha = 1 / 137.03599
        self.b = 4.27
        if (pot_name == 'pionless_2'):
            self.vkr = 2.0
            self.v0r = -133.3431
            self.v0s = -9.0212
            self.ar3b = np.sqrt(68.48830)
            self.v_2b = self.pionless_2b
            self.v_3b = self.pionless_3b
        elif (pot_name == 'pionless_4'):
            self.vkr = 4.0
            self.v0r = -487.6128
            self.v0s = -17.5515
            self.ar3b = np.sqrt(677.79890)
            self.v_2b = self.pionless_2b
            self.v_3b = self.pionless_3b
        elif (pot_name == 'pionless_6'):
            self.vkr = 6.0
            self.v0r = -1064.5010
            self.v0s = -26.0830
            self.ar3b = np.sqrt(2652.65100)
            self.v_2b = self.pionless_2b
            self.v_3b = self.pionless_3b
        elif (pot_name == 'pionless_lo_a'):
            self.R0 = 1.7
            self.R1 = 1.5
            self.C01 = -4.38524414
            self.C10 = -8.00783936
            lamchi = 1000./self.hc
            fpi = 92.40/self.hc
            if (pot_3b_name == 'R3_1.0'):
               self.R3 = 1.0
               self.ce3b = 1.8354
            elif (pot_3b_name == 'R3_1.5'):
               self.R3 = 1.5
               self.ce3b = 4.6301
            elif (pot_3b_name == 'R3_2.0'):
               self.R3 = 2.0
               self.ce3b =  11.6871
            elif (pot_3b_name == 'R3_2.5'):
               self.R3 = 2.5
               self.ce3b =  27.4702
            else:
               self.R3 = 1.
               self.ce3b =  0
            self.ce3b = jnp.sqrt( self.ce3b / lamchi / fpi**4 * self.hc / jnp.pi**3 / self.R3**6 )
            self.v_2b = self.pionless_2b_lo
            self.v_3b = self.pionless_3b_lo
        elif (pot_name == 'pionless_lo_o'):
            self.R0 = 1.54592984
            self.R1 = 1.83039397
            self.C01 = -5.27518671
            self.C10 = -7.04040080
            lamchi = 1000./self.hc
            fpi = 92.40/self.hc
            if (pot_3b_name == 'R3_1.0'):
               self.R3 = 1.0
               self.ce3b = 1.0786
            if (pot_3b_name == 'R3_1.1'):
               self.R3 = 1.1
               self.ce3b = 1.2945
            elif (pot_3b_name == 'R3_1.5'):
               self.R3 = 1.5
               self.ce3b = 2.7676
            elif (pot_3b_name == 'R3_2.0'):
               self.R3 = 2.0
               self.ce3b =  6.95356
            elif (pot_3b_name == 'R3_2.5'):
               self.R3 = 2.5
               self.ce3b =  16.21993
            else:
               self.R3 = 1.
               self.ce3b =  0
            self.ce3b = jnp.sqrt( self.ce3b / lamchi / fpi**4 * self.hc / jnp.pi**3 / self.R3**6 )
            self.v_2b = self.pionless_2b_lo
            self.v_3b = self.pionless_3b_lo

        nr_test = 100
        r_test = jnp.linspace(0,5,nr_test)
        file_pot = open("pot_nn.dat", "w")
        pot_test = np.zeros(shape=(8,nr_test))
        pot_test[0,:] = r_test
        for i in range(r_test.shape[0]):
            pot_test[1:7,i] =  self.v_2b(r_test[i])
            pot_test[7,i] =  self.v_em(r_test[i])
        np.savetxt(file_pot, np.transpose(pot_test), delimiter=' ', newline=os.linesep)
        file_pot.close()

    @partial(jit, static_argnums=(0,))
    def pionless_2b(self, rr):
        pot_2b=jnp.zeros(6)
        x = self.vkr * rr
        vr = jnp.exp( -x**2 / 4.0 )
        pot_2b = pot_2b.at[0].set(self.v0r * vr)
        pot_2b = pot_2b.at[2].set(self.v0s * vr)
        return pot_2b

    @partial(jit, static_argnums=(0,))
    def pionless_3b(self, rr):
        x = self.vkr * rr
        vr = jnp.exp( -x**2 / 4.0 )
        pot_3b = self.ar3b * vr
        return pot_3b

    @partial(jit, static_argnums=(0,))
    def pionless_2b_lo(self, rr):
        pot_2b = jnp.zeros(6)
        C0_r = 1. / (jnp.sqrt(jnp.pi)*self.R0)**3*jnp.exp( -( rr / self.R0 )**2 )
        C1_r = 1. / (jnp.sqrt(jnp.pi)*self.R1)**3*jnp.exp( -( rr / self.R1 )**2 )
        pot_2b = pot_2b.at[0].set( 3. * ( self.C01 * C1_r + self.C10 * C0_r ) )
        pot_2b = pot_2b.at[1].set( self.C01 * C1_r - 3. * self.C10 * C0_r )
        pot_2b = pot_2b.at[2].set( -3. * self.C01 * C1_r + self.C10 * C0_r )
        pot_2b = pot_2b.at[3].set( -1. * ( self.C01 * C1_r + self.C10 * C0_r ) )
        pot_2b = pot_2b / 16. * self.hc
        return pot_2b

    @partial(jit, static_argnums=(0,))
    def pionless_3b_lo(self, rr):
        pot_3b = self.ce3b * jnp.exp( - ( rr / self.R3 )**2 )
        return pot_3b

    @partial(jit, static_argnums=(0,))
    def v_em(self, rr):
        rr = jnp.maximum(rr,0.0001)
        br = self.b * rr
        fcoul = 1 - (1 + 11 * br / 16 + 3 * br**2 / 16 + br**3 / 48) * jnp.exp(-br)
        pot_em = self.alpha * self.hc * fcoul / rr
        return pot_em


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('events', '0004_auto_20150221_2127'),
    ]

    operations = [
        migrations.CreateModel(
            name='CalendarEvent',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('description', models.TextField(null=True, blank=True)),
                ('start', models.DateField()),
                ('end', models.DateField(null=True, blank=True)),
                ('color', models.ForeignKey(blank=True, to='events.EventColor', null=True)),
                ('type', models.ForeignKey(to='events.EventType')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.RemoveField(
            model_name='event',
            name='color',
        ),
        migrations.RemoveField(
            model_name='event',
            name='type',
        ),
        migrations.DeleteModel(
            name='Event',
        ),
    ]


from github import Github
import csv
import os

def importStageThree(token, strRepo):
    g = Github(token)
    repo = g.get_repo(strRepo)

    #Read commit SHAs from data2.csv
    read_file = open('data2.csv', encoding='utf-8')
    csvreader = csv.DictReader(read_file)

    read_file_header = []
    read_file_header = next(csvreader)

    commits = []
    i = 0
    for row in csvreader:
        if i >= 1000:
            break
        commits.append(row)
        i += 1

    read_file.close()

    #Delete file if it exists
    file = 'data3.csv'
    if (os.path.exists(file) and os.path.isfile(file)):
        os.remove(file)

    csvFile = open(file, 'w+', encoding='utf-8')

    csv_columns = ['path','size']

    writer = csv.DictWriter(csvFile, fieldnames=csv_columns)
    writer.writeheader()

    for row in commits:
        git_tree = repo.get_git_tree(row['tree_SHA'], True)
        git_tree_list = git_tree.tree

        for i in range(len(git_tree_list)):
            if (git_tree_list[i].size != None):
                writer.writerow(
                    {
                        "path" : git_tree_list[i].path,
                        "size" : git_tree_list[i].size
                    }
                )

    csvFile.close()

def visualizeStageThree():
    print('TBD')


import pickle
from collections import defaultdict
from random import shuffle

pieces = {"N": ["knight", "night", "nike", "9", "nine", "ninth", "white", "flight", "light", "might"],
          "B": ["bishop", "ship"],
          "Q": ["queen", "quin", "green", "coin", "korean"],
          "K": ["king", "kink", "pink", "can", "sync", "qing", "ping", "change"],
          "": [""],
          "R": ["rook", "broke", "brook", "brooke", "ruk", "rooke", "rug", "rukh", "ruke", "route", "luke", "rup",
                "group", "rub", "crook", "rock", "rilke", "truck", "rue", "chuck", "ruck", "struck", "stroke", "rogue"]}
files = {"a": ["a", "aa", "eye", "hey", "i"], "b": ["b", "be", "bee", "by", "me", "p"], "c": ["c", "ce", "si", "sea"],
         "d": ["d", "de", "t", "ty", "the", "tea"],
         "e": ["e", "ee", "v", "yv", "y", "ye", "yee"],
         "f": ["f", "fe", "ff", "at"],
         "g": ["g", "ge", "j", "ja", "ji", "gi", "qi"], "h": ["h", "he", "age", "page", "paige"], "": [""]}
ranks = {"1": ["1", "one", "von", "van", "mon", "onne", "wang", "wong", "wan", "ven", "vaughn"],
         "2": ["2", "two", "to", "too", "ii"],
         "3": ["3", "three", "tree", "free"],
         "4": ["4", "four", "fore", "for", "fool", "full", "pool", "por", "poor", "force", "forth", "fault", "port",
               "fall"],
         "5": ["5", "five", "fight", "fife", "v"],
         "6": ["6", "six", "cigs", "sics", "stings", "sings", "tix"],
         "7": ["seven", "7"],
         "8": ["8", "eight"], "": [""]}

extra_data = [("95", "N5"), ("changeaah", "Ka8"), ("brookepaigega", "Rhg8"),
              ("epor", "e4"), ("ybor", "e4"), ("83", "a3"), ("84", "a4"), ("18", "a8"), ("indyto", "Qd2")]
extra_data = []  # Don't use extra data
data = []
for piece, piece_names in pieces.items():
    for piece_name in piece_names:
        for file, file_names in files.items():
            for file_name in file_names:
                for file2, file_names2 in files.items():
                    for file_name2 in file_names2:
                        if file == file2:
                            continue
                        for rank, rank_names in ranks.items():
                            for rank_name in rank_names:
                                name = piece_name + file_name + file_name2 + rank_name
                                notation = piece + file + file2 + rank
                                if file and file2:
                                    if piece not in ["", "N", "R"]:
                                        continue
                                    file_difference = abs(ord(file) - ord(file2))
                                    file_difference_allowed = 7
                                    if piece == "":
                                        file_difference_allowed = 1
                                    elif piece == "N":
                                        file_difference_allowed = 2
                                    if file_difference > file_difference_allowed:
                                        continue
                                data.append(
                                    (name, notation))

for piece, piece_names in pieces.items():
    for piece_name in piece_names:
        data.append((piece_name, piece))

for file, file_names in files.items():
    for file_name in file_names:
        data.append((file_name, file))

for rank, rank_names in ranks.items():
    for rank_name in rank_names:
        data.append((rank_name, rank))

# Always take longest notation if there are duplicate names
# longest = defaultdict(list)
# for name, notation in data:
#    longest[name].append(notation)

# for name in longest.keys():
#    longest[name].sort(key=lambda x: len(x), reverse=True)

# data = [(name, notations[0]) for name, notations in longest.items()]

# Always take shortest notation if there are duplicate names
shortest = defaultdict(list)
for name, notation in data:
    shortest[name].append(notation)

for name in shortest.keys():
    shortest[name].sort(key=lambda x: len(x))

data = [(name, notations[0]) for name, notations in shortest.items()]

data = list(set(data))

length_dict = defaultdict(int)
length_data = defaultdict(list)
for name, notation in data:
    length_dict[len(notation)] += 1
    length_data[len(notation)].append((name, notation))
shuffle(length_data[4])
length_data[4] = length_data[4][:len(length_data[3]) // 2]
data = length_data[1] + length_data[2] + length_data[3] + length_data[4] + extra_data
print(data)
print(len(data))
print(length_dict)
filename = 'data.bin'
outfile = open(filename, 'wb')
pickle.dump(data, outfile)
outfile.close()