#-----------------------------------------------
# Import
#-----------------------------------------------

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

import pandas as pd
import os, csv
import re
import enchant

from operator import itemgetter

#-----------------------------------------------
# Global variables
#-----------------------------------------------

BAU_folder = "G:/My Drive/Learning and Development/L&D Systems Training/BAU and Aris Processes and Activities" # master folder
d = enchant.Dict("en_US")
funct_excel_files = 	[]
rasci_excel_files = 	[]
manual_excel_files = 	[]

#-----------------------------------------------
# Definitions
#-----------------------------------------------

def documents_setup():

	# If modifying these scopes, delete the file token.pickle.
	print(" - Getting Scopes")
	SCOPES = 	[
					'https://www.googleapis.com/auth/presentations',
					'https://www.googleapis.com/auth/spreadsheets'
				]

	# document ID's
	print(" - Getting document ID's")
	BAU_SHEET_ID		= '19R5DH0wZWuntZ81RR1Pd6eUxqDbkCutKp5uW9lipcT0'

	# sheet ranges
	print(" - Getting sheet ranges")
	BAU_SHEET_RANGE 	= '*DC!A1:BL'

	creds = None

	print(" - Checking for token (pickle) ")
	if os.path.exists('token.pickle'):
		with open('token.pickle', 'rb') as token:
			creds = pickle.load(token)
	# If there are no (valid) credentials available, let the user log in.
	if not creds or not creds.valid:
		if creds and creds.expired and creds.refresh_token:
			creds.refresh(Request())
		else:
			flow = InstalledAppFlow.from_client_secrets_file(
				'client_secret.json', SCOPES)
			creds = flow.run_local_server(port=0)
		# Save the credentials for the next run
		with open('token.pickle', 'wb') as token:
			pickle.dump(creds, token)

	service 		= build('slides', 'v1', credentials=creds)
	service_sheet 	= build('sheets', 'v4', credentials=creds)

	# Call the Slides API
	print(" - Calling document API's")
	global bau_sheet_result

	bau_sheet_result 	= service_sheet.spreadsheets().values().get(spreadsheetId=BAU_SHEET_ID, range=BAU_SHEET_RANGE).execute()

def get_bau_values():

	bau_rows 	= bau_sheet_result.get('values', [])

	# get the number for each column by using their name
	L4Name_col_num 				= bau_rows[0].index("L4Name")
	ArtifactNum_col_num			= bau_rows[0].index("Artifact Number (Auto)")
	System_col_num				= bau_rows[0].index("System")
	TransactionCode_col_num		= bau_rows[0].index("Txs Code")
	DC_Returns_col_num 			= bau_rows[0].index("RETURNS_DC")
	RC_Returns_CEN_col_num		= bau_rows[0].index("RETURNS_RC (CEN)")
	RC_Returns_BRK_col_num		= bau_rows[0].index("BRK RC")

	global BAU_L4Name
	global BAU_ArtifactNum
	global BAU_System
	global BAU_TransactionCode
	global BAU_DC_Returns
	global BAU_RC_Returns_CEN
	global BAU_RC_Returns_BRK

	BAU_L4Name 			= [row[L4Name_col_num] for row in bau_rows]
	BAU_ArtifactNum 	= [row[ArtifactNum_col_num] for row in bau_rows]
	BAU_System			= [row[System_col_num] for row in bau_rows]
	BAU_TransactionCode = [row[TransactionCode_col_num] for row in bau_rows]
	BAU_DC_Returns		= [row[DC_Returns_col_num] for row in bau_rows]
	BAU_RC_Returns_CEN	= [row[RC_Returns_CEN_col_num] for row in bau_rows]
	BAU_RC_Returns_BRK	= [row[RC_Returns_BRK_col_num] for row in bau_rows]

#..................................................................
# Get files
def getFiles():

	xlsx_files_count = 0
	gsheet_files_count = 0

	# go through all the files in the folder
	for path, subdirs, files in os.walk(BAU_folder):
		for name in files:

			# find all excel files
			if name.endswith(".xlsx"):

				xlsx_files_count += 1

				# get all files that are in Functions folder
				if(path.split("\\")[-1] == "Functions"):

					# get exported files
					if name.endswith("Manual Copy Paste.xlsx") == False:
						funct_excel_files.append(os.path.join(path, name))

					# get manual copy-paste files
					else:
						manual_excel_files.append(os.path.join(path, name))

				# get all files that are in RASCI folder
				if(path.split("\\")[-1] == "RASCI"):
					rasci_excel_files.append(os.path.join(path, name))

			# get all google sheet files
			if name.endswith(".gsheet"):
				gsheet_files_count += 1

	print("Function files found: " + str(len(funct_excel_files)))
	print("Manual copy-paste files fount: " + str(len(manual_excel_files)))
	print("RASCI files found: " + str(len(rasci_excel_files)))
	print(xlsx_files_count)
	print(gsheet_files_count)

L3_Number = []
L3_function_name = []
L3_description = []

L4_function = []
L4_description = []
row_counter = 0

# ====================================
# MANUAL COPY PASTE
# ====================================

manual_list = []
not_transaction_code = "HEADERDETAIL,MARKOUT,EQUIPUNITID,FLOWTHRU,PICKLIST,WRICEF"

def readL4Manual_Excel_Sheet1(manual_excel_files):
	print("Reading Manual Copy-Paste Excel")

	for manual_path in manual_excel_files:

		split_path = manual_path.split("\\")[-1].split(" ")
		names = ["L3Name", "L3Num", "L3Desc", "L4Name", "L4Desc", "L4Roles", "L4System"]
		df = pd.read_excel(manual_path, sheet_name="Sheet1", engine='openpyxl', usecols="A:D", header=None, names=names)

		row_activities = 2
		row_name = 1
		for row in df.iloc[:,0].tolist():
			if row=="Activities" or row=="[-]":
				break
			else:
				row_activities += 1

		for row in df.iloc[:,0].tolist():
			if row=="Name":
				break
			else:
				row_name += 1

		# L3 Information
		L3Name = " ".join(split_path[2:]).split("-")[0]
		L3Num = split_path[1].replace("0", "").replace("-", ".")
		L3Desc = df.iloc[row_activities-3][0]

		for i in range(row_name,len(df)):#list((df.iloc[row_counter:len(df)])):
			row = list(df.iloc[i])

			RC = False
			DC = False
			Overview = ""
			ProcessSteps = ""
			Note = ""
			Other = ""
			Transaction_code = ""
			switch = "Overview"

			# print(row)
			if (row[0]!=""):
				# print(i)

				try:
					L4Name = row[0]

					if "RC" in L4Name:
						RC = True
					if "DC" in L4Name:
						DC = True
				except:
					L4Name = ""

				try:
					L4Desc = row[1]
					print("-----------------------------------------")

					# process_list = ["process steps:", "process steps", "Process steps:", "Process steps"]
					# note_list = ["Note:", "Note", "note"]
					# other_list =

					for line in L4Desc.splitlines():#.split(char(10)):
						line_clean = line.strip().replace(":", "").lower()

						for wrong_char in "#.,/_+()'':-*+&[ ];":
							line_clean = line_clean.replace(wrong_char, "").replace('"', "").replace("CTRL+", "").strip().lower()
						# print(line_clean)

						if line_clean == "overview":
							switch == "Overview"

						if line_clean[:12] == "processsteps":
							print(line_clean)
							# print("Process Step")
							switch = "Process Steps"

						if line_clean == "note":
							switch = "Note"

						if line_clean == "other":
							switch = "Other"

						# get transaction codes
						for word in line.split(" "):
							clean_word = word
							for wrong_char in " #.,/_+()'':-*+&[];":
								clean_word = clean_word.replace(wrong_char, "").replace('"', "").replace("CTRL+", "").strip()

							# remove words that are not transaction codes
							for bad_word in not_transaction_code.split(","):
								if bad_word in clean_word or clean_word in bad_word:

									clean_word = ""

									# print(bad_word)

							if("WRICEF58" == clean_word):
								print(clean_word)

							if clean_word == clean_word.upper() and clean_word != "" and clean_word.isdigit() == False and len(clean_word) >= 5 and d.check(clean_word) == False and clean_word not in Transaction_code and clean_word not in not_transaction_code:
								Transaction_code += clean_word + ", "

						if switch == "Overview":
							Overview += line + chr(10)
						if switch == "Process Steps":
							ProcessSteps += line + chr(10)
						if switch == "Note":
							Note += line + chr(10)
						if switch == "Other":
							Other += line + chr(10)

					if "RC" in L4Desc:
						RC = True
					if "DC" in L4Desc:
						DC = True

							# process_line.append(line)

					# for PS in process_list:
					# 	if PS in L4Desc:
					# 		ProcessSteps = re.split(PS,L4Desc)[-1].lstrip("\n").lstrip(" ").lstrip("\n").lstrip(" ")
					# 		Overview = re.split(PS,L4Desc)[0]
					# 		break

					# for note in note_list:
					# 	if note in L4Desc:
					# 		Note = re.split(grp,L4Desc)[-1].lstrip("\n").lstrip(" ").lstrip("\n").lstrip(" ")
					# 		Overview = re.split(grp,L4Desc)[0]
					# 		break

					# if ProcessSteps == "":
					# 	Overview = L4Desc

					# # seperate and get Process Steps and Overview
					# if "Process Steps:" in L4Desc:
					# 	ProcessSteps = re.split(r'Process Steps:',L4Desc)[-1].lstrip("\n").lstrip(" ").lstrip("\n").lstrip(" ")
					# 	Overview = re.split(r'Process Steps:|Process Steps',L4Desc)[0]
					# elif "Process Steps" in L4Desc:
					# 	ProcessSteps = re.split(r'Process Steps',L4Desc)[-1].lstrip("\n").lstrip(" ").lstrip("\n").lstrip(" ")
					# 	Overview = re.split(r'Process Steps:|Process Steps',L4Desc)[0]
					# elif "Process steps:" in L4Desc:
					# 	ProcessSteps = re.split(r'Process steps:',L4Desc)[-1].lstrip("\n").lstrip(" ").lstrip("\n").lstrip(" ")
					# 	Overview = re.split(r'Process Steps:|Process Steps|Process steps:',L4Desc)[0]
					# elif "Process steps" in L4Desc:
					# 	ProcessSteps = re.split(r'Process steps',L4Desc)[-1].lstrip("\n").lstrip(" ").lstrip("\n").lstrip(" ")
					# 	Overview = re.split(r'Process Steps:|Process Steps|Process steps',L4Desc)[0]
					# else:
					# 	print("There is NO PS")
					# 	Overview = L4Desc

					# check for RC and DC

				except:
					L4Desc = ""

				try:
					L4Roles = row[2]
				except:
					L4Roles = ""

				try:
					L4System = row[3]
				except:
					L4System = ""

				bau_num = ""
				num_counter = 0
				for num in BAU_L4Name:
					if num.lower().strip().replace(' ', '') == L4Name.lower().strip().replace(' ', ''):
						bau_num = 		BAU_ArtifactNum[num_counter]
						BAU_L4Name_value 			= BAU_L4Name[num_counter]
						BAU_ArtifactNum_value		= BAU_ArtifactNum[num_counter]
						BAU_System_value			= BAU_System[num_counter]
						BAU_TransactionCode_value 	= BAU_TransactionCode[num_counter]
						BAU_DC_Returns_value		= BAU_DC_Returns[num_counter]
						BAU_RC_Returns_CEN_value	= BAU_RC_Returns_CEN[num_counter]
						BAU_RC_Returns_BRK_value	= BAU_RC_Returns_BRK[num_counter]
						break

					num_counter += 1
				if bau_num == "":
					# print(L4Name.lower().strip().replace(' ', ''))
					pass

				# leadingZero_bau_num = []
				# for single_num in bau_num:
				if "-" in bau_num:
					leadingZero_bau_num = (bau_num.split("-")[0] + "-" + bau_num.split("-")[1].zfill(2))
				elif bau_num == "":
					leadingZero_bau_num = "NA"
				else:
					leadingZero_bau_num = bau_num

				# print(leadingZero_bau_num)

				# 	print
				# try:
				# 	bau_num = BAU_ArtifactNum[BAU_L4Name.index(L4Name.strip())]
				# except:
				# 	bau_num = "~ " + str(L4Name)

				manual_list.append([
					L3Name,
					L3Num,
					L3Desc,
					L4Name,
					L4Desc,
					Overview,
					ProcessSteps,
					Note,
					Other,
					Transaction_code[:-2],
					RC,
					DC,
					L4Roles,
					L4System,
					leadingZero_bau_num,
					BAU_L4Name_value,
					BAU_ArtifactNum_value,
					BAU_System_value,
					BAU_TransactionCode_value,
					BAU_DC_Returns_value,
					BAU_RC_Returns_CEN_value,
					BAU_RC_Returns_BRK_value
					])

	global manual_list_sorted
	manual_list_sorted = sorted(manual_list, key=itemgetter(14))

