import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import os
import lob_for_futures as lobFut
from lob_for_futures import *
import os
import matplotlib.pyplot as plt

from dateutil.parser import parse
from pandas.tseries.offsets import BDay
import pickle as pkl
import fnmatch
import pickle
import datetime as dt
from datetime import timedelta
import glob
import fathon
from fathon import fathonUtils as fu
import itertools
import pyinform as pyinf
import pingouin as pig
from scipy.stats import entropy
from scipy.spatial.distance import jensenshannon
from scipy.special import kl_div
import time
dataFolder = lobFut.dataFolder
quotes =[f for f in os.listdir(dataFolder) if str('_quotes') in f]
trades =[f for f in os.listdir(dataFolder) if str('_trades') in f]

symbolIdx = 2

symbols = [f.split("_")[0] for f in quotes]

symbol = sorted(symbols)[symbolIdx]
print(symbol)
quotesFileCh = os.path.join(dataFolder, quotes[symbolIdx])
tradesFileCh = os.path.join(dataFolder, trades[symbolIdx])

# get common Dates
quotesDates = sorted([f.split(".csv")[0] for f in os.listdir(quotesFileCh)])
tradesDates = sorted([f.split(".csv")[0] for f in os.listdir(tradesFileCh)])
intersectionDates = list(set(quotesDates).intersection(tradesDates))

trades_cols = ['size', 'time', 'type', 'value']
experimentsDestination = '/media/ak/T7/MFDFA Experiments'

if __name__ == '__main__':
    # params i need for fathon
    winSizes = fu.linRangeByStep(5, 60)
    revSeg = True
    polOrd = 1
    # load all teh dataframes at once with this
    start = time.time()
    print(start)
    # go through all the dataframes and take out n, f and h, h_ intercept
    # somehow one list comprehension blows up in memory

    h_dict = defaultdict(dict)

    symbolIdx = 0

    symbol = sorted(symbols)[symbolIdx]
    print(symbol)
    quotesFileCh = os.path.join(dataFolder, quotes[symbolIdx])
    tradesFileCh = os.path.join(dataFolder, trades[symbolIdx])

    # get common Dates
    quotesDates = sorted([f.split(".csv")[0] for f in os.listdir(quotesFileCh)])
    tradesDates = sorted([f.split(".csv")[0] for f in os.listdir(tradesFileCh)])
    intersectionDates = list(set(quotesDates).intersection(tradesDates))

    trades_cols = ['size', 'time', 'type', 'value']

    # params for the clocks

    calendar_resample_freq = "300S"
    trade_volume_width = 100
    ticks_width = 100
    usd_volume_width = 100
    dates_choice = intersectionDates

    testClass = DataLoader(data_location=dataFolder,
                           symbol=symbol,
                           dates=dates_choice,
                           use_columns=trades_cols,
                           calendar_resample=calendar_resample_freq,
                           trade_volume_width=trade_volume_width,
                           ticks_width=ticks_width,
                           usd_volume_width=usd_volume_width)

    hash_of_file = "_".join(
        (str(symbol), "volume_width", str(trade_volume_width), "calendar_resample", str(calendar_resample_freq)))

    # load data
    input_dict = testClass.load_and_format_data()

    tick_bar_dfs = []
    volume_bar_dfs = []
    usd_volume_bar_dfs = []
    calendar_bar_dfs = []
    dates = list(input_dict.keys())

    bar_returns = dict()
    for date in dates:
        df = testClass.load_and_format_data()[str(date)]
        input_dict = testClass.get_bars(df)
        tick_bar_df = testClass.get_concat_data(testClass._bars_dict)['tick_bars']
        volume_bar_df = testClass.get_concat_data(testClass._bars_dict)['volume_bars']
        usd_volume_bar_df = testClass.get_concat_data(testClass._bars_dict)['usd_volume_bars']
        calendar_bar_df = testClass.get_concat_data(testClass._bars_dict)['calendar_bars']
        vr = returns(volume_bar_df.micro_price_close).replace([np.inf, -np.inf], 0)  # volume
        tr = returns(tick_bar_df.micro_price_close).replace([np.inf, -np.inf], 0)  # tick
        dr = returns(usd_volume_bar_df.micro_price_close).dropna().replace([np.inf, -np.inf], 0)  # usd volume
        df_ret = returns(calendar_bar_df.micro_price_close).dropna().replace([np.inf, -np.inf], 0)  # calendar
        bar_returns[date] = {'tick': tr,
                             'volume': vr,
                             'dollar': dr,
                             'calendar': df_ret}
    dict_dfa = defaultdict(dict)
    for i, j in itertools.product(['tick', 'volume', 'dollar', 'calendar'], dates):
        data = (bar_returns[j][i])
        a = fu.toAggregated(np.asanyarray(data))
        pydfa = fathon.DFA(a)
        pymfdfa = fathon.MFDFA(a)
        n, F = pydfa.computeFlucVec(winSizes, revSeg=revSeg, polOrd=polOrd)
        dict_dfa[j][i] = dict(zip(n, F))  # dictionary to match all the n and F values

        H, H_intercept = pydfa.fitFlucVec()  # same for H values
        h_dict[j][i] = [H, H_intercept]

        print('for date', j, ' and bar type', i, 'you get', H)

        # everything below here is to store

    pickle_out_filename = os.path.join(experimentsDestination, symbol, 'DFA_' +
                                       'n_f_values' +"volume_width"+ str(trade_volume_width)
                                       + "calendar_resample"+ str(calendar_resample_freq)+
                                       '_bar_' + str(i) + '_' + str(j) + '.pkl')
    pickle.dump(dict_dfa, open(pickle_out_filename, 'wb'), protocol=pickle.HIGHEST_PROTOCOL)
    print('just saved: ', pickle_out_filename)

    pickle_out_filename_two = os.path.join(experimentsDestination, symbol, 'DFA_' +
                                       'n_f_values' +"volume_width"+ str(trade_volume_width)
                                       + "calendar_resample"+ str(calendar_resample_freq)+
                                       '_bar_' +
                                       'H_values' + '_bar_' + str(i) + '_' + str(j) + '.pkl')
    pickle.dump(h_dict, open(pickle_out_filename_two, 'wb'), protocol=pickle.HIGHEST_PROTOCOL)
    print('just saved: ', pickle_out_filename_two)


import math
t = (" Desafio 18 ")
print(f"{t:=^20}")
n = float(input("Digite o ângulo em graus: "))
sen = math.sin(math.radians(n))
cos = math.cos(math.radians(n))
tg = math.tan(math.radians(n))
print(f"Para o ângulo de {n}, o SENO é {sen:.2f}!")
print(f"Para o ângulo de {n}, o COSSENO é {cos:.2f}!")
print(f"Para o ângulo de {n}, a TANGENTE é {tg:.2f}!")


import streamlit as st
import preprocessor, helper
import matplotlib.pyplot as plt

st.sidebar.title("Whatsapp Chat Analyzer")
uploaded_file = st.sidebar.file_uploader("Choose a file")
if uploaded_file is not None:
    bytes_data = uploaded_file.getvalue()
    data=bytes_data.decode("utf-8")
    df = preprocessor.preprocess(data)

    st.dataframe(df)
    #to extract users
    users_list=df['user'].unique().tolist()
    users_list.remove('group_notification')
    users_list.sort()
    users_list.insert(0,"Overall")

    selected_user = st.sidebar.selectbox("show Analysis wrt",users_list)

    if st.sidebar.button("Show Analysis"):
        col1, col2, col3, col4 = st.columns(4)
        num_message, words, num_media_msg,links = helper.fetch_stats(selected_user,df)
        with col1:
            st.header("Total Messages")
            st.title(num_message)
        with col2:
            st.header("Total Words")
            st.title(words)
        with col3:
            st.header("Media")
            st.title(num_media_msg)
        with col4:
            st.header("Links")
            st.title(links)

        #finding the busiest users in the group
        if selected_user == 'Overall':
            st.title('Busiest User')
            x, new_df =helper.busiest_user(df)
            fig, ax = plt.subplots()
            col1, col2 = st.columns(2)
            with col1:
                ax.bar(x.index,x.values,color='yellow')
                plt.xticks(rotation='vertical')
                st.pyplot(fig)
            with col2:
                st.dataframe(new_df)

        #WordCloud
        st.title("Word Cloud")
        df_wc =helper.create_wordcloud(selected_user,df)
        fig,ax = plt.subplots()
        ax.imshow(df_wc)
        st.pyplot(fig)


from math import inf
from . import utils

def get_ranking_groups(evaluated_solutions):
    to_rank = evaluated_solutions[:]
    ranked = []

    while to_rank:
        dominated = []
        this_rank = []

        to_rank.sort(key=lambda solution: solution['evaluation'])

        to_rank[0]['rank'] = len(ranked)
        this_rank.append(to_rank[0])
        i = 0
        j = 1
        while j < len(to_rank):
            if not utils.is_dominated_by(to_rank[j]['evaluation'], to_rank[i]['evaluation']):
                to_rank[j]['rank'] = len(ranked)
                this_rank.append(to_rank[j])
                i = j
                j = i+1
            else:
                dominated.append(to_rank[j])
                j += 1

        ranked.append(this_rank)
        to_rank = dominated

    return ranked

def get_hyperspace_contributions_and_sort(ranking_groups, reference_point):
    for group in ranking_groups:

        for i, sol in enumerate(group):
            if i == 0:
                point1 = (reference_point[1] - sol['evaluation'][1])
            else:
                point1 = (group[i-1]['evaluation'][1] - sol['evaluation'][1])

            if i == len(group)-1:
                point2 = (reference_point[0] - sol['evaluation'][0])
            else:
                point2 = (group[i+1]['evaluation'][0] - sol['evaluation'][0])

            sol['score'] = point1*point2

        group.sort(key=lambda solution: solution['score'], reverse=True)

def get_crowding_distances_and_sort(ranking_groups):
    for group in ranking_groups:

        for i, sol in enumerate(group):
            if i in (0, len(group)-1):
                sol['score'] = inf
            else:
                sol['score'] = (2*(group[i+1]['evaluation'][0] - group[i-1]['evaluation'][0]) +
                                2*(group[i-1]['evaluation'][1] - group[i+1]['evaluation'][1]))

        group.sort(key=lambda solution: solution['score'], reverse=True)

def get_SMSEMOA_ranker(reference_point):

    def SMSEMOA_ranker(solutions):
        ranking_groups = get_ranking_groups(solutions)
        get_hyperspace_contributions_and_sort(ranking_groups, reference_point)

        flattened = [solution for group in ranking_groups for solution in group]
        return flattened

    return SMSEMOA_ranker

def get_NSGAII_ranker():

    def NSGAII_ranker(solutions):
        ranking_groups = get_ranking_groups(solutions)
        get_crowding_distances_and_sort(ranking_groups)

        flattened = [solution for group in ranking_groups for solution in group]
        return flattened

    return NSGAII_ranker


import numpy as np
import cv2
import config

all_frames = []
for i, filename in enumerate(config.input_filenames):
    frame = cv2.imread(filename)
    frame = cv2.resize(frame, (config.target_width, config.target_height), interpolation=cv2.INTER_AREA)
    all_frames.append(frame)
    cv2.imwrite(config.frame_path + str(i) + '.png', frame)
all_frames = np.stack(all_frames, axis=0)
np.save(config.frame_path + 'all_frames', all_frames)
print('All Frames Saved: ' + config.frame_path + 'all_frames.npy')

from raft.api import do_match
from fastwarp.api import flow_to_normal as flow_to_normal

def compute_flow(f, t):
    frame = cv2.imread(config.frame_path + str(f) + '.png')
    target_frame = cv2.imread(config.frame_path + str(t) + '.png')
    flow = do_match(frame, target_frame, scale=1.0, iter=20)
    flag = str(f) + 'T' + str(t)
    np.save(config.flow_path + flag, flow)
    cv2.imwrite(config.flow_path + flag + '.png', flow_to_normal(flow, uint8=True))
    print('Flow Computed: ' + flag)
    return flow

all_flows = []
for i in range(config.file_count):
    flows = []
    for t in config.key_flow_range(i):
        flow = compute_flow(i, t)
        flows.append(flow)
    flows = np.stack(flows, axis=0)
    all_flows.append(flows)
all_flows = np.stack(all_flows, axis=0)

np.save(config.flow_path + 'all_flows', all_flows)
print('All Flows Saved: ' + config.flow_path + 'all_flows.npy')


import numpy as np
import cv2
from matplotlib import pyplot as plt

