from flask import Flask
from flask import render_template, url_for, request, flash, redirect
import sqlite3
import transferserver
import chatserver
import _thread
import threading
import multiprocessing

app = Flask(__name__)
app.secret_key = "supersecretkey"

all_processes = []

def createTableData():

    items = []

    conn = sqlite3.connect('serversdatabase.db')
    cur = conn.cursor()

    try:
        cur.execute('SELECT * FROM servers')
        conn.commit()
    except:
        cur.execute("CREATE TABLE servers(name TEXT, type TEXT, port TEXT, status TEXT)")
        conn.commit()

    liste = cur.fetchall()

    for i in liste:
        templist = ['name', 'type', 'port', 'status']
        tempdict = {}

        cpt = 0
        for j in i:
            tempdict[templist[cpt]] = j
            cpt += 1

        items.append(tempdict)

    cur.close()
    conn.close()

    return items

def bootAllServers():

    global all_processes

    items = []

    conn = sqlite3.connect('serversdatabase.db')
    cur = conn.cursor()

    cur.execute('SELECT * FROM servers')
    conn.commit()

    liste = cur.fetchall()

    for i in liste:
        templist = []
        cpt = 0
        for j in i:
            templist.append(j)
            cpt += 1
        items.append(templist)

    cur.close()
    conn.close()

    for row in items:

        if row[3] == "Up":

            process = multiprocessing.Process(target=startOneServ, args=(row[0], row[1], row[2]))
            process.start()
            all_processes.append([process, row[0]])

@app.route("/backend/addServer", methods=['POST'])
def addServer():

    namevar = request.form['name']
    typevar = request.form['type']
    portvar = request.form['port']
    statusvar = "Down"

    conn = sqlite3.connect('serversdatabase.db')
    cur = conn.cursor()

    data = (namevar, typevar, portvar, statusvar)

    cur.execute("INSERT INTO servers(name, type, port, status) VALUES(?, ?, ?, ?)", data)

    conn.commit()

    cur.close()
    conn.close()

    flash("Server added.")

    headers = ["Server's name", "Server's type", 'Port', 'Status']

    return redirect(url_for('index'))
    return render_template('index.html', headers=headers, objects=createTableData())

@app.route("/backend/deleteServer", methods=['POST'])
def deleteServer():

    namevar = request.form['name']
    typevar = request.form['type']
    portvar = request.form['port']

    conn = sqlite3.connect('serversdatabase.db')
    cur = conn.cursor()

    data = (namevar, typevar, portvar)

    cur.execute('SELECT * FROM servers WHERE name = ? AND type = ? AND port = ?', data)
    conn.commit()

    liste = cur.fetchall()

    if len(liste) > 0:

        cur.execute('DELETE FROM servers WHERE name = ? AND type = ? AND port = ?', data)
        flash("Server deleted.")
        conn.commit()

    else:
        flash("Error. Please check and retry server's information.")

    headers = ["Server's name", "Server's type", 'Port', 'Status']

    return redirect(url_for('index'))
    return render_template('index.html', headers=headers, objects=createTableData())

def startOneServ(name, type, port):

    if type == "File transfer":

        x = name
        vars()[x] = name

        name = transferserver.Server(int(port))
        print(x + " started.")
        name.start()

        statusvar = "Up"

        conn = sqlite3.connect('serversdatabase.db')
        cur = conn.cursor()

        data = (statusvar, x, type, port)

        cur.execute('UPDATE servers SET status = ? WHERE name = ? AND type = ? AND port = ?', data)
        conn.commit()

    elif type == "Chat":

        x = name
        vars()[x] = name

        name = chatserver.listening_serv(int(port))

        print(x + " started.")

        name.run()

        statusvar = "Up"

        conn = sqlite3.connect('serversdatabase.db')
        cur = conn.cursor()

        data = (statusvar, x, type, port)

        cur.execute('UPDATE servers SET status = ? WHERE name = ? AND type = ? AND port = ?', data)
        conn.commit()

@app.route("/backend/startServer", methods=['POST'])
def startServer():

    global all_processes

    namevar = request.form['name']
    typevar = request.form['type']
    portvar = request.form['port']

    statusvar = "Up"

    conn = sqlite3.connect('serversdatabase.db')
    cur = conn.cursor()

    data = (statusvar, namevar, typevar, portvar)

    cur.execute('UPDATE servers SET status = ? WHERE name = ? AND type = ? AND port = ?', data)
    conn.commit()

    process = multiprocessing.Process(target=startOneServ, args=(namevar, typevar, portvar))
    process.start()
    all_processes.append([process, namevar])

    print(namevar + " started.")

    headers = ["Server's name", "Server's type", 'Port', 'Status']

    return redirect(url_for('index'))
    return render_template('index.html', headers=headers, objects=createTableData())

@app.route("/backend/stopServer", methods=['POST'])
def stopServer():

    global all_processes

    namevar = request.form['name']
    typevar = request.form['type']
    portvar = request.form['port']

    statusvar = "Down"

    conn = sqlite3.connect('serversdatabase.db')
    cur = conn.cursor()

    data = (statusvar, namevar, typevar, portvar)

    cur.execute('UPDATE servers SET status = ? WHERE name = ? AND type = ? AND port = ?', data)
    conn.commit()

    for proc in range(0, len(all_processes)):
        if all_processes[proc][1] == namevar:
            all_processes[proc][0].terminate()
            all_processes.pop(proc)

    headers = ["Server's name", "Server's type", 'Port', 'Status']

    return redirect(url_for('index'))
    return render_template('index.html', headers=headers, objects=createTableData())

@app.route("/backend/stopAllServers", methods=['POST'])
def stopAllServers():

    global all_processes

    statusvar = "Down"

    conn = sqlite3.connect('serversdatabase.db')
    cur = conn.cursor()

    data = (statusvar,)

    cur.execute('UPDATE servers SET status = ?', data)
    conn.commit()

    for proc in range(0, len(all_processes)):
        all_processes[proc][0].terminate()
        all_processes.pop(proc)

    headers = ["Server's name", "Server's type", 'Port', 'Status']

    return redirect(url_for('index'))
    return render_template('index.html', headers=headers, objects=createTableData())

@app.route('/')
def index():

    headers = ["Server's name", "Server's type", 'Port', 'Status']

    return render_template('index.html', headers=headers, objects=createTableData())

if __name__ == '__main__':

    boot = threading.Thread(target=bootAllServers)
    boot.start()

    app.run(debug=True)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 16:01:01 2020

@author: chen

549. Binary Tree Longest Consecutive Sequence II
Medium

535

41

Add to List

Share
Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree.

Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid. On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.

Example 1:

Input:
        1
       / \
      2   3
Output: 2
Explanation: The longest consecutive path is [1, 2] or [2, 1].

Example 2:

Input:
        2
       / \
      1   3
Output: 3
Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].

Note: All the values of tree nodes are in the range of [-1e7, 1e7].