# ====================================
# Start
# ====================================

documents_setup()
get_bau_values()
getFiles()
# readL3Function_Excel_SheetA(funct_excel_files)
readL4Manual_Excel_Sheet1(manual_excel_files)

# ====================================
# Write to CSV
# ====================================

# write to csv
with open('ARIS_manual_list.csv', 'w', newline='', encoding='utf-8') as f:
	print("Exporting to CSV")

	fieldnames =[
	"L3Name",
	"L3Num",
	"L3Desc",
	"L4Name",
	"L4Desc",
	"Overview",
	"Process Steps",
	"Note",
	"Other",
	"Transaction Code",
	"RC",
	"DC",
	"L4Roles",
	"L4System",
	"BAU Numbers",
	"BAU_L4Name_value",
	"BAU_ArtifactNum_value",
	"BAU_System_value",
	"BAU_TransactionCode_value",
	"BAU_DC_Returns_value",
	"BAU_RC_Returns_CEN_value",
	"BAU_RC_Returns_BRK_value"
	]

	thewriter = csv.DictWriter(f, fieldnames=fieldnames)

	counter = 0

	# write headers
	thewriter.writerow({
		"L3Name":"L3Name",
		"L3Num":"L3Num",
		"L3Desc":"L3Desc",
		"L4Name":"L4Name",
		"L4Desc":"L4Desc",
		"Overview":"Overview",
		"Process Steps":"Process Steps",
		"Note":"Note", "Other":"Other",
		"Transaction Code":"Transaction Code",
		"RC":"RC",
		"DC":"DC",
		"L4Roles":"L4Roles",
		"L4System":"L4System",
		"BAU Numbers":"BAU Numbers",
		"BAU_L4Name_value":"BAU_L4Name_value",
		"BAU_ArtifactNum_value":"BAU_ArtifactNum_value",
		"BAU_System_value":"BAU_System_value",
		"BAU_TransactionCode_value":"BAU_TransactionCode_value",
		"BAU_DC_Returns_value":"BAU_DC_Returns_value",
		"BAU_RC_Returns_CEN_value":"BAU_RC_Returns_CEN_value",
		"BAU_RC_Returns_BRK_value":"BAU_RC_Returns_BRK_value"
		})

	for i in manual_list_sorted:
		# for x in i:
		thewriter.writerow({
			"L3Name":i[0],
			"L3Num":i[1],
			"L3Desc":i[2],
			"L4Name":i[3],
			"L4Desc":i[4],
			"Overview":i[5],
			"Process Steps":i[6],
			"Note":i[7],
			"Other":i[8],
			"Transaction Code":i[9],
			"RC":i[10],
			"DC":i[11],
			"L4Roles":i[12],
			"L4System":i[13],
			"BAU Numbers":i[14],
			"BAU_L4Name_value":i[15],
			"BAU_ArtifactNum_value":i[16],
			"BAU_System_value":i[17],
			"BAU_TransactionCode_value":i[18],
			"BAU_DC_Returns_value":i[19],
			"BAU_RC_Returns_CEN_value":i[20],
			"BAU_RC_Returns_BRK_value":i[21]
			})


# Working!

t = int(input())

sentences = []
solved = []

for i in range (t):
    string = input()
    sentences.append(string.split())

for strings in sentences:
    longest = max(strings, key=len)
    dim = len(longest) + 2
    sol = ""
    sol += dim*'*'

    for string in strings:
        sol += '\n'
        string = '*' + string + (len(longest) - len(string))*' ' + '*'
        sol += string
    sol += '\n'
    sol += dim*'*'

    solved.append(sol)

for i in solved:
    print(i)


import numpy as np
import torch as th
from torch import nn
from torch import optim
import random

from collections import deque

np.random.seed(1)

class DeepQLearning:
    def __init__(
            self,
            n_actions,
            n_features,
            learning_rate,
            discount_factor,
            e_greedy,
            replace_target_iter,
            memory_size,
            batch_size
    ):
        # store paremeters into object attributes
        self.action_count = n_actions
        self.feature_count = n_features
        self.gamma = discount_factor
        self.epsilon = e_greedy
        self.batch_size = batch_size

        self.replace_target_counter = 0
        self.replace_target_iter = replace_target_iter

        self.hidden_size = 100

        # initialize experience replay buffer
        # deque -> with maxlen specified, when inserted element makes the deque larger than the maxlen, the corresponding number of elements are removed from the opposite side
        self.experience = deque([], maxlen=memory_size)

        # construct two networks
        self.Q_target = self.construct_network()
        self.Q_estim = self.construct_network()

        self.optimizer = optim.Adam(
            self.Q_estim.parameters(), lr=learning_rate)
        self.criterion = nn.MSELoss()

    # builds a torch network with given architecture
    def construct_network(self):
        return nn.Sequential(
            # one input layer taking a state as an input
            nn.Linear(self.feature_count, self.hidden_size),
            nn.ReLU(),
            # # one hidden layer
            # nn.Linear(self.hidden_size, self.hidden_size),
            # nn.ReLU(),
            # one output layer which returns Q values of all actions for given input state
            nn.Linear(self.hidden_size, self.action_count),
        ).float()

    def store_transition(self, s, a, r, next_s):
        # save tuple into experience buffer
        # deque takes care about forgetting old experiences
        self.experience.append((s, a, r, next_s))

    def choose_action(self, state):
        # take random action with probability epsilon
        if random.random() < self.epsilon:
            return random.randrange(self.action_count)

        state = th.from_numpy(state).float()
        # otherwise take best action according to Q_estim i.e. argmax_a Q_estim(s, a)
        with th.no_grad():
            a_vals = self.Q_estim(state)
        return th.argmax(a_vals).item()

    def learn(self):
        self.optimizer.zero_grad()

        # draw batch from experience replay buffer
        batch = random.sample(self.experience, self.batch_size)

        # split tuples in the batch by element types (s, a, r, s')
        transposed = list(zip(*batch))
        states = th.tensor(np.array(transposed[0])).float()
        actions = th.tensor(transposed[1])
        rewards = th.tensor(transposed[2]).float()
        next_states = th.tensor(np.array(transposed[3])).float()

        # compute targets from the frozen neural network
        with th.no_grad():
            # target = R_t+1 + gamma * max_a q~(s_t+1, a, w-)
            # add detach because we dont want to compute gradient w.r.t. to targets
            targets = rewards + self.gamma * \
                self.Q_target(next_states).detach().max(1)[0]

        # compute predictions q^(s_t, a_t, w_t)
        estimates = self.Q_estim(states)[range(len(actions)), actions]

        # select MSE as loss and compute its gradient
        loss = self.criterion(targets, estimates) / 2
        loss.backward()

        # make a step in opitmization
        self.optimizer.step()

        # if the counter reached replace_target_iter, freeze current weights
        self.replace_target_counter += 1
        if self.replace_target_counter == self.replace_target_iter:
            self.replace_target_counter = 0
            self.Q_target.load_state_dict(self.Q_estim.state_dict())


def is_valid(isbn):
    digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    character = ["X"]
    isbn_list = [ch for ch in isbn if ch in digits + character]
    isbn_dict = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "X": 10}
    if len(isbn_list) == 10 and set(isbn_list[0:9]).issubset(digits) and isbn_list[-1] in digits + character:
        sum = 0
        for i in range(0, len(isbn_list)):
            sum += (10 - i) * isbn_dict[isbn_list[i]]
    else:
        return False
    return sum % 11 == 0


from geneticAlgorithm import geneticAlgorithm, Element

from random import randint, choice

HealthDNA = "cctcacagctatccgtgcggcagtagcggcgcaaatctattagcggcttaggtagaagttagcacggctcccgaatgtggaaattcgtcggtataccgca"
TARGET =    "cctcacagctatccgtgcggcagtagcggcgcaaatctattagataggaaggtagaagttagcacggctcccgaatgtggaaattcgtcggtataccgca"
Population = 200
Tries = 75

def first_generation_creator():
    return [DNAsequence(HealthDNA) for _ in range(Population)]

def stop_condition(string, current_fitness, i):
    return current_fitness == 0

# Elitarny model pobierania kolejnych elementów
def equalitarianism(generation):
    max_selected = int(len(generation) / 15)
    sorted_by_assess = sorted(generation, key=lambda x: x.fitness)
    return sorted_by_assess[:max_selected]

class DNAsequence(Element):
    POSSIBILITIES = '''agtc'''

    def __init__(self, DNAsequence):
        self.DNAsequence = DNAsequence
        super().__init__()

    # Sprawdz przystosowanie - po prostu porównaj 2 stringi
    def evaluate_function(self):
        diff = 0
        for letter1, letter2 in zip(self.DNAsequence, TARGET):
            if letter1 != letter2:
                diff += 1
        return diff

    # wez dwa dna przeklei troche z jednego i polacz od lososwego indexu do losowego indexu
    def crossover_DNA(self, element2: 'Element' ) -> 'Element':
        length = int(randint(0, len(self.DNAsequence) - 1))
        new_DNAsequence = self.DNAsequence[:length] + element2.DNAsequence[length:]
        return DNAsequence(new_DNAsequence)

    # Mutacja - zamien litere
    def mutation_of_DNA(self):
        random_index = randint(0, len(self.DNAsequence) - 1)
        DNAsequence_as_list = list(self.DNAsequence)
        DNAsequence_as_list[random_index] = choice(self.POSSIBILITIES)
        self.DNAsequence = "".join(DNAsequence_as_list)

    # wypisanie elementu "printable"
    def __repr__(self):
        return self.DNAsequence

whole_process = '''{
    "HealthyDNA":"''' + str(HealthDNA) + '''",
    "UnhealthyDNA": "''' + str(TARGET) + '''",
    "ElementsInPopulation": "''' + str(Population) + '''",
    "NumberOfPopulation": "''' + str(Tries) + '''",
    "Data":{
    '''
next_try = 0;

for i in range(Tries):
    json_file = '"'+str(next_try)+'":' + '{'
    ga = geneticAlgorithm(first_generation_creator, equalitarianism, stop_condition)
    for result in ga.run():
        json_file = json_file + result + ","
    json_file = json_file[:-1]
    json_file = json_file + "}"
    # json_filesentence.strip()
    # print(json_file)
    whole_process = whole_process + json_file + ",";
    next_try = next_try + 1;
whole_process = whole_process[:-1]
whole_process = whole_process + "}}"

file = open("output.json","w+")
file.write(whole_process)
file.close;


# File Name: create_event_files
# Author: Khang Vo
# Date Created: 3/6/2022
# Date Last Modified: 11/13/2022
# Python Version: 3.9

import os
import glob
import time

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

# event function
def event(hdf_path, output_path):

    file_list = sorted(os.listdir(hdf_path))

    # iterate through files in file list and read only merged file
    for file in file_list:
        if "merge" in file:
            df_hdf = pd.read_csv(hdf_path + "/" + file, sep="\t", low_memory=False)

            c_hdf = df_hdf[["iyr", "mon", "iday", "ihr", "min", "sec", "glat", "glon", "depth", "ievt", "mb"]]

            c_hdf.to_csv(output_path + "/temp_event.txt", sep="\t", index=False)

            with open(output_path + "/temp_event.txt", "r") as infile:
                with open(output_path + "/" + file[7:14] + "_event.txt", "w") as outfile:
                    # outfile.write("iyr" + "\t")
                    # outfile.write("mon" + "\t")
                    # outfile.write("iday" + "\t")
                    # outfile.write("ihr" + "\t")
                    # outfile.write("min" + "\t")
                    # outfile.write("sec" + "\t")
                    # outfile.write("glat" + "\t")
                    # outfile.write("glon" + "\t")
                    # outfile.write("depth" + "\t")
                    # outfile.write("ievt" + "\t")
                    # outfile.write("mb" + "\n")
                    next(infile)
                    for line in infile:
                        fields = line.split()
                        iyr = fields[0]
                        mon = fields[1]
                        iday = fields[2]
                        ihr = fields[3]
                        min = fields[4]
                        sec = fields[5]
                        glat = fields[6]
                        glon = fields[7]
                        depth = fields[8]
                        ievt = fields[9]
                        mb = fields[10]
                        outfile.write(str(iyr).zfill(2) + str(mon).zfill(2) + str(iday).zfill(2) + "\t")
                        outfile.write(str(ihr).zfill(2) + str(min).zfill(2) + str(format(float(sec), ".2f").zfill(5)) + "\t")
                        outfile.write(glat + "\t")
                        outfile.write(glon + "\t")
                        outfile.write(depth + "\t")
                        outfile.write(mb + "\t")
                        outfile.write("0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t")
                        outfile.write(ievt + "\t")
                        outfile.write("0" + "\n")

            os.remove(output_path + "/temp_event.txt")