# Read image
img1 = cv2.imread('basmati.pgm')
img2 = cv2.imread('basmati2.pgm')

# Initiate SURF detector
surf = cv2.xfeatures2d.SURF_create()

# Convering to Gray
img1= cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
img2= cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)

# find the keypoints and descriptors with SURF
kp1, des1 = surf.detectAndCompute(img1,None)
kp2, des2 = surf.detectAndCompute(img2,None)

# no.of keypoints
print(len(des1))
print(len(des2))

# BFMatcher with default params
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1,des2, k=2)

# Create images with keypoints
img1=cv2.drawKeypoints(img1,kp1,img1)
cv2.imwrite('2surf_keypoints.jpg',img1)

img2=cv2.drawKeypoints(img2,kp2,img2)
cv2.imwrite('3surf_keypoints.jpg',img2)

# Apply ratio test
good = []
for m,n in matches:
    if m.distance < 0.75*n.distance:
        good.append([m])

print("matches ")
print(len(good))


# https://leetcode.com/problems/reverse-linked-list/

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head is None or head.next is None:
            return head

        nextNode = head.next
        head.next = None
        prevNode = head
        while nextNode is not None:
            curNode = nextNode
            nextNode = curNode.next
            curNode.next = prevNode
            prevNode = curNode

        return prevNode


import matplotlib.pylab as plt

days = [1,2,3,4,5]
sleeping = [7,8,6,11,7]
eating = [2,3,4,3,2]
working = [7,8,7,2,2]
playing = [8,5,7,8,13]

slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']

cols = ['r','g','y','b']

plt.pie(slices,
        labels = activities ,
        colors = cols,
        startangle=90,
        shadow=True,
        explode=(0,0.1,0,0.1),
        autopct='%1.1f%%')

#plt.xlabel('X')
#plt.ylabel('Y')

plt.legend()

plt.title('Intresting Graph\nCheck it Out')
plt.show()


#https://stackoverflow.com/questions/66724687/how-to-solve-a-429-too-many-requests-when-running-discord-py-bot-on-repl-it
#read if get 429 error
from discord.ext import commands
import discord, os, random, time, requests
from keep_alive import keep_alive
import json, asyncio
from replit import db

def _reset():
  db["lastbump"] = 10
  db["reminded"] = False
  exit()

token = os.environ["token"]
intents=discord.Intents.all()

bot = commands.Bot(command_prefix="!",intents=intents)
bot.remove_command('help')
guilds = [871696913987162112]

class userdata:
  def __init__(self):
    pass

  def getdata(self, username):
    try:
      x = requests.get(f"https://scratchdb.lefty.one/v3/user/info/{username}", timeout=10)
    except Exception as e:
      return ["....","Scratchdb took too long to respond"+str(e)]
    statuscode = x.status_code
    if statuscode != 200:
      return ["...",statuscode]
    x = x.json()
    self.username = x["username"]
    self.id = str(x["id"])
    self.pfp = f"https://cdn2.scratch.mit.edu/get_image/user/{self.id}_90x90.png?v="
    self.rank = x["status"]
    self.joined = x["joined"]
    self.WIWO = x["work"]
    self.AM = x["bio"]
    self.country = x["country"]
    self.followers = x["statistics"]["followers"]
    self.following = x["statistics"]["following"]
    return "done"

def _joke(typeofjoke):
  x = requests.get(f"https://official-joke-api.appspot.com/jokes/{typeofjoke}/random")
  if x.status_code != 200:
    return "An error has occurred. please try again later."
  x = x.json()
  if len(x) == 0:
    return "An error has occurred. please try again later."
  x = x[0]
  return [x["setup"],x["punchline"]]

def _fact():
  x = requests.get("https://uselessfacts.jsph.pl/random.json?language=en")
  if x.status_code != 200:
    return "An error has occurred. please try again later."+str(x.status_code)
  else:
    return x.json()["text"]

user = userdata()