"""

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def longestConsecutive(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def longest_path(root):
            if not root:
                return 0, 0
            inc, dec = 1, 1
            l_inc, l_dec = longest_path(root.left)
            r_inc, r_dec = longest_path(root.right)
            if root.left:
                if root.left.val == root.val + 1:
                    inc = max(inc, 1 + l_inc)
                if root.left.val == root.val - 1:
                    dec = max(dec, 1 + l_dec)
            if root.right:
                if root.right.val == root.val + 1:
                    inc = max(inc, 1 + r_inc)
                if root.right.val == root.val - 1:
                    dec = max(dec, 1 + r_dec)
            res[0] = max(res[0], inc + dec - 1)
            return (inc, dec)

        res = [0]
        longest_path(root)
        return res[0]

549_Binary Tree Longest Consecutive Sequence II.py


from typing import Optional

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def getMinimumDifference(root: Optional[TreeNode]) -> int:
    xs = []
    def traverse(node):
        if not node:
            return
        traverse(node.left)
        xs.append(node.val)
        traverse(node.right)

    traverse(root)
    min_diff = float("infinity")
    for a, b in zip(xs, xs[1:]):
        min_diff = min(min_diff, abs(a - b))

    return min_diff


# Fix tabular format
import sys
import os
import time

stime = time.time()

score = None
scoreDict = {}
rows = []
for n, line in enumerate(open(sys.argv[1])):
    if n<=1: continue
    line = line.strip().split()
    if len(line) > 0:
        if line[0] =="a":
            score = float(line[1].replace("score=", ""))
            rows = []
            continue
        elif line[0] == "s":
            rows.append(line[0:6])
            continue
    elif len(line) == 0 and score is not None:
            try:
                evalue = (float(rows[0][5]) * float(rows[1][5])) / (2 ** score)
            except:
                evalue = 0.0
            if rows[1][4] == "-":
                fixBp = int(rows[1][5]) - 1 - int(rows[1][2])
                scoreDict["{}_{}_{}_{}".format(rows[0][1], int(rows[0][2]), rows[1][1], fixBp )] = (evalue, score)
            else:
                scoreDict["{}_{}_{}_{}".format(rows[0][1], int(rows[0][2]), rows[1][1], int(rows[1][2]))] = (evalue, score)
            score = ""
    else:
        continue

for line in open(sys.argv[2]):
    line = line.strip().split()
    evalue, score = scoreDict["{}_{}_{}_{}".format(line[1], int(line[8])-1, line[0], int(line[6]) - 1)]
    if score > 0: print("{}\t{:.2e}\t{}".format('\t'.join(line), evalue, int(score)))


# -*- coding: utf-8 -*-
#导入其他模块的符号集，Urllib 模块提供了读取web页面数据的接口，
#使我们可以像读取本地文件一样读取www和ftp上的数据
import urllib.request
import re
import html.parser as h
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
#定义函数，urllib.urlopne()打开一个url地址，read()方法读取url上的数据，
#返回网页，即将页面下载下来
def getHtml(url):
    page = urllib.request.urlopen(url)
    #print(page.info())
    html = page.read()
    return html

#输出该网页内容
#print (html)

#获取图片
def getImg(html):
    reg = r''
    imgre = re.compile(reg)
    #html=html.encode('utf-8')
    imglist = re.findall(imgre,html)
    print("the informations of images")
    print(imglist)
    x=0
    for imgre in imglist:
        urllib.request.urlretrieve(imgre,'%s.jpg'%x)
        x=x+1

def getAuthor(html):
	#作者姓名
    reau=r'
(.*?)
'
    #author=re.compile(reau)
    author_list=re.findall(reau,html,re.S|re.M)
    print('the name of author:')
    for content in author_list:
        print(content)

    #作者信息
    reau1=r'
(.*?)
'
    author_list=re.findall(reau1,html,re.S|re.M)
    #print("the author_list is:",author_list)
    print('the informations of author:')
    for content in author_list:
        if "href" not in content:
    	    print(content)
        else:
    	    print('the research direction of author:')
    	    reau3=r'(.*?)'
    	    author_direction=re.findall(reau3,content,re.S|re.M)
    	    print(author_direction)
    	    #if content in author_direction:
    	        #print(content)
    	    #print(content)
    #print(author_list)
    reau2=r'
(.*?)
'
    author_list=re.findall(reau2,html,re.S|re.M)
    print('the email of author:')
    for content in author_list:
    	print(content)

    #发表过的论文，论文信息存在html的table标签内,tr行td列
    res_tr=r'
(.*?)
'#第一行
    m_tr=re.findall(res_tr,html,re.S|re.M)
    for line in m_tr:
        res_td=r'(.*?)	'#第一列
        m_td=re.findall(res_td,line,re.S|re.M)
        for mm in m_td:
            if "href" in mm:#第一列内a标签
                restr = r'(.*?)'
                h = re.findall(restr,mm,re.S|re.M)
                print("The name of the paper:")
                print(h),
            if "class" in mm:#第一列内div标签
                restr=r'
(.*?)
'
                h2=re.findall(restr,mm,re.S|re.M)
                print("author names,Magazine name and date of publication:")
                print(h2)

    #合作过的学者信息,信息在html的ul标签内
    res_ul=r'
(.*?)
'
    m_ul=re.findall(res_ul,html,re.S|re.M)
    for line in m_ul:
        if "href" in line:
            #print(line)
            restr=r'(.*?)'
            h3=re.findall(restr,line,re.S|re.M)
            print("the name of cooperative scholars:")
            #h3=unicode(h3).encode("utf-8")
            print(h3)

    #页面内的url
    res_url = r"(?<=href=\").+?(?=\")|(?<=href=\').+?(?=\')"
    link = re.findall(res_url, html, re.I|re.S|re.M)
    print('the url list:')
    for url in link:
        print (url)

url=["https://scholar.google.com/citations?user=hNTyptAAAAAJ&hl=en","https://scholar.google.com/citations?user=Jj00ksMAAAAJ&hl=en","https://scholar.google.com/citations?user=09kJn28AAAAJ&hl=en","https://scholar.google.com/citations?user=q92q8SMAAAAJ&hl=en"]
y=0
for u in url:
    #print(url[0])
    #print(url[1])
    html = getHtml(url[y])
    #print(html)
    html=html.decode('ISO-8859-1')#ISO-8859-1
    getAuthor(html)
    #getImg(html)
    y=y+1


# Alex Johnson
# CS 4300 - Computer Graphics
# Assignment 06 - 3D Animation
# Part I : Scripting

# Initial source code from '3D_Scripting_Mac/CS4800/simple_animation.py'
# These scripts have been included in the .zip file, and can be
# found in the '/examples folder'.

# Maya's Python commands can be found online at:
# http://download.autodesk.com/us/maya/2010help/CommandsPython/index_all.html

import maya.cmds as cmds
import random

# Start scene with a "clean slate"
# -> erase any artifacts on stage
newfile = cmds.file(f=True, new=True)

#*************************************
#       Scene Configuration
#*************************************

# Set playback options
cmds.playbackOptions( loop='continuous' )
cmds.playbackOptions( minTime='0sec', maxTime='5sec', ast=0, ps=1.8)

# set initial perspective position
cmds.setAttr('persp.translateX', -15.000)
cmds.setAttr('persp.translateY', 10.000)
cmds.setAttr('persp.translateZ', 20.000)

# set initial perspective angle
cmds.setAttr('persp.rotateX', -15.000)
cmds.setAttr('persp.rotateY', -35.000)
cmds.setAttr('persp.rotateZ', 0.000)

#*************************************
#      Object Configuration
#*************************************

# Create a sphere, with 10 subdivisions in the X direction,
# and 15 subdivisions in the Y direction,
# the radius of the sphere is 20.
# http://download.autodesk.com/us/maya/2010help/CommandsPython/polySphere.html
cmds.polySphere(n='sphere01', sx=15, sy=20, r=1)

# Query the radius of the new sphere
r = cmds.polySphere('sphere01', q=True, sx=True )

# Set sphere's pivot point to the bottom.
# -> Makes scaling the sphere upon collision easier
cmds.move(0, -1, "sphere01.scalePivot","sphere01.rotatePivot", absolute=True)

# Create polygon cube (Ground)
# result is a 20 units height rectangular box
# with 10 subdivisions along X, 15 along Y and 20 along Z.
c = cmds.polyCube(sx=10, sy=15, sz=5, h=.25, w=5, d=5)
cmds.setKeyframe(c, v=-0.3, at='translateY', itt='linear', ott='linear', t = 0)

#*************************************
#     Perspective Movement
#*************************************

## Pull Back perspective over 200 frames.
# start perspective change
cmds.setKeyframe( 'persp', v=-20,      at='translateX', itt='linear', ott='linear', t = 0)
cmds.setKeyframe( 'persp', v=15,       at='translateY', itt='linear', ott='linear', t = 0)
cmds.setKeyframe( 'persp', v=25,       at='translateZ', itt='linear', ott='linear', t = 0)

# finish perspective change
cmds.setKeyframe( 'persp', v=-15,    at='translateX', itt='linear', ott='linear', t = 200)
cmds.setKeyframe( 'persp', v=10,     at='translateY', itt='linear', ott='linear', t = 200)
cmds.setKeyframe( 'persp', v=20,     at='translateZ', itt='linear', ott='linear', t = 200)

#*************************************
#      Camera Configuration
#*************************************

## Create camera
cameraName = cmds.camera()
cameraShape = cameraName[1]

#*************************************
#      Camera Movement
#*************************************

## Move camera through scene
# Camera Start Position
cmds.setKeyframe(cameraName, v=6.8,       at='translateX', itt='spline', ott='spline', t = 0)
cmds.setKeyframe(cameraName, v=9.5,       at='translateY', itt='spline', ott='spline', t = 0)
cmds.setKeyframe(cameraName, v=15.8,      at='translateZ', itt='spline', ott='spline', t = 0)

cmds.setKeyframe(cameraName, v=-24.3,     at='rotateX', itt='spline', ott='spline', t = 0)
cmds.setKeyframe(cameraName, v=22.7,      at='rotateY', itt='spline', ott='spline', t = 0)
cmds.setKeyframe(cameraName, v=0,         at='rotateZ', itt='spline', ott='spline', t = 0)

# Camera End Position
cmds.setKeyframe(cameraName, v=-3.3,      at='translateX', itt='spline', ott='spline', t = 150)
cmds.setKeyframe(cameraName, v=4.0,       at='translateY', itt='spline', ott='spline', t = 150)
cmds.setKeyframe(cameraName, v=5.6,       at='translateZ', itt='spline', ott='spline', t = 150)

cmds.setKeyframe(cameraName, v=-18.3,     at='rotateX', itt='spline', ott='spline', t = 150)
cmds.setKeyframe(cameraName, v=-34.1,     at='rotateY', itt='spline', ott='spline', t = 150)
cmds.setKeyframe(cameraName, v=0.0,       at='rotateZ', itt='spline', ott='spline', t = 150)

#*************************************
#    Sphere Animation - Translate
#*************************************

# Animate a sphere as it bounces vertically.
# Translate manages it's vertical position

cmds.setKeyframe( 'sphere01', v=6.0,     at='translateY', itt='spline', ott='spline', t = 60)
cmds.setKeyframe( 'sphere01', v=1.0,     at='translateY', itt='spline', ott='spline', t = 90)
cmds.setKeyframe( 'sphere01', v=1.0,     at='translateY', itt='spline', ott='spline', t = 110)
cmds.setKeyframe( 'sphere01', v=5.5,     at='translateY', itt='spline', ott='spline', t = 160)

#*************************************
#    Sphere Animation - Scale
#*************************************

# Animate a sphere as it bounces vertically.
# Scale manages the shape deformation/compressions

# Initial keyframe
cmds.setKeyframe( 'sphere01', v=1.0,     at='scaleY', itt='linear', ott='linear', t = 60)

# Start Compression
cmds.setKeyframe( 'sphere01', v=1.0,     at='scaleX', itt='linear', ott='linear', t = 90)
cmds.setKeyframe( 'sphere01', v=1.0,     at='scaleY', itt='linear', ott='linear', t = 90)
cmds.setKeyframe( 'sphere01', v=1.0,     at='scaleZ', itt='linear', ott='linear', t = 90)

# Max Compression
cmds.setKeyframe( 'sphere01', v=1.3,     at='scaleX', itt='spline', ott='spline', t = 100)
cmds.setKeyframe( 'sphere01', v=0.6,     at='scaleY', itt='spline', ott='spline', t = 100)
cmds.setKeyframe( 'sphere01', v=1.3,     at='scaleZ', itt='spline', ott='spline', t = 100)

# End Compression
cmds.setKeyframe( 'sphere01', v=1.0,     at='scaleX', itt='linear', ott='linear', t = 110)
cmds.setKeyframe( 'sphere01', v=1.0,     at='scaleY', itt='linear', ott='linear', t = 110)
cmds.setKeyframe( 'sphere01', v=1.0,     at='scaleZ', itt='linear', ott='linear', t = 110)

# End rebound compressions
cmds.setKeyframe( 'sphere01', v=1.2,     at='scaleY', itt='linear', ott='linear', t = 130)

# Final keyframe
cmds.setKeyframe( 'sphere01', v=1.0,     at='scaleY', itt='linear', ott='linear', t = 150)


#create basic map
##import random
##maps['default']=[]
##for y in range(50):
##    maps['default'].append([])
##    for x in range(50):
##        maps['default'][y].append(random.choice(["d", "g", "l", "s"]))

maps['default']=load_map(path('maps','theroad.py'))

#basic isometric world: a campaign can specify a new Two,
#or it can create a new class that inherets from World, that
#way they have access to every element of the engine :D
world=isometric.World(map=maps['default'],
                      tiles=terrain,
                      tile_size=[100, 50])

#the starting camera pos, change this to where you place
#the players first house, or to where you want them to start
camera_pos=[-10,-10]

#create basic race and other datas :)
#any of these things can be left blank, but it is recommended that you fill them ;)
races['default']=Race(name="default",#name and race['name'] should be the same
                      captain_image=images['coil_captain'],#the image for a unit that doesnt have your elder
                      elder_image=images['coil_elder'],#the image for your elder unit
                      house_image=images['building/coil_tower'],
                      soldier_types={"Shock":{"speed":1,
                                              "attack":2,
                                              "defense":1,
                                              "dodge":1,
                                              'consumes':1}},
                      flag_image=images['flag'],
                      select_image=images['select'],
                      bubbles=images['bubbles'],
                      start_troops=100,
                      start_food=100,
                      house_food_production=2,#amount per 5 seconds
                      house_troop_production=10)#seconds

# and a race for the baddies
races['frostlen']=Race(name="frostlen",#name and race['name'] should be the same
                      captain_image=images['frostlen_captain'],#the image for a unit that doesnt have your elder
                      elder_image=images['frostlen_elder'],#the image for your elder unit
                      house_image=images['building/frostlen_castle'],
                      soldier_types={"Shock":{"speed":1,
                                              "attack":1,
                                              "defense":1,
                                              "dodge":1,
                                              'consumes':1}},
                      flag_image=images['flag'],
                      select_image=images['select'],
                      bubbles=images['bubbles'],
                      start_troops=75,
                      start_food=75,
                      house_food_production=2,#amount per 5 seconds
                      house_troop_production=10)#seconds

races['vampire']=Race(name="vampire",#name and race['name'] should be the same
                      captain_image=images['vampire_captain'],#the image for a unit that doesnt have your elder
                      elder_image=images['vampire_elder'],#the image for your elder unit
                      house_image=images['building/lycan_lair'],
                      soldier_types={"Shock":{"speed":1,
                                              "attack":1,
                                              "defense":1,
                                              "dodge":1,
                                              'consumes':1}},
                      flag_image=images['flag'],
                      select_image=images['select'],
                      bubbles=images['bubbles'],
                      start_troops=65,
                      start_food=65,
                      house_food_production=2,#amount per 5 seconds
                      house_troop_production=10)#seconds

#the campaign stuff, which includes actually creating players and stuff will
#go here later, for now just make the races ;)

new_campaign=Campaign(name="basic")

thePlayer = Player("jimbob", races['default'], color=[125,0,175,255])
thePlayer.create_house(world, [11,9])
thePlayer.create_house(world, [12,11])
thePlayer.houses[0].make_unit("bob II", 50)
thePlayer.houses[1].make_unit("bob III", 50)

badGuyOne = Player("evilDoer", races['frostlen'])
badGuyOne.create_house(world, [8,16])
badGuyOne.create_house(world, [20,25])
badGuyOne.houses[0].make_unit("Evil Minion",65)
badGuyOne.houses[1].make_unit("Bad Mr. Frosty",15)
badGuyOne.houses[1].make_unit("Mr. Snow-Evils",15)
badGuyOne.armies[0].goto = [11,9]

badGuyTwo = Player("vampy", races['vampire'])
badGuyTwo.create_house(world, [20,8])
badGuyTwo.houses[0].make_unit("Vampireguy",65)
badGuyTwo.ai = ChaserAI(badGuyTwo,enemies=[thePlayer, badGuyOne])

badGuyOne.ai = ChaserAI(badGuyOne,enemies=[badGuyTwo])

event1_trigger = """if player.active_entity and not player.active_entity.tile_pos==[0,0]:trigger=True"""
event1_event = "bottompanel.get('messages').add_message('You moved your unit! Great Job!')"
event1 = Event(trigger = event1_trigger, event = event1_event)

scenario1=Scenario(name="scenario1", events=[event1], player=thePlayer, enemies = [badGuyOne, badGuyTwo])

scenario1.cities=[]
scenario1.cities.append(City(world, 'Hello', 150,
                             images['city/camp'],
                             [2,1]))

new_campaign.scenarios['scenario1']=scenario1
new_campaign.start_scenario='scenario1'
new_campaign.current_scenario=scenario1

campaigns['default']=new_campaign


#Basic tests I hope to get
#Test to see if a chosen number breaks the collatz conjecture
#add that number to a list of numbers that work
#add all the numbers that were required to show that the first number works to a list
#(if var(a) is 16, it will go 16, 8, 4, 2, 1. Add all of those numbers to a list)
#With this list, I should be able to make a program that checks to see if a number is part of a list
#So I can quickly 'prove' the collatz conjecture without infinite calculations
import time

print('This runs the collatz conjecture for everynumber from 1 to 1000000.')

quick = []
#Make a list for every number that works
#time.sleep(3)

for i in range(1, 1000001, 1):
    a = i
    if a in quick:
            a = 1
    else:
        c = i
        while a != 1:
                if a % 2 == 0:
                        b = a
                        a = b / 2
                else:
                        b = a
                        a = b * 3 + 1
        quick.append(c)
print(quick)


"""
This script includes the Demo class to perform the object instance
segmentation demo.
"""

import os
import cv2
import pycocotools.mask as pycocomask

from detectron2.data.datasets import register_coco_instances
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog, DatasetCatalog
from detectron2.utils.visualizer import ColorMode

class Demo:
    """
    The Demo class provides functions to demonstrate object instance
    segmentation on a COCOpen-generated datset.
    ...

    Attributes
    ----------
    parameters : dict
        contains all parameters used to generate the demo dataset

    Methods
    -------
    make_new_dirs():
        Make new directories where the demo files are saved
    demo():
        Runs the demo to visualize object instance segmentation
    """

    # Constructor
    def __init__(
        self,
        parameters: dict,
    ) -> None:
        # Initializing parameters
        self.parameters = parameters

        # Initializing root and destination directory
        self.root_dir = self.parameters["directory"]["root_dir"]
        self.data_dir_name = self.parameters["directory"]["dataset_dir_name"]

        # Saving all directory names
        self.dataset_dir = self.root_dir + f"/datasets/{self.data_dir_name}"
        self.demo_dir = self.root_dir + "/demo"
        self.demo_dataset_dir = self.demo_dir + f"/{self.data_dir_name}"
        self.vis_dir = self.demo_dataset_dir + "/visualization"
        self.mask_dir = self.demo_dataset_dir + "/masks"

    def make_new_dirs(self):
        """
        Make new directories where the demo files are saved
        """
        try:
            os.mkdir(self.demo_dir)
        except FileExistsError:
            print("demo directory already exists!")
        try:
            os.mkdir(self.demo_dataset_dir)
        except FileExistsError:
            print("demo dataset directory already exists!")
        try:
            os.mkdir(self.vis_dir)
        except FileExistsError:
            print("visualization directory already exists!")
        try:
            os.mkdir(self.mask_dir)
        except FileExistsError:
            print("masks directory already exists!")

    def demo(self):
        """
        Runs the demo to visualize object instance segmentation
        """
        data = self.parameters["dataset_verification"]["which_dataset"]
        register_coco_instances(
            data,
            {},
            f"{self.dataset_dir}/{data}/{data}.json",
            f"{self.dataset_dir}/{data}/",
        )
        dicts = DatasetCatalog.get(f"{data}")
        metadata = MetadataCatalog.get(f"{data}")

        count = self.parameters["dataset_verification"]["number_of_images"]
        for i, d in enumerate(dicts[:count]):
            img = cv2.imread(d["file_name"])
            annos = d["annotations"]
            mask_list = []
            for anno in annos:
                encoded = anno["segmentation"]
                instance_annotation = pycocomask.decode(encoded) * 255
                instance_img = cv2.cvtColor(instance_annotation, cv2.COLOR_GRAY2BGR)
                x, y, w, h = anno["bbox"]
                mask = cv2.rectangle(
                    instance_img, (x, y), (x + w, y + h), (255, 255, 255), 2
                )
                mask_list.append(mask)

            # horizontally concatenate visualization of object instance
            # segmentation masks
            cat_masks = cv2.hconcat(mask_list)

            # visualize object instance segmentation on cocopen-generated data
            visualizer = Visualizer(
                img, metadata, scale=0.5, instance_mode=ColorMode.IMAGE
            )
            out = visualizer.draw_dataset_dict(d)

            # save masks and visualizations
            cv2.imwrite(f"{self.vis_dir}/{str(i)}.png", out.get_image())
            cv2.imwrite(f"{self.mask_dir}/{str(i)}.png", cat_masks)


import calculator
import os
import unit_converter

def user_choice():
    while True:
        print("What do you want to do?")
        user_input = input("1. Calculate numbers\n2. Convert units\n3. Exit\n")
        if user_input == "":
            print("Field cannot be empty.")
        else:
            return int(user_input)

def next_action():
    action_continue = input("If you want to continue press ENTER")
    if not action_continue:
        os.system('cls' if os.name == 'nt' else 'clear')

user_input = user_choice()

while user_input == 1 or 2 or 3:
    if user_input == 1:
        print("Calculator supports these operations", calculator.operations_list())

        calculator.get_result()

        next_action()

    elif user_input == 2:
        unit_converter.print_units_list()

        unit_converter.get_result()

        next_action()

    elif user_input == 3:
        break

    user_input = user_choice()


"""
in this module we shall aim to address swapping the positive and negative elements
in a list so that the negative elments appear firs then the positive ones. No order is
required
"""

def rearrange_pos_neg_numbers_in_list(li):
    start_index = 0

    for index in range(start_index, len(li)):
        if li[index] > 0:
            for inner_index in reversed(range(start_index + 1, len(li))):
                if li[inner_index] < 0:
                    li[index], li[inner_index] = li[inner_index], li[index]
                if inner_index == index:
                    break

    return li

li = [-21, 9, -1, 2, -3, 13, -4, -17, 12]

print(rearrange_pos_neg_numbers_in_list(li))


# code for https://adventofcode.com/2022/day/1 problem 1
# program contants
INPUTFILE = "../input.txt"  # the file with our puzzle input

def main():
    # will contain our answer: the number of calories held by
    # the elf with the most calories of food in their inventory
    mostFoodCarried = 0

    # read our input to a string
    with open(INPUTFILE) as f:
        data = f.read().strip()

    # each elf has an inventory seperated by a blank line
    inventories = data.split("\n\n")
    for inventory in inventories:
        # each inventory consists of numbers of calories, one number per line
        calCounts = inventory.split("\n")
        # we sum these numbers to get the total calories in the inventory
        total = sum([int(calCount) for calCount in calCounts])
        # we compare this to our current maximum and change it if it's bigger
        mostFoodCarried = max(total, mostFoodCarried)

    print(mostFoodCarried)

if __name__ == "__main__":
    main()


"""
Heat load estimation for the RADES-BabyIAXO cryostat.