# abs function
def obs(res_path, output_path):
    file_list = sorted(os.listdir(res_path))

    # iterate through files in file list and read only merged file
    for file in file_list:
        if "merge" in file:
            df_res = pd.read_csv(res_path + "/" + file, sep="\t", low_memory=False)

            c_res = df_res[["sta", "ttime", "wgt", "phasej", "ievt"]]

            c_res.to_csv(output_path + "/temp_abs.txt", sep="\t", index=False)

            ievt_seen = set()

            with open(output_path + "/temp_abs.txt", "r") as infile:
                with open(output_path + "/" + file[7:14] + "_obs.txt", "w") as outfile:
                    # outfile.write("sta" + "\t")
                    # outfile.write("ttime" + "\t")
                    # outfile.write("wgt" + "\t")
                    # outfile.write("phasej" + "\n")
                    next(infile)
                    for line in infile:
                        fields = line.split()
                        sta = fields[0]
                        ttime = fields[1]
                        wgt = fields[2]
                        phasej = fields[3]
                        ievt = fields[4]
                        if ievt not in ievt_seen:
                            outfile.write("# " + ievt + "\n")
                            ievt_seen.add(ievt)
                        outfile.write(sta + "\t")
                        outfile.write(ttime + "\t")
                        outfile.write(wgt + "\t")
                        outfile.write(phasej + "\n")

            os.remove(output_path + "/temp_abs.txt")

if __name__ == "__main__":

    # user specified working directory
    input_path = "/Users/khangvo/PycharmProjects/Puerto_Rico_Project/files/03_study_area"
    output_path = "/Users/khangvo/PycharmProjects/Puerto_Rico_Project/files/04_TeletomoDD_files"

    event(input_path + "/hdf", output_path)
    obs(input_path + "/res", output_path)


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

from django.shortcuts import render
from maintenance.models import MaintenanceRequest
from maintenance.serializers import MaintenanceReadSerializer, MaintenancePostSerializer, MaintenanceUpdateSerializer, CommentSerializer
from rest_framework.views import APIView
from rest_framework import status

# Create your views here.

from rest_framework.response import Response

class MaintenanceListView(APIView):

    def get(self, request, apartment_key='0'):
        if (apartment_key == '0'):
            maint_requests = MaintenanceRequest.objects.exclude(status='complete').order_by('date_submitted')
        else:
            maint_requests = MaintenanceRequest.objects.filter(apartment_no=apartment_key).exclude(status='complete').order_by('date_submitted')

        serializer = MaintenanceReadSerializer(maint_requests, many=True)
        return Response(serializer.data)

    def post(self, request):
        print(request.data)
        this_req = request.data

        this_req['resident'] = 1
        this_req['category'] = 1
        this_req['staff'] = [1]

        serializer = MaintenancePostSerializer(data=this_req)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
            #################### END POST RELATED METHODS ####################

class MaintenanceDetailView(APIView):

    def get(self, request, maint_id='0'):
        if (maint_id != '0'):
            maint_request = MaintenanceRequest.objects.get(id=maint_id)

            serializer = MaintenanceReadSerializer(maint_request)
            return Response(serializer.data)

class MaintenanceUpdateView(APIView):

    def get(self, request, maint_id='0'):
        if (maint_id != '0'):
            maint_request = MaintenanceRequest.objects.get(id=maint_id)

            serializer = MaintenanceReadSerializer(maint_request)
            return Response(serializer.data)

    def post(self, request, maint_id='0'):
        if (maint_id != '0'):
            this_update = request.data
            this_update['request'] = maint_id

            ## Update the status of maintenance request object
            maint_request = MaintenanceRequest.objects.get(id=maint_id)
            maint_request.status = this_update['update_type']
            maint_request.save()

            serializer = MaintenanceUpdateSerializer(data=this_update)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
                #################### END POST RELATED METHODS ####################

class MaintenanceCommentView(APIView):

    def get(self, request, maint_id='0'):
        if (maint_id != '0'):
            maint_request = MaintenanceRequest.objects.get(id=maint_id)

            serializer = MaintenanceReadSerializer(maint_request)
            return Response(serializer.data)

    def post(self, request, maint_id='0'):
        if (maint_id != '0'):
            this_update = request.data
            this_update['request'] = maint_id

            serializer = CommentSerializer(data=this_update)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
                #################### END POST RELATED METHODS ####################

class StaffMaintenanceView(APIView):

    def get(self, request, staff_id='0'):
        if (staff_id != '0'):
            maint_requests = MaintenanceRequest.objects.filter(staff__id=staff_id)

            serializer = MaintenanceReadSerializer(maint_requests)
            return Response(serializer.data)

class CategoryMaintenanceView(APIView):

    def get(self, request, category_id='0'):
        if (category_id != '0'):
            maint_requests = MaintenanceRequest.objects.filter(category__id=category_id)

            serializer = MaintenanceReadSerializer(maint_requests)
            return Response(serializer.data)


import os
import sys
import constants
import argparse
from HTMLOperations import HTMLOperations
from XMLOperations import XMLOperations
from AggregateOperations import AggregateOperations

parser = argparse.ArgumentParser(description="Generate insights from text snapshots of your Whatsapp group chats.")
parser.add_argument("filename", type=str, help="Name of the text snapshot as a .txt file stored in the Inputs folder")
parser.add_argument("--show_graphs", type=str, help="Show graphs showing aggregate metrics (y/yes), default not shown", nargs="?", const="n", default="n")
parser.add_argument("--search_text", type=str, help="Optional search text to highlight in the generated output")

if __name__ == "__main__":
    args = parser.parse_args()
    filename = args.filename
    show_graphs = args.show_graphs
    search_text = args.search_text

    os.environ["show_graphs"] = show_graphs

    head, tail = os.path.split(filename)
    file_path = filename
    print('Head: ' + head)
    print('Tail: ' + tail)

    filename = tail
    print ("Input File name: " + filename)
    filename_without_extension = filename.strip().split('.')[0]
    print ("File name without extension: " + filename_without_extension)
    html_filename = filename_without_extension + ".html"
    xml_filename = filename_without_extension + ".xml"

    if not head:
        input_file_complete_location = os.path.join(constants.INPUT_FILES_FOLDER_NAME, filename)
    else:
        input_file_complete_location = file_path

    # Create the output folder if it does not exist
    if not os.path.exists(constants.OUTPUT_FILES_FOLDER_NAME):
        os.makedirs(constants.OUTPUT_FILES_FOLDER_NAME)

    html_output_file_complete_location = os.path.join(constants.OUTPUT_FILES_FOLDER_NAME, html_filename)
    xml_output_file_complete_location = os.path.join(constants.OUTPUT_FILES_FOLDER_NAME, xml_filename)

    # Generate the HTML output
    operations = HTMLOperations(input_file_complete_location, html_output_file_complete_location)
    operations.generate_output_file(search_text)
    print("Completed generating the HTML for the messages")

    # Generate the XML output
    operations = XMLOperations(input_file_complete_location, xml_output_file_complete_location)
    operations.generate_output_file(search_text)
    print("Completed generating the XML for the messages")

    # Generate the aggregate analysis
    operations = AggregateOperations(input_file_complete_location, None)
    operations.generate_output_file(None)
    print("Completed generating the images")
    print("All files are present in the Output folder in the same location as main.py script...")


#! /usr/bin/env python3

from __future__ import division

import os, sys
import tqdm
import torch
import torch.optim as optim
from terminaltables import AsciiTable
from torchsummary import summary

from src.Model.load_model import load_model
from src.utils.gUtils import Logger
from src.utils.torchUtils import to_cpu, set_seed
from src.utils.loss import compute_loss
from src.Dataset.KITTI2D_Dataset import dataloader_factory
from src.testME import evaluate

TRAIN_CONFIG = {
    "model": "configs/yolov3-custom.cfg",
    "pretrained_weights": "checkpoints/yolov3_ckpt_300.pth",  # if the training should start with pretrained-weights
    "train_path": "data",
    "valid_path": "data",
    "classes_names": ["Car", "Van", "Truck", "Pedestrian", "Misc"],
    "logdir": "logs",
    "epochs": int(200),
    "epochBaseNum": int(
        0
    ),  # NOTE:set this if you want to continue with pretrained wights but don't want to overwrite previous weights
    "n_cpu": int(4),
    "seed": -1,  # with any number other than -1 it sets the seeds for numpy and troch
    "checkpoint_interval": int(1),
    "iou_thres": 0.5,  # IOU threshold for evalutation
    "conf_thres": 0.1,  # Object confidence threshold
    "nms_thres": 0.5,  # IOU threshold for non-maximum suppression
    "multiscale_training": False,  # NOTE: this option dosent produce good results for now and needs more testing
    "verbose": False,
}

def trainME(CONFIG):
    print(f"Training began with following configs: \n")
    for key, value in CONFIG.items():
        print(key, "->", value)

    if CONFIG["seed"] != -1:
        set_seed(CONFIG["seed"])

    epochBaseNum = CONFIG["epochBaseNum"]
    # set tensorboard logging
    logger = Logger(CONFIG["logdir"])

    # Create directories
    os.makedirs("output", exist_ok=True)
    os.makedirs("checkpoints", exist_ok=True)

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    print(f"\n Creating the Model with pretraind { CONFIG['pretrained_weights']} ...\n")
    model = load_model(CONFIG["model"], CONFIG["pretrained_weights"])

    # Print model:
    if CONFIG["verbose"]:
        summary(model, input_size=(3, model.hyperparams["height"], model.hyperparams["height"]))

    mini_batch_size = model.hyperparams["batch"] // model.hyperparams["subdivisions"]
    # create training and validation dataloaders

    dataloader = dataloader_factory(
        data_path=CONFIG["train_path"],
        batch_size=mini_batch_size,
        img_size=model.hyperparams["height"],
        n_cpu=CONFIG["n_cpu"],
        mode="Train",
        multiscale_training=False,
    )

    # Load validation dataloader
    validation_dataloader = dataloader_factory(
        data_path=CONFIG["valid_path"],
        batch_size=mini_batch_size,
        img_size=model.hyperparams["height"],
        n_cpu=CONFIG["n_cpu"],
        mode="Validate",
    )

    # optimization:
    params = [p for p in model.parameters() if p.requires_grad]
    if model.hyperparams["optimizer"] == None:
        model.hyperparams["optimizer"] = "adam"

    if model.hyperparams["optimizer"] == "adam":
        optimizer = optim.Adam(
            params,
            lr=model.hyperparams["learning_rate"],
            weight_decay=model.hyperparams["decay"],
        )
    elif model.hyperparams["optimizer"] == "sgd":
        optimizer = optim.SGD(
            params,
            lr=model.hyperparams["learning_rate"],
            weight_decay=model.hyperparams["decay"],
            momentum=model.hyperparams["momentum"],
        )
    else:
        raise Exception("\n Expected one of adam or sgd for optimizer got {}".format(model.hyperparams["optimizer"]))

    for epoch in range(CONFIG["epochs"]):

        print("\n---- Training Epoch ----")

        model.train()

        for batch_i, (imgs, targets) in enumerate(tqdm.tqdm(dataloader, desc=f"Training Epoch {epochBaseNum + epoch}")):
            # for batch_i, (imgs, targets) in enumerate(dataloader):

            batches_done = len(dataloader) * epoch + batch_i
            imgs = imgs.to(device, non_blocking=True)
            targets = targets.to(device)
            outputs = model(imgs)
            loss, loss_components = compute_loss(outputs, targets, model)
            loss.backward()

            # optimizer
            if batches_done % model.hyperparams["subdivisions"] == 0:
                # adapting learning rate
                lr = model.hyperparams["learning_rate"]
                if batches_done < model.hyperparams["burn_in"]:
                    # Burn in
                    lr *= batches_done / model.hyperparams["burn_in"]
                else:
                    # else set learning rate got from hyperparams
                    for threshold, value in model.hyperparams["lr_steps"]:
                        if batches_done > threshold:
                            lr *= value
                # Log the learning rate
                logger.scalar_summary("train/learning_rate", lr, batches_done)
                # Set learning rate
                for g in optimizer.param_groups:
                    g["lr"] = lr
                optimizer.step()
                optimizer.zero_grad()

                # set loggings
                print(
                    AsciiTable(
                        [
                            ["Type", "Value"],
                            ["IoU loss", float(loss_components[0])],
                            ["Object loss", float(loss_components[1])],
                            ["Class loss", float(loss_components[2])],
                            ["Loss", float(loss_components[3])],
                            ["Batch loss", to_cpu(loss).item()],
                        ]
                    ).table
                )

            # Tensorboard:
            tensorboard_log = [
                ("train/iou_loss", float(loss_components[0])),
                ("train/obj_loss", float(loss_components[1])),
                ("train/class_loss", float(loss_components[2])),
                ("train/loss", to_cpu(loss).item()),
            ]
            logger.list_of_scalars_summary(tensorboard_log, batches_done)
            model.seen += imgs.size(0)

        # Save model to checkpoint file
        if epoch % CONFIG["checkpoint_interval"] == 0:
            checkpointNum = epochBaseNum + epoch
            checkpoint_path = f"checkpoints/yolov3_ckpt_{checkpointNum}.pth"
            print(f"---- saving checkpoint: '{checkpoint_path}' ----")
            torch.save(model.state_dict(), checkpoint_path)

        print("\n---- Evaluating ----")
        # Evaluate the model on the validation set
        metrics_output = evaluate(
            model,
            validation_dataloader,
            CONFIG["classes_names"],
            img_size=model.hyperparams["height"],
            iou_thres=CONFIG["iou_thres"],
            conf_thres=CONFIG["conf_thres"],
            nms_thres=CONFIG["nms_thres"],
            verbose=CONFIG["verbose"],
        )

        if metrics_output is not None:
            precision, recall, AP, f1, ap_class = metrics_output
            evaluation_metrics = [
                ("validation/precision", precision.mean()),
                ("validation/recall", recall.mean()),
                ("validation/mAP", AP.mean()),
                ("validation/f1", f1.mean()),
            ]
            logger.list_of_scalars_summary(evaluation_metrics, epoch)