@bot.event
async def on_ready():
  print("Bot is ready!")
  channel = bot.get_channel(877770366741803062)
  while True:
    t = (db["lastbump"] + 2*60*60) - int(time.time()//1)
    if t <= 0:
      if db["reminded"] == False:
        db["reminded"] = True
        await channel.send("Time to bump! use `!d bump` command to bump.")

    await asyncio.sleep(1)

@bot.event
async def on_member_join(member):
  role = discord.utils.get(member.guild.roles, name="member")
  print(bool(role == 875675800886726666))
  await member.add_roles(role)
  await member.send("Hey, this feature is in testing. Please go to #general in scratchers hub and confirm you got this DM. Thanks.")

@bot.command() #name
async def tester(ctx):
  await ctx.send("I do work!")

@bot.command()
async def help(ctx, command=None):
  title = ["Flip a coin","Random Number","Say pong","Roll a dice","Calculator","Scratch User Search","Tell a joke","Tell a fact","Tell bots password"]
  value = ["`!flipcoin`","`!rand <num> <num>` with `<num>` being optional","`!ping`","`!rolldice <num>`where <num> is optional. it specifies number of dice.","`!calc <equation>`","`!stats <username>` where <username> is mandatory","`!joke <type>` where `<type>` is optional.\n Type has 3 options:\n General (default), programming, knock-knock","`!fact`", "`!password`"]
  inline= [False, False, False, False,False,False,False,False,False]
  comms = ["flipcoin","rand","ping","rolldice","calc","stats","joke","fact","password"] #everything in comms should be lowercase

  if command == None:
    embed = discord.Embed(title="Commands", description="All commands must start with the prefix `!`",color=discord.Colour.blue())
    for a, b, c in zip(title,value,inline):
      embed.add_field(name = a ,value = b ,inline = c)

  else:
    if not command.lower() in comms:
      embed = discord.Embed(title="Command not found", description=f"{command} was not found. type `!help` to see all commands",color=discord.Colour.red())

      embed.add_field(name="not found...",value=f"{command} not found. Type `!help` to see all commands.")
    else:
      indexcomms = comms.index(command.lower())
      embed = discord.Embed(title=title[indexcomms], description=value[indexcomms],color=discord.Colour.dark_green())

  embed.set_footer(text="`!help <command>` will help you find only the specific command's info. example: `!help flipcoin`")
  await ctx.send(embed=embed)

@bot.command()
async def ping(ctx):
  await ctx.send("Pong")

@bot.command()
async def sleep(ctx):
    await ctx.send("Thanks! bye ðŸ‘‹ zzzzz....")
    await asyncio.sleep(10)
    await ctx.send("Im back! Thanks for the nap time!")

@bot.command()
async def member(ctx):
  member = await ctx.message.guild.query_members(user_ids=[ctx.author.id])
  member = member[0]
  await member.add_roles(discord.utils.get(member.guild.roles, name="member"))
  await ctx.send(f"{ctx.message.author.mention} your got member role.")

@bot.command()
async def rolldice(ctx, num=1):
  numberdice = random.randint(1,6*num)
  print(type(num))
  await ctx.send(f"You rolled a {numberdice}")

@bot.command()
async def flipcoin(ctx):
	heads_tails = ['Heads', 'Tails']
	choice = random.choice(heads_tails)
	await ctx.send(choice)

@bot.command()
async def rand(ctx, num1=0, num2=10):
  if num2 >= num1:
    random_number = random.randint(int(num1), int(num2))
    await ctx.send(str(random_number))
  else:
    await ctx.send("Syntax: !<num1> <num2> and num1 is bigger or equal to num 2")

@bot.command()
async def joke(ctx,t="general"):
  res = _joke(t)
  if "error" in res:
    await ctx.send(f"{ctx.message.author.mention} {res}.\n type `!help joke` for info on command.")
  else:
    await ctx.send(f"{ctx.message.author.mention}\n{res[0]}\n{res[1]}")

@bot.command()
async def fact(ctx):
  x = _fact()
  await ctx.send(f"{ctx.message.author.mention} {x}")
  """
  with open("test.json","r") as file:
    alljoke = json.load(file)
    alljoke.append(x)
  with open("test.json","w") as file:
    json.dump(alljoke)
  """

@bot.command()
async def password(ctx):
  await ctx.send(f"{ctx.message.author.mention}\nhttps://tenor.com/view/rick-astley-rick-roll-dancing-dance-moves-gif-14097983\nWhat did you expect?")

@bot.command()
async def d(ctx, bump=None):
  if bump == "bump":
    t = (db["lastbump"] + 2*60*60) - int(time.time()//1)
    if t <= 0:
      db["lastbump"] = int(time.time()//1)
      db["reminded"] = False
      t = (db["lastbump"] + 2*60*60) - int(time.time()//1)
      await ctx.send(f"{ctx.message.author.mention} Thanks to bump!\n{t} secs left to bump next time.")
    else:
      await ctx.send(f"Please wait {t} secs before bumping. :)")

@bot.command()
async def stats(ctx,username=None):
  if username == None:
    await ctx.send("Syntax: `!stats <user>` where <user> is mandatory")
  else:
    code = user.getdata(username)
    if "..." in code:
      if code[1] == 404:
        await ctx.send(f"{ctx.message.author.mention} User doesn't exist")
      else:
        await ctx.send(f"{ctx.message.author.mention} An error occurred. please try again")
    elif "...." in code:
      await ctx.send(f"{ctx.message.author.mention} {code[1]}")
    else:
      embed = discord.Embed(title = user.username, description=f"Stats of {user.username} on Scratch \n https://scratch.mit.edu/users/{user.username}",color=discord.Colour.orange())
      embed.set_thumbnail(url=user.pfp)
      embed.add_field(name = "User ID:",value= f"`{user.id}`", inline = True)
      embed.add_field(name = "Country:",value=f"`{user.country}`", inline = True)
      embed.add_field(name = "Followers:",value=f"`{user.followers}`",inline=True)
      embed.add_field(name = "Rank:",value=f"`{user.rank}`", inline = True)
      embed.add_field(name = "Joined:",value=f"`{user.joined}`", inline = True)
      embed.add_field(name = "Following:",value=f"`{user.following}`",inline=True)
      embed.add_field(name = "About Me:",value= f"`{user.AM}`", inline = False)
      embed.add_field(name = "What I'm Working On:",value=f"`{user.WIWO}`", inline = False)
      embed.set_footer(text="Data from https://scratchdb.lefty.one/ created by @datonelefty")
      await ctx.send(embed=embed)

@bot.command()
async def calc(ctx, eqn=None):
  if eqn == None:
    await ctx.send("What??!!")
  else:
    await ctx.send("WIP. gotta calculate "+eqn)

keys = ["rude","online","spam","good","lol"]
ans = ["don't be a fool","yep","Heyheyhey!! ","thx!",":rofl:",]
mentioning = [True, False,True,False,False]
@bot.event
async def on_message(message):
  if bot.user.mentioned_in(message):
    await message.channel.send('Why u pinged me?? I was sleeping :( .\nUse `!sleep` to make me sleep again')

  elif message.mentions and not message.author.bot:
    mentions = ""
    for member in message.mentions: #member.name also exists
      ping = f"<@!{member.id}>"
      if ping in message.content:
        mentions += member.mention + ", "
    if mentions != "":
      await message.channel.send(f"Dont ping {mentions[:-2]}")

  for key, val, ment in zip(keys, ans, mentioning):
    if message.content.lower() == key:
      if ment:
        await message.channel.send(f"{message.author.mention} "+val)
      else:
        await message.channel.send(val)

  await bot.process_commands(message)#it neccesarry for the on_message stuff not to override the commands

keep_alive()
bot.run(token)


import argparse
import csv
import re

from openpyxl import load_workbook

parser = argparse.ArgumentParser(
    description='Converts the first sheet of an .xlsx-file to a .csv-file'
)
parser.add_argument('xlsxfile', help='The .xlsx file to be converted')
parser.add_argument('-o,--output', dest='output', help='Name of the output file')
parser.add_argument(
    '-s,--sheet',
    dest='sheet',
    help='Name of sheet to convert to .xlsx. By default the first sheet will be converted',
)

def main():
    args = parser.parse_args()

    csv_rows = []

    wb = load_workbook(args.xlsxfile)

    sheet_index = 0
    if args.sheet:
        assert args.sheet in wb.sheetnames
        sheet_index = wb.sheetnames.index(args.sheet)

    ws = None
    for sheet in wb:
        if args.sheet:
            if sheet.title == args.sheet:
                ws = sheet
                break
        else:
            ws = sheet

    if ws is None:
        print(f'Sheet with name "{args.name}" not found')
        exit(1)

    for xls_row in ws:
        csv_row = []
        for xls_cell in xls_row:
            csv_row.append(xls_cell.value)
        csv_rows.append(csv_row)

    if args.output:
        output_filename = args.output
    else:
        output_filename = re.sub(r'\.xlsx$', '.csv', args.xlsxfile)
    with open(output_filename, 'w') as output_file:
        writer = csv.writer(output_file)
        writer.writerows(csv_rows)


import random

def living_people():
    N = 100
    li = []
    for i in range(N):
        a = random.randint(1900, 2000)
        b = random.randint(1900, 2000)
        born = min(a,b)
        dead = max(a,b)
        li.append([born, dead])

    histo = [0 for i in range(100)]

    for born, dead in li:
        for j in range(born-1900, dead-1900):
            histo[j] += 1
    print(histo)

living_people()


# Import dependencies
from bs4 import BeautifulSoup as bs
from splinter import Browser
import pandas as pd
from webdriver_manager.chrome import ChromeDriverManager

def scrape_all():
    browser = Browser('chrome', **executable_path, headless=False)
    news_title, news_paragraph = mars_news(browser)
    data = {
        "news_title": news_title,
        "news_paragraph": news_paragraph,
        "featured_image": featured_image(browser),
        "facts": mars_facts(),
        "last_modified": dt.datetime.now()
    }
    browser.quit()
    return data

def scrape():
    executable_path = {'executable_path': ChromeDriverManager().install()}
    browser = Browser('chrome', **executable_path, headless=False)
    mars={}

    # Get the URL for NASA latest news
    url = 'https://redplanetscience.com/'
    # Open the URL
    browser.visit(url)

    # Create the html
    html = browser.html
    soup = bs(html, 'html.parser')

    # Get the latest news
    news_latest = soup.find("div", class_="content_title").text
    news_latest_p = soup.find("div", class_="article_teaser_body").text
    mars["news_latest"]=news_latest
    mars["news_latest_p"]=news_latest_p

    # Get the images in the JPL Mars Space Image - Featured Image
    url = 'https://spaceimages-mars.com/'
    browser.visit(url)
    browser.find_by_tag("button")[1].click()

    html = browser.html
    jpl_image = bs(html, "html.parser")
    image = jpl_image.find('img', class_="fancybox-image").get('src')
    # image = jpl_image.find('img', class_="fancybox-image")
    feature_image = "https://spaceimages-mars.com/"+image
    mars["featured_image_url"]=feature_image

    # Mars facts
    url = "https://galaxyfacts-mars.com/"
    mars_df = pd.read_html(url)
    mars_df=mars_df[0]

    mars_df.columns=["Description", "Mars", "Earth"]
    mars_df.set_index("Description", inplace=True)
    mars_df
    mars_df_html = mars_df.to_html()
    mars_df_html
    mars["facts"]=mars_df_html

    # Mars hemisphere
    url = "https://marshemispheres.com/"
    browser.visit(url)
    result = browser.find_by_css("a.product-item img")
    hemisphere_img_url = []
    for i in range(len(result)):
        hemisphere = {}
        browser.find_by_css("a.product-item img")[i].click()
        element = browser.links.find_by_text('Sample').first
        img_url = element["href"]
        hemisphere["img_url"]=img_url
        hemisphere["title"]=browser.find_by_css("h2.title").text
        hemisphere_img_url.append(hemisphere)
        browser.back()
    hemisphere_img_url

    return mars

if __name__ == "__main__":
        print(scrape())


from choir.layers import ShapeSpec
from .backbone import (
    BACKBONE_REGISTRY,
    FPN,
    Backbone,
    ResNet,
    ResNetBlockBase,
    build_backbone,
    build_resnet_backbone,
    make_stage,
)
from .meta_arch import (
    META_ARCH_REGISTRY,
    build_model,
)
from .proposal_generator import (
    PROPOSAL_GENERATOR_REGISTRY,
    ANCHOR_GENERATOR_REGISTRY,
    RPN_HEAD_REGISTRY,
    build_proposal_generator,
    build_anchor_generator,
    build_rpn_head,
)
from .roi_heads import (
    ROI_BOX_HEAD_REGISTRY,
    ROI_HEADS_REGISTRY,
    ROIHeads,
    StandardROIHeads,
    FastRCNNOutputLayers,
    build_box_head,
    build_roi_heads,
)
from .transformers import TRANSFORMER_REGISTRY, build_transformers
from .test_time_augmentation import DatasetMapperTTA, HOIRWithTTA

_EXCLUDE = {"ShapeSpec"}
__all__ = [k for k in globals().keys() if k not in _EXCLUDE and not k.startswith("_")]


import os
import sys
#下面三行代码可以解决没有模块的报错
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
import  unittest
import  logging
from test_case.read_API import readData
import  logging.config

from  test_request.test_re import requ
path11=os.path.dirname(os.path.dirname(__file__))
logging.config.fileConfig(path11+'/test_log/log.conf')
logging = logging.getLogger()

class test_weater(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        logging.info('Start')

    @classmethod
    def tearDownClass(cls):
        logging.info('End')

    def setUp(self):
        self.data = readData(r'D:\soft\github1\web_api\test_excel\API.xls')
        self.ex = self.data.excelApi()
        #print(self.ex)

    def test_a(self):
        #print(self.ex[0]['result']['status'],type(self.ex[0]['result']['status']))
        if self.ex[0]['result']['status']==1000:
            tag=True
        self.assertTrue(tag)

    def test_b(self):
        if self.ex[1]['result']['status']==1002:
            tag=True
        self.assertTrue(tag)

if __name__ == '__main__':
    suite=unittest.TestSuite()
    tests=[test_weater('test_a'),test_weater('test_b')]
    suite.addTests(tests)
    runner=unittest.TextTestRunner(verbosity=2)
    runner.run(suite)


# Question 1
def set_repr():
    list1 = list((input("\nEnter a list of elements separated by a blank space : ").strip().split()))
    if len(list1) == len(set(list1)):
        print("True. The entered list constitutes a set.")

    else:
        output_set = set(list1)
        print(f'False, the set should be {output_set}')

set_repr()


'''
@Author: Wu Yuhui
@Time  : 2019.04.24
'''
import numpy as np

class HMM():
    def __init__(self):
        # 状态空间, N = 3
        # Y   =   { 0       1       2       }
        # weather : sunny   cloudy  rainy
        self.N = 3
        # 观测值集合 (输出空间), M = 3
        # X   =   { 0       1       2       }
        # stone is: hot     cold    wet
        self.M = 3
        self.Pi = np.array( [30/47, 9/47, 8/47] )
        self.A = np.array([ [0.8, 0.1, 0.1],
                            [0.3, 0.4, 0.3],
                            [0.4, 0.2, 0.4] ])
        self.B = np.array([ [0.8, 0.2, 0.1],
                            [0.1, 0.5, 0.2],
                            [0.1, 0.3, 0.7] ]).T

    def forward(self, observe_sequence):
        # N * len(observe_sequence)
        dp = np.array([[0.0 for t in range(len(observe_sequence))] for i in range(self.N)])
        # Init
        for i in range(self.N):
            dp[i][0] = self.Pi[i] * self.B[i][observe_sequence[0]]
        # Bottom-up
        for t in range(1, len(observe_sequence)):
            for i in range(self.N):
                dp[i][t] = sum( [dp[k][t-1] * self.A[k][i] * self.B[i][observe_sequence[t]]
                                for k in range(self.N)] )
        # Add the last column up
        p = sum([ dp[i][-1] for i in range(self.N) ])
        return p

    def viterbi(self, observe_sequence):
        # Both N * len(observe_sequence)
        dp = np.array([[0.0 for t in range(len(observe_sequence))] for i in range(self.N)])
        path = np.array([[0 for t in range(len(observe_sequence))] for i in range(self.N)])
        # Init
        for i in range(self.N):
            dp[i][0] = self.Pi[i] * self.B[i][observe_sequence[0]]
            path[i][0] = 0
        # Bottom-up
        for t in range(1, len(observe_sequence)):
            for i in range(self.N):
                tmp = [dp[k][t-1] * self.A[k][i] for k in range(self.N)]
                path[i][t] = tmp.index(max(tmp))
                dp[i][t] = tmp[path[i][t]] * self.B[i][observe_sequence[t]]
        # Backtrack to get state_sequence
        tmp = [dp[i][-1] for i in range(self.N)]
        end_state = tmp.index(max(tmp))
        state_sequence = np.array([0 for i in range(len(observe_sequence))])
        state_sequence[-1] = end_state
        for t in range(len(observe_sequence) - 1):
            state_sequence[-(t+2)] = path[state_sequence[-(t+1)]][-(t+1)]
        return state_sequence

if __name__ == '__main__':
    hmm = HMM()
    observe = input("请输入观测序列(用\',\'分隔):") # 0,0,1,2,1,2,1,0
    observe_sequence = [int(t) for t in observe.split(",")]
    # test forward algo
    p = hmm.forward(observe_sequence)
    print("该观测序列由该模型产生的概率为:" + str(p))
    # test viterbi algo
    state_sequence = hmm.viterbi(observe_sequence)
    state_sequence_read = []
    for state in state_sequence:
        if state == 0:
            state_sequence_read.append("晴")
        elif state == 1:
            state_sequence_read.append("阴")
        elif state == 2:
            state_sequence_read.append("雨")
        else:
            pass
    print("该观测序列对应的最优状态序列为:" + str(state_sequence_read))


import marshmallow
from flask import Blueprint
from flask import render_template, request, url_for, redirect

from app.iris_engine.utils.tracker import track_activity
from app.models.models import AssetsType, CaseAssets
from app.forms import AddAssetForm
from app import db
from app.schema.marshables import AssetSchema

from app.util import response_success, response_error, login_required, admin_required, api_admin_required, \
    api_login_required

manage_assets_blueprint = Blueprint('manage_assets',
                                    __name__,
                                    template_folder='templates')

@manage_assets_blueprint.route('/manage/asset-type/list')
@api_login_required
def list_assets(caseid):
    # Get all assets
    assets = AssetsType.query.with_entities(
        AssetsType.asset_name,
        AssetsType.asset_description,
        AssetsType.asset_id
    ).all()

    data = [row._asdict() for row in assets]

    # Return the assets
    return response_success("", data=data)

@manage_assets_blueprint.route('/manage/asset-type/<int:cur_id>', methods=['GET'])
@api_login_required
def view_asset_api(cur_id, caseid):
    # Get all assets
    asset_type = AssetsType.query.with_entities(
        AssetsType.asset_name,
        AssetsType.asset_description,
        AssetsType.asset_id
    ).filter(
        AssetsType.asset_id == cur_id
    ).first()

    if not asset_type:
        return response_error(f'Invalid asset type ID {cur_id}')

    # Return the assets
    return response_success("", data=asset_type._asdict())

@manage_assets_blueprint.route('/manage/asset-type/update/<int:cur_id>/modal', methods=['GET'])
@login_required
def view_assets_modal(cur_id, caseid, url_redir):
    if url_redir:
        return redirect(url_for('manage_assets.manage_assets', cid=caseid))

    form = AddAssetForm()
    asset = AssetsType.query.filter(AssetsType.asset_id == cur_id).first()
    if not asset:
        return response_error("Invalid asset type ID")

    form.asset_name.render_kw = {'value': asset.asset_name}
    form.asset_description.render_kw = {'value': asset.asset_description}

    return render_template("modal_add_asset_type.html", form=form, assettype=asset)

@manage_assets_blueprint.route('/manage/asset-type/update/<int:cur_id>', methods=['POST'])
@api_admin_required
def view_assets(cur_id, caseid):
    if not request.is_json:
        return response_error("Invalid request")

    asset = AssetsType.query.filter(AssetsType.asset_id == cur_id).first()
    if not asset:
        return response_error("Invalid asset type ID")

    asset_schema = AssetSchema()

    try:

        asset_sc = asset_schema.load(request.get_json(), instance=asset)

        if asset_sc:
            track_activity("updated asset type {}".format(asset_sc.asset_name), caseid=caseid)
            return response_success("Asset type updated", asset_sc)

    except marshmallow.exceptions.ValidationError as e:
        return response_error(msg="Data error", data=e.messages, status=400)

    return response_success("Unexpected error server-side. Nothing updated", data=asset)

@manage_assets_blueprint.route('/manage/asset-type/add/modal', methods=['GET'])
@admin_required
def add_assets_modal(caseid, url_redir):
    if url_redir:
        return redirect(url_for('manage_assets.manage_assets', cid=caseid))
    form = AddAssetForm()

    return render_template("modal_add_asset_type.html", form=form, assettype=None)

@manage_assets_blueprint.route('/manage/asset-type/add', methods=['POST'])
@api_admin_required
def add_assets(caseid):
    if not request.is_json:
        return response_error("Invalid request")

    asset_schema = AssetSchema()

    try:

        asset_sc = asset_schema.load(request.get_json())
        db.session.add(asset_sc)
        db.session.commit()

    except marshmallow.exceptions.ValidationError as e:
        return response_error(msg="Data error", data=e.messages, status=400)

    track_activity("Added asset type {asset_name}".format(asset_name=asset_sc.asset_name), caseid=caseid, ctx_less=True)
    # Return the assets
    return response_success("Added successfully", data=asset_sc)

@manage_assets_blueprint.route('/manage/asset-type/delete/<int:cur_id>', methods=['GET'])
@api_admin_required
def delete_assets(cur_id, caseid):
    asset = AssetsType.query.filter(AssetsType.asset_id == cur_id).first()
    if not asset:
        return response_error("Invalid asset ID")

    case_linked = CaseAssets.query.filter(CaseAssets.asset_type_id == cur_id).first()
    if case_linked:
        return response_error("Cannot delete a referenced asset type. Please delete any assets of this type first.")

    db.session.delete(asset)
    track_activity("Deleted asset type ID {asset_id}".format(asset_id=cur_id), caseid=caseid, ctx_less=True)

    return response_success("Deleted asset type ID {cur_id} successfully".format(cur_id=cur_id))


#!/home/blast/anaconda3/bin/python3
import os
import subprocess
import tempfile
from pyfaidx import Fasta
import click
import matplotlib.pyplot as plt
from dna_features_viewer import GraphicFeature, GraphicRecord
from bokeh.resources import CDN
from bokeh.embed import file_html
from Bio import SeqIO

@click.command()
@click.option('-i', '--input', 'input', default=None,
			  help="Input hmmer TBLOUT file", type=click.File(mode='r'))
@click.option('-f', '--fasta', 'fasta', default=None,
			  help="T6SS cluster alignment being processed, chose from [L, 1, 2, 3, 4, 5]",
			  type=str)
@click.option('-a', '--faa', 'faa', default=None,
			  help="T6SS cluster alignment being processed, chose from [L, 1, 2, 3, 4, 5]",
			  type=click.File(mode='r'))
@click.option('-n', '--fna', 'fna', default=None,
			  help="T6SS cluster alignment being processed, chose from [L, 1, 2, 3, 4, 5]",
			  type=click.File(mode='r'))
@click.option('-g', '--gff', 'gff', default=None,
			  help="T6SS cluster alignment being processed, chose from [L, 1, 2, 3, 4, 5]",
			  type=click.File(mode='r'))
@click.option('-o', '--output', 'output', default='-',
			  help="Output file path",
			  type=click.Path(exists=True))
@click.option('--name', 'name', default=None,
			  help="Output file name",
			  type=str)
@click.option('--log', 'log', default="conservation.log", type=click.File(mode="w"))
def main(input, faa, fna, fasta, gff, output, log, name):
	gff_path = gff.name
	gff_data = {}
	header = []
	mol_length = {}
	genome = Fasta(fasta)
	for rec in gff:
		rec = rec.rstrip()
		if rec.startswith("##"): continue
		elif rec.startswith("# Seq"):
			header.append(rec.rstrip())
			length = int(rec.split(";")[1].split("=")[1])
		elif rec.startswith("#"): continue
		elif rec == '"': continue
		else:
			line = rec.rstrip().split("\t")
			if line[0] not in gff_data:
				gff_data[line[0]] = {}
			if line[0] not in mol_length:
				mol_length[line[0]] = length
			id = line[8].split(";")[0].split("_")[1]
			id = f"{line[0]}_{id}"
			gff_data[line[0]][id] = line
	# print(f"Sequence length: {mol_length}")
	# print(gff_data)
	hits = {}
	prots = {}
	for line in input:
		if not line.startswith("#"):
			line = line.rstrip().split()
			prots[line[2]] = line[0]
			if line[0] in hits and line[2] not in hits[line[0]]:
				hits[line[0]].append(line[2])
			else:
				hits[line[0]] = [line[2]]
	# import pprint
	# pp = pprint.PrettyPrinter(indent=4)
	# pp.pprint(hits)
	# pp.pprint(prots)
	if "vgrg" in hits:
		for vgrg in hits['vgrg']:
			contig, id = vgrg.rsplit("_",1)
			if f"{contig}_{int(id)-1}" in prots:
				genes = build_cluster(fwd=True, start=f"{contig}_{int(id)-1}", hcp=True, annotations=hits, peptides=prots)
				# print(genes)
			elif  f"{contig}_{int(id)+1}" in prots:
				genes = build_cluster(fwd=False, start=f"{contig}_{int(id)+1}", hcp=True, annotations=hits, peptides=prots)
				# print(genes)
			else:
				genes= build_cluster(fwd=False, start=vgrg, hcp=False, annotations=hits, peptides=prots)
				# print(genes)
			if any(genes[x] in ['hydrolase', 'lipase'] for x in genes):
				print(f"Found Aux1 or Aux4")
				gff_data = add_names(genes, gff_data, "Aux 1 or 4")
			elif any(genes[x] in ['ntpase', 'transferase', 'lysm'] for x in genes):
				print(f"Found Aux2")
				gff_data = add_names(genes, gff_data, "Aux2")
			else:
				print(f"Unknown partial cluster\n{genes}")
	print("Searching for Aux3 cluster")
	cluster3 = {}
	if "aux3" in hits:
		print("Aux3 present")
		for aux3 in hits["aux3"]:
			contig, id = aux3.rsplit("_",1)
			if f"{contig}_{int(id)-1}" in prots:
				cluster3[aux3] = "effector"
				cluster3[f"{contig}_{int(id)-1}"] = "PAAR"
				cluster3[f"{contig}_{int(id)+1}"] = "immunity"
			elif f"{contig}_{int(id)+1}" in prots:
				cluster3[aux3] = "effector"
				cluster3[f"{contig}_{int(id)+1}"] = "PAAR"
				cluster3[f"{contig}_{int(id)-1}"] = "immunity"
			else:
				pass
		# print(cluster3)
		gff_data = add_names(cluster3, gff_data, "Aux3")
	else:
		print("No Aux3")

	nucl = tempfile.NamedTemporaryFile(mode="r+", suffix=".nucl")
	hmmout = tempfile.NamedTemporaryFile(mode="r+", suffix=".bed")
	aux5gff = tempfile.NamedTemporaryFile(mode="r+", suffix=".gff")
	aux5_nhmmer = f" nhmmer --cpu 4 --F1 .1 -o /dev/null --tblout {nucl.name} /home/blast/prediction_server/server/hmm_profiles//aux5 {fasta}"
	print(f"Searching for Aux5 clusters: {aux5_nhmmer}")
	subprocess.call(aux5_nhmmer, shell=True)
	aux5_pres = False
	for l in nucl:
		if l.startswith("#"): continue
		l = l.rstrip().split()
		percID = (max(int(l[7]),int(l[6])) - min(int(l[7]),int(l[6])))/6000
		if percID > 0.9:
			hmmout.write(f"{l[0]}\t{l[8]}\t{l[9]}\n")
			aux5_pres = True
	hmmout.seek(0)
	print(hmmout.read())
	bedtool_cmd = f"bedtools intersect -a {gff_path} -b {hmmout.name} > {aux5gff.name}"
	subprocess.call(bedtool_cmd, shell=True)
	if aux5_pres:
		nucleotides = Fasta(fna.name)
		aux5_fh = tempfile.NamedTemporaryFile(mode="r+", suffix=".fasta")
		for rec in aux5gff:
			rec.rstrip()
			if rec == "": continue
			else:
				line = rec.rstrip().split("\t")
				id = line[8].split(";")[0].split("_")[1]
				id = f"{line[0]}_{id}"
				aux5_fh.write(f">{id}\n{str(nucleotides[id])}\n")
		aux5_fh.seek(0)
		# print(aux5_fh.read())
		aux5hmms = ['aux5_hcp.hmm', 'aux5_vgrg.hmm', 'aux5_tap.hmm', 'aux5_eff.hmm']
		aux5hmmstat = {'aux5_hcp.hmm' : 228, 'aux5_vgrg.hmm': 2100, 'aux5_tap.hmm' : 747, 'aux5_eff.hmm': 1725}
		aux5 = {}
		for hmm in aux5hmms:
			a5hmmout = tempfile.NamedTemporaryFile(mode="r+", suffix=".out")
			a5nhmmer_cmd = f"nhmmer --F1 .1 -o /dev/null --tblout {a5hmmout.name} /home/blast/prediction_server/server/hmm_profiles/{hmm} {aux5_fh.name}"
			print(f"Running nhmmer: {a5nhmmer_cmd}")
			subprocess.call(a5nhmmer_cmd, shell=True, stderr=subprocess.DEVNULL )
			for l in a5hmmout:
				if l.startswith("#"): continue
				l = l.rstrip().split()
				percID = (max(int(l[7]),int(l[6])) - min(int(l[7]),int(l[6])))/aux5hmmstat[hmm]
				if percID > 0.9:
					print(f"Found result for {hmm}: {l[0]}")
					aux5[l[0]] = l[2].split("_")[1]
		# pp.pprint(aux5)
		gff_data = add_names(aux5, gff_data, "Aux5")
	annotation = {}
	uhOhSpaghettiOs = True
	for contig in gff_data:
		annotation[contig] = {}
		features = []
		for seq in gff_data[contig]:
			if gff_data[contig][seq][8].startswith("Name="):
				label = gff_data[contig][seq][8].split(";")[0].split("=")[1]
				# print(f"label={label},start={gff_data[contig][seq][3]}, end={gff_data[contig][seq][4]}, strand={gff_data[contig][seq][6]}1")
				features.append(
					GraphicFeature(start=int(gff_data[contig][seq][3]),
										   end=int(gff_data[contig][seq][4]),
										   strand=int(f"{gff_data[contig][seq][6]}1"),
										   color="#ffd700",
										   label=label)
					)
				annotation[contig][seq] = label
				annotation[seq] = label
			else:
				# print(f"label={None},start={gff_data[contig][seq][3]}, end={gff_data[contig][seq][4]}, strand={gff_data[contig][seq][6]}1")
					features.append(
							GraphicFeature(start=int(gff_data[contig][seq][3]),
								           end=int(gff_data[contig][seq][4]),
								           strand=int(f"{gff_data[contig][seq][6]}1")
								           )
							)

		# print(mol_length[contig])
		# sequence = str(genome[contig])
		if annotation[contig] != {}:
			uhOhSpaghettiOs = False
			record = GraphicRecord(sequence_length=mol_length[contig], features=features)
			plot = record.plot_with_bokeh(figure_width=15)
			with open(f"{output}/{contig}.html", "w+") as f:
				f.write(file_html(plot, CDN, f"{contig}"))
		proteins = Fasta(faa.name)

		with open(f"{output}/proteins.faa", "w+") as p_fh:
			for seq in proteins.keys():
				if seq in annotation:
					p_fh.write(f">{annotation[seq]}\n{str(proteins[seq])}\n")
				else:
					p_fh.write(f">{seq}\n{str(proteins[seq])}\n")
		cds = Fasta(faa.name)
		with open(f"{output}/nucleotides.fna", "w+") as n_fh:
			for seq in cds.keys():
				if seq in annotation:
					n_fh.write(f">{annotation[seq]}\n{str(cds[seq])}\n")
				else:
					n_fh.write(f">{seq}\n{str(cds[seq])}\n")

	if uhOhSpaghettiOs:
		with open(f"{output}/nohits.html", "w+") as sadface:
			sadface.write('

No T6SS predicted :(

T6SS.Vibriocholera.com

\n')

def build_cluster(fwd, start, hcp, annotations, peptides):
	contig, id = start.rsplit("_",1)
	id = int(id)
	genes = {}
	if not hcp:
		print("No HCP")
		fwd_list, rev_list = {start: peptides[start]}, {start: peptides[start]}
		count = 0
		while count <= 1:
			id += 1
			if id == 0: break
			orf = f"{contig}_{id}"
			if orf not in peptides:
				count += 1
				fwd_list[orf] = "predicted T6SS protein"
			else:
				fwd_list[orf] = peptides[orf]
			# 	count += -1
		count = 0
		while count <= 1:
			id += -1
			if id == 0: break
			orf = f"{contig}_{id}"
			if orf not in peptides:
				count += 1
				rev_list[orf] = "predicted T6SS protein"
			else:
				rev_list[orf] = peptides[orf]
			# 	count += -1
			# fwd_list.append(f"{contig}_{int(id)}")
		if len(fwd_list) > len(rev_list):
			return fwd_list
		else:
			return rev_list
	else:
		print("HCP present")
		genes[start] = peptides[start]
		count = 0
		if fwd: incr = 1
		else: incr = -1
		while count <= 1:
			id += incr
			if id == 0: break
			orf = f"{contig}_{id}"
			if orf not in peptides:
				count += 1
				genes[orf] = "predicted T6SS protein"
			else:
				genes[orf] = peptides[orf]
			# 	count += -1
			# genes.append(f"{contig}_{int(id)}")
		return genes

def add_names(genes, gff_data, cluster_name):
	for gene in genes:
		contig, id = gene.rsplit("_", 1)
		if gene in gff_data[contig]:
			info = gff_data[contig][gene][8]
			info = f"Name={gene}|{cluster_name}|{genes[gene]};{info}"
			print(info)
			gff_data[contig][gene][8] = info
	return gff_data

if __name__ == "__main__":
	main()


import time
import sys
import logging
from common.common import Coords, ClicPoint, DragAndDropsRecorder

class ForgeStrategy:
    def __init__(self, first_runes: ClicPoint, second_runes: ClicPoint, n_first_runes: int, n_second_runes: int, dry_run: bool):
        self.first_runes: ClicPoint = first_runes
        self.second_runes: ClicPoint = second_runes
        self.n_first_runes = n_first_runes
        self.n_second_runes = n_second_runes
        self.dry_run = dry_run

    def use_runes(self, runes: ClicPoint, times: int):
        if self.dry_run:
            runes.point_at()
        else:
            for _ in range(times):
                runes.clic()

    def forge(self):
        while True:
            self.use_runes(self.first_runes, self.n_first_runes)
            self.use_runes(self.second_runes, self.n_second_runes)

if __name__ == "__main__":
    n_first_runes: int = int(sys.argv[1])
    n_second_runes: int = int(sys.argv[2])
    dry_run = "--dry-run" in sys.argv

    ClicPoint.actions_delay_seconds = 0.3
    dd_recorder = DragAndDropsRecorder()
    dd_recorder.start()
    time.sleep(6)
    dd_recorder.stop()

    forge_strat = ForgeStrategy(
        ClicPoint(Coords(*dd_recorder.clicks[-2])),
        ClicPoint(Coords(*dd_recorder.clicks[-1])),
        n_first_runes,
        n_second_runes,
        dry_run
    )

    logging.getLogger().setLevel("INFO")
    logging.info(f"Entering forge with last vector={dd_recorder.last_vector().tuple}, dry_run= {dry_run}")
    forge_strat.forge()


import cv2
from PIL import Image
import numpy as np
from sklearn import preprocessing
import matplotlib.pyplot as plt

class PCAWhitening:
    def __init__(self, epsilon=1E-6):
        self.epsilon = epsilon
        # self.mean = None
        self.eigenvalue = None
        self.eigenvector = None
        self.pca = None

    def fit(self, x):
        print("Fit IN")
        print("Fit self : " + str(self))
        print("Fit x : " + str(x))
        """"
        self.mean = np.mean(x, axis=0) #列に沿って平均化
        # CIFA-10の場合は画像を複数取り込む
        各列の平均を元から引く
        print("Fit self.mean " + str(self.mean))
        x_ = x - self.mean  # 平均値で引く
        """
        x_ = x
        print("Fit OVR 2" + "shape:¥n" + str(x_.shape) + str(x_))

        cov = np.dot(x_.T, x_)  # 転置と元の積
        print("Fit OVR 3" + "shape:¥n" + str(cov.shape) + str(cov))

        E, D, _ = np.linalg.svd(cov)  # 特異値分解
        print("Fit OVR 4 E: " + str(E))
        print(",D : " + str(D))

        D = np.sqrt(D) + self.epsilon
        self.eigenvalue = D
        self.eigenvector = E
        print("Fit OVR 5")

        self.pca = np.dot(np.diag(1. / D), E.T)
        print("Fit END")
        return self

    def transform(self, x):
        # x_ = x - self.mean
        x_ = x
        return np.dot(x_, self.pca.T)

def normalizeMinMax(x, axis=0, epsilon=1E-5):
    vmin = np.min(x, axis)
    vmax = np.max(x, axis)
    return (x - vmin) / (vmax - vmin + epsilon)

def normalizeImage(x):
    img = x.reshape(x.shape[0] * x.shape[1], x.shape[2])
    img = normalizeMinMax(img, axis=0)
    return img.reshape(x.shape)

def normalizeImage2(x, epsilon=1E-6):
    vmin = np.min(x)
    vmax = np.max(x)
    return (x - vmin) / (vmax - vmin + epsilon)

if __name__ == '__main__':

    # 画像の読み込み
    img = cv2.imread("cat9.png", 1)  # ndarray形式?
    # print(img)

    # 基本表示
    # cv2.imshow('frame',img )
    print("shape 0 :" + str(img.shape[0]))  # たて
    print("shape 1 :" + str(img.shape[1]))  # 横
    print("shape 2 :" + str(img.shape[2]))  # 3がでる　RGBってことか

    r=(img[:,:,0].reshape(1,-1))
    g=(img[:, :, 1].reshape(1, -1))
    b=(img[:, :, 2].reshape(1, -1))
    print(r)
    print(g)
    print(b)

    rgb = np.append(r, g, axis=0)
    rgb = np.append(rgb, b, axis=0)
    print(rgb)
    # print(img_pcaw)


import json

import requests

from automatic_walk_time_tables.utils import path

def fetch_map_numbers(path_: path.Path) -> str:
    url = "http://awt-swiss-tml-api:1848/map_numbers"

    # Convert path to LV95 and save the coordinates in an array
    coordinates = [pkt.point.to_LV95() for pkt in path_.way_points]
    coordinates = [[pkt.lat, pkt.lon] for pkt in coordinates]

    payload = json.dumps(coordinates)
    headers = {'Content-Type': 'application/json'}
    req = requests.request("GET", url, headers=headers, data=payload)

    return req.text


import tkinter as tk
import tkinter.messagebox as messagebox
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

def henon(a, b, x0, y0, iterations):
    x = [x0]
    y = [y0]

    for i in range(iterations):
        xn = y[i] + 1 - a * x[i]**2
        yn = b * x[i]
        x.append(xn)
        y.append(yn)

    binary_values = []
    for i in range(len(x)):
        binary_values.append(str(int(x[i] >= y[i])))

    binary_text = " ".join(binary_values)
    binary_textbox.delete("1.0", tk.END)
    binary_textbox.insert(tk.END, binary_text)

    # Guardar los números binarios en un archivo de texto
    with open("archivo_cifrado.txt", "w") as file:
        file.write(binary_text)

    # Mostrar mensaje de éxito al guardar el archivo
    messagebox.showinfo("Archivo cifrado","Cifrado correctamente")

def validate_float(entry):
    try:
        float(entry.get())
        return True
    except ValueError:
        return False

def validate_int(entry):
    try:
        int(entry.get())
        return True
    except ValueError:
        return False

def plot_henon():
    if not validate_float(a_entry) or not validate_float(b_entry) \
            or not validate_float(x0_entry) or not validate_float(y0_entry) \
            or not validate_int(iterations_entry):
        messagebox.showerror("Error", "Invalid input! Please enter numeric values.")
        return

    a = float(a_entry.get())
    b = float(b_entry.get())
    x0 = float(x0_entry.get())
    y0 = float(y0_entry.get())
    iterations = int(iterations_entry.get())

# Mensaje de errores
    if a < -1.5 or a > 1.5:
        messagebox.showerror("Error", "Valor (a) fuera del rango")
        return
    if b < 0.1 or b > 0.4:
        messagebox.showerror("Error", "Valor (b) fuera del rango")
        return

    henon(a, b, x0, y0, iterations)

# Crear la ventana principal
window = tk.Tk()
window.title("Atractor de Henón")
window.geometry("500x400")
window.configure(background="white")

# Crear el marco para los valores binarios
binary_frame = tk.Frame(window, bg="white")
binary_frame.pack(pady=10)

# Crear el menú desplegable para editar las variables
menu_frame = tk.Frame(window, bg="white")
menu_frame.pack(pady=10)

a_label = tk.Label(menu_frame, text="a:", font=("Arial", 12), bg="white")
a_label.grid(row=0, column=0, padx=5)
a_entry = tk.Entry(menu_frame, font=("Arial", 12))
a_entry.grid(row=0, column=1)
a_entry.insert(0, "0.0")

a_info_label = tk.Label(menu_frame, text="Rango aceptado: -1.5 a 1.5", font=("Arial", 10), bg="white")
a_info_label.grid(row=0, column=2)

b_label = tk.Label(menu_frame, text="b:", font=("Arial", 12), bg="white")
b_label.grid(row=1, column=0, padx=5)
b_entry = tk.Entry(menu_frame, font=("Arial", 12))
b_entry.grid(row=1, column=1)
b_entry.insert(0, "0.1")

b_info_label = tk.Label(menu_frame, text="Rango aceptado: 0.1 a 0.4", font=("Arial", 10), bg="white")
b_info_label.grid(row=1, column=2)

x0_label = tk.Label(menu_frame, text="x0:", font=("Arial", 12), bg="white")
x0_label.grid(row=2, column=0, padx=5)
x0_entry = tk.Entry(menu_frame, font=("Arial", 12))
x0_entry.grid(row=2, column=1)
x0_entry.insert(0, "0.1")

y0_label = tk.Label(menu_frame, text="y0:", font=("Arial", 12), bg="white")
y0_label.grid(row=3, column=0, padx=5)
y0_entry = tk.Entry(menu_frame, font=("Arial", 12))
y0_entry.grid(row=3, column=1)
y0_entry.insert(0, "0.1")

iterations_label = tk.Label(menu_frame, text="Iteraciones:", font=("Arial", 12), bg="white")
iterations_label.grid(row=4, column=0, padx=5)
iterations_entry = tk.Entry(menu_frame, font=("Arial", 12))
iterations_entry.grid(row=4, column=1)
iterations_entry.insert(0, "1")

# Crear el marco para la caja de texto
textbox_frame = tk.Frame(window, bg="gray")
textbox_frame.pack(pady=10)

# Crear la caja de texto para los valores binarios
binary_textbox = tk.Text(textbox_frame, height=5, width=40, font=("Arial", 12))
binary_textbox.pack()

# Función para guardar los números binarios en un archivo de texto
def save_binary_values():
    binary_values = binary_textbox.get("1.0", tk.END)
    with open("binary_values.txt", "w") as file:
        file.write(binary_values)
    messagebox.showinfo("Archivo Guardado", "Guardado correctamente")

# Crear el botón para graficar
plot_button = tk.Button(window, text="Codificar", command=plot_henon, width=7, height=1, font=("Arial", 12))
plot_button.pack(pady=10)

# Crear el botón para guardar los números binarios
save_button = tk.Button(window, text="Guardar", command=save_binary_values, width=7, height=1, font=("Arial", 12))
save_button.pack(pady=10)

# Ejecutar la ventana principal
window.mainloop()


#2583 영역 구하기
import sys
sys.setrecursionlimit(10001)
dx=[-1,0,1,0]
dy=[0,1,0,-1]
def DFS(x,y):
    global cnt
    for i in range(4):
        xx=x+dx[i]
        yy=y+dy[i]
        if 0<=xx<n and 0<=yy<m and board[xx][yy]==0:
            cnt+=1
            board[xx][yy]=1 #벽으로 만들고
            DFS(xx,yy)

m,n,k=map(int,input().split())
board=[[0]*m for _ in range(n)]

#직사각형 색칠하기
for _ in range(k):
    lx,ly,rx,ry=map(int,input().split())
    for row in range(lx,rx):
        for col in range(ly,ry):
            board[row][col]=1

res=0
cntList=[]
for i in range(n):
    for j in range(m):
        if board[i][j]==0:
            cnt=0
            res+=1
            DFS(i,j)
            if cnt==0:
                cnt=1
            cntList.append(cnt)

print(res)
cntList.sort()
for x in cntList:
    print(x,end=' ')


import argparse
import sys
import os
if __name__=='__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--output', help='output file')
    parser.add_argument('--list', help="image list")
    args = parser.parse_args()
    with open(args.output,"r") as f:
        output=f.readlines()
    with open(args.list,"r") as f:
        list=f.readlines()
    if (len(output)!=len(list)):
        print("the length of the output and image list are not identical, please double check")
        sys.exit()
    else:
        for i in range (0,len(output)):
            line_out=output[i].strip('\n')
            label=int(line_out[0])
            if (label):
                line_list=list[i].strip('\n')
                file_name=os.path.split(line_list)
                date=file_name[1].split("_lola",1)[0]
                print(date)


import sys

from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel
from PySide6.QtGui import QIcon

class MainWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setWindowTitle('UI Tutorial')
        self.setGeometry(450, 250, 400, 350)
        self.setWindowIcon(QIcon(r"C:\WORK\2023_februar_ui\icon\test.png"))
        # vertikális elrendezés
        vbox = QVBoxLayout()

        # signal kezelés -> figyelni kell azokat a jeleket, amelyekkel a műveletet akarom végezni
        btn = QPushButton('Change text')
        self.label = QLabel('Hello szia')

        vbox.addWidget(btn)
        vbox.addWidget(self.label)

        self.setLayout(vbox)

        btn.clicked.connect(self.change_text)

    def change_text(self):
        import random
        colors = {
            1: 'purple',
            2: "green",
            3: 'red'
        }
        self.label.setText(f"I changed this: {random.randint(10, 20)}")
        self.label.setStyleSheet(f"color: {colors[random.randint(1, 3)]}")

if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec())


import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
import keras as K
import numpy as np
import matplotlib.pyplot as plt

def load_data(excel_file_path):
    classification = pd.read_excel(excel_file_path, sheet_name=0, header=0)
    target_var = "label"
    features = list(classification.columns)
    features.remove(target_var)
    class_type = classification[target_var].unique()
    class_dict = dict(zip(class_type, range(len(class_type))))
    classification['target'] = classification[target_var].apply(lambda x: class_dict[x])
    lb = LabelBinarizer()
    lb.fit(list(class_dict.values()))
    transformed_labers = lb.transform(classification['target'])
    y_bin_labels = []
    for i in range(transformed_labers.shape[1]):
        y_bin_labels.append('y' + str(i))
        classification['y' + str(i)] = transformed_labers[:, i]

    train_x, test_x, train_y, test_y = train_test_split(classification[features], classification[y_bin_labels],
                                                        train_size=0.7, test_size=0.3, random_state=0)
    return train_x, test_x, train_y, test_y, class_dict

train_x, test_x, train_y, test_y, class_dict = load_data(r'C:\Users\Asher\Desktop\self_\SVM_three_data.xlsx')

init = K.initializers.glorot_uniform(seed=1)
simple_adam = K.optimizers.Adam()
model = K.models.Sequential()
model.add(K.layers.Dense(units=5, input_dim=3, kernel_initializer=init, activation='relu'))
model.add(K.layers.Dense(units=6, kernel_initializer=init, activation="relu"))
model.add(K.layers.Dense(units=3,kernel_initializer=init, activation="softmax"))
model.compile(loss="categorical_crossentropy", optimizer=simple_adam, metrics=["accuracy"])

batch_size = 1
epochs = 1
print("startring training")
history = model.fit(train_x, train_y, batch_size=batch_size, epochs=epochs, shuffle=True, verbose=1,
                    validation_data=(test_x, test_y))
print("training finished \n")

eval = model.evaluate(test_x, test_y, verbose=0)
unknown = np.array([[0.6024, 0.03579, 0.7795]], dtype=np.float32)
predicted = model.predict(unknown)
print("predicted softmax vector is:", predicted)
specied_dict = {v:k for k,v in class_dict.items()}
print("predicted species is:", specied_dict[np.argmax(predicted)])


#!/usr/bin/env python3

import os
import logging
import traceback
import inspect
import datetime
import functools

logs_dir_name = 'logs'
__dir__ = os.path.dirname(os.path.abspath(__file__))

if logs_dir_name not in os.listdir(os.path.join(__dir__, '../')):
    os.mkdir(''.join((os.path.join(__dir__, '../'), logs_dir_name)))

_now = datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')
_logs_dir_path = os.path.join(__dir__, ''.join(('../', logs_dir_name, '/')))
log_fp = ''.join((_logs_dir_path, _now, ".log"))

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename=log_fp,
                    filemode='w')

_console = logging.StreamHandler()
_console.setLevel(logging.INFO)
_formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
_console.setFormatter(_formatter)
LOGGER = logging.getLogger('czb test')
LOGGER.addHandler(_console)

def logged(func):
    """创建一个日志装饰器，它会记录所装饰函数的入参和
    """
    result = None

    @functools.wraps(func)
    def inner(*args, **kwargs):

        try:
            nonlocal result
            result = func(*args, **kwargs)
            LOGGER.info('模块:{}\n 调用函数 {} 传入参数: {},{}\n 返回结果: {}'
                        .format(inspect.getmodule(func), func.__name__,
                                args, kwargs, result))
            return result
        except Exception as Ex:
            LOGGER.error("{}方法入参:{},{}".format(func.__name__, args, kwargs))
            e = traceback.format_exc()
            LOGGER.error('Exception：{}'.format(e))
            raise Ex

    return inner


"""
    Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar. No final, mostre:
        - Qual é o tatal gasto na compra.
        - Quantos produtos custam mais de R$1000.
        - qual é o nome do produto mais barato.
"""
mais1000 = total = menor = c = 0
barato = ''
while (True):
    nome = input('Digite o nome do produto: ').strip()
    preço = float(input('Digite o preço do item R$: '))
    c += 1
    resp = ''
    total += preço
    if (c == 1 or preço < menor):
        menor = preço
        barato = nome
    if (preço > 1000):
        mais1000 += 1
    while (resp != 's' and resp != 'n'):
        resp = input('Quer continuar [S/N]: ').strip().lower()
    if (resp == 'n'):
        break
print(f'O total da comprar foi R${total:.2f}')
print(f'temos {mais1000} Produtos a cima de R$1000')
print(f'{barato} foi o item mais barato. que custá: {menor:.2f}')


import os
import argparse
import numpy as np
import pandas as pd
from env import custor_Env

parser = argparse.ArgumentParser()
parser.add_argument("--order_path", default="data/order.csv")
parser.add_argument("--stock_path", default="data/stock.csv")
args = parser.parse_args()

env = custor_Env(args)

# hyper-parameters for RL training
N_epiosde = 1

if __name__ == "__main__":

    for eps in range(N_epiosde):
        state = env.reset()

        for st in range(env.max_steps):
            action = np.random.randint(10, size=(24, 8))
            state, reward, done, info = env.step(action)
            # print(state)
            print(reward)
            # print(f"submission : {info['submission']} ")


import os.path
import unittest

from hamcrest import assert_that, contains_string

from heimer_tools.convert import illustrated_dot_data
from heimer_tools.convert import simple_dot_data

DATA_DIR = '/home/romilly/git/active/heimer-tools/data'

def path_to(relative_path: str):
    return os.path.join(DATA_DIR, relative_path)

def read(file_name):
    with open(file_name) as f:
        contents = f.read()
    return contents

class IllustratedDotFileTestCase(unittest.TestCase):
    def test_small_map(self):
        expected = read(path_to('test.dot'))
        df = illustrated_dot_data(path_to('test.alz'))
        self.assertEqual(expected, df)

    def test_big_map(self):
        dot_data = illustrated_dot_data(path_to('exponential.alz'))
        assert_that(dot_data, contains_string('digraph G {'))
        assert_that(dot_data, contains_string('Becoming an Expert'))

class SimpleDotFileTestCase(unittest.TestCase):
    def test_small_map(self):
        expected = read(path_to('simple.dot'))
        df = simple_dot_data(path_to('test.alz'))
        self.assertEqual(expected, df)

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


import logging
import superdesk

from copy import copy

from eve.utils import ParsedRequest
from eve.versioning import resolve_document_version

from superdesk.users.services import current_user_has_privilege
from superdesk.resource import Resource
from superdesk.errors import StopDuplication, SuperdeskApiError, InvalidStateTransitionError
from superdesk.notification import push_notification
from superdesk.utc import utcnow
from superdesk.metadata.utils import item_url
from superdesk.services import BaseService
from superdesk.metadata.item import metadata_schema, ITEM_STATE, CONTENT_STATE, ITEM_TYPE
from superdesk import get_resource_service, config
from superdesk.activity import add_activity, ACTIVITY_CREATE, ACTIVITY_UPDATE
from superdesk.workflow import is_workflow_state_transition_valid
from apps.archive.common import (
    get_item_expiry,
    item_operations,
    ITEM_OPERATION,
    update_version,
    insert_into_versions,
    is_assigned_to_a_desk,
    convert_task_attributes_to_objectId,
    on_create_item,
    ARCHIVE,
    get_subject,
)
from flask_babel import _, lazy_gettext

task_statuses = ["todo", "in_progress", "done"]
default_status = "todo"
ITEM_SEND = "send"
item_operations.append(ITEM_SEND)
MACRO_INCOMING = "incoming"
MACRO_OUTGOING = "outgoing"
MACRO_ONSTAGE = "onstage"

logger = logging.getLogger(__name__)

def init_app(app) -> None:
    endpoint_name = "tasks"
    service = TasksService(str(TaskResource.datasource["source"]), backend=superdesk.get_backend())
    TaskResource(endpoint_name, app=app, service=service)

def compare_dictionaries(original, updates):
    original_keys = set(original.keys())
    updates_keys = set(updates.keys())
    intersect_keys = original_keys.intersection(updates_keys)
    added = list(updates_keys - original_keys)
    modified = [o for o in intersect_keys if original[o] != updates[o]]
    modified.extend(added)
    return modified

def send_to(doc, update=None, desk_id=None, stage_id=None, user_id=None, default_stage="incoming_stage"):
    """Send item to given desk and stage.

    Applies the outgoing and incoming macros of current and destination stages

    :param doc: original document to be sent
    :param update: updates for the document
    :param desk: id of desk where item should be sent
    :param stage: optional stage within the desk
    :param default_stage: if no stage_id is passed then it determines the stage in that desk the doc is assigned,
            either the the incomming stage or the working stage.
    """

    original_task = doc.setdefault("task", {})
    current_stage = None
    if original_task.get("stage"):
        current_stage = get_resource_service("stages").find_one(req=None, _id=original_task.get("stage"))
    desk = destination_stage = None
    task = {"desk": desk_id, "stage": stage_id, "user": original_task.get("user") if user_id is None else user_id}

    if current_stage:
        apply_stage_rule(doc, update, current_stage, MACRO_OUTGOING)

    if desk_id:
        desk = superdesk.get_resource_service("desks").find_one(req=None, _id=desk_id)
        if not desk:
            raise SuperdeskApiError.notFoundError(_("Invalid desk identifier {desk_id}").format(desk_id=desk_id))

        if not current_user_has_privilege("move") and str(user_id) not in [
            str(x.get("user", "")) for x in desk.get("members", [])
        ]:
            raise SuperdeskApiError.forbiddenError(_("User is not member of desk: {desk_id}").format(desk_id=desk_id))

        task["desk"] = desk_id
        if not stage_id:
            task["stage"] = desk.get(default_stage)
            destination_stage = get_resource_service("stages").find_one(req=None, _id=desk.get(default_stage))

    if stage_id:
        destination_stage = get_resource_service("stages").find_one(req=None, _id=stage_id)
        if not destination_stage:
            raise SuperdeskApiError.notFoundError(_("Invalid stage identifier {stage_id}").format(stage_id=stage_id))

        task["desk"] = destination_stage["desk"]
        task["stage"] = stage_id

    if update:
        update.setdefault("task", {})
        update["task"].update(task)
        update["expiry"] = get_item_expiry(desk=desk, stage=destination_stage)
    else:
        doc["task"].update(task)
        doc["expiry"] = get_item_expiry(desk=desk, stage=destination_stage)

    if destination_stage:
        apply_stage_rule(doc, update, destination_stage, MACRO_INCOMING, desk=desk, task=task)
        if destination_stage.get("task_status"):
            if update:
                update["task"]["status"] = destination_stage["task_status"]
            else:
                doc["task"]["status"] = destination_stage["task_status"]

def apply_stage_rule(doc, update, stage, rule_type, desk=None, task=None):
    macro_type = "{}_macro".format(rule_type)

    if stage.get(macro_type):
        try:
            original_doc = dict(doc)
            macro = get_resource_service("macros").get_macro_by_name(stage.get(macro_type))
            if not macro:
                logger.warning("macro %s is missing", stage.get(macro_type))
                return
            macro["callback"](doc, desk=desk, stage=stage, task=task)
            if update:
                modified = compare_dictionaries(original_doc, doc)
                for i in modified:
                    update[i] = doc[i]
        except StopDuplication:
            raise
        except Exception as ex:
            message = _("Error:{exception} in {rule_type} rule:{rule} for stage:{stage}").format(
                exception=str(ex), rule_type=rule_type, rule=macro.get("label"), stage=stage.get("name")
            )
            raise SuperdeskApiError.badRequestError(message)

def apply_onstage_rule(doc, _id):
    """Apply any on stage macro/rule that may be defined for the stage.

    :param doc:
    :param _id:
    :return:
    """
    doc[config.ID_FIELD] = _id
    stage = get_resource_service("stages").find_one(req=None, _id=doc.get("task", {}).get("stage"))
    if stage:
        apply_stage_rule(doc, None, stage, "onstage")

class TaskResource(Resource):
    datasource = {
        "source": "archive",
        "default_sort": [("_updated", -1)],
        "filter": {"task": {"$exists": True}},
        "elastic_filter": {
            "bool": {
                "must": {"exists": {"field": "task"}},
                "must_not": {"term": {ITEM_STATE: "spiked"}},
            }
        },
    }

    item_url = item_url
    schema = {
        "expiry": {"type": "string"},
        "slugline": metadata_schema["slugline"],
        "description_text": metadata_schema["description_text"],
        "type": metadata_schema["type"],
        "task": {
            "type": "dict",
            "schema": {
                "status": {"type": "string", "allowed": task_statuses, "default": default_status},
                "due_date": {"type": "datetime"},
                "started_at": {"type": "datetime"},
                "finished_at": {"type": "datetime"},
                "user": Resource.rel("users", True),
                "desk": Resource.rel("desks", True),
                "stage": Resource.rel("stages", True),
            },
        },
    }
    privileges = {"POST": "tasks", "PATCH": "tasks", "DELETE": "tasks"}

class TasksService(BaseService):
    def get(self, req, lookup):
        if req is None:
            req = ParsedRequest()
        return self.backend.get("tasks", req=req, lookup=lookup)

    def update_times(self, doc):
        task = doc.get("task", {})
        status = task.get("status", None)
        if status == "in_progress":
            task.setdefault("started_at", utcnow())

        if status == "done":
            task.setdefault("finished_at", utcnow())

    def __is_content_moved_from_desk(self, doc):
        """
        Returns True if the 'doc' is being moved from a desk. False otherwise.
        """
        return doc.get("task", {}).get("desk", None) is None

    def __is_content_assigned_to_new_desk(self, original, updates):
        """Checks if the content is assigned to a new desk.

        :return: True if the content is being moved to a new desk. False otherwise.
        """
        return str(original.get("task", {}).get("desk", "")) != str(updates.get("task", {}).get("desk", ""))

    def __update_state(self, updates, original):
        if self.__is_content_assigned_to_new_desk(original, updates):
            # check if the preconditions for the action are in place
            original_state = original[ITEM_STATE]
            if not is_workflow_state_transition_valid("move", original_state):
                raise InvalidStateTransitionError()

            updates[ITEM_STATE] = (
                CONTENT_STATE.DRAFT if self.__is_content_moved_from_desk(updates) else CONTENT_STATE.SUBMITTED
            )
            resolve_document_version(updates, ARCHIVE, "PATCH", original)

    def update_stage(self, doc):
        task = doc.get("task", {})
        desk_id = task.get("desk", None)
        stage_id = task.get("stage", None)
        send_to(doc=doc, desk_id=desk_id, stage_id=stage_id)

    def on_create(self, docs):
        on_create_item(docs)
        for doc in docs:
            resolve_document_version(doc, ARCHIVE, "POST")
            self.update_times(doc)
            self.update_stage(doc)
            convert_task_attributes_to_objectId(doc)

    def on_created(self, docs):
        push_notification(self.datasource, created=1)
        push_notification("task:new")
        for doc in docs:
            insert_into_versions(doc["_id"])
            if is_assigned_to_a_desk(doc):
                add_activity(
                    ACTIVITY_CREATE,
                    "added new task {{ subject }} of type {{ type }}",
                    self.datasource,
                    item=doc,
                    subject=get_subject(doc),
                    type=doc[ITEM_TYPE],
                )

    def on_update(self, updates, original):
        self.update_times(updates)
        if is_assigned_to_a_desk(updates):
            self.__update_state(updates, original)
        new_stage_id = str(updates.get("task", {}).get("stage", ""))
        old_stage_id = str(original.get("task", {}).get("stage", ""))
        new_user_id = updates.get("task", {}).get("user", "")
        if new_stage_id and new_stage_id != old_stage_id:
            updates[ITEM_OPERATION] = ITEM_SEND
            send_to(doc=original, update=updates, desk_id=None, stage_id=new_stage_id, user_id=new_user_id)
            resolve_document_version(updates, ARCHIVE, "PATCH", original)
        convert_task_attributes_to_objectId(updates)
        update_version(updates, original)

    def on_updated(self, updates, original):
        updated = copy(original)
        updated.update(updates)
        if self._stage_changed(updates, original):
            insert_into_versions(doc=updated)
        new_task = updates.get("task", {})
        old_task = original.get("task", {})
        if new_task.get("stage") != old_task.get("stage"):
            push_notification(
                "task:stage",
                new_stage=str(new_task.get("stage", "")),
                old_stage=str(old_task.get("stage", "")),
                new_desk=str(new_task.get("desk", "")),
                old_desk=str(old_task.get("desk", "")),
            )
        else:
            push_notification(self.datasource, updated=1)

        if is_assigned_to_a_desk(updated):
            if self.__is_content_assigned_to_new_desk(original, updates) and not self._stage_changed(updates, original):
                insert_into_versions(doc=updated)
            add_activity(
                ACTIVITY_UPDATE,
                "updated task {{ subject }} for item {{ type }}",
                self.datasource,
                item=updated,
                subject=get_subject(updated),
                type=updated["type"],
            )

    def on_deleted(self, doc):
        push_notification(self.datasource, deleted=1)

    def assign_user(self, item_id, updates):
        return self.patch(item_id, updates)

    def _stage_changed(self, updates, original):
        new_stage_id = str(updates.get("task", {}).get("stage", ""))
        old_stage_id = str(original.get("task", {}).get("stage", ""))
        return new_stage_id and new_stage_id != old_stage_id

superdesk.privilege(name="tasks", label=lazy_gettext("Tasks Management"), description=lazy_gettext("Tasks Management"))


import matplotlib; matplotlib.use('Agg')  # fixes issue if no GUI provided
import matplotlib.pyplot as plt
import numpy as np
import os
import glob
import pandas as pd
import importlib
from PIL import (Image, ImageDraw)
import keras
from keras import backend as K
from keras.preprocessing.image import array_to_img
import math
import itertools

from keras_easy import models

def save_history(run_config, history, prefix):
    if 'acc' not in history.history:
        return

    img_path = os.path.join(run_config.output.plots, '{}-%s.jpg'.format(prefix))

    # summarize history for accuracy
    plt.plot(history.history['acc'])
    plt.plot(history.history['val_acc'])
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.savefig(img_path % 'accuracy')
    plt.close()

    # summarize history for loss
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper right')
    plt.savefig(img_path % 'loss')
    plt.close()

def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    confusion_matrix_dir = '../data/confusion_matrix_plots'
    if not os.path.exists(confusion_matrix_dir):
        os.mkdir(confusion_matrix_dir)

    plt.cla()
    plt.figure()
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, cm[i, j],
                 horizontalalignment="center",
                 color="#BFD1D4" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

    if normalize:
        plt.savefig(os.path.join(confusion_matrix_dir, 'normalized.jpg'))
    else:
        plt.savefig(os.path.join(confusion_matrix_dir, 'without_normalization.jpg'))

def get_dir_imgs_number(dir_path):
    allowed_extensions = ['*.png', '*.jpg', '*.jpeg', '*.bmp']
    number = 0
    for e in allowed_extensions:
        number += len(glob.glob(os.path.join(dir_path, e)))
    return number

def set_samples_info(run_config):
    """Walks through the train and valid directories
    and returns number of images"""
    if run_config.data.use_dir:
        white_list_formats = {'png', 'jpg', 'jpeg', 'bmp'}
        dirs_info = {run_config.data.train_dir: 0, run_config.data.validation_dir: 0}
        for d in dirs_info:
            iglob_iter = glob.iglob(d + '**/*.*')
            for i in iglob_iter:
                filename, file_extension = os.path.splitext(i)
                if file_extension[1:] in white_list_formats:
                    dirs_info[d] += 1
        run_config.nb_train_samples = dirs_info[run_config.data.train_dir]
        run_config.nb_validation_samples = dirs_info[run_config.data.validation_dir]
    else:
        run_config.nb_train_samples = len(pd.read_csv(run_config.data.train_file))
        run_config.nb_validation_samples = len(pd.read_csv(run_config.data.validation_file))

def get_class_weight(d):
    white_list_formats = {'png', 'jpg', 'jpeg', 'bmp'}
    class_number = dict()
    dirs = sorted([o for o in os.listdir(d) if os.path.isdir(os.path.join(d, o))])
    k = 0
    for class_name in dirs:
        class_number[k] = 0
        iglob_iter = glob.iglob(os.path.join(d, class_name, '*.*'))
        for i in iglob_iter:
            _, ext = os.path.splitext(i)
            if ext[1:] in white_list_formats:
                class_number[k] += 1
        k += 1

    total = np.sum(list(class_number.values()))
    max_samples = np.max(list(class_number.values()))
    mu = 1. / (total / float(max_samples))
    keys = class_number.keys()
    class_weight = dict()
    for key in keys:
        score = math.log(mu * total / float(class_number[key]))
        class_weight[key] = score if score > 1. else 1.

    return class_weight

def set_classes(run_config):
    if run_config.data.use_dir:
        d = run_config.data.train_dir
        run_config.classes = sorted([o for o in os.listdir(d) if os.path.isdir(os.path.join(d, o))])
    else:
        run_config.classes = None

def override_keras_directory_iterator_next():
    """Overrides .next method of DirectoryIterator in Keras
      to reorder color channels for images from RGB to BGR"""
    from keras.preprocessing.image import DirectoryIterator

    original_next = DirectoryIterator.next

    # do not allow to override one more time
    if 'custom_next' in str(original_next):
        return

    def custom_next(self):
        batch_x, batch_y = original_next(self)
        batch_x = batch_x[:, ::-1, :, :]
        return batch_x, batch_y

    DirectoryIterator.next = custom_next

def get_classes_in_keras_format(run_config):
    if run_config.classes:
        return dict(zip(run_config.classes, range(len(run_config.classes))))
    return None

def get_model_class_instance(run_config, *args, **kwargs):
    # module = importlib.import_module("keras_easy.models.{}".format(run_config.main.model))
    # return module.inst_class(run_config, *args, **kwargs)
    return models.get_model(run_config, *args, **kwargs)

def get_activation_function(m, layer):
    x = [m.layers[0].input, K.learning_phase()]
    y = [m.get_layer(layer).output]
    return K.function(x, y)

def get_activations(activation_function, X_batch):
    activations = activation_function([X_batch, 0])
    return activations[0][0]

def plot_predictions(run_config, img_array, y_pred, y_true=None):
    """save each image with predicted and real points drawn on it"""
    preds_dir = os.path.join(run_config.data.data_dir, "predictions")
    os.makedirs(preds_dir, exist_ok=True)
    img = array_to_img(img_array)
    draw = ImageDraw.Draw(img)
    xy = [(int(y_pred[2*k]*img.size[0]/1000), int(y_pred[2*k+1]*img.size[1]/1000)) for k in range(len(y_pred)//2)]
    draw.line(xy, fill=(255, 0, 0), width=1)
    print("Y_TRUE: ", y_true)
    if (y_true is not None) and (y_true is not np.nan):
        print("Y_TRUE: ", y_true)
        xy = [(int(y_true[2*k]*img.size[0]/1000), int(y_true[2*k+1]*img.size[1]/1000)) for k in range(len(y_true)//2)]
        draw.line(xy, fill=(0, 255, 0), width=1)
    del draw
    img.save(os.path.join(preds_dir , str(np.random.randint(1e7)) + ".png"), "PNG")

def save_activations(run_config, model, inputs, files, layer, batch_number):
    all_activations = []
    ids = []
    af = get_activation_function(model, layer)
    for i in range(len(inputs)):
        acts = get_activations(af, [inputs[i]])
        all_activations.append(acts)
        ids.append(files[i].split('/')[-2])

    submission = pd.DataFrame(all_activations)
    submission.insert(0, 'class', ids)
    submission.reset_index()
    if batch_number > 0:
        submission.to_csv(run_config.activations_path, index=False, mode='a', header=False)
    else:
        submission.to_csv(run_config.activations_path, index=False)

def lock(config):
    if os.path.exists(config.lock_file):
        exit('Previous process is not yet finished.')

    with open(config.lock_file, 'w') as lock_file:
        lock_file.write(str(os.getpid()))

def unlock(run_config):
    if os.path.exists(run_config.lock_file):
        os.remove(run_config.lock_file)

def is_keras2():
    return keras.__version__.startswith('2')

def get_keras_backend_name():
    try:
        return K.backend()
    except AttributeError:
        return K._BACKEND

def tf_allow_growth():
    import tensorflow as tf
    from keras.backend.tensorflow_backend import set_session

    tf_config = tf.ConfigProto()
    tf_config.gpu_options.allow_growth = True
    sess = tf.Session(config=tf_config)
    set_session(sess)

def set_img_format():
    try:
        if K.backend() == 'theano':
            K.set_image_data_format('channels_first')
        else:
            K.set_image_data_format('channels_last')
    except AttributeError:
        if K._BACKEND == 'theano':
            K.set_image_dim_ordering('th')
        else:
            K.set_image_dim_ordering('tf')


class Tile(object):
    """
    Represents an envi tile (a blocked sub matrix of a scene in bsq)
    """
    def __init__(self):
        self._aquisitionDate = ""
        self._pathRow = ""
        self._leftUpperLat = 0.0
        self._leftUpperLon = 0.0
        self._rightLowerLat = 0.0
        self._rightLowerLon = 0.0
        self._width = -1
        self._height = -1
        self._band = -1
        self._xPixelWidth = 0.0
        self._yPixelWidth = 0.0
        self._content = bytearray()

    def update(self, leftUpper, rightLower, width, height, band,
               pathRow, acquisitionDate, xPixelWidth, yPixelWidth):
        leftUpperLat, leftUpperLon = leftUpper
        rightLowerLat, rightLowerLon = rightLower

        self._aquisitionDate = acquisitionDate
        self._pathRow = pathRow
        self._leftUpperLat = leftUpperLat
        self._leftUpperLon = leftUpperLon
        self._rightLowerLat = rightLowerLat
        self._rightLowerLon = rightLowerLon
        self._width = width
        self._height = height
        self._band = band
        self._xPixelWidth = xPixelWidth
        self._yPixelWidth = yPixelWidth

    def get_coordinate(self, index):
        index = index//2
        x = index % self._width
        y = index // self._width
        newLon = self._leftUpperLon + self._xPixelWidth * x
        newLat = self._leftUpperLat - self._yPixelWidth * y
        return (newLat, newLon)

    def get_content_index_from_coordinate(self, coord):
        lat, lon = coord
        latDiff = int(self._leftUpperLat - lat)
        lonDiff = int(lon - self._leftUpperLon)

        if latDiff < 0 or lonDiff < 0:
            return -1

        x = lonDiff // self._xPixelWidth
        y = latDiff // self._yPixelWidth

        return int(2 * (y * self._width + x))

class Cube(object):
    def __init__(self):
        """

        :return:
        """

class TimeSeries(object):
    def __init__(self):
        """

        :return:
        """


class Solution:
    def maxSubarraySumCircular(self, A: List[int]) -> int:
        # Kadane's algorithm : https://www.youtube.com/watch?v=86CQq3pKSUw

        def Kadane(A):
            cur_max = max_sum = A[0]
            cur_min = min_sum = A[0]
            sum = A[0]
            for i in range(1, len(A)):
                cur_max = max(A[i], cur_max + A[i])
                max_sum = max(max_sum, cur_max)
                cur_min = min(A[i], cur_min + A[i])
                min_sum = min(min_sum, cur_min)
                sum += A[i]
            return max(max_sum, sum-min_sum) if max_sum > 0 else max_sum

        return Kadane(A)


import Utils
from fractions import Fraction

def simplifyFraction(nj, numerator, denominator):
	if denominator == 0:
		return (0, 0)
	if numerator == 0:
		return (0, 0)

	numFactors = nj.getFactors(numerator)
	denFactors = nj.getFactors(denominator)

	i = 0
	while i < len(denFactors):
		currFactor = denFactors[i]
		if currFactor in denFactors and currFactor in numFactors:
			denFactors.remove(currFactor)
			numFactors.remove(currFactor)
		else:
			i += 1

	newNumerator = 1
	for f in numFactors:
		newNumerator *= f

	newDenominator = 1
	for f in denFactors:
		newDenominator *= f

	return (newNumerator, newDenominator)

nj = Utils.NumberJuggler(2000000)
specialFracs = []

for numer in range(10, 100):
	for denom in range(numer + 1, 100):
		# print(str(numer) + "/" + str(denom))

		sNumer = list(str(numer))
		sDenom = list(str(denom))

		i = 0
		while i < len(sDenom):
			digit = sDenom[i]
			if digit in sNumer and digit in sDenom:
				sNumer.remove(digit)
				sDenom.remove(digit)
			else:
				i += 1

		if len(sNumer) > 0 and len(sDenom) > 0:
			newNumer = int(''.join(sNumer))
			newDenom = int(''.join(sDenom))

			if simplifyFraction(nj, numer, denom) == simplifyFraction(nj, newNumer, newDenom) and (newNumer != numer or newDenom != denom) and numer % 10 != 0:
				# print(str(numer) + "/" + str(denom) + " == " + str(newNumer) + "/" + str(newDenom))
				specialFracs.append((newNumer, newDenom))

print(specialFracs)
result = [1, 1]
for frac in specialFracs:
	result[0] *= frac[0]
	result[1] *= frac[1]

print(simplifyFraction(nj, result[0], result[1]))


from customtkinter import filedialog
from output import UNI
import customtkinter
import winreg
import shutil
import ctypes
import os

## GLOBAL FUNCTIONS

def CreateUNIBATFile(ProjectLocation: str, ProjectName: str) -> None:
    try:
        os.makedirs(f"{os.path.join(ProjectLocation, ProjectName)}/core/editor", exist_ok=True)
        with open(f"{os.path.join(ProjectLocation, ProjectName)}/core/editor/Editor.py", 'x') as EDITORFILE:
            pass
        # To copy content from existing editor.py to the new editor.py
        with open('./Editor.py', 'r') as EditorFile:
            content = EditorFile.read()
            with open(f"{os.path.join(ProjectLocation, ProjectName)}/core/editor/Editor.py", 'w') as NewEditorFile:
                NewEditorFile.write(content)
        # To copy content from existing output.py to the new output.py
        with open('./output.py', 'r') as OutputFile:
            content = OutputFile.read()
            with open(f"{os.path.join(ProjectLocation, ProjectName)}/core/editor/output.py", 'w') as NewOutputFile:
                NewOutputFile.write(content)

        os.makedirs(f"{ProjectLocation}/{ProjectName}/core/public/", exist_ok=True)
        shutil.copy('./images/UNIBATFILEicon.ico', f"{ProjectLocation}/{ProjectName}/core/public/")
        shutil.copy('./images/UNI_Dark.ico', f"{ProjectLocation}/{ProjectName}/core/public/")

        ctypes.windll.shell32.ShellExecuteW(None, "runas", "python", f'"{os.path.abspath(__file__)}"', None, 1) ## Giving ADMIN RIGHTS

        try:
            file_extension = ".UNI.bat"
            python_script = f"{ProjectLocation}/{ProjectName}/core/editor/editor.py"
            icon_path = f"{ProjectLocation}/{ProjectName}/core/public/UNIBATFILEicon.ico"

            try:
                with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, file_extension) as UNIBAT_KEY:
                    winreg.SetValue(UNIBAT_KEY, "DefaultIcon", winreg.REG_SZ, icon_path)
                    command_key = winreg.CreateKey(UNIBAT_KEY, r"shell\open\command")
                    winreg.SetValue(command_key, "", winreg.REG_SZ, f'python "{python_script}" "%1"')
            except Exception as error:
                UNI.Error(f"Exception Error - {ProjectName}: {type(error)} -> {str(error)}")
        except Exception as error:
            UNI.Error(f"Exception Error - {ProjectName}: {type(error)} -> {str(error)}")

    except Exception as error:
        UNI.Error(f"Exception Error - {ProjectName}: {type(error)} -> {str(error)}")

def CreateProject(ProjectName: str, ProjectLocation: str) -> None:
        AllowedCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
        UNI.Success(f"Creating {{{ProjectName}}} at \n\t\t {ProjectLocation}")
        if all(char in AllowedCharacters for char in ProjectName) and len(ProjectName) >= 3:
            try:
                os.mkdir(path=os.path.join(ProjectLocation, ProjectName))
                # CREATE A .UNIBAT FILE TO RUN OUR PROJECT
                try:
                    ProjectUNIBAT_File = open(f"{ProjectLocation}/{ProjectName}/{ProjectName}.UNI.bat", 'w+')
                    ProjectUNIBAT_File.write(f'''
                                            @echo off
                                            pip install customtkinter
                                            python "{ProjectLocation}/{ProjectName}/core/editor/Editor.py"
                                            pause
                                                ''')
                    ProjectUNIBAT_File.close()
                except FileExistsError as FEerror:
                    UNI.Error(f"Project Name - {ProjectName} -> File Exists Error: {FEerror}")

                # UNIBAT FILE CODE
                CreateUNIBATFile(ProjectLocation=ProjectLocation, ProjectName=ProjectName)
                UNI.Success("Project Created Successfully at {}".format((os.path.join(ProjectLocation, ProjectName)).replace('\\', '/')))
                os.startfile(os.path.join(ProjectLocation, ProjectName))
                root.destroy()
            except Exception as error:
                UNI.Error(f"Exception Error - {ProjectName}: {type(error)} -> {str(error)}")
        else:
            UNI.Error(f"Project Name - {ProjectName} -> Invalid Name \n\t\t Only A-Z, a-z, and _ are allowed \n\t\t\t\tor\n\t\t\t Project Name is too shot")

class HUB_APP:
    def __init__(self) -> None:
        pass

    def Application() -> None:
        customtkinter.set_appearance_mode("dark")
        customtkinter.set_default_color_theme("dark-blue")

        global root
        root = customtkinter.CTk()
        root.geometry("500x350")
        root.iconbitmap("./images/UNI_Dark.ico")
        root.title("UNI ENGINE HUB")

        UNI.Success("Application Booted")

        frame = customtkinter.CTkFrame(master=root)
        frame.pack(pady=20, padx=60, fill="both", expand=True)

        label = customtkinter.CTkLabel(master=frame, text="UNI ENGINE")
        label.pack(pady=12, padx=10)

        def SelectProjectLocation() -> str:
            path = filedialog.askdirectory(title="Browse Project Directory")
            return path

        def ProjectLocationButton() -> None:
            global _path_
            _path_ = SelectProjectLocation()

        global ProjectName
        ProjectName = customtkinter.CTkEntry(master=frame, placeholder_text="Enter Project Name")
        ProjectName.pack(pady=12, padx=10)
        ProjectLocationBtn = customtkinter.CTkButton(master=frame, text="Browse Project Location", command=ProjectLocationButton)
        ProjectLocationBtn.pack(pady=12, padx=10)

        def CreateProjectButton() -> None:
            CreateProject(ProjectName=ProjectName.get(), ProjectLocation=_path_)

        CreateProjectBtn = customtkinter.CTkButton(master=frame, text="Create Project", command=CreateProjectButton)
        CreateProjectBtn.pack(pady=12, padx=10)

        def ExitHubButton() -> None:
            try:
                 UNI.Warn("\n\t\t\t\t Exiting UNI ENGINE HUB")
                 root.destroy()
            except BaseException as BEError:
                 UNI.Error(f"Exception Error: {BEError}")

        HUBExitBtn = customtkinter.CTkButton(master=frame, text="EXIT", fg_color="Maroon", hover_color="#610c04", command=ExitHubButton)
        HUBExitBtn.pack(pady=12, padx=10)

        root.mainloop()