Multiple unsorted approaches and calculations.

09.06.2021
"""

import math
import numpy as np
import scipy as sp
from scipy import constants
from scipy import optimize
from scipy import integrate
import matplotlib.pyplot as plt

from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

################################################################################
## 1.1 Definition of the functions used in the later calculation ##

# Function: calculating the surface of a cylinder depending on the length and the diameter
def surface_cylinder(L, D):
    A = sp.constants.pi * D * L + 2 * sp.constants.pi * D**2 / 4
    return A #m²

#Function: calculating the heat load of conduction according to Fourier's law
def Q_cond(A_surface, d_distance, T_hot, T_cold, lambda_cond):
    return A_surface * lambda_cond * 1/d_distance * (T_hot - T_cold) #W

# Function: calculating the heat load of thermal radiation for a cold surface which is enclosed by a warm surface
# According to "Tieftemperaturtechnologie" by Frey and Ekin for diffuse reflection
def Q_therm_rad(A_hot, A_cold, T_hot, T_cold, epsilon_hot, epsilon_cold):
    # Emission coefficent for an enclosed vessel
    epsilon_effective = 1/ (1/epsilon_cold + A_cold/A_hot * (1/epsilon_hot - 1)) #-
    # Simple equation with an effective emission coefficent
    Q_rad = epsilon_effective * sp.constants.Stefan_Boltzmann * A_cold * (T_hot**4 - T_cold**4) #W
    return Q_rad #W

# Function: calculating the heat load of gas conduction between the hot vessel and the colder MLI
# Assumption: mean free path >> distance between the walls
# According to Grohmann lecture and Frey and Ekin (Ekin already simplified a lot)
def Q_gas_cond(A_cold, T_hot, T_cold, pressure_vac):
    # Equation to calculate acommodation coefficent alpha_0
    # alpha_hot = 0.3
    # alpha_cold = 1
    # alpha_0 = alpha_cold * alpha_hot / (alpha_hot + alpha_cold * (1-alpha_hot) * A_cold/A_hot)
    # print(alpha_0)

    # Good assumption for helium according to Grohmann lecture and Ekin
    alpha_0 = 0.5 #-   ->conservative value
    kappa = 5/3 #-

    # Arithmetic mean for K according to Grohmann lecture
    T_mean = (T_hot + T_cold)/2.0 #K
    # "Constant" factor K
    K = (sp.constants.R / (8 * sp.constants.pi * 4*10**-3 * T_mean)) * (kappa+1)/(kappa-1) #W/(m²PaK)
    # Final equation
    Q_gas = A_cold * alpha_0 * K * pressure_vac * (T_hot - T_cold) #W
    return Q_gas #W

# Function: calculating the heat transport in MLI due to thermal radiation and conduction
# The model's values are based on experience with the LHC cryostat
# According to Parma
def q_MLI_Parma(N_MLI, T_hot, T_cold):
    # Empirical model parameters
    alpha = 1.401*10**-4
    beta = 3.741*10**-9

    return (beta/(N_MLI+1) * (T_hot**4-T_cold**4)) + (alpha/(N_MLI+1) * (T_hot+T_cold)/2 * (T_hot-T_cold)) #W/m²

# Function: calculating the heat transport in MLI due to thermal radiation and conduction
# The model's values are based on experience with the LHC cryostat
# According to Riddone
def q_MLI_Riddone(N_MLI, T_hot, T_cold):
    # Empirical model parameters
    alpha = 1.401*10**-4
    beta = 3.741*10**-9

    return (beta/(N_MLI) * (T_hot**4-T_cold**4)) + (alpha/(N_MLI) * (T_hot+T_cold)/2 * (T_hot-T_cold)) #W/m²

# Integral thermal conductivity of PTFE according to NIST
# Integral form, just put in the upper and the lower boundaries
# Data and equation range: 4 - 300 K
# Curve fit % error relative to data: 5
def lambda_PTFE(T_cold, T_hot):
    result_int = sp.integrate.quad(lambda x: 10**(2.7380 + -30.677*math.log(x,10) + 89.430*math.log(x,10)**2 + -136.99*math.log(x,10)**3
                                              + 124.69*math.log(x,10)**4 + -69.556*math.log(x,10)**5 + 23.320*math.log(x,10)**6
                                              + -4.3135*math.log(x,10)**7 + 0.33829*math.log(x,10)**8), T_cold, T_hot)
    return result_int[0] #W/m

# Integral thermal conductivity of Cu RRR = 50 according to NIST
# Integral form, just put in the upper and the lower boundaries
# Data and equation range: 4 - 300 K
# Curve fit % error relative to data: 2
def lambda_Cu_50(T_cold, T_hot):
    result_int = sp.integrate.quad(lambda x: 10**((1.8743 + -0.6018*x**0.5 + 0.26426*x + -0.051276*x**1.5 + 0.003723*x**2)
                                                 /(1 + -0.41538*x**0.5 + 0.13294*x + -0.0219*x**1.5 + 0.0014871*x**2)), T_cold, T_hot)
    return result_int[0] #W/m

# Integral thermal conductivity of Cu OFHC RRR = 100 according to NIST
# Data and equation range: 4 - 300 K
# Curve fit % error relative to data: 1
def lambda_Cu_100(T_cold, T_hot):
    result_int = sp.integrate.quad(lambda x: 10**((2.2154 + -0.88068*x**0.5 + 0.29505*x + -0.04831*x**1.5 + 0.003207*x**2)
                                                 /(1 + -0.47461*x**0.5 + 0.13871*x + -0.02043*x**1.5 + 0.001281*x**2)), T_cold, T_hot)
    return result_int[0] #W/m

# Integral thermal conductivity of Cu RRR = 300 according to NIST
# Integral form, just put in the upper and the lower boundaries
# Data and equation range: 4 - 300 K
# Curve fit % error relative to data: 1
def lambda_Cu_300(T_cold, T_hot):
    result_int = sp.integrate.quad(lambda x: 10**((1.357 + 2.669*x**0.5 + -0.6683*x + 0.05773*x**1.5 + 0*x**2)
                                                 /(1 + 0.3981*x**0.5 + -0.1346*x + 0.01342*x**1.5 + 0.0002147*x**2)), T_cold, T_hot)
    return result_int[0] #W/m

# Specific Heat capacity  of Cu according to NIST
# Data and equation range: 4 - 300 K
# Curve fit % error relative to data: 10 (T < 15K); 5 (T ≥ 15K)
def cp_Cu(T):
    return 10**(-1.91844 + -0.15973*math.log(T,10) + 8.61013*math.log(T,10)**2 + -18.996*math.log(T,10)**3
                + 21.9661*math.log(T,10)**4 + -12.7328*math.log(T,10)**5 + 3.54322*math.log(T,10)**6
                + -0.3797*math.log(T,10)**7 + 0*math.log(T,10)**8) #J/kgK

# Thermal conductivity of SST304 according to NIST
# Data and equation range: 1 - 300 K
# Curve fit % error relative to data: 2
def lambda_SST304(T):
    return 10**(-1.4087 + 1.3982*math.log(T,10) + 0.2543*math.log(T,10)**2 + -0.6260*math.log(T,10)**3
                + 0.2334*math.log(T,10)**4 + 0.4256*math.log(T,10)**5 + -0.4658*math.log(T,10)**6
                + 0.1650*math.log(T,10)**7 + -0.0199*math.log(T,10)**8) #W/(mK)

# Integral thermal conductivity of SST304 according to NIST
# Integral form, just put in the lower and upper boundaries
# Data and equation range: 1 - 300 K
# Curve fit % error relative to data: 2
def lambda_int_SST304(T_cold, T_hot):
    result_int = sp.integrate.quad(lambda x: 10**(-1.4087 + 1.3982*math.log(x,10) + 0.2543*math.log(x,10)**2 + -0.6260*math.log(x,10)**3
                                                  + 0.2334*math.log(x,10)**4 + 0.4256*math.log(x,10)**5 + -0.4658*math.log(x,10)**6
                                                  + 0.1650*math.log(x,10)**7 + -0.0199*math.log(x,10)**8), T_cold, T_hot)
    return result_int[0] #W/m

################################################################################
## 1.2 Geometry data and boundary conditions ##

# Length and diameter of the cold mass, thermal shield and vacuum chamber, respectively
L_CM = 9.90 #m
D_CM = 0.60 #m
L_TS = 9.95 #m
D_TS = 0.65 #m
L_VC = 10.0 #m
D_VC = 0.70 #m

# Temperature of the respective vessel/layer
T_CM = 4.0 #K
T_TS = 35.0 #K
T_VC = 293.0 #K

# Pressure in the vacuum system
pressure_vac = 10**-4 #Pa

# Emission coefficent of the respective vessel/layer
epsilon_TS = 0.03 #-
epsilon_VC = 0.08 #-
epsilon_MLI = 0.023 #-

# Surface of the ideal cylinders of the cold mass, thermal shield and vacuum chamber, respectively
A_CM = surface_cylinder(L_CM, D_CM) #m²
A_TS = surface_cylinder(L_TS, D_TS) #m²
A_VC = surface_cylinder(L_VC, D_VC) #m²

################################################################################
## 2.1.1 Calculation of the heat load with effective heat conduction coeff. and equilibrium on the first MLI layer ##
## Variation of T_TS and T_CM and calculation of the respective heat load ##

# Effective heat conduction coefficent of the respective MLI
lambda_eff_MLI_30 = 4*10**-5 #W/(mK)
lambda_eff_MLI_20 = 4*10**-5 #W/(mK)

# MLI thickness (value from Frey, Tieftemperaturtechnologie for 25 layers)
d_MLI_eff = 0.0125 #m

# print("q_MLI_Tieftemp: ", lambda_eff_MLI_30/d_MLI_eff)
"""
# Definition of an function to be able to use the newton method to find the MLI temperaure
def func_newton(x, A_hot, A_cold, T_hot, epsilon_hot, epsilon_MLI, pressure_vac, lambda_eff, d_MLI_eff, T_cold):
    Q_rad = Q_therm_rad(A_hot, A_cold, T_hot, x, epsilon_hot, epsilon_MLI)
    Q_gas = Q_gas_cond(A_cold, T_hot, x, pressure_vac)
    Q_cond_MLI = Q_cond(A_cold, d_MLI_eff, x, T_cold, lambda_eff)
    return Q_rad + Q_gas - Q_cond_MLI