if __name__ == "__main__":
    curr_path = os.getcwd()
    sys.path.append(curr_path)
    trainME(TRAIN_CONFIG)


import os
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By

class SearchTests(unittest.TestCase):

	def setUp(self):
		dire = os.path.dirname(os.path.abspath(__file__))
		chrome_driver_path = dire + "/chromedriver"
		self.driver = webdriver.Chrome(chrome_driver_path)

	def test_search(self):
		#assert "Login" in driver.title
		driver = self.driver
		driver.get("http://localhost:3000")
		input_search_box = driver.find_element_by_id("input-text-mainpage")
		input_search_box.clear()
		input_search_box.send_keys("Tonja Burlew")
		search_button = driver.find_element_by_id("search-button")
		search_button.click()
		assert "Tonja Burlew" in driver.page_source

	def tearDown(self):
		self.driver.close()

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


from rest_framework import viewsets

from currency.models import Rate, Source, ContactUs
from currency.api.serializers import RateSerializer, SourceSerializer, ContactUsSerializer
from currency.api.paginators import TenThousandPagination
from currency.filters import RateFilter, ContactUsFilter

from django_filters import rest_framework as filters
from rest_framework import filters as rest_framework_filters

class SourceViewSet(viewsets.ModelViewSet):
    queryset = Source.objects.all()
    serializer_class = SourceSerializer
    pagination_class = TenThousandPagination

class RateViewSet(viewsets.ModelViewSet):
    queryset = Rate.objects.all()
    serializer_class = RateSerializer
    pagination_class = TenThousandPagination
    filter_backends = (
        filters.DjangoFilterBackend,
        rest_framework_filters.OrderingFilter,
    )
    filterset_class = RateFilter
    ordering_fields = (
        'id',
        'buy',
        'sale',
        'source',
    )

class ContactUsViewSet(viewsets.ModelViewSet):
    queryset = ContactUs.objects.all()
    serializer_class = ContactUsSerializer
    pagination_class = TenThousandPagination
    filter_backends = (
        filters.DjangoFilterBackend,
        rest_framework_filters.OrderingFilter,
        rest_framework_filters.SearchFilter,
    )
    filterset_class = ContactUsFilter
    ordering_fields = (
        'id',
        'subject',
    )
    search_fields = ['subject', 'message']


import requests
import urllib3
import os.path
from datetime import datetime
from urllib3 import disable_warnings

def printmsg(msg):
    print(f"{str(datetime.now())[:-7]}\t{msg}")

session = requests.session()
path = os.path.split(os.path.realpath(__file__))[0]
if os.path.exists(path + "/jwt"):
    printmsg("cookie存在")
    with open(path + "/jwt", "r") as f:
        jwt = f.read()
else:
    jwt = input("请输入authorization(格式为Bearer zxcmzxncwqe):")

session.headers = {
    "User-Agent": "BiyaWallet/2.2.71 (iPhone; iOS 16.4.1; Scale/3.00)",
    "Authorization": jwt
}
urllib3.disable_warnings()
urls = {
    "api-wtrading": "https://api-wtrading.biya.in",
    "api-wuser": "https://api-wuser.biya.in",
    "api-se": "https://api-se.biya.in"
}

apis = {
    "自选股": "/v1/stock/followList?lang=en-us",
    "卖出直到取消": "/v1/security/limitOrder",
}

def follow_list(session):
    '''
    @:param: requests.session
    查看当前自选股
    '''
    res = session.post(f'{urls["api-wtrading"]}{apis["自选股"]}', verify=False, json={
        "language": "en-us",
        "listRows": "20",
        "lang": "en-us",
        "type": 3,
        "page": "1"
    })
    res_status = res.json()
    # print(res_status)
    if res_status["code"] != 200:
        return False
    return True

def sell_until_cancel(session):
    res = session.post(f"{urls['api-wtrading']}{apis['卖出直到取消']}", json={
        "quantity": "1",  # 数量
        "limit_price": "50.0000",  # 卖出价格
        "order_type": "LMT",
        "security_name": "英特尔,Intel Corp.",
        "symbol": "INTC",
        "action": "SELL",
        "language": "zh-cn"
        ,"lang": "zh-cn",
        "symbol_type": "1",
        "order_expired_flag": "GTC",  # 可选DAY，GTC
        "currency": "USD",
        "outside_rth": 1
    }, verify=False)
    res_status = res.json()
    printmsg(res_status["msg"])

def run(session):
    if follow_list(session):
        with open(path + "/jwt", "w") as f:
            f.write(jwt)
        sell_until_cancel(session)
    else:
        printmsg("jwt不正确，退出")

if __name__ == "__main__":
    run(session)


print("Enter the size of the diamond!")
while True:
    ko = input("> ")
    if ko == "exit" or ko == "e" or ko == "quit" or ko == "stop":
        print("Bye Bye!")
        break
    scan = int(ko) / 2
    scan = scan + 0.5
    size = int(scan)
    test = 3
    letzter = int(size) * 2 - 1
    u = int(size) - 1
    x = int(letzter / 2 - 0.5)

    q = int(size) * 2 - 1
    w = 2
    t = q-w

    for i in range(u):
        print(" ", end="")
    print("*")

#obere Hälfte des Diamanten von "tannenbaum.py"
    for i in range(u):
        for i in range(u - 1):
            print(" ", end="")
            if i == u - 2:
                u = u - 1

        for i in range(test):
            print("*", end="")
            if i == test - 1:
                print("")

            if i == test - 1:
                test = test + 2

#Falls Der input gerade ist wird noch eine mitte eingefügt:
    if int(ko) % 2 == 0:
        print("*" * letzter,end="")
        print("")

#Untere hälfte des Diamanten:
    for i in range(size-1):
        print(" " * u,end="")
        for i in range(t):
            print("*",end="")
            if i == (t - 1):
                t = t - 2
        print("")
        u = u + 1
    print("")


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

from ..base.addon import BaseAddon

class RestartFailed(BaseAddon):
    __name__ = "RestartFailed"
    __type__ = "addon"
    __version__ = "1.65"
    __status__ = "testing"

    __config__ = [
        ("enabled", "bool", "Activated", False),
        ("interval", "int", "Check interval in minutes", 90),
    ]

    __description__ = """Restart all the failed downloads in queue"""
    __license__ = "GPLv3"
    __authors__ = [("Walter Purcaro", "vuolter@gmail.com")]

    def periodical_task(self):
        self.log_info(self._("Restarting all failed downloads..."))
        self.pyload.api.restart_failed()

    def activate(self):
        self.periodical.start(self.config.get("interval") * 60)


import matplotlib.pyplot as plt
from utils import roundup
import random
import math
from config import config as cfg
import os

dest = os.path.dirname(__file__)

def rr_plot(list_of_processes, timestamp):

    # every file will be saved to given dir
    target = dest + "/" + timestamp
    os.makedirs(target, exist_ok=True)
    os.path.join(target)

    # setting size of the plot according to the biggest termination time
    width_xaxis = []
    for process in list_of_processes:
        width_xaxis.append(process.termination_time)
    width_value = max(width_xaxis)
    height_value = cfg["RR"]["PROCESS_RANGE"] * 5 + 5

    # scalable plot
    WIDTH = math.ceil((width_value + 150) / 50)
    HEIGHT = math.ceil((height_value + 150) / 50)
    BAR_HEIGHT = 2

    fig, gnt = plt.subplots(figsize=(WIDTH, HEIGHT))

    plt.title(f'GANNT PLOT FOR {cfg["RR"]["PROCESS_RANGE"]} PROCESSES, RR, '
              f'QUANTUM {cfg["RR"]["QUANTUM"]} [MS]')

    # setting size of graph
    gnt.set_ylim(0, height_value)
    gnt.set_xlim(0, roundup(width_value + 15))

    gnt.set_xlabel('Time[ms]')
    gnt.set_ylabel('Process')

    gnt.set_yticks([i for i in range(5, cfg["RR"]["PROCESS_RANGE"] * 5 +
                                     5, 5)])
    gnt.invert_yaxis()

    # grid settings and visibility
    gnt.grid(True)
    gnt.set_axisbelow(True)

    names = []
    # mark results
    for index, process in enumerate(list_of_processes):
        names.append("P" + str(process.name))
        # show waiting times from lists
        for interval in process.waiting_list:
            gnt.broken_barh([(interval[0], interval[1] - interval[0])],
                            ((index * 5 + 5) - BAR_HEIGHT / 2,
                             BAR_HEIGHT),
                            facecolors='#8e8888', label='waiting time')
        # show working times from lists
        for interval in process.working_list:
            gnt.broken_barh([(interval[0], interval[1] - interval[0])],
                            ((index * 5 + 5) - BAR_HEIGHT / 2,
                             BAR_HEIGHT),
                            facecolors='#00ff00', label='burst time')
        # add termination time annotation to every process
        gnt.annotate(f'{process.termination_time}',
                     xy=(
                         process.termination_time,
                         index * 5 + 5 + BAR_HEIGHT / 2),
                     xytext=(BAR_HEIGHT * 10, 5),
                     xycoords='data',
                     textcoords='offset pixels', ha='center', va='center')

    gnt.set_yticklabels(names)

    # fix legend visibility
    hand, labl = gnt.get_legend_handles_labels()
    handout = []
    lablout = []
    for h, l in zip(hand, labl):
        if l not in lablout:
            lablout.append(l)
            handout.append(h)
    gnt.legend(handout, lablout, prop={'size': 6})

    # save to file
    title = "RR_CHART_" + timestamp + ".png"
    sub = timestamp + "/"
    plt.savefig(sub + title)

# used to generate random colors for fcfs plot
randomhex = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c',
             'd', 'e', 'f']