# Create lists for the different temperatures to be calculated
T_TS_lst = [35.0, 45.0, 50.0, 55.0, 65.0, 75.0, 80.0] #K
T_CM_lst = [i for i in np.arange(4,15.5,0.5)] #K

# Allocate a matrix for the heat load depending on the anchoring temperatures
Q_TS_matrix = np.zeros([len(T_TS_lst), len(T_CM_lst)], dtype=float)
Q_CM_matrix = np.zeros([len(T_TS_lst), len(T_CM_lst)], dtype=float)

# Two for loops to calculate every point of the matrix
for i in range(0,len(T_TS_lst)):
    for j in range(0,len(T_CM_lst)):
        # Find fitting T_MLI_30 temperature for the respective T_TS and T_CM pair using the newton method
        T_MLI_30 = sp.optimize.newton(func_newton, T_VC, args=(A_VC, A_TS, T_VC, epsilon_VC, epsilon_MLI, pressure_vac, lambda_eff_MLI_30, d_MLI_eff, T_TS_lst[i]),
                                      rtol=10**-4, disp=True)
        # Find fitting T_MLI_30 temperature for the respective T_TS and T_CM pair using the newton method
        T_MLI_20 = sp.optimize.newton(func_newton, T_TS, args=(A_TS, A_CM, T_TS_lst[i], epsilon_TS, epsilon_MLI, pressure_vac, lambda_eff_MLI_20, d_MLI_eff, T_CM_lst[j]),
                                      rtol=10**-4, disp=True)

        # Save the sum of both heat loads on a matrix for postprocessing
        Q_TS_matrix[i][j] = Q_cond(A_TS, d_MLI_eff, T_MLI_30, T_TS_lst[i], lambda_eff_MLI_30)
        Q_CM_matrix[i][j] = Q_cond(A_CM, d_MLI_eff, T_MLI_20, T_CM_lst[j], lambda_eff_MLI_20)
"""
################################################################################

################################################################################
## 2.1.2 Calculation of the heat load with effective heat conduction coeff. ##
## Variation of T_TS and T_CM and calculation of the respective heat load ##
"""
# Create lists for the different temperatures to be calculated
T_TS_lst = [35.0, 45.0, 50.0, 55.0, 65.0, 75.0, 80.0] #K
T_CM_lst = [i for i in np.arange(4,15.5,0.5)] #K

# Allocate a matrix for the heat load depending on the anchoring temperatures
Q_TS_matrix = np.zeros([len(T_TS_lst), len(T_CM_lst)], dtype=float)
Q_CM_matrix = np.zeros([len(T_TS_lst), len(T_CM_lst)], dtype=float)

# Two for loops to calculate every point of the matrix
for i in range(0,len(T_TS_lst)):
    for j in range(0,len(T_CM_lst)):
        # Save the sum of both heat loads on a matrix for postprocessing
        Q_TS_matrix[i][j] = Q_cond(A_TS, d_MLI_eff, T_VC, T_TS_lst[i], lambda_eff_MLI_30)
        Q_CM_matrix[i][j] = Q_cond(A_CM, d_MLI_eff, T_TS_lst[i], T_CM_lst[j], lambda_eff_MLI_20)

print(Q_TS_matrix)
print(Q_CM_matrix)
"""
################################################################################

################################################################################
## 2.2 Calculation of the heat load for an MLI system with the model from Parma ##
## Variation of T_TS and T_CM and calculation of the respective heat load ##
"""
# Create lists for the different temperatures to be calculated
# T_TS_lst = [35.0, 45.0, 50.0, 55.0, 65.0, 75.0, 80.0] #K
# T_CM_lst = [i for i in np.arange(4,15.5,0.5)] #K

T_TS_lst = [35.0, 45.0, 50.0, 60.0, 80.0] #K
T_CM_lst = [4.0, 5.0, 10.0, 15.0] #K

# Allocate a matrix for the heat load depending on the anchoring temperatures
Q_TS_matrix = np.zeros([len(T_TS_lst), len(T_CM_lst)], dtype=float)
Q_CM_matrix = np.zeros([len(T_TS_lst), len(T_CM_lst)], dtype=float)

# Two for loops to calculate every point of the matrix
for i in range(0,len(T_TS_lst)):
    for j in range(0,len(T_CM_lst)):
        # Save the sum of both heat loads on a matrix for postprocessing
        Q_TS_matrix[i][j] = A_TS * q_MLI_Parma(30, T_VC, T_TS_lst[i]) + Q_gas_cond(A_TS, T_VC, T_TS_lst[i], pressure_vac)
        Q_CM_matrix[i][j] = A_CM * q_MLI_Parma(10, T_TS_lst[i], T_CM_lst[j]) + Q_gas_cond(A_CM, T_TS_lst[i], T_CM_lst[j], pressure_vac)

print(Q_TS_matrix)
print(Q_CM_matrix)
"""
################################################################################

################################################################################
## 2.3 Calculation of the heat load with the model from Parma and no MLI layer on the cold mass ##
## Variation of T_TS and T_CM and calculation of the respective heat load ##
"""
# Emission coefficent for the cold mass assuming a polished SST surface
epsilon_CM = 0.07

# Create lists for the different temperatures to be calculated
# T_TS_lst = [35.0, 45.0, 50.0, 55.0, 65.0, 75.0, 80.0] #K
# T_CM_lst = [i for i in np.arange(4,15.5,0.5)] #K
T_TS_lst = [35.0, 45.0, 50.0, 80.0] #K
T_CM_lst = [4.0, 5.0, 10.0, 15.0] #K

# Allocate a matrix for the heat load depending on the anchoring temperatures
Q_TS_matrix = np.zeros([len(T_TS_lst), len(T_CM_lst)], dtype=float)
Q_CM_matrix = np.zeros([len(T_TS_lst), len(T_CM_lst)], dtype=float)

# Two for loops to calculate every point of the matrix
for i in range(0,len(T_TS_lst)):
    for j in range(0,len(T_CM_lst)):
        # Save the sum of both heat loads on a matrix for postprocessing
        Q_TS_matrix[i][j] = A_TS * q_MLI_Parma(30, T_VC, T_TS_lst[i])
        # Q_CM_matrix[i][j] = A_CM * q_MLI_Parma(0, T_TS_lst[i], T_CM_lst[j])
        Q_CM_matrix[i][j] = (Q_therm_rad(A_TS, A_CM, T_TS_lst[i], T_CM_lst[j], epsilon_TS, epsilon_CM)
                           + Q_gas_cond(A_CM, T_TS_lst[i], T_CM_lst[j], 10**-2))

# print(Q_TS_matrix)
# print(Q_CM_matrix)
"""
################################################################################

################################################################################
## 2.3.2 Calculation of the heat load for an MLI system with the model from Riddone ##
## Variation of T_TS and T_CM and calculation of the respective heat load ##
"""
# Create lists for the different temperatures to be calculated
# T_TS_lst = [35.0, 45.0, 50.0, 55.0, 65.0, 75.0, 80.0] #K
# T_CM_lst = [i for i in np.arange(4,15.5,0.5)] #K

T_TS_lst = [35.0, 45.0, 50.0, 60.0, 80.0] #K
T_CM_lst = [4.0, 5.0, 10.0, 15.0] #K

# Allocate a matrix for the heat load depending on the anchoring temperatures
Q_TS_matrix = np.zeros([len(T_TS_lst), len(T_CM_lst)], dtype=float)
Q_CM_matrix = np.zeros([len(T_TS_lst), len(T_CM_lst)], dtype=float)

# Two for loops to calculate every point of the matrix
for i in range(0,len(T_TS_lst)):
    for j in range(0,len(T_CM_lst)):
        # Save the sum of both heat loads on a matrix for postprocessing
        Q_TS_matrix[i][j] = A_TS * q_MLI_Riddone(30, T_VC, T_TS_lst[i]) + Q_gas_cond(A_TS, T_VC, T_TS_lst[i], pressure_vac)
        Q_CM_matrix[i][j] = A_CM * q_MLI_Riddone(10, T_TS_lst[i], T_CM_lst[j]) + Q_gas_cond(A_CM, T_TS_lst[i], T_CM_lst[j], pressure_vac)

# print(Q_TS_matrix)
# print(Q_CM_matrix)
"""
################################################################################

################################################################################
## 2.7 Thickness of the thermal shield to yield an acceptable dT of the shield ##
# Assuming radial uniformity to get a 1D problem
"""
# Assuming a thermal shield at 50K = T_0
T_0 = 50.0
# Specific heat load on the thermal shield covered with 30 layers of MLI
q_TS = q_MLI_Parma(30, T_VC, T_0)
# Thermal conductivity coefficent @ 50K for Cu-RRR=30
lambda_Cu_30_50K = 732   #W/(mK)
# Maximal prescribed dT of the thermal shield
dT_max = 10.0 #K

# Minimal thickness as a function of the maximum dT
thickness_TS = (q_TS * L_TS*L_TS) / (2 * lambda_Cu_30_50K * dT_max)
# print("Thickness TS: ", thickness_TS)

# Function for calculation of the local temperature with Neumann BC
# Note: x is the dimensionless length
def temp_distribution_shield_Neumann(x, L, thickness, T_0, q, heat_cond_coeff):
    # return T_0 - (q * L*L * x*x)/(2 * heat_cond_coeff * thickness) + (q * L*L * x)/(heat_cond_coeff * thickness)
    return T_0 - (q * L*L)/(heat_cond_coeff * thickness) * (0.5*x*x - x)

def temp_distribution_shield_Dirichlet(x, L, thickness, T_0, q, heat_cond_coeff):
    return T_0 - (q * L*L)/(heat_cond_coeff * thickness) * (0.5*x*x - 0.5*x)

# print(temp_distribution_shield(0.5, L_TS, thickness_TS, T_0, q_TS, lambda_Cu_30_50K))

# # Creating a plot of the temperature distribution along the length of the
# x_lst = [i for i in np.arange(0,1.05,0.05)]
# T_TS_local_lst = [0] * len(x_lst)
# for i in range(0,len(x_lst)):
#     T_TS_local_lst[i] = temp_distribution_shield_Neumann(x_lst[i], L_TS, thickness_TS, T_0, q_TS, lambda_Cu_30_50K)
# plt.plot(x_lst, T_TS_local_lst)
# plt.xlabel("Dimensionless length x / -")
# plt.ylabel("Temperature TS / K")
# plt.show()
"""
################################################################################

################################################################################
## 2.8 Thermal shield service box temperautre gradient ##
# Assuming radial uniformity to get a 1D problem
"""
# Geometry shield: 60 cm diameter and 1 m length
# Thickness shield = 1.5 mm
# Material: Al -> 711 W/mK @ 35 K
# Specific Heat load: 5.3 W per 2.45 m² of the SB TS
thickness = 1.5e-3 #m
cond_coeff = 711 #W/mK
specific_heat_SB = 5.3/2.45 #W/m²
length = 1.0 #m
temperature_TS_SB = 33 #K

# Function for calculation of the local temperature with Neumann BC
# Note: x is the dimensionless length
# x = 0 is the beginning of the shield, x = 1 is the end of the shield
def temp_distribution_shield_Neumann(x, L, thickness, T_0, q, heat_cond_coeff):
    # return T_0 - (q * L*L * x*x)/(2 * heat_cond_coeff * thickness) + (q * L*L * x)/(heat_cond_coeff * thickness)
    return T_0 - (q * L*L)/(heat_cond_coeff * thickness) * (0.5*x*x - x)

def temp_distribution_shield_Dirichlet(x, L, thickness, T_0, q, heat_cond_coeff):
    return T_0 - (q * L*L)/(heat_cond_coeff * thickness) * (0.5*x*x - 0.5*x)

# print(temp_distribution_shield_Neumann(0.5, length, thickness, temperature_TS_SB, specific_heat_SB, cond_coeff))
"""
################################################################################

################################################################################
## 3. Mechanical stability of the vessels ##

## 3.1 Using Parma's rule of thumb
# t/r >3.7%
# t=13mm @ 35cm radius
#
# print(0.037*0.3)

# # Thickness of the different vessels using rule of thumb from Parma
# t_VC = 13 mm
# t_TS = 12 mm
# t_CM = 11.1 mm

# # Weight of the vessels - ballpark
# density_SST304 = 8030 #kg/m³
# density_Cu = 8900 #kg/m³
# print("weight_TS: ", 0.002 * density_Cu * A_TS)
# print("weight_CM: ", 0.005 * density_SST304 * A_CM)

#
# weight_VC = density_SST304 * A_VC * 0.037*0.35 #kg
# weight_TS = density_Cu * A_TS * 0.037*0.325 #kg
# weight_CM = density_SST304 * A_CM * 0.037*0.3 + density_SST304 * A_CM * 0.037*0.3 #kg
#
# print("weight_VC: ", weight_VC)
# print("weight_TS: ", weight_TS)
# print("weight_CM: ", weight_CM)

# ## 3.2 Using Tresca failure criterion ##
# # sigma_admissible > p*r/t
# # sigma_admissible = yield strength / safety factor
# # Values for the yield strength according to Ekin
# yield_SST304 = 240 *10**6
# yield_Cu = 70 *10**6
# # Chosing an adequate safety factor
# safety_factor = 2
# # Calculating sigma admissible
# sigma_a_SST304 = yield_SST304 / safety_factor
# sigma_a_Cu = yield_Cu / safety_factor
# # Print the result
# print("Thickness Tresca failure criterion: ", 2* 1.013*10**5 * 0.30 / sigma_a_SST304)

# ## 3.3 Using bending structural analysis ##
# t_TS = 0.008 #m
# r_TS = 0.325 #m
# l_TS = 9.9 #m
# # Youngs modulus of Copper
# YM_Cu = 117*10**9
#
# # Calculation of bending stress
# w_TS = density_Cu * A_TS * t_TS * 9.81 #N
# moment_TS = (w_TS * l_TS) / 8
# I_TS = sp.pi*0.25*(r_TS**4 - (r_TS-t_TS)**4)
# sigma_B_TS = (moment_TS*r_TS)/I_TS
# print("sigma_B_TS: ", sigma_B_TS*10**-6)
#
# #Calculation of the bending height assuming ideal phytagoras law
# bending_TS = l_TS/2 * ((1+sigma_B_TS/YM_Cu)**2 -1)**0.5
# print("bending_TS: ", bending_TS)

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

## 4. Mechanical analysis of el. equipment insert
"""
radius_insert = 0.2 #m
length_insert = 0.3 #m
press_max = 1.013*10**5 #Pa

## Tresca failure criterion
# sigma_admissible > p*r/t
# sigma_admissible = yield strength / safety factor
# Values for the yield strength according to https://www.curbellplastics.com/Research-Solutions/Plastic-Material-Properties/G10-FR-4-Glass-Epoxy-Properties
yield_G10 = 260 *10**6 #Pa
# Chosing an adequate safety factor
safety_factor = 2
# Calculating sigma admissible
sigma_a_G10 = yield_G10 / safety_factor
# Print the result
print("Thickness Tresca failure criterion: ", 1.013*10**5 * radius_insert / sigma_a_G10)

## Buckling analysis
# Infinite thin tube
# Values for the Young's modulus according to https://www.curbellplastics.com/Research-Solutions/Plastic-Material-Properties/G10-FR-4-Glass-Epoxy-Properties
# E_G10 = 16547417504 #Pa
# Values for the Young's modulus according to G:\Departments\TE\Groups\CRG\Sections\CI\Projects_and_Services\Cryolab\He II pressurized G10 insert\1 - Project documents\G10 data sheets (Von Roll)
E_G10 = 20e9 #Pa

# Poission's ratio: just assumption
poisson_G10 = 0.25

# thickness of insert
thickness_insert = 0.002 #m
print("Critical pressure from buckling analysis: ", 10**-5 * E_G10/(4*(1-poisson_G10**2)) * (thickness_insert/radius_insert)**3)

A_insert = sp.pi*0.25* ((2*radius_insert)**2-(2*radius_insert-2*thickness_insert)**2) # m²
print("Heat load insert SST: ", A_insert*1/1*lambda_int_SST304(50,300))
print("Heat load insert G10 TS: ", A_insert*1/(1*length_insert)*(133.2-8.48))
print("Heat load insert G10 CM: ", A_insert*1/(0.4)*(8.48-0.0901))

#Additional radiation:
A_thermPlate = sp.pi*0.25* 0.4**2 # m²
print("Radiation on therm plate: ", 67.5e-3*A_thermPlate)
"""

################################################################################
## 5. Postprocessing and visualization ##

# # Restructuring because the values need to be in a 2D array (not lists) and in equal size for 3D plotting
# T_TS_plot_array = np.transpose(np.array([np.array(T_TS_lst)])) * np.full((1,len(T_CM_lst)), 1)
# T_CM_plot_array = np.full((len(T_TS_lst),1), 1) * np.array(T_CM_lst)

# # Plotting the heat loads at the respective temperaure pairs in a 3D plot
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')

# ax.plot_surface(T_TS_plot_array, T_CM_plot_array, Q_TS_matrix)
#                 #cmap=cm.coolwarm, linewidth=0, antialiased=False)
# ax.plot_surface(T_TS_plot_array, T_CM_plot_array, Q_CM_matrix)

# ax.set_xlabel('T_TS / K')
# ax.set_ylabel('T_CM / K')
# ax.set_zlabel('Q_TS/Q_CM / W')
# # ax.set_zlabel('Q_CM / W')

# # plt.show()

# ## Simple plot to show Parma model ##
# T_warm = [i for i in np.arange(35,81,1.0)]
# HL = [0] * len(T_warm)
# for i in range(0,len(T_warm)):
#     HL[i] = A_CM * q_MLI_Parma(20, T_warm[i], 4.5)
# plt.plot(T_warm, HL)
# plt.xlabel("Temperature TS / K")
# plt.ylabel("Heat load CM @4.5K / W")
# plt.show()

"""
################################################################################
## Parma Slides Exercise ##

A_VV = sp.pi
A_TS = sp.pi * 0.8
A_CM = sp.pi * 0.6

HL_CM = Q_therm_rad(2.51, 1.88, 80.0, 2.0, 0.1, 0.06)
# HL_CM = Q_therm_rad(3.14, 2.51, 293, 80.0, 0.2, 0.1)
# Q_therm_rad(A_hot, A_cold, T_hot, T_cold, epsilon_hot, epsilon_cold)

q_MLI = q_MLI_Parma(30, 290, 80.0) * 2.51
# q_MLI_Parma(N_MLI, T_hot, T_cold)

print("HL_CM: ", HL_CM)
print("q_MLI: ", q_MLI)