def fcfs_plot(list_of_processes, timestamp):

    # every file will be saved to given dir
    target = dest + "/" + timestamp
    os.makedirs(target, exist_ok=True)
    os.path.join(target)

    # setting size of the plot according to the biggest termination time
    width_xaxis = []
    for process in list_of_processes:
        width_xaxis.append(process.termination_time)
    width_value = max(width_xaxis)

    # resetting to default
    plt.style.use('default')

    # scalable plot
    WIDTH = math.ceil((width_value + 150) / 50)
    HEIGHT = math.ceil((len(list_of_processes)*16)/100)
    fig, gnt = plt.subplots(figsize=(WIDTH, max(HEIGHT, 4)))

    # title
    processes = cfg["FCFS"]["PROCESS_RANGE"]
    if cfg["SUB"]["USE_RR_TO_FCFS"]:
        processes = cfg["RR"]["PROCESS_RANGE"]
    plt.title(f'GANNT PLOT FOR {processes} PROCESSES, FCFS')

    # Y axis height
    gnt.set_ylim(0, 4)

    # X axis width according to the rounded biggest value of all termination
    # times
    gnt.set_xlim(0, roundup(width_value))

    # X, Y axis labels
    gnt.set_xlabel('Time[ms]')
    # I decided to left Y axis without label
    gnt.set_yticks([2])
    gnt.set_yticklabels([' '])

    gnt.invert_yaxis()

    # grid tools and visibility
    gnt.grid(True)
    gnt.set_axisbelow(True)

    # show working times of each process from the list
    for index, process in enumerate(list_of_processes):
        # working list consist of one sub-list
        res_0 = process.working_list[0]
        res_1 = process.working_list[1]
        gnt.broken_barh([(res_0, res_1 - res_0)], (1, 2),
                        # pick random color of process on graph
                        # disclaimer: sometimes it is difficult to read values
                        # on a blending-color background
                        facecolors=f'#{random.choice(randomhex)}'
                                   f'{random.choice(randomhex)}'
                                   f'{random.choice(randomhex)}'
                                   f'{random.choice(randomhex)}'
                                   f'{random.choice(randomhex)}'
                                   f'{random.choice(randomhex)}',
                        label=f'P{process.name}')
        # termination time annotation arrangement scheme
        if index % 3 == 0:
            # place lower (the lower value the lower placement)
            value = -30
        elif index % 3 == 1:
            # place even
            value = 0
        else:
            # place higher (the higher value the higher placement)
            value = 30
        gnt.annotate(f'{process.termination_time}',
                     xy=(res_1, 2), xytext=(0, value),
                     xycoords='data',
                     textcoords='offset pixels', ha='center', va='center')

    # fix legend
    hand, labl = gnt.get_legend_handles_labels()
    handout = []
    lablout = []
    for h, l in zip(hand, labl):
        if l not in lablout:
            lablout.append(l)
            handout.append(h)
    gnt.legend(handout, lablout, prop={'size': 7-int(processes/20)},
               bbox_to_anchor=(1.07, 1))

    # save to file
    title = "FCFS_CHART_" + timestamp + ".png"
    sub = timestamp + "/"
    plt.savefig(sub + title)


import binascii
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
from Crypto.Util import Counter
import argparse

# length in bytes
KEY_LEN = 16
NONCE_LEN = 16

# counter length in bits
CTR_LEN = 128

def int_of_string(s):
    return int(binascii.hexlify(s), 16)

def byte_xor(ba1, ba2):
    non_xor_len = len(ba1) - len(ba2)
    if non_xor_len < 0:
        non_xor_len = 0

    return ba1[:non_xor_len] + bytes([_a ^ _b for _a, _b in zip(ba1, ba2)])

# corruption is an int (decimal)
def corrupt_ct(ct, corruption):
    # convert corruption int to bytes
    return byte_xor(ct, corruption.to_bytes((corruption.bit_length() // 8) + 1, byteorder="big"))

def encrypt_message(key, plaintext):
    iv = get_random_bytes(NONCE_LEN)
    ctr = Counter.new(CTR_LEN, initial_value=int_of_string(iv))
    aes = AES.new(key, AES.MODE_CTR, counter=ctr)
    return (iv, aes.encrypt(plaintext))

def decrypt_message(key, iv, ciphertext):
    ctr = Counter.new(CTR_LEN, initial_value=int_of_string(iv))
    aes = AES.new(key, AES.MODE_CTR, counter=ctr)
    return aes.decrypt(ciphertext)

# hamming distance is in bits
def hamming_distance(ba1, ba2):
    a1 = bytes_to_int(ba1)
    a2 = bytes_to_int(ba2)

    x = a1 ^ a2
    set_bits = 0

    while (x > 0):
        set_bits += x & 1
        x >>= 1

    return set_bits

def bytes_to_int(ba):
    return int.from_bytes(ba, byteorder="big")

def bytes_to_bits(ba):
    return bin(int.from_bytes(ba, byteorder="big"))

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description="Explore malleability of ciphertexts in AES-CTR")
    parser.add_argument('xor_with', type=int, help="integer to xor ciphertext with")
    args = parser.parse_args()

    key = get_random_bytes(KEY_LEN)
    data = b'contagion'

    (iv, ct) = encrypt_message(key, data)
    corrupted_ct = corrupt_ct(ct, args.xor_with)

    # decrypt original ciphertext
    recover_pt = decrypt_message(key, iv, ct)

    # decrypt corrupted ciphertext
    recover_corr_pt = decrypt_message(key, iv, corrupted_ct)

    assert(hamming_distance(recover_pt, recover_corr_pt) == hamming_distance(ct, corrupted_ct))


from classManejador import manejador

def menu(m):
    print("---------->MENU<----------")
    print("Opcion 1: Mostrar para cada variable el dia y hora de menor y mayor valor")
    print("Opcion 2: Indicar la temperatura promedio por cada hora")
    print("Opcion 3: Listado de valores")
    print("Opcion 0: Salir\n")
    op = int(input("INGRESE NUMERO DE OPCION: "))
    print("----------------------------------------")

    while True:
        if op == 1:
            m.opcion1()     #PROBLEMA CON LOS INDICES DE LA MATRIZ
        elif op == 2:
            m.opcion2()
        elif op == 3:
            dia = int(input("Ingrese numero de dia a listar: "))
            m.opcion3(dia)
        elif op == 0:
            print("Saliendo...")
            break
        else:
            print("OPCION INVALIDA")
        op = int(input("INGRESE NUMERO DE OPCION: "))

if __name__ == '__main__':
    m = manejador()
    m.cargadatos()  #ITEM 2 -> REALIZAR LA CARGA DE LA MATRIZ CON INSTANCIA DE LA CLASE REGISTRO
    menu(m)


import logging

logger = logging.getLogger(__name__)

from .base_info_loss import BaseInfoLossMetric
from .am import AttributeInfoLoss
from .dm import OutDegreeInfoLoss, InDegreeInfoLoss, OutInDegreeInfoLoss

class AttributeOutInDegreeInfoLoss(BaseInfoLossMetric):
    def __init__(self, subgraph, args):
        super().__init__(subgraph, args)

        self.attribute_info_loss_fn = AttributeInfoLoss(subgraph, args)
        self.out_in_degree_info_loss_fn = OutInDegreeInfoLoss(subgraph, args)

        self.alpha_adm = args['alpha_adm']

    def calculate_for_each_entity(self, entity_ids):
        am_result = self.attribute_info_loss_fn.calculate_for_each_entity(entity_ids)
        dm_result = self.out_in_degree_info_loss_fn.calculate_for_each_entity(entity_ids)

        result = {}
        for entity_id in entity_ids:
            am_score = am_result[entity_id]
            dm_score = dm_result[entity_id]

            result[entity_id] = am_score * self.alpha_adm + (1 - self.alpha_adm) * dm_score

        return result

    def call(self, entity_ids):
        result = self.calculate_for_each_entity(entity_ids)
        score = sum(result.values()) / len(entity_ids)

        return score


import difflib
import string

from nltk import word_tokenize

# This function extracts the name of the user from the user's input.
def extract_name(sentence):
    # Handle exception
    if sentence.strip().find(' ') == -1:
        return sentence

    # De-punctuate and tokenise sentences.
    tran_punc = str.maketrans({key: None for key in string.punctuation})
    sentence = sentence.translate(tran_punc)
    sequence = word_tokenize(sentence)

    # Generate bigram tokens for sentences.
    phrases = []
    for w in range(len(sequence)-1):
        phrases.append((sequence[w] + ' ' + sequence[w+1]))

    # Match the bigram tokenised sentences with the keywords in the list and extract the name.
    name_statements = ['name is', 'i am', 'call me']
    for s in name_statements:
        for t in phrases:
            if difflib.SequenceMatcher(None, s, t.lower()).ratio() > 0.7:
                return sentence.split(t)[-1].strip()

    # If no keyword is matched, the last word of the sentence is used as the name by default.
    return sentence.split()[-1]


"""
https://www.youtube.com/watch?v=PjhlUzp_cU0&t=960s

나도코딩
파이썬 코딩 무료 강의 (활용편5) - 데이터 분석 및 시각화, 이 영상 하나로 끝내세요

2022-08-02 03:58:10 ~ 04:05:02
"""

import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family'] = 'AppleGothic'
matplotlib.rcParams['font.size'] = 15
matplotlib.rcParams['axes.unicode_minus'] = False

'''
막대 그래프 (심화)
'''
# 가로 그래프 화
labels = ['강백호', '서태웅', '정대만']  # 이름
values = [190, 187, 184]  # 키

plt.barh(labels, values)

# x축 값 범위 조정
plt.xlim(175, 195)

# 바의 패턴 지정
'''
https://matplotlib.org/stable/gallery/shapes_and_collections/hatch_style_reference.html
위의 링크에서 다른 패턴 예시 확인  할 수 있음
'''

bar = plt.bar(labels, values)
bar[0].set_hatch('/')  # ////
bar[1].set_hatch('x')  # xxx
bar[2].set_hatch('.')  # ...

# 막대 별로 값 나타내기
bar = plt.bar(labels, values)
plt.ylim(175, 195)
for idx, rect in enumerate(bar):
    plt.text(idx, rect.get_height()+0.5, values[idx], ha='center', color='blue')
    # + 0.5 = 막대 바와 텍스트 간의 거리 조정
    # ha = 각 바 위에 텍스트의 가로 위치 ex) 가운데


from collections import defaultdict
from typing import Dict, Any, List, Union
import re

from io import BytesIO
import serial
import bdDetect
import braille
import inputCore
from logHandler import log
import hwIo
from baseObject import ScriptableObject
import wx
import threading
from globalCommands import SCRCAT_BRAILLE
import ui
import time

from . import constants
from . import gestures

def bytesToInt(byteData: bytes):
	"""Converts bytes to its integral equivalent."""
	return int.from_bytes(byteData, byteorder="big", signed=False)

class BrailleDisplayDriver(braille.BrailleDisplayDriver, ScriptableObject):
	_dev: hwIo.IoBase
	# Used to for error checking.
	_awaitingFrameReceipts: Dict[int, Any]
	name = constants.name
	# Translators: Names of braille displays.
	description = constants.description
	isThreadSafe = True
	supportsAutomaticDetection = True
	timeout = 0.2
	supportedSettings = (
		braille.BrailleDisplayDriver.HIDInputSetting(useConfig=True),
	)

	@classmethod
	def registerAutomaticDetection(cls, driverRegistrar: bdDetect.DriverRegistrar):
		driverRegistrar.addUsbDevices(bdDetect.KEY_HID, {
			"VID_C251&PID_1122",  # Esys (version < 3.0, no SD card
			"VID_C251&PID_1123",  # Esys (version >= 3.0, with HID keyboard, no SD card
			"VID_C251&PID_1124",  # Esys (version < 3.0, with SD card
			"VID_C251&PID_1125",  # Esys (version >= 3.0, with HID keyboard, with SD card
			"VID_C251&PID_1126",  # Esys (version >= 3.0, no SD card
			"VID_C251&PID_1127",  # Reserved
			"VID_C251&PID_1128",  # Esys (version >= 3.0, with SD card
			"VID_C251&PID_1129",  # Reserved
			"VID_C251&PID_112A",  # Reserved
			"VID_C251&PID_112B",  # Reserved
			"VID_C251&PID_112C",  # Reserved
			"VID_C251&PID_112D",  # Reserved
			"VID_C251&PID_112E",  # Reserved
			"VID_C251&PID_112F",  # Reserved
			"VID_C251&PID_1130",  # Esytime
			"VID_C251&PID_1131",  # Reserved
			"VID_C251&PID_1132",  # Reserved
		})
		driverRegistrar.addUsbDevices(bdDetect.KEY_SERIAL, {
			"VID_28AC&PID_0012",  # b.note
			"VID_28AC&PID_0013",  # b.note 2
			"VID_28AC&PID_0020",  # b.book internal
			"VID_28AC&PID_0021",  # b.book external
		})

		driverRegistrar.addBluetoothDevices(lambda m: m.id.startswith("Esys"))

	@classmethod
	def getManualPorts(cls):
		return braille.getSerialPorts()

	def __init__(self, port="Auto"):
		super().__init__()
		self.numCells = 0
		self.deviceType = None
		self._deviceData = {}
		self._awaitingFrameReceipts = {}
		self._frameLength = None
		self._frame = 0x20
		self._frameLock = threading.Lock()
		self._hidKeyboardInput = False
		self._hidInputBuffer = b""

		for portType, portId, port, portInfo in self._getTryPorts(port):
			# At this point, a port bound to this display has been found.
			# Try talking to the display.
			self.isHid = portType == bdDetect.KEY_HID
			try:
				if self.isHid:
					self._dev = hwIo.Hid(
						port,
						onReceive=self._onReceive,
						# Eurobraille wants us not to block other application's access to this handle.
						exclusive=False
					)
				else:
					self._dev = hwIo.Serial(
						port,
						baudrate=constants.BAUD_RATE,
						bytesize=serial.EIGHTBITS,
						parity=serial.PARITY_EVEN,
						stopbits=serial.STOPBITS_ONE,
						timeout=self.timeout,
						writeTimeout=self.timeout,
						onReceive=self._onReceive
					)
			except EnvironmentError:
				log.debugWarning(f"Error while connecting to port {port}", exc_info=True)
				continue

			for i in range(3):
				# Request device identification
				self._sendPacket(constants.EB_SYSTEM, constants.EB_SYSTEM_IDENTITY)
				# Make sure visualisation packets are disabled, as we ignore them anyway.
				self._sendPacket(constants.EB_VISU, constants.EB_VISU_DOT, constants.EB_FALSE)
				# A device identification results in multiple packets.
				# Make sure we've received everything before we continue
				while self._dev.waitForRead(2 * self.timeout):
					continue
				if self.numCells and self.deviceType:
					break
			if self.numCells and self.deviceType:
				# A display responded.
				log.info("Found {device} connected via {type} ({port})".format(
					device=self.deviceType, type=portType, port=port))
				if self.deviceType.startswith(("bnote", "bbook")):
					# send identifier to bnote / bbook with current COM port
					comportNumber = f'{int(re.match(".*?([0-9]+)$", port).group(1)):02d}'
					identifier = f"NVDA/{comportNumber}".encode()
					log.debug(f"sending {identifier} to eurobraille display")
					self._sendPacket(constants.EB_SYSTEM, constants.EB_CONNECTION_NAME, identifier)
				break
			self._dev.close()

		else:
			raise RuntimeError("No supported Eurobraille display found")

		self.keysDown = defaultdict(int)
		self._ignoreCommandKeyReleases = False

	def terminate(self):
		try:
			if self.deviceType.startswith(("bnote", "bbook")):
				# reset identifier to bnote / bbook with current COM port
				self._sendPacket(constants.EB_SYSTEM, constants.EB_CONNECTION_NAME, b'')
			super().terminate()
		finally:
			# We must sleep before closing the port as not doing this can leave
			# the display in a bad state where it can not be re-initialized.
			time.sleep(self.timeout)
			self._dev.close()
			self._dev = None
			self._deviceData.clear()

	def _prepFirstByteStreamAndData(
			self,
			data: bytes
	) -> (bytes, Union[BytesIO, hwIo.IoBase], bytes):
		if self.isHid:
			# data contains the entire packet.
			# HID Packets start with 0x00.
			byte0 = data[0:1]
			assert byte0 == b"\x00", "byte 0 is %r" % byte0
			# Check whether there is an incomplete packet in the buffer
			if self._hidInputBuffer:
				data = self._hidInputBuffer + data[1:]
				self._hidInputBuffer = b""
			byte1 = data[1:2]
			stream = BytesIO(data)
			stream.seek(2)
			return byte1, stream, data
		else:  # is serial
			return data, self._dev, data

	def _onReceive(self, data: bytes):
		byte1, stream, data = self._prepFirstByteStreamAndData(data)

		if byte1 == constants.ACK:
			frame = ord(stream.read(1))
			self._handleAck(frame)
		elif byte1 == constants.STX:
			length = bytesToInt(stream.read(2)) - 2  # length includes the length itself
			packet: bytes = stream.read(length)
			if self.isHid and not stream.read(1) == constants.ETX:
				# Incomplete packet
				self._hidInputbuffer = data
				return
			packetType: bytes = packet[0:1]
			packetSubType: bytes = packet[1:2]
			packetData: bytes = packet[2:] if length > 2 else b""
			if packetType == constants.EB_SYSTEM:
				self._handleSystemPacket(packetSubType, packetData)
			elif packetType == constants.EB_MODE:
				if packetSubType == constants.EB_MODE_DRIVER:
					log.debug("Braille display switched to driver mode, updating display...")
					braille.handler.update()
				elif packetSubType == constants.EB_MODE_INTERNAL:
					log.debug("Braille display switched to internal mode")
			elif packetType == constants.EB_KEY:
				self._handleKeyPacket(packetSubType, packetData)
			elif packetType == constants.EB_IRIS_TEST and packetSubType == constants.EB_IRIS_TEST_sub:
				# Ping command sent by Iris every two seconds, send it back on the main thread.
				# This means that, if the main thread is frozen, Iris will be notified of this.
				log.debug("Received ping from Iris braille display")
				wx.CallAfter(self._sendPacket, packetType, packetSubType, packetData)
			elif packetType == constants.EB_VISU:
				log.debug("Ignoring visualisation packet")
			elif packetType == constants.EB_ENCRYPTION_KEY:
				log.debug("Ignoring encryption key packet")
			else:
				log.debug(f"Ignoring packet: type {packetType}, subtype {packetSubType}, data {packetData}")

	def _handleAck(self, frame: int):
		try:
			super()._handleAck()
		except NotImplementedError:
			log.debugWarning(f"Received ACK for frame {frame} while ACK handling is disabled")
		else:
			try:
				del self._awaitingFrameReceipts[frame]
			except KeyError:
				log.debugWarning(f"Received ACK for unregistered frame {frame}")

	def _handleSystemPacket(self, packetType: bytes, data: bytes):
		if packetType == constants.EB_SYSTEM_TYPE:
			deviceType = ord(data)
			self.deviceType = constants.DEVICE_TYPES[deviceType]
			if 0x01 <= deviceType <= 0x06:  # Iris
				self.keys = constants.KEYS_IRIS
			elif 0x07 <= deviceType <= 0x0d:  # Esys
				self.keys = constants.KEYS_ESYS
			elif 0x0e <= deviceType <= 0x11:  # Esitime
				self.keys = constants.KEYS_ESITIME
			elif 0x12 <= deviceType <= 0x13:
				self.keys = constants.KEYS_BNOTE
			elif 0x14 <= deviceType <= 0x15:
				self.keys = constants.KEYS_BBOOK
			else:
				log.debugWarning(f"Unknown device identifier {data}")
		elif packetType == constants.EB_SYSTEM_DISPLAY_LENGTH:
			self.numCells = ord(data)
		elif packetType == constants.EB_SYSTEM_FRAME_LENGTH:
			self._frameLength = bytesToInt(data)
		elif packetType == constants.EB_SYSTEM_PROTOCOL and self.isHid:
			protocol = data.rstrip(b"\x00 ")
			try:
				version = float(protocol[:4])
			except ValueError:
				pass
			else:
				self.receivesAckPackets = version >= 3.0
		elif packetType == constants.EB_SYSTEM_IDENTITY:
			return  # End of system information
		self._deviceData[packetType] = data.rstrip(b"\x00 ")

	def _handleKeyPacket(self, group: bytes, data: bytes):
		if group == constants.EB_KEY_USB_HID_MODE:
			assert data in [constants.EB_TRUE, constants.EB_FALSE]
			self._hidKeyboardInput = constants.EB_TRUE == data
			return
		if group == constants.EB_KEY_QWERTY:
			log.debug("Ignoring Iris AZERTY/QWERTY input")
			return
		if group == constants.EB_KEY_INTERACTIVE and data[0:1] == constants.EB_KEY_INTERACTIVE_REPETITION:
			log.debug(f"Ignoring routing key {data[1] - 1} repetition")
			return
		arg = bytesToInt(data)
		if arg == self.keysDown[group]:
			log.debug("Ignoring key repetition")
			return
		self.keysDown[group] |= arg
		isIris = self.deviceType.startswith("Iris")
		if not isIris and group == constants.EB_KEY_COMMAND and arg >= self.keysDown[group]:
			# Started a gesture including command keys
			self._ignoreCommandKeyReleases = False
		else:
			if isIris or group != constants.EB_KEY_COMMAND or not self._ignoreCommandKeyReleases:
				try:
					inputCore.manager.executeGesture(gestures.InputGesture(self))
				except inputCore.NoInputGestureAction:
					pass
				self._ignoreCommandKeyReleases = not isIris and (group == constants.EB_KEY_COMMAND or self.keysDown[constants.EB_KEY_COMMAND] > 0)  # noqa E501
			if not isIris and group == constants.EB_KEY_COMMAND:
				self.keysDown[group] = arg
			else:
				del self.keysDown[group]

	def _sendPacket(self, packetType: bytes, packetSubType: bytes, packetData: bytes = b""):
		packetSize = len(packetData) + 4
		packetBytes = bytearray(
			b"".join([
				constants.STX,
				packetSize.to_bytes(2, "big", signed=False),
				packetType,
				packetSubType,
				packetData,
				constants.ETX
		]))
		if self.receivesAckPackets:
			with self._frameLock:
				frame = self._frame
				# Assumption: frame will only ever be 1 byte, otherwise consider byte order
				packetBytes.insert(-1, frame)
				self._awaitingFrameReceipts[frame] = packetBytes
				self._frame = frame + 1 if frame < 0x7F else 0x20
		packetData = bytes(packetBytes)
		if self.isHid:
			self._sendHidPacket(packetData)
		else:
			self._dev.write(packetData)

	def _sendHidPacket(self, packet: bytes):
		assert self.isHid
		blockSize = self._dev._writeSize - 1
		# When the packet length exceeds C{blockSize}, the packet is split up into several block packets.
		# These blocks are of size C{blockSize}.
		for offset in range(0, len(packet), blockSize):
			bytesToWrite = packet[offset:(offset + blockSize)]
			hidPacket = b"".join([
				b"\x00",
				bytesToWrite,
				b"\x55" * (blockSize - len(bytesToWrite))  # padding
			])
			self._dev.write(hidPacket)

	def display(self, cells: List[int]):
		# cells will already be padded up to numCells.
		self._sendPacket(
			packetType=constants.EB_BRAILLE_DISPLAY,
			packetSubType=constants.EB_BRAILLE_DISPLAY_STATIC,
			packetData=bytes(cells)
		)

	def _get_hidKeyboardInput(self):
		return self._hidKeyboardInput

	def _set_hidKeyboardInput(self, state: bool):
		self._sendPacket(
			packetType=constants.EB_KEY,
			packetSubType=constants.EB_KEY_USB_HID_MODE,
			packetData=constants.EB_TRUE if state else constants.EB_FALSE
		)
		for i in range(3):
			self._dev.waitForRead(self.timeout)
			if state is self._hidKeyboardInput:
				break

	scriptCategory = SCRCAT_BRAILLE

	def script_toggleHidKeyboardInput(self, gesture: inputCore.InputGesture):
		def announceUnavailableMessage():
			# Translators: Message when HID keyboard simulation is unavailable.
			ui.message(_("HID keyboard input simulation is unavailable."))

		if not self.isHid:
			announceUnavailableMessage()
			return

		state = not self.hidKeyboardInput
		self.hidKeyboardInput = state

		if state is not self._hidKeyboardInput:
			announceUnavailableMessage()
		elif state:
			# Translators: Message when HID keyboard simulation is enabled.
			ui.message(_('HID keyboard simulation enabled'))
		else:
			# Translators: Message when HID keyboard simulation is disabled.
			ui.message(_('HID keyboard simulation disabled'))

	# Translators: Description of the script that toggles HID keyboard simulation.
	script_toggleHidKeyboardInput.__doc__ = _("Toggle HID keyboard simulation")

	__gestures = {
		"br(eurobraille.esytime):l1+joystick1Down": "toggleHidKeyboardInput",
		"br(eurobraille):switch1Left+joystick1Down": "toggleHidKeyboardInput",
		"br(eurobraille.esytime):l8+joystick1Down": "toggleHidKeyboardInput",
		"br(eurobraille):switch1Right+joystick1Down": "toggleHidKeyboardInput",
	}
	gestureMap = gestures._gestureMap


import numpy as np
import pandas as pd
from scipy import interpolate as intp
from scipy import optimize
import matplotlib.pyplot as plt
import gsw
from tqdm import tqdm
import multiprocessing
from joblib import Parallel,delayed

def find_sigma0_z(salinity, temperature, pressure, latitude, longitude, sigmas):
    """
    Find the depth of the isopycnal using T/S from a cast
    Inputs:
        salinity    (array) : Salinity in PSU
        temperature (array) : In-situ temperature (C)
        latitude    (array) : Latitude of the sample
        longitude   (array) : Longitude of the sample
        sigmas      (array) : Isopycnals for which to find the depth
    Outputs:
        sigma_z     (array) : Depth of the isopycnals
    Algorithm:
        1. Convert in-situ salinity and temperature to Absolute Salinity and Conservative Temperature
        2. Calculate sigma0
        3. Check to ensure the isopycnal surface spans the density range of the water column
        4. Build interpolating functions for both T and S
        5. Sweep down and find the first place where the specified density exists in between adjacent points
        6. Use the EOS to find the where the zero crossing is
    """

    def dens_diff(pressure, SA_f, CT_f, target_sigma0):
        return np.square(gsw.sigma0(SA_f(pressure),CT_f(pressure)) - target_sigma0)

    def return_early(is_scalar):
        if is_scalar:
            return np.nan
        else:
            return np.nan*np.ones(sigmas.shape)

    # Promote to single element array if only one level requested
    valid = (~np.isnan(salinity)) & (~np.isnan(temperature)) & (~np.isnan(pressure))
    salinity = salinity[valid]
    temperature = temperature[valid]
    pressure = pressure[valid]
    longitude = longitude[valid]
    latitude = latitude[valid]

    is_scalar = type(sigmas) == type(0.)
    if is_scalar:
        sigmas = np.array([sigmas])

    if valid.sum() < 3:
        return return_early(is_scalar)

    pressure = np.array(pressure)
    SA = gsw.SA_from_SP(salinity, pressure, longitude, latitude)
    CT = gsw.CT_from_t(salinity, temperature, pressure)

    P_sort = np.unique(pressure)
    if len(P_sort) < 3:
        return return_early(is_scalar)

    SA_sort = np.zeros(P_sort.shape)
    CT_sort = np.zeros(P_sort.shape)
    # Loop through all pressures that overlap, average the temperatures and salinity accordingly
    for idx, P in enumerate(P_sort):
        presidx = (pressure == P)
        SA_sort[idx] = SA[presidx].mean()
        CT_sort[idx] = CT[presidx].mean()

    SA_intp = intp.interp1d(P_sort, SA_sort, kind='quadratic')
    CT_intp = intp.interp1d(P_sort, CT_sort, kind='quadratic')

    sigma0 = gsw.sigma0(SA_sort,CT_sort)
    sigma0_max = sigma0.max()
    sigma0_min = sigma0.min()

    sigma0_z = np.zeros(len(sigmas))

    for sigidx, siglev in enumerate(sigmas):
        if (siglev < sigma0_min) or (siglev > sigma0_max):
            sigma0_z[sigidx] = np.nan
        else:
            for botidx in range(len(sigma0)-1):
                if (siglev >= sigma0[botidx]) & (siglev <= sigma0[botidx+1]):
                    start_idx = botidx
                    break

            out = optimize.minimize_scalar(dens_diff,
                                            bounds=[P_sort[botidx],P_sort[botidx+1]],
                                            method='Bounded',
                                            args=(SA_intp, CT_intp, siglev))

            sigma0_z[sigidx] = out.x

    if is_scalar:
        sigma0_z = np.squeeze(sigma0_z)

    return sigma0_z

def process_cruise(cruise_df,sigma0_vals):
    nsigma0 = len(sigma0_vals)
    stations = cruise_df.station.unique()
    cols = ['latitude','longitude'] + [ f'{sig0}_z' for sig0 in sigma0_vals ]
    df_out = pd.DataFrame(columns = cols)
    for station in stations:
        df = cruise_df[ cruise_df.station == station ]
        sigma0_z = find_sigma0_z(df.salinity,df.temperature,df.pressure,df.latitude,df.longitude,sigma0_vals)
        if (np.isnan(sigma0_z).sum() != len(sigma0_vals)):
            out = np.nan*np.ones(nsigma0+2)
            out[0] = df.latitude.mean()
            out[1] = df.longitude.mean()
            out[2:] = sigma0_z
            df_out = df_out.append( pd.DataFrame([out], columns = cols), ignore_index = True )

    return df_out

if __name__ == '__main__':
  num_cores = multiprocessing.cpu_count()
  path = '/home/ashao/data/glodap/'
  path = ''
  glodap = pd.read_csv(path+'GLODAPv2.2019_Merged_Master_File.csv')
  cruise_ids = glodap.cruise.unique()
  glodap_by_cruise = [ glodap[(glodap.cruise == cruise_id) & (glodap.salinityqc == 1)] for cruise_id in cruise_ids ]
  inputs = tqdm( glodap_by_cruise )
  siglevels = np.linspace(26,27,11)
  out = Parallel(n_jobs=num_cores)(delayed(process_cruise)(cruise_df.replace(-9999,np.nan),siglevels) for cruise_df in inputs)
  out = pd.concat(out,ignore_index=True)
  out.to_csv('sigma_levels_z.csv')


'''
https://leetcode.com/problems/longest-mountain-in-array/
You may recall that an array arr is a mountain array if and only if:
arr.length >= 3
There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.

Example 1:
Input: arr = [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
'''
'''
Time:O(n)
Space:O(1)
'''
class Solution:
    def longestMountain(self, arr: List[int]) -> int:
        res = 0
        left = 0
        while left<len(arr):
            right = left
            if right+1<len(arr) and arr[right+1]>arr[right]:
                while right+1<len(arr) and arr[right+1]>arr[right]:
                    right += 1
                if right+1<len(arr) and arr[right+1]<arr[right]:
                    while right+1<len(arr) and arr[right+1]<arr[right]:
                        right += 1
                    res = max(res, right-left+1)
            left = max(left+1, right)
        return res


import pygame
from variables import *

def plot_results(herbivores_counts, predators_counts, plants_counts):
    import matplotlib.pyplot as plt

    time_steps = list(range(len(herbivores_counts)))

    plt.plot(time_steps, herbivores_counts, label="Herbivores", color="blue")
    plt.plot(time_steps, predators_counts, label="Predators", color="red")
    plt.plot(time_steps, plants_counts, label="Plants", color="green")

    plt.xlabel("Time Steps")
    plt.ylabel("Count")
    plt.title("Population Dynamics")
    plt.legend()

    plt.show()

    print(herbivores_counts)
    print(predators_counts)
    print(plants_counts)

def draw_button(screen, button_rect, text): #simulation control buttons
    pygame.draw.rect(screen, (100, 100, 100), button_rect, 0)
    pygame.draw.rect(screen, (200, 200, 200), button_rect, 1)

    font = pygame.font.Font(None, 24)
    label = font.render(text, 1, (255, 255, 255))
    screen.blit(label, (button_rect.x + button_rect.width // 2 - label.get_width() // 2,
                        button_rect.y + button_rect.height // 2 - label.get_height() // 2))

def draw_text_box(screen, base_font, text, color, input_rect): #animal number control text boxes
    pygame.draw.rect(screen, color, input_rect)
    text_surface = base_font.render(text, True, (255, 255, 255))
    screen.blit(text_surface, (input_rect.x + 5, input_rect.y + 5))
    input_rect.w = max(100, text_surface.get_width() + 10)


#!/usr/bin/env python3
import subprocess, time, re, socket, argparse, os, asyncio, sys
import urllib
import socket
import geoip2.database
from IPy import IP
from prometheus_client import Counter, start_http_server, Gauge

metric_labels = ['src_pod', 'src_user', 'src_org', 'dst_ip', 'dst_proto', 'dst_country', 'dst_continent']

geo_reader = geoip2.database.Reader('/opt/GeoLite2-Country.mmdb')

host_name = os.environ.get('HOSTNAME')
if host_name is None:
    host_name = socket.gethostname()
src_pod = host_name
try:
    host_name = urllib.parse.unquote(host_name.replace('-', '%')).partition('%')[2].rpartition('%')[0]
    (src_user, _, src_org) = host_name.partition('@')
except Exception as e:
    src_user = 'Unknown'
    src_org = 'Unknown'

# Helper for building regex.
def re_param(name, pattern):
    return f'(?P<{name}>{pattern})'

# Pre-compile regex for matching tcpdump output:
pattern = '.*' + '.*'.join([
    'proto ' + re_param('proto', '\w+') + ' ',
    'length ' + re_param('length', '\d+'),
    '\n\s*' + re_param('src', '[\w\d\.-]+') + '\.' + re_param('srcp', '[\w\d-]+') +
    ' > ' +
    re_param('dst', '[\w\d\.-]+') + '\.' + re_param('dstp', '[\w\d-]+'),
]) + '.*'
dump_matcher = re.compile(pattern)

# Parse output from tcpdump and update the Prometheus counters.
def parse_packet(line):
    m = dump_matcher.match(line)
    if not m:
        return
    metric_labels = ['src_pod', 'src_user', 'src_org', 'dst_ip', 'dst_proto', 'dst_country']
    dst_ip = m.group('dst')
    if IP(dst_ip).iptype() != 'PUBLIC':
        return

    proto = m.group('proto').lower()
    if proto != 'icmp':
        proto += '/' + m.group('dstp')
    else:
        dst_ip += '.' + m.group('dstp') # in icmp, dstp matches last part of ip

    try:
        geo_response = geo_reader.country(dst_ip)
        country = geo_response.country.name
        continent = geo_response.continent.name
    except Exception as e:
        country = 'Unknown'
        continent = 'Unknown'

    labels = {
        'src_pod': src_pod,
        'src_user': src_user,
        'src_org': src_org,
        'dst_ip': dst_ip,
        'dst_proto': proto,
        'dst_country': country,
        'dst_continent': continent
    }
    packets.labels(**labels).inc()
    throughput.labels(**labels).inc(int(m.group('length')))

# Run tcpdump and stream the packets out
async def stream_packets():
    p = await asyncio.create_subprocess_exec(
        'tcpdump', '-i', opts.interface, '-v', '-n', stdout=asyncio.subprocess.PIPE)
    start_time = time.time()
    while True:
        if time.time() - start_time > 60:
            packets._metrics.clear()
            throughput._metrics.clear()
            start_time = time.time()
        # When tcpdump is run with -v, it outputs two lines per packet;
        # readuntil ensures that each "line" is actually a parse-able string of output.
        line = await p.stdout.readuntil(b' IP ')
        if len(line) <= 0:
            # print(f'No output from tcpdump... waiting.')
            time.sleep(1)
            continue
        try:
            parse_packet(line.decode('utf-8'))
        except BaseException as e:
            # print(f'Failed to parse line "{line}" because: {e}')
            pass

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--interface', '-i', default=os.getenv('NOE_INTERFACE', 'eth0'),
        help='The network interface to monitor.')
    parser.add_argument('--port', '-p', default=int(os.getenv('NOE_PORT', 9000)),
        help='The Prometheus metrics port.')
    parser.add_argument('--metric_prefix', '-s', default=os.getenv('NOE_METRIC_PREFIX', 'noe'),
        help='Metric prefix (group) for Prometheus')
    opts = parser.parse_args()

    packets = Gauge(f'{opts.metric_prefix}_packets', 'Packets transferred per minute', metric_labels)
    throughput = Gauge(f'{opts.metric_prefix}_bytes', 'Bytes transferred per minute', metric_labels)

    start_http_server(int(opts.port))
    asyncio.run(stream_packets())


from pathlib import Path
import openpyxl as xl
import datelist
import os

import master

step = "one"
status = ""
# making the dir if path not exist
path = Path("c:/it/PayrollAuto/")
if path.exists():
    # making temp directory if not exist
    if not Path(master.temppath).exists():
        os.mkdir(master.temppath)
    # checking the file exists to do automation
    if master.file.exists():
        # load the master file
        print("Step " + step)
        wb = xl.load_workbook(master.filepath+"empshiftsum.xlsx")
        sh1 = wb["Sheet1"]
        sh2 = wb.create_sheet("stepone")
        maxrow = sh1.max_row
        # print(maxrow)
        # loop through each row
        for row in range(1,maxrow+1):
            raw_data = sh1.cell(row,1).value
            raw_wrhr = sh1.cell(row,7).value
            # it will store the working hours in new sheet
            # print(row)
            # print(type(raw_wrhr))
            if isinstance(raw_wrhr,float) or isinstance(raw_wrhr,int):
                new_raw_wrhr = sh2.cell(row,5)
                new_raw_wrhr.value = raw_wrhr
            # it will check the rows with date and overcome the exception is it's run in the month of Jan
            # if it's not date than it means it's either company or employee
            if not raw_data.find(str(datelist.curt_year)) != -1 and not raw_data.find(str(datelist.curt_year-1)) != -1:
                # company
                if raw_data.upper().find(master.company) != -1:
                    new_raw_comp = sh2.cell(row,4)
                    new_raw_comp.value = raw_data
                    new_raw_compcode = sh2.cell(row,1)
                    new_raw_compcode.value = master.company_code
                # employee
                else:
                    # print(raw_data)
                    new_raw_emp = sh2.cell(row,2)
                    new_raw_emp.value = raw_data
                    new_raw_compcode = sh2.cell(row,1)
                    new_raw_compcode.value = master.company_code
            else:

                new_raw_compcode = sh2.cell(row, 1)
                new_raw_compcode.value = master.company_code
                # removing empty rows and taking only date
                if isinstance(raw_wrhr,float) or isinstance(raw_wrhr,int):
                    new_raw_date = sh2.cell(row,3)
                    new_raw_date.value = raw_data
        # saving in the workbook
        wb.save(master.temppath + "stepone.xlsx")
        status = "Done"
    else:
        print("Please copy the empshiftsum.xlsx inside c:/it/PayrollAuto/")
else:
    path = "c:/it/PayrollAuto/"
    os.mkdir(path)


left = lambda i : i*2+1
right = lambda i: i*2+2

def max_heapify(arr, size , i):
    largest = i
    if left(i) < size  and arr[left(i)] > arr[largest]:
        largest = left(i)
    if right(i) < size  and arr[right(i)] > arr[largest]:
        largest = right(i)

    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]
        max_heapify(arr,size,largest)

def build_max_heap(arr):

    for i in reversed(range(0, len(arr)//2)):
        max_heapify(arr, len(arr) , i)

def heap_sort(arr):
    build_max_heap(arr)
    index = 0
    for i in reversed(range(1, len(arr))):
        arr[0], arr[i] = arr[i] , arr[0]
        index += 1
        max_heapify(arr, len(arr)-index ,0)

x = [3,2,5,1,10,12,9]
heap_sort(x)
print(x)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 15 14:55:14 2021

@author: sahyadri
"""

import json
import numpy as np
import re
import argparse
import glob
import os
from datetime import date

def find_star(data):
    """
    Function to find the position of a given star (Alpheratz; could be any other)
    in a hyg.json file

    Parameters
    ----------
    data : dict
        Json object contain the hyg.json data.

    Returns
    -------
    long : float
        Longitude of the specified star in the hyg.json file.

    """
    #want to find position of a star based on its name
    features = data['features']
    names = [x['properties']['name'] for x in features]
    pos = np.where([x=='Alpheratz' for x in names])[0][0] #can change name
    long = features[pos]['geometry']['coordinates'][0]
    return long

def load_json(filepath):
    """
    Opens a json file and stores its data as a dictionary

    Parameters
    ----------
    filepath : string
        Path to the json file to be opened.

    Returns
    -------
    data : dict
        Dictionary containing data from a json file.

    """
    file =  open(filepath)
    data = json.load(file)
    return data

def calc_diff(latest_long, prev_long):
    """
    Function to calculate the shift from one day to the other. Computes the diff
    in longitudes for one star accross consecutive hyg.json files.

    Parameters
    ----------
    latest_long : float
        Longitude of selected star from latest hyg.json file.
    prev_long : float
        Longitude of selected star from previous hyg.json file.

    Returns
    -------
    diff : float
        Difference between the two longitudes.

    """
    diff = latest_long - prev_long
    return diff

def compute_coords(prev_const, diff):
    """
    Function to update the constellations by addition of the difference to the
    longitudes for all points making up a constellation. The addition checks if
    the longitude jumps above 360 or below 0 and corrects for those. It uses
    list_comprehension to update the nested list structure in the const.json
    files.

    Parameters
    ----------
    prev_const : dict
        Dictionary with previous date's constalltion data.
    diff : float
        Diff b/w longitudes of selected star accross consecutive days.

    Returns
    -------
    updated_const : dictionary
        Dictionary containing constellation points with all points updated.

    """
    for i, item in enumerate(prev_const['constellations']):
        Lines = item['points']
        # 360-long if long exceeds 360 and 360+long if long becomes -ve.
        updated_coords = [[[360-(y[0]+diff),y[1]] if y[0]+diff >= 360
                           else [360+y[0]+diff,y[1]] if y[0]+diff < 0
                           else [y[0]+diff,y[1]] for y in x] for x in Lines]
        prev_const['constellations'][i]['points'] = updated_coords
    updated_const = prev_const
    return updated_const

def extract_date(latest_file_name):
    filename = latest_file_name.split('/')[-1]
    filename = filename.split('_')
    month, day = filename[1], filename[2]
    year = re.split('g', filename[0], 1)[1]
    const_filename = 'const{}_{}_{}_00_00_00.json'.format(year, month, day)
    return const_filename

#added an argument parser to add choice b/w past or today modes.
parser = argparse.ArgumentParser(description='Constellation update')
parser.add_argument('opt',
                    metavar='option',
                    type=str,
                    help='Choice of run mode: "today" or "past"')
args = parser.parse_args()
option = args.opt

#loading the reference hyg.json and constellation files
ref_hyg = load_json('var/www/FDL/json/ALL/hyg2010_01_31_00_00_00.json')
prev_const = load_json('var/www/FDL/json/ALL/const_01_31_2010.json')

if option == 'today':
    #iter_list = glob.glob('var/www/FDL/json/ALL/hyg*.json')
    #iter_list = glob.glob('/home/sahyadri/Desktop/CAMS-India/hyg*.json')
    #latest_file = max(iter_list, key=os.path.getctime) #most recently created file.
    today = str(date.today())
    date_list = today.split('-')
    year, month, day = date_list[0], date_list[1], date_list[2]
    file_name = 'var/www/FDL/json/ALL/hyg{}_{}_{}_00_00_00.json'.format(year,month,day)
    print(file_name)
    latest_hyg = load_json(file_name)
    latest_long = find_star(latest_hyg)
    ref_long = find_star(ref_hyg)
    diff = calc_diff(latest_long, ref_long)
    new_const = compute_coords(prev_const, diff) #updated const json object!
    new_filename = extract_date(file_name)
    #creating a new const.json file
    new_file = open(new_filename,'w+')
    json.dump(new_const, new_file)
    new_file.close()

elif option == 'past':
    #for hyg_file in glob.glob('var/www/FDL/json/ALL/hyg*.json'):
    for hyg_file in glob.glob('var/www/FDL/json/ALL/hyg*.json'):
        latest_hyg = load_json(hyg_file)
        latest_long = find_star(latest_hyg)
        ref_long = find_star(ref_hyg)
        diff = calc_diff(latest_long, ref_long)
        new_const = compute_coords(prev_const, diff) #updated const json object!
        new_filename = extract_date(hyg_file)
        #creating a new const.json file
        new_file = open(new_filename,'w+')
        json.dump(new_const, new_file)
        new_file.close()
else:
    print('invalid options...write only "today" or "past"')


"""ORM-like approach to neo4j nodes
"""
import json
from abc import ABC, abstractmethod
from typing import Literal

class _Neo4jObject(ABC):

    @property
    @abstractmethod
    def label(self) -> str:
        raise NotImplementedError('This method must be implemented')

    @classmethod
    @abstractmethod
    def create(cls, tx, **kwargs) -> int:
        raise NotImplementedError('This method must be implemented')

class _Node(_Neo4jObject):
    """
    """

    @classmethod
    def _raw_query(
        cls,
        tx,
        creation_action: Literal['MERGE', 'CREATE'],
        **kwargs
    ) -> int:
        obj = ', '.join([f'{k}: {json.dumps(v)}' for k, v in kwargs.items()])  # Creates a string as follow: key1: $key1, key2: $key2,
        query = f'{creation_action} (n:{cls.label} {{{obj}}}) RETURN ID(n) AS node_id'
        result = tx.run(query)
        record = result.single()
        return record['node_id']

    @classmethod
    def create(cls, tx, **kwargs) -> int:
        return cls._raw_query(tx, 'CREATE', **kwargs)

    @classmethod
    def get_or_create(cls, tx, **kwargs) -> int:
        return cls._raw_query(tx, 'MERGE', **kwargs)

class _Realtionship(_Neo4jObject):
    """
    """

    @classmethod
    def _raw_query(
        cls,
        tx,
        creation_action: Literal['CREATE', 'MERGE'],
        condition: str
    ) -> int:
        """Match two nodes and creates a relationship between them

        :param tx: Neo4j transaction object
        :param creation_action: How to create the relationship
        :param condition: How to find the two nodes: a, b
        """
        query = f'MATCH (a), (b) WHERE {condition} {creation_action} (a)-[r:{cls.label}]->(b) RETURN ID(r) as relationship_id'
        result = tx.run(query)
        record = result.single()
        return record['relationship_id']

class DeepRequestNode(_Node):
    label = 'DeepRequest'

class UserNode(_Node):
    label = 'UserNode'

class AdjectiveNode(_Node):
    label = 'AdjectiveNode'

class RequestAdjectiveRealtionship(_Realtionship):
    label = 'IS'

    @classmethod
    def get_or_create(cls, tx, node_a_id, node_b_id):
        cls._raw_query(tx, 'MERGE', f'ID(a) = {node_a_id} AND ID(b) = {node_b_id}')

class UserDeepRequestRealtionship(_Realtionship):
    label = 'REQUESTED'

    @classmethod
    def get_or_create(cls, tx, node_a_id, node_b_id):
        cls._raw_query(tx, 'MERGE', f'a.user_id = {node_a_id} AND ID(b) = {node_b_id}')

    # @staticmethod
    # def matched_nodes(tx, deep_id, number_of_related):
    #     query = """
    #     MATCH (d1:DeepRequest)-->(a:AdjectiveNode)<--(d2:DeepRequest)
    #     WHERE ID(d1) = $deep_id
    #     WITH d1, d2, collect(a) as related_adjectives
    #     WHERE size(related_adjectives) > $number_of_related
    #     RETURN d1, d2, related_adjectives
    #     """
    #     result = tx.run(query, deep_id=deep_id, number_of_related=number_of_related)
    #     record = result.single()
    #     return record['node_id']


import os
import csv

csvfilepath = os.path.join('Resources', 'election_data.csv')

count = 0
candidate_list =[]
uni_candiates = []
vote_count = []
vote_percentage = []

with open(csvfilepath) as csvfile:
    reader = csv.reader(csvfile, delimiter = ',')
    header = next(reader)

    for row in reader:

        count = count + 1

        candidate_list.append(row[2])

    for name in set(candidate_list):
        uni_candiates.append(name)

        y = candidate_list.count(name)
        vote_count.append(y)

        z = (y/count)*100
        vote_percentage.append(z)

    winning_vote_count = max(vote_count)

    winner = uni_candiates[vote_count.index(winning_vote_count)]

print('Election Results''\n')
print('----------------------------------''\n')
print(f'Total Votes: {count}''\n')
print('----------------------------------''\n')
for i in range(len(uni_candiates)):
            print(uni_candiates[i] + ": " + str(vote_percentage[i]) +"% (" + str(vote_count[i])+ ")")
print('----------------------------------''\n')
print(f'The winner is: {winner}')

with open('election_results.txt', 'w') as text:
    text.write("Election Results\n")
    text.write('----------------------------------''\n')
    text.write(f'Total Votes: {count}''\n')
    print('----------------------------------''\n')
    for i in range(len(uni_candiates)):
            text.write(uni_candiates[i] + ": " + str(vote_percentage[i]) +"% (" + str(vote_count[i])+ ")")
    text.write('----------------------------------''\n')
    text.write(f'The winner is: {winner}')