# a) Bare cold mass:                                HL_CM = 73 W
# b) Cold mass wrapped with 1 layer of Al foil:     HL_CM = 41 W
# c) Cold mass wrapped with 30 layers of MLI:       HL_CM = 1.96 W
#       calculated the heat load with the formula and 290K and not 293K because there is vacuum in between
# d) Addition of thermal shield actively cooled:    HL_CM = 0.29 W,     HL_TS = 79 W
# e) Wrapping of MLI around thermal shield:         HL_CM = 0.29 W,     HL_TS = 2.38 W
# f) Adding 1 Al foil around cold mass:             HL_CM = 0.187 W,    HL_TS = 2.38 W

################################################################################
"""

"""
################################################################################
## Heat Load Cooper Shield ##
# Using the equations from Boyan's master thesis

# Heat conduction coeff lambda from the literature for a vacuum pressure under 10^-4 mbar and 20 layers of MLI
lambda_apparent = 2.4 * 10**-3; #W/mK

# Surface of the cryostats assuming cylindrical shape
# Main cryostat assuming an value from Boyan's master thesis
A_mc = 1.89 + 0.56; #m^2
# Remote cryostat assuming the cooper shield sitting in the middle between the bore and the cavity - d = 65cm
A_rc = 10 * 3.14159 * 0.65 + 3.14159 * 0.5 * 0.65**2; #m^2

# Temperatures
T_warm = 295; #K
T_shield = 50; #K

# Heat loads Q
Q_mc = lambda_apparent * A_mc * (T_warm - T_shield); #W
Q_rc = lambda_apparent * A_rc * (T_warm - T_shield); #W

print("Heat load main cryostat: ", Q_mc, " W")
print("Heat load remote cryostat: ", Q_rc, " W")
################################################################################
"""


import argparse
import json
import logging
import random
from pathlib import Path
from typing import (Any, )

import jsonlines
import torch
import numpy as np
from tqdm import tqdm
# from tqdm.contrib.logging import tqdm_logging_redirect
from data_loader import MyDataset

from validator import get_completeness
from validator import get_soundness

# Fix random seeds for reproducibility
SEED = 42
torch.manual_seed(SEED)  # pytorch random seed
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(SEED)  # numpy random seed
random.seed(SEED)  # python random seed

def main(config: dict[str, Any]):

    solution_prefix = Path(config['solution_prefix'])

    # Set variables related to `validate_labeling_config`
    validate_labeling_config = config['validate_labeling']
    logging.info(validate_labeling_config)
    labeled_path = validate_labeling_config['labeled_data']
    testcases_path = validate_labeling_config['testcase']
    output_path = validate_labeling_config['output']
    get_soundness_args = validate_labeling_config['get_soundness']['args']
    get_completeness_args = (
        validate_labeling_config['get_completeness']['args'])

    testcases_dictionary: dict[list[str]] = {}
    with jsonlines.open(testcases_path, 'r') as dataset:
        for data in tqdm(dataset, desc='Loading testcases'):
            name = data['name']
            testcases = data['public_tests']['input']
            # testcases.extend(data['private_tests']['input'])
            # testcases.extend(data['generated_tests']['input'])
            testcases_dictionary[name] = testcases

    soundness = []
    completeness = []

    sound_and_complete_dataset = []
    labeled_dataset = jsonlines.open(labeled_path, 'r')
    for labeled_data in tqdm(labeled_dataset, desc=f'Testing {labeled_path}'):
        grammar = labeled_data['grammar']
        name = labeled_data['name']
        description = labeled_data['description']
        specification = MyDataset.get_specification(description)
        testcases = testcases_dictionary[name]
        solution_dir = solution_prefix / name

        is_sound = get_soundness(
            grammar,
            solution_dir,
            solution_sampling_seed=42,
            name=name,
            specification=specification,
            **get_soundness_args
        )
        is_complete = get_completeness(
            grammar, testcases,
            name=name,
            specification=specification,
            **get_completeness_args
        )
        if is_sound and is_complete:
            sound_and_complete_dataset.append(labeled_data)

        soundness.append(is_sound)
        completeness.append(is_complete)
    correctness = list(map(lambda e: all(e), zip(completeness, soundness)))

    labeled_dataset.close()
    average_soundness = sum(soundness) / len(soundness)
    average_completeness = sum(completeness) / len(completeness)
    average_correctness = sum(correctness) / len(correctness)

    with jsonlines.open(output_path, 'w') as output:
        output.write_all(sound_and_complete_dataset)

    print("Soundness & Completeness & Sound. \\& Compl. \\\\")
    print(f"{average_soundness * 100:.2f} & ", end='')
    print(f"{average_completeness * 100:.2f} & ", end='')
    print(f"{average_correctness * 100:.2f} \\\\")

if __name__ == "__main__":
    logger = logging.getLogger('validator')
    logger.setLevel(logging.ERROR)
    # logger.setLevel(logging.INFO)
    logger.addHandler(logging.FileHandler('validate_labeling.log'))

    parser = argparse.ArgumentParser()
    parser.add_argument('--labeled-data')
    parser.add_argument('--testcase')
    parser.add_argument('--test', action='store_true')
    parser.add_argument('--output', default='/dev/null')
    args = parser.parse_args()

    with open('./config.json') as fp:
        config = json.load(fp)

    data_dir = Path(config['data_dir'])
    unlabeled_test_data = data_dir / config['unlabeled_test_data']
    unlabeled_valid_data = data_dir / config['unlabeled_valid_data']
    testcases_path = (
        unlabeled_test_data if args.test else unlabeled_valid_data)
    trainer_config = config['trainer']
    model_dir = Path(trainer_config['save_dir'])
    labeled_data_base = (
        'model_labeled_test_data.jsonl' if args.test
        else 'model_labeled_valid_data.jsonl'
    )
    labeled_data = model_dir / labeled_data_base

    defaults = {
        'labeled_data': labeled_data,
        'testcase': testcases_path,
        'output': args.output,
    }

    task = 'validate_labeling'
    task_config = config.setdefault(task, {})
    for k in defaults.keys():
        if getattr(args, k, None) is not None:
            task_config[k] = getattr(args, k)
        task_config.setdefault(k, defaults[k])

    main(config)


import sysv_ipc, json, sys

class IPCInterface:
    def __init__(self) -> None:
        config = json.load(open('ipc_config.json'))
        self.main_channel_id = config['main_channel_id']

    def sendMsg(self, data_in_bytes: bytes):
        try:
            size_of_val = len(data_in_bytes)

            memory = sysv_ipc.SharedMemory(self.main_channel_id, mode=0o666, size=size_of_val, flags=sysv_ipc.IPC_CREAT)

            if memory.size != size_of_val:
                raise ValueError('memory.size != size_of_val; trying to fix...')

            memory.write(data_in_bytes)
            memory.detach()

        except:
            memory_to_remove = sysv_ipc.SharedMemory(self.main_channel_id, mode=0o666, flags=sysv_ipc.IPC_CREAT)
            memory_to_remove.remove()
            self.sendMsg(data_in_bytes)

    def readMsg(self) -> bytes:
        memory = sysv_ipc.SharedMemory(self.main_channel_id, mode=0o666,  flags=sysv_ipc.IPC_CREAT)
        res = memory.read()
        memory.detach()
        return res


from django.urls import path
from . import views

urlpatterns = [
    path('', views.catalog, name='catalog'),
    path('cart/', views.cart, name='cart'),
    path('cart/remove/', views.removeItemFromCart),
    path('cart/checkout/', views.checkout),
    path('cart/checkout/complete/', views.submitOrder),
    path('admin-login/', views.admin_login, name='admin_login'),
    path('admin-dashboard/', views.admin_dashboard, name='admin'),

]


# O(k) time| space : k is number of keys
def flatten_dictionary(dictionary):
      return flatten("",dictionary,{}, ".")

def flatten(initial_key,dictionary,flat_diction,sep):
  for k,v in dictionary.items():
    if not initial_key:
      new_key = k
    elif not k:
      new_key = initial_key
    else:
      new_key = initial_key + sep + k

    if isinstance(v, dict):
        flatten(new_key,v,flat_diction,sep)
    else:
        flat_diction[new_key] = v

  return flat_diction


import xml.sax

class MyClass(xml.sax.ContentHandler):
    def __init__(self):
        self.currentElement = ""
        self.name = ""
        self.year = ""
        self.country = ""

    def startElement(self, tag, attributes):
        self.currentElement = tag
        if tag == "singsong":
            self.name = attributes["name"]
            self.year = attributes["year"]
            self.country = attributes["country"]

    def endElement(self, tag):
        if tag == "singsong":
            print("* "*30)
            print(self.name.ljust(30), self.year.rjust(10), self.country.center(20))

#run code
if __name__ == "__main__":
    sax_parser = xml.sax.make_parser()
    handlerObj = MyClass()
    sax_parser.setContentHandler(handlerObj)

    print("Name".ljust(30), "Year".rjust(10), "Country".center(20))
    sax_parser.parse("./data/sing_song_01.xml")


from tqdm import tqdm
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from utils.datasets import getTestDataset
from models.model_tfc import jsccEnd2End_tfc

dataset_root = '/workspace/dataset/cifar-10-batches-py'
test_ds, shape = getTestDataset(dataset_root)

BW = 6
train_SNRs = [1, 4, 7, 13, 19]
plot_color = ['#0072bd', '#d95319', '#edb120', '#7e2f8e', '#77ac30']
plot_marker = ['-*', '-|', '-o', '-s', '-d']
test_SNRs = [1, 4, 7, 10, 13, 16, 19 ,22, 25]

for i, train_SNR in enumerate(train_SNRs):
    model_dir = f'./logs/BW{BW}_{train_SNR}dB/weights'
    avg_PSNR = []

    for test_SNR in tqdm(test_SNRs):
        test_model = jsccEnd2End_tfc(shape, 1/BW, test_SNR)
        test_model.load_weights(model_dir)
        PSNRs = []
        for image in test_ds:
            output = test_model(image)
            PSNRs.append(tf.image.psnr(image, output, max_val=255))
        avg_PSNR.append(np.mean(PSNRs))
    plt.plot(test_SNRs, avg_PSNR, plot_marker[i], color=plot_color[i], label=f'deepJSCC (SNR_train = {train_SNR}dB)')

plt.title(f'AWGN Channel (k/n = 1/{BW}) [self made]')
plt.xlabel('SNR_test (dB)')
plt.ylabel('PSNR (dB)')
plt.axis((0, 25, 20, 36))
plt.legend()
plt.show()


import pytest
from urlfix.urlfix import URLFix
from urlfix.dirurlfix import DirURLFix
import os
from shutil import copytree, rmtree
# better recursive glob unlike using glob
# Only limitation is we are unable to figure out if something is null
from pathlib import Path

dir_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "testfiles")
repl_f = os.path.join(dir_path, "replacement.txt")

def make_file(f_path):
    return os.path.join(dir_path, f_path)

@pytest.fixture
def test_object(in_f="", kind="file", **kwargs):
    def usable_test_object(i_file="", out_f = repl_f, kind = "file",  **kwargs):
        return URLFix(input_file=make_file(i_file), output_file = out_f,  **kwargs) if kind=="file" else DirURLFix(make_file(i_file))
    return usable_test_object

def remove_output_files(dir_used=dir_path):
    for out_file in Path(dir_used).rglob("*_output.*"):
        print(f"Removing no longer needed file: {out_file}")
        os.remove(out_file)

obj_list = ["testurls.md", "testurls.txt"]
@pytest.mark.parametrize("in_file", obj_list)
def test_instance_creation(in_file, obj_list, test_object):
    assert isinstance(in_file, URLFix)

    with pytest.raises(ValueError) as err:
        test_object(i_file = "testurls.txt", out_f = "").replace_urls()
    assert str(err) == "Please provide an output file to write to."

def test_replace_urls(test_object):
    err_msg = f"Need both input and output files but {make_file('doesnt_exist.txt')} does not exist."
    with pytest.raises(FileNotFoundError, match = err_msg):
        test_object(i_file="doesnt_exist.txt").replace_urls()

def test_md_files(test_object):
    assert test_object(i_file = "testurls.md").replace_urls(verbose=False) == 3

def test_txt_files(test_object):
    assert test_object(i_file = "testurls.txt").replace_urls(verbose=True) == 2

def test_rmd_files(test_object):
    rmd_obj = test_object(i_file = "testrmd.rmd")
    assert rmd_obj.replace_urls(verbose=True) == 2

def test_rst_files(test_object):
    rst_obj = test_object(i_file="testurls.rst")
    assert rst_obj.replace_urls(verbose=True) == 5

def test_non_support(test_object):
    # Check that non-supported formats are skipped and an error raised
    # Using match as asserting on the expected error message seems to fail for whatever reason
    err_msg = "File format pdf is not yet supported"
    with pytest.raises(NotImplementedError, match  = err_msg):
        test_object(i_file = "unsupported.pdf", kind="file").replace_urls()

# Directory based tests

def test_instance_creation(test_object):
    assert isinstance(test_object(i_file = "testdir", kind="dir"), DirURLFix)

def test_dir_checks(test_object):
    # Use known changed URLs doc
    with pytest.raises(OSError) as err:
        test_object(i_file = "non_existent", kind="dir").replace_urls()
        assert str(err) == "Path does not exist!"
    with pytest.raises(NotADirectoryError) as err:
        test_object(i_file = "testurls.txt", kind="dir").replace_urls()
        assert str(err.exception) == "Input path must be a directory!"

def test_skips(test_object):
    # Check that if a known URL is provided, it is skipped
    number_moved_list = test_object(i_file="testdir", kind="dir").replace_urls(
            correct_urls=["https://zenodo.org/badge/DOI/10.5281/zenodo.3891106.svg"],
            verbose=True)
    # # Since we have three files, assert that the length returned is 3
    assert len(number_moved_list) == 3
    assert number_moved_list[0] == 3
    # # 1 since we provided correct URLs. TODO: Figure out how to run both tests
    # # 3 since we match double links if []()[]()
    assert number_moved_list[1] == 3
    assert number_moved_list[2] == 2
    remove_output_files()

def test_inplace_repls(test_object):
    number_moved_l = test_object(i_file = "testinplace",kind="dir").replace_urls(verbose=1,
                inplace=True)
    assert number_moved_l[0] == 3
    assert number_moved_l[1] == 3
    assert number_moved_l[2] == 2

    # If inplace replacement works, then these should all be zeros
    after_inplace = test_object(i_file = "testinplace",kind="dir").replace_urls(verbose=1, inplace=True)
    assert all(x == 0 for x in after_inplace)
    # If tests pass, restore files in the target directory
    test_files = os.path.join(dir_path, "testdir")
    test_inplace_files = os.path.join(dir_path, "testinplace")
    print("Restoring inplace replacement test files after tests....")
    rmtree(test_inplace_files)
    copytree(test_files, test_inplace_files)

# TODO: Make it possible to use our fixture for this
def test_recursion():
    # Make path to recursion tests
    recursive_path = os.path.join(dir_path, "recursive")
    recursive_object = DirURLFix(recursive_path, recursive=False)
    number_moved_list = recursive_object.replace_urls(verbose=1)
    # Since we have two root files, then non-recursive replacements should be of length 2
    assert len(number_moved_list) == 2
    # For the first file, we expect only 3 urls to have moved while for the second we expect 5
    assert number_moved_list[0] == 3
    assert number_moved_list[1] ==  5
    remove_output_files()
    # Next, we set recursion to true
    recursive_recursive_object = DirURLFix(recursive_path, recursive=True)
    number_moved_list_recurse = recursive_recursive_object.replace_urls(verbose=1)
    # The first two values are root files as above
    # The second list contains recursive replacements
    assert len(number_moved_list_recurse) == 3
    # 3 because we have three files in the directory recursive/testdir
    assert len(number_moved_list_recurse[2]) == 3
    # Do not test since we have already tested the same directory before?
    # test sub-recursion
    remove_output_files()

def test_sub_recursion(test_object):
    print("Testing sub-recursion")
    recursive_path = os.path.join(dir_path, "recursive")
    moved_list = DirURLFix(recursive_path, recursive=True, sub_recursive=True).replace_urls(verbose=1)
    # Assert that we have the expected number of files:
    assert len(moved_list) == 3
    remove_output_files()


from tkinter import *
from math import *

#settings
window_size = 500
space = window_size / 20

#window
win = Tk()
win.title("spiral lol")
win.resizable(False, False)
win.geometry(str(window_size) + "x" + str(window_size))
win.configure(background="white")

# variabes
run = False
steps = 0
digit = 1
neededSteps = 1
direction = "right"
xpo = window_size / 2
ypo = window_size / 2

def activate():
    global run
    run = True
    startButton.destroy()

# main
def main():
    global run
    global steps
    global digit
    global neededSteps
    global direction
    global xpo
    global ypo

    if run == True:
        # 1. print
        label = Label(win, text=digit, bg="white")
        label.place(x=xpo,y=ypo)
        print("digit: ", digit, " neededSteps: ", neededSteps, " direction: ", direction)

        # 2. move
        if steps < floor(neededSteps):
            if direction == "right":
                xpo += space
            elif direction == "up":
                ypo -= space
            elif direction == "left":
                xpo -= space
            elif direction == "down":
                ypo += space
            steps += 1
            digit += 1

        # 3. turn
        if steps == floor(neededSteps):
            if direction == "right":
                direction = "up"
            elif direction == "up":
                direction = "left"
            elif direction == "left":
                direction = "down"
            elif direction == "down":
                direction = "right"
            steps = 0
            neededSteps += 0.5

        #stop drawing
        if xpo > window_size or ypo > window_size:
            run = False

    win.after(100, main)

# start
startButton = Button(win, text="start", padx=50, pady=50, command=activate, fg="blue", bg="white")
startButton.place(x=window_size/2-65,y=window_size/2-65)

#update
win.after(100, main)
win.mainloop()


from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.urls import path
from . import views

urlpatterns = [
    url(r'change_password', views.change_password, name='change_password'),
    url('index', views.index, name='index'),
    url('dashboard/', views.dashboard, name='dashboard'),
    url('show_user/', views.show_user, name='show_user'),
    url('show_role/', views.show_role, name='show_role'),
    url('show_permission/', views.show_permission, name='show_permission'),
    url('show_role_to_user/', views.show_role_to_user, name='show_role_to_user'),
    url('show_permission_to_role', views.show_permission_to_role, name='show_permission_to_role'),
    url('add_user/', views.add_user, name='add_user'),
    url('add_role/', views.add_role, name='add_role'),
    url('add_permission/', views.add_permission, name='add_permission'),
    url('add_role_to_user/', views.add_role_to_user, name='add_role_to_user'),
    url('add_permission_to_role', views.add_permission_to_role, name='add_permission_to_role'),
    path('<int:id>/update_user', views.update_user, name='update_user'),
    #path('update_user', views.update_user, name='update_user'),
    path(r'<int:id>/update_role/', views.update_role, name='update_role'),
    path('<int:id>/update_permission/', views.update_permission, name='update_permission'),
    path('<int:id>/update_role_to_user/', views.update_role_to_user, name='update_role_to_user'),
    path('<int:id>/update_permission_to_role', views.update_permission_to_role, name='update_permission_to_role'),
    path('<int:id>/delete_user/', views.delete_user, name='delete_user'),
    path('delete_user/', views.delete_user, name='delete_user'),
    path('<int:id>/delete_role/', views.delete_role, name='delete_role'),
    path('<int:id>delete_permission/', views.delete_permission, name='delete_permission'),
    path('<int:id>/delete_role_to_user/', views.delete_role_to_user, name='delete_role_to_user'),
    path('<int:id>/delete_permission_to_role', views.delete_permission_to_role, name='delete_permission_to_role'),
    url(r'logout/', auth_views.LogoutView.as_view(template_name='myapp/logout.html'), name='logout'),
    url(r'', auth_views.LoginView.as_view(template_name='myapp/login.html'), name='login'),

   #path('hello',views.Hello.as_view()),
]


import time
from mtablica import MonitorowanaTablica
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

N = 50  # liczba elementów, można zmieniać
FPS = 60  # klatki na sekundę do parametru interval

tablica = MonitorowanaTablica(0, 1000, N, "T") # zbadaj też opcje: "S", "A", "T"

###############################################
############ Przykład: Quick Sort #########

def quicksort(tablica, start, end):
    if end - start > 1:
        p = partition(tablica, start, end)
        quicksort(tablica, start, p)
        quicksort(tablica, p + 1, end)

def partition(tablica, start, end):
    pivot = tablica[start]
    i = start + 1
    j = end - 1

    while True:
        while (i <= j and tablica[i] <= pivot):
            i = i + 1
        while (i <= j and tablica[j] >= pivot):
            j = j - 1

        if i <= j:
            tablica[i], tablica[j] = tablica[j], tablica[i]
        else:
            tablica[start], tablica[j] = tablica[j], tablica[start]
            return j

algorytm = "QuickSort"
t0 = time.perf_counter()

quicksort(tablica, 0, len(tablica))

delta_t = time.perf_counter() - t0
###############################################
###############################################
print(f"Sortowanie: {algorytm}")
print(f"Tablica posortowana w czasie {delta_t*1000:.1f} ms. Liczba operacji: {len(tablica.pelne_kopie):.0f}.")
###############################################

# konfiguracja wyświetlania histogramu
plt.rcParams["font.size"] = 16
fig, ax = plt.subplots(figsize=(16, 8))
container = ax.bar(np.arange(0, len(tablica), 1), tablica.pelne_kopie[0], align="edge", width=0.8)
fig.suptitle(f"Sortowanie: {algorytm}")
ax.set(xlabel="Indeks", ylabel="Wartość")
ax.set_xlim([0, N])
txt = ax.text(0.01, 0.99, "", ha="left", va="top", transform=ax.transAxes)

# funkcja aktualizująca stan poszczególnych klatek do wyświetlenia
def update(frame):
    txt.set_text(f"Liczba operacji = {frame}")
    for rectangle, height in zip(container.patches, tablica.pelne_kopie[frame]):
        rectangle.set_height(height)
        rectangle.set_color("darkblue")

    idx, op = tablica.aktywnosc(frame)
    if op == "get":
        container.patches[idx].set_color("green")
    elif op == "set":
        container.patches[idx].set_color("red")

    return (txt, *container)

# tu akumulowana jest animacja, wyświetlna komendą show
ani = FuncAnimation(fig, update, frames=range(len(tablica.pelne_kopie)), blit=True, interval=1000./FPS, repeat=False)
plt.show()


# -*- coding: utf-8 -*-

import discord
from discord.ext import commands, tasks
import asyncio
from dateutil.relativedelta import relativedelta as rdelta
import traceback
import m10s_util as ut
import textwrap

import config
import aiohttp

from discord import app_commands

class m10s_direct_msg(commands.Cog):

    def __init__(self, bot):
        self.bot: commands.Bot = bot

    @commands.command()
    @commands.is_owner()
    @ut.runnable_check()
    async def send_dm(self, ctx, target_id:int, *, content:str):
        try:
            user = await self.bot.fetch_user(target_id)
        except discord.NotFound:
            await ctx.author.send("該当ユーザーが見つかりませんでした。")
        except discord.HTTPException:
            await ctx.author.send("ユーザーの取得に失敗しました。")
        else:
            m  = await ctx.author.send(f"`{str(user)}`に```\n{content}```と送信してもよろしいですか？")
            await m.add_reaction("⭕")
            await m.add_reaction("❌")
            try:
                r,u = await self.bot.wait_for("reaction_add", timeout=30, check=lambda r,u:u.id == ctx.author.id and str(r.emoji) in ["⭕","❌"])
            except asyncio.TimeoutError:
                await m.edit("タイムアウトしました。再度操作を行ってください。")
            if str(r.emoji) == "⭕":
                try:
                    await user.send(content)
                except:
                    await ctx.author.send("送信に失敗しました。")
                else:
                    await ctx.author.send("送信しました。")
            else:
                await ctx.author.send("キャンセルしました。")

async def setup(bot):
    await bot.add_cog(m10s_direct_msg(bot))


from __future__ import absolute_import

import numpy as np

from luchador import nn
from tests.unit import fixture

class SessionTest(fixture.TestCase):
    def _test_load_dataset(self, dtype1, dtype2):
        name = 'test_load_dataset_{}_{}'.format(dtype1, dtype2)
        shape = (3, 3)
        target_value = 10

        variable = nn.make_variable(name=name, shape=shape, dtype=dtype1)
        value = target_value * np.ones(shape, dtype=dtype2)

        session = nn.Session()
        session.load_dataset({name: value}, cast=not dtype1 == dtype2)

        updated_value = session.run(outputs=variable)
        self.assertTrue(np.all(target_value == updated_value))

    def test_load_dataset_float32(self):
        """Variable value is set via Session.load_dataset when dtype=float32"""
        self._test_load_dataset('float32', 'float32')

    def test_load_dataset_float64(self):
        """Variable value is set via Session.load_dataset when dtype=float64"""
        self._test_load_dataset('float64', 'float64')

    def test_load_dataset_downcast(self):
        """Variable value is set when data is downcasted"""
        self._test_load_dataset('float32', 'float64')

    def test_load_dataset_upcast(self):
        """Variable value is set when data is downcasted"""
        self._test_load_dataset('float64', 'float32')

    def test_apply_gradient_directory(self):
        """Variables can be updated by appyling gradient directly"""
        w_0 = 6
        with nn.variable_scope(self.get_scope()):
            x = nn.Input(shape=(), name='x')
            w = nn.make_variable(
                name='w', shape=(),
                initializer=nn.initializer.ConstantInitializer(w_0),
            )
            y = w * x

            sgd = nn.optimizer.SGD(learning_rate=1.0)
            update_op = sgd.minimize(y, w)
            dw = nn.get_tensor('{}_grad'.format(w.name))

            session = nn.Session()
            session.initialize()

            val0 = 3.
            session.run(updates=update_op, givens={dw: val0})
            val_w = session.run(outputs=w)

            np.testing.assert_almost_equal(val_w, w_0 - val0)

    def test_check_optimizer_slot(self):
        """Slot variables are updated when applying gradient directly"""
        name, b1_0, b2_0 = 'Adam', 0.5, 0.4
        opt = nn.optimizer.Adam(
            learning_rate=1.0, name=name, beta1=b1_0, beta2=b2_0)
        with nn.variable_scope(self.get_scope()):
            x = nn.Input(shape=(), name='x')
            w = nn.make_variable(shape=(), name='w')
            update_op = opt.minimize(w * x, w)

            dw = nn.get_tensor('{}_grad'.format(w.name))
            b1 = nn.get_variable('{}/beta1_power'.format(name))
            b2 = nn.get_variable('{}/beta2_power'.format(name))

        session = nn.Session()
        session.initialize()

        for i in range(10):
            b1_val, b2_val = session.run(outputs=[b1, b2])
            np.testing.assert_almost_equal(b1_val, b1_0 ** (i + 1))
            np.testing.assert_almost_equal(b2_val, b2_0 ** (i + 1))
            session.run(updates=update_op, givens={dw: 1.0})


import requests
import datetime
from database import engine, SessionLocal
from sqlalchemy.orm import Session
import models
import pandas as pd
from sqlalchemy import create_engine, desc

try:
    db = SessionLocal()
    db: Session
finally:
    db.close()

now1 = datetime.datetime.now()
coinList = db.query(models.coinList).filter(models.coinList.delflag == 0).all()

for coin in coinList:
    try:
        now = datetime.datetime.now()

        # csv 파일 읽어오기
        try:
            current_time = now.strftime("%d%H%M")
            df = pd.read_csv(f"./csv/{coin.coin_name}{current_time}.csv")
        except:
            now = now - datetime.timedelta(minutes=1)
            current_time = now.strftime("%d%H%M")
            df = pd.read_csv(f"./csv/{coin.coin_name}{current_time}.csv")

        # 기간 지정
        end_date = pd.to_datetime(current_time)

        # 12일 EMA 계산
        ema12 = df['close'].ewm(span=12).mean()
        # 26일 EMA 계산
        ema26 = df['close'].ewm(span=26).mean()
        # MACD 계산
        macd = ema12 - ema26

        # Signal line 계산
        signal_line = macd.ewm(span=9).mean()

        # MACD histogram 계산
        macd_histogram = macd - signal_line

        disparityMa = df["close"].rolling(window=12).mean()
        disparity = float(disparityMa) / float(df["close"][-1]) * 100

        print(disparityMa)

    except Exception as e:
        print(e, coin.coin_name)

now2 = datetime.datetime.now()
print(now2-now1)


from typing import TYPE_CHECKING, Any, Final

from aiogram import BaseMiddleware

from bot.database.repository.repository import Repository

if TYPE_CHECKING:
    from collections.abc import Awaitable, Callable

    from aiogram.types import TelegramObject
    from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker

class RepositoryMiddleware(BaseMiddleware):
    """Мидлварь для добавления класса-репозитория в аргументы обработчиков телеграма."""

    SESSION_KEY: Final[str] = "session"
    REPOSITORY_KEY: Final[str] = "repo"

    def __init__(
        self,
        session_maker: "async_sessionmaker[AsyncSession]",
        session_key: str = SESSION_KEY,
        repository_key: str = REPOSITORY_KEY,
    ) -> None:
        self.session_maker = session_maker
        self.session_key = session_key
        self.repository_key = repository_key

    async def __call__(
        self,
        handler: "Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]]",
        event: "TelegramObject",
        data: dict[str, Any],
    ) -> Any:
        async with self.session_maker.begin() as session:
            data[self.session_key] = session
            data[self.repository_key] = Repository(session)
            return await handler(event, data)


"""
@author: LowinLi
字典处理
"""

import jieba_fast
from tqdm import tqdm
import pandas as pd
import re

jieba_fast.enable_parallel()

def main(file="../data/0609/merge_data_plus_shuffle_lm_512.txt"):
    token_dict = {}
    with open(file, "r") as f:
        lines = f.readlines()
    for line in tqdm(lines):
        tokens = jieba_fast.lcut(line)
        for token in tokens:
            if token in token_dict:
                token_dict[token] += 1
            else:
                token_dict[token] = 1
    df = pd.DataFrame({"word": token_dict.keys(), "count": token_dict.values()})
    pat = re.compile(
        "[\u4e00-\u9fa5]|[\u3002\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b]"
    )  # 所有中文和中文标点
    df["chinese"] = df["word"].apply(lambda x: bool(pat.search(x)))
    df = df[df["chinese"]]
    df = df.sort_values("count", ascending=False)
    with open("special_tokens.txt", "r") as f:
        vocabs = f.read()

    df["length"] = df["word"].apply(lambda x: len(x))
    # 5000个字和标点
    for word in (df["word"][df["length"] == 1].iloc[:5000]).tolist():
        vocabs += word + "\n"
    # 15000-106个词
    for word in (df["word"][df["length"] > 1].iloc[: 15000 - 106]).tolist():
        vocabs += word + "\n"
    with open("../data/0609/vocab.txt", "w") as f:
        f.write(vocabs)

if __name__ == "__main__":
    main()


from extras.blackjack import logo
import random as r
import subprocess as s

#! My_attempt(failed)

    # cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    # user_deck = [r.choice(cards), r.choice(cards)]
    # computer_deck = [r.choice(cards), r.choice(cards)]
    # result_of_a_game = ""
    # game_is_not_end = True
    # s.call("clear")
    # ask_for_game = input("Do you want to play some Blackjack? y/n: ").lower()

    # if ask_for_game != "y":
    #     exit("So why you are here?")
    # s.call("clear")
    # print(logo)

    # def blackjack(deck):
    #     result = False
    #     if sum(deck) == 21:
    #         result = True
    #     return result

    # def over_21(deck):
    #     result = False
    #     if sum(deck) > 21:
    #         if 11 in deck:
    #             if sum(deck) - 10 < 21:
    #                 return result
    #             else:
    #                 result = True
    #                 return result
    #         else:
    #             result = True
    #             return result
    #     else:
    #         return result

    # while game_is_not_end:
    #     user_deck = [r.choice(cards), r.choice(cards)]
    #     computer_deck = [r.choice(cards), r.choice(cards)]
    #     if blackjack(computer_deck) == True:
    #         result_of_a_game = "lose"
    #         game_is_not_end = False
    #         print("Computer has blackjack:", computer_deck, "You are", result_of_a_game)

    #     elif blackjack(user_deck) == True:
    #         result_of_a_game = "win"
    #         game_is_not_end = False
    #         print("You have blackjack:", user_deck, "You are", result_of_a_game)

    #     elif over_21(user_deck) == True:
    #         result_of_a_game = "lose"
    #         game_is_not_end = False
    #         print("Computer deck is:", computer_deck, "\nUser deck is:", user_deck, "You are", result_of_a_game)

    #     else:
    #         print("sup")
    #         print("Computer deck is:", computer_deck, "\nUser deck is:", user_deck)
    #         game_is_not_end = False

s.call("clear")

def deal_card():
    """Returns a random card from the deck"""
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    card = r.choice(cards)
    return card

def calculate_score(cards):
    """Take a list of cards an return the score calculated from the cards"""
    if sum(cards) ==21 and len(cards) == 2:
        return 0
    if 11 in cards and sum(cards) > 21:
        cards.remove(11)
        cards.append(1)
    return sum(cards)

def compare(user_score, computer_score):
    if user_score == computer_score:
        return "Draw"
    elif computer_score == 0:
        return "Lose, opponent has Blackjack!"
    elif user_score == 0:
        return "You win with a Blackjack!"
    elif user_score > 21:
        return "You went over. You lose!"
    elif computer_score > 21:
        return "Opponent went over. You win!"
    elif user_score > computer_score:
        return "You win!"
    else:
        return "You lose!"

def play_game():

    user_cards = []
    computer_cards = []
    is_game_over = False
    user_score = 99
    computer_score = 99

    print(logo)
    for _ in range(2):
        user_cards.append(deal_card())
        computer_cards.append(deal_card())

    while not is_game_over:
        user_score = calculate_score(user_cards)
        computer_score = calculate_score(computer_cards)
        print(f"Your cards: {user_cards} current score: {user_score}")
        print(f"Computer's first card: {computer_cards[0]}")

        if user_score == 0 and computer_score == 0 or user_score > 21:
            is_game_over = True
        else:
            user_should_deal = input("Type 'y' to get another card, type 'n' to pass:\t")
            if user_should_deal == "y":
                user_cards.append(deal_card())
            else:
                is_game_over = True

    while computer_score != 0 and computer_score < 17:
        computer_cards.append(deal_card())
        computer_score = calculate_score(computer_cards)

    print(f"    Your final hand: {user_cards}, final_score: {user_score}")
    print(f"    Computer's final hand : {computer_cards}, final_score: {computer_score}")
    print(compare(user_score, computer_score))

while input("Do you want to play the game of Blackjack? Type 'y' or 'n'\t") == 'y':
    s.call("clear")
    play_game()


from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import csv
import os.path

def abstracts_sims(pairsSet, fileName):
    if not os.path.isfile(fileName):

        # Import node information
        with open("./node_information.csv", "r") as f:
            reader = csv.reader(f)
            node_info = list(reader)
        IDs = [element[0] for element in node_info]

        print("Cosine similarities for the abstracts are calculated.")

        corpus = [element[5] for element in node_info]
        vectorizer = TfidfVectorizer(stop_words="english")
        # each row is a node in the order of node_info
        features_TFIDF = vectorizer.fit_transform(corpus)  # compute TFIDF vector of each paper's abstract
        abstractsSimilarities = cosine_similarity(features_TFIDF)

        sims = []

        for i in range(len(pairsSet)):
            source = pairsSet[i][0]  # an ID of edges
            target = pairsSet[i][1]  # an ID of edges

            ## find an index maching to the source and target ID
            index_source = IDs.index(source)
            index_target = IDs.index(target)

            sims.append(abstractsSimilarities[index_source, index_target])

        with open(fileName, 'w') as f:
            csv_out = csv.writer(f)
            for row in sims:
                csv_out.writerow([row])