# This script analyzes the runtime of different experiments from 'timing_info'
# The goal is to compute  min, max, avg, std deviation of timing for each '$SOLVER_both' setting
# We will report on min, max, avg, std deviation of timing 'with and without' support computation
# The final results will be put into the $ANALYSES_DIR$ directory

__author__ = "Elaheh"
__date__ = "$Jan 30, 2016 5:35:12 AM$"

import os, sys, shelve
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
import numpy as np

TIMEOUT = 700.0
SOLVERS = ['z3', 'yices', 'smtinterpol', 'mathsat']
MINING_DIR = 'mining'
ANALYSES_DIR = 'timing_analyses'
TIMING_INFO = 'timing_info'
NUM_OF_MODELS = 395
TIMINGS =  ['jsupport', 'z3_both', 'z3_both_no_sup',
            'yices_both',  'yices_both_no_sup',
            'smtinterpol_both', 'smtinterpol_both_no_sup',
            'mathsat_both', 'mathsat_both_no_sup',
            'z3_k_ind', 'z3_k_ind_no_sup',
            'z3_pdr', 'z3_pdr_no_sup',
            'yices_k_ind', 'yices_k_ind_no_sup',
            'yices_pdr', 'yices_pdr_no_sup',
            'smtinterpol_k_ind', 'smtinterpol_k_ind_no_sup',
            'smtinterpol_pdr', 'smtinterpol_pdr_no_sup',
            'mathsat_k_ind', 'mathsat_k_ind_no_sup',
            'mathsat_pdr', 'mathsat_pdr_no_sup',
            'z3_both_sup', 'z3_k_ind_sup', 'z3_pdr_sup',
            'yices_both_sup', 'yices_k_ind_sup', 'yices_pdr_sup',
            'smtinterpol_both_sup', 'smtinterpol_k_ind_sup', 'smtinterpol_pdr_sup',
            'mathsat_both_sup', 'mathsat_k_ind_sup', 'mathsat_pdr_sup']

LEGENDS =  ['JSupport', 'Z3 with support computation', 'Z3 wihtout support computation',
            'Yices with support computation', 'Yices wihtout support computation',
            'SMTInterpol with support computation', 'SMTInterpol wihtout support computation',
            'MathSAT with support computation', 'MathSAT wihtout support computation']

if not os.path.exists(MINING_DIR):
    print(MINING_DIR + " does not exists! first, try to run mining scripts.")
    sys.exit(-1)

if os.path.exists(ANALYSES_DIR):
    print(ANALYSES_DIR + " alrady exists! first, delete directory: "+ ANALYSES_DIR)
    sys.exit(-1)
os.mkdir(ANALYSES_DIR)

#
# Load timing info
#

reader = shelve.open(os.path.join(MINING_DIR, 'timing_info'))
all_timings = []
for i in range(9):
    all_timings.append(reader[TIMINGS[i]])

# Add support computation time for _both setting
sup_timings = []
for solver in SOLVERS:
    sup_timings.append(reader[solver+'_both_sup'])

reader.close()

#
# Compute min, max, avg, std deviation storing them on disk
#
writer = open(os.path.join(ANALYSES_DIR, 'timing_analyses.txt'), 'a')

for i, legend in enumerate(LEGENDS):
    writer.write('###################  timing report on the \"'+ legend + '\" setting  ###################\n')
    all_timings[i] = [float(x) for x in all_timings[i]]
    # Clean unknown runtimes
    for t, time in enumerate(all_timings[i]):
        if time >= TIMEOUT:
            all_timings[i][t] = float('nan')
    writer.write('\nminimum runtime is: ' + str(min(all_timings[i])))
    writer.write('\nmaximum runtime is: ' + str(max(all_timings[i])))
    writer.write('\npopulation standard deviation runtime is: ' + str(np.nanstd(all_timings[i])))
    writer.write('\naverage runtime is: ' + str(np.nanmean(all_timings[i])))
    writer.write('\n-------------------------------------------------------------------------------------------------')
    writer.write('\nfor '+ str(NUM_OF_MODELS) + ' models, the following shows runtimes in \"'+ legend + '\" setting')
    writer.write('\neach item in the following list is related to a model in the benchmarks.\n\n')
    writer.write(str([round(float(i), 2) for i in all_timings[i]]) + '\n\n\n\n')
writer.close()

#
# Calculate support overhead
# This shows what percentage of the overal runtime is because of support comutation
# Formula:  overhead_percentage = 100 * (SupportRuntime/ Runtime)
#

# required indices in all_timings [1, 3, 5, 7]
for indx, item in enumerate(sup_timings):
    for i in range(len(item)):
        sup_timings[indx][i] = 100.00 * (float(item[i])/ all_timings[indx + 1][i])

# in the following lists, indices show 'z3', 'yices', 'smtinterpol', 'mathsat', respectively
mean_overheads = []
max_overheads = []
min_overheads = []
stdev_overheads = []

for item in sup_timings:
    mean_overheads.append(np.nanmean(item))
    stdev_overheads.append(np.nanstd(item))
    min_overheads.append(min(item))
    max_overheads.append(max(item))
del sup_timings

#
# Report on support runtime overhead
#
writer = open(os.path.join(ANALYSES_DIR, 'sup_overhead.txt'), 'a')
writer.write("this is to report the overhead of support computation on different solvers\n")
writer.write("This report is based on the results when both k_induction and PDR were activated.\n\n")
writer.write("This shows what percentage of the overal runtime is because of support comutation:\n")
writer.write("         Formula:  overhead_percentage = 100 * (SupportRuntime/ Runtime)\n\n\n")

for i, solver in enumerate(SOLVERS):
    writer.write('\n\n###################  runtime overhead on \"'+ solver + '\"  ###################\n')
    writer.write('\naverage overhead is: ' + str(mean_overheads[i]) + "%")
    writer.write('\npopulation standard deviation overhead is: ' + str(stdev_overheads[i]) + "%")
    writer.write('\nminimum overhead is: ' + str(min_overheads[i]) + "%")
    writer.write('\nmaximum overhead is: ' + str(max_overheads[i]) + "%")
writer.close()

#
# Visualize the results
#

# Build a list for x-axis
x_axis = []
for i in range(NUM_OF_MODELS):
    x_axis.append(i)

x = np.arange(NUM_OF_MODELS)
fig = plt.figure()
ax = plt.subplot(111)

#colors = cm.rainbow(np.linspace(0, 1, len(LEGENDS)))

'''for indx, legend in enumerate(LEGENDS):
    #plt.scatter(x_axis, all_timings[indx], label=legend, color=colors[indx])
    plt.plot(x_axis, all_timings[indx], label=legend)'''

'''for indx in range(3):
    #plt.scatter(x_axis, all_timings[indx], label=legend, color=colors[indx])
    plt.plot(x_axis, all_timings[indx], label=LEGENDS[indx])  '''
'''
plt.plot(x_axis, all_timings[1], label=LEGENDS[1])
plt.plot(x_axis, all_timings[3], label=LEGENDS[3])
plt.plot(x_axis, all_timings[5], label=LEGENDS[5])
plt.plot(x_axis, all_timings[7], label=LEGENDS[7])
'''
plt.plot(x_axis, all_timings[1], label=LEGENDS[1])
plt.plot(x_axis, all_timings[2], label=LEGENDS[2])
plt.xlabel('LUS models')
plt.ylabel('Runtime (sec)')
plt.title('Computational runtime')
plt.tight_layout()

#plt.subplots_adjust(left=0.125, bottom=0.5, right=0.9, top=0.9, wspace=0.2, hspace=0.2)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.legend(loc=2, prop={'size':14})
fig.savefig(os.path.join(ANALYSES_DIR, 'timing_analyses.png'))
plt.show()
plt.close(fig)


try:
    import asyncio
except Exception:
    pass
from multiprocessing import JoinableQueue
import logging
import sys
import threading
import time
import tornado.ioloop
import tornado.web
if (sys.version_info >= (3, 0)):
    from time import monotonic
else:
    from monotonic import monotonic

HEALTH_CHECK_SERVER = None

class TornadoRequestHandler(tornado.web.RequestHandler):
    """Request handler for when we are using tornado"""
    def get(self):
        """Handle GET requests"""
        response = None
        content_type = 'text/plain'
        response = "FAIL\n"
        status_code = 503

        # Return health if we have been marked as healthy in the last 5 minutes
        elapsed = monotonic() - HEALTH_CHECK_SERVER.last_healthy
        if elapsed < 300:
            response = "OK\n"
            status_code = 200

        if response is not None:
            self.set_status(status_code)
            self.set_header("Content-Type", content_type)
            self.set_header("Referrer-Policy", "no-referrer")
            self.set_header("Access-Control-Allow-Origin", "*")
            self.write(response)

class HealthCheckServer(object):
    """Local HTTP server for interacting with the extension"""
    def __init__(self, server_port):
        global HEALTH_CHECK_SERVER
        HEALTH_CHECK_SERVER = self
        self.thread = None
        self.messages = JoinableQueue()
        self.server_port = server_port
        self.last_healthy = monotonic()
        self.__is_started = threading.Event()

    def start(self):
        """Start running the server in a background thread"""
        self.__is_started.clear()
        self.thread = threading.Thread(target=self.run)
        self.thread.daemon = True
        self.thread.start()
        self.__is_started.wait(timeout=30)

    def stop(self):
        """Stop running the server"""
        logging.debug("Shutting down extension server")
        self.must_exit = True
        if self.thread is not None:
            ioloop = tornado.ioloop.IOLoop.instance()
            ioloop.add_callback(ioloop.stop)
            self.thread.join()
        self.thread = None
        logging.debug("Extension server stopped")

    def healthy(self):
        """Mark the last time that the agent was healthy"""
        self.last_healthy = monotonic()

    def is_ok(self):
        """Check that the server is responding and restart it if necessary"""
        import requests
        end_time = monotonic() + 30
        server_ok = False
        proxies = {"http": None, "https": None}
        while not server_ok and monotonic() < end_time:
            try:
                requests.get('http://127.0.0.1:{}/'.format(self.server_port), timeout=10, proxies=proxies)
                server_ok = True
            except Exception:
                pass
            if not server_ok:
                time.sleep(5)
        return server_ok

    def run(self):
        """Main server loop"""
        logging.debug('Starting health check server on port %d', self.server_port)
        try:
            asyncio.set_event_loop(asyncio.new_event_loop())
        except Exception:
            pass
        application = tornado.web.Application([(r"/.*", TornadoRequestHandler)])
        application.listen(self.server_port, '0.0.0.0')
        self.__is_started.set()
        tornado.ioloop.IOLoop.instance().start()


import json

DEFAULT_TRUTH_THRESHOLD = 0.5

def get_eval_values(relation, results, discretize = False, truth_threshold = DEFAULT_TRUTH_THRESHOLD):
    """
    Take in the results from inference (for a single predicate),
    and format the data for each relation into two lists of floats representing the predicted and truth value for each data point.
    These lists should be able to be directly passed into general sklean evaluation/scoring metrics.
    Return: (expected, predicted)
    """

    # Order results/truth to match.
    expected = list(sorted([list(map(str, row)) for row in relation.get_truth_data()]))
    if (len(expected) == 0):
        return [], []

    predicted = list(sorted([list(map(str, row)) for row in results]))

    if (len(expected) > len(predicted)):
        raise ValueError("Expecting (%d) more values than actually predicted (%d)." % (len(expected), len(predicted)))

    # If the sizes don't match, then that means there may be latent or missing variables.
    output_warning = False
    if (len(expected) != len(predicted)):
        new_expected = []
        new_predicted = []

        expected_map = {tuple(row[0:-1]) : float(row[-1]) for row in expected}
        predicted_map = {tuple(row[0:-1]) : float(row[-1]) for row in predicted}

        for key in expected_map:
            if (key not in predicted_map):
                if (not output_warning):
                    print("WARNING: Atom(s) for the %s relation were found in truth (len: %d) that were not in the predictions (len: %d). Example: %s(%s)." % (relation.name(), len(expected), len(predicted), relation.name(), ', '.join(map(str, key))))
                    output_warning = True

                continue

            new_expected.append(expected_map[key])
            new_predicted.append(predicted_map[key])

        expected = new_expected
        predicted = new_predicted
    else:
        # Once sorted, just get the values.
        expected = [float(row[-1]) for row in expected]
        predicted = [float(row[-1]) for row in predicted]

    if (discretize):
        expected = [int(value >= truth_threshold) for value in expected]
        predicted = [int(value >= truth_threshold) for value in predicted]

    return expected, predicted

def get_eval_categories(relation, results, label_indexes = [-1]):
    """
    Like get_eval_values(), but will get labels instead of truth values.
    Labels are identified using label_indexes (negative indexes are allowed).
    Any label that is not an index is used to identify the entity represented by the data point.
    Returns: (expected label, predicted label, entity)
    """

    label_indexes = [index if (index >= 0) else (relation.arity() + index ) for index in label_indexes]
    entity_indexes = list(sorted(set(range(relation.arity())) - set(label_indexes)))

    # {(entity): [(best label), best value], ...}
    expected_values = {}
    predicted_values = {}

    for (source, dest) in [(relation.get_truth_data(), expected_values), (results, predicted_values)]:
        for row in source:
            value = float(row[-1])
            entity = tuple([str(row[index]) for index in entity_indexes])
            label = tuple([str(row[index]) for index in label_indexes])

            if ((entity not in dest) or (value > dest[entity][1])):
                dest[entity] = [label, value]

    if (len(expected_values) != len(predicted_values)):
        print("Warning: found different sizes for truth (%d) and predictions (%d)." % (len(expected_values), len(predicted_values)))

    entities = list(sorted(set(expected_values.keys()) & set(predicted_values.keys())))

    expected = [expected_values[entity][0] for entity in entities]
    predicted = [predicted_values[entity][0] for entity in entities]

    return expected, predicted, entities

def load_json_with_comments(path):
    contents = []
    with open(path, 'r') as file:
        for line in file:
            line = line.strip()
            if (line == '' or line.startswith('#') or line.startswith('//')):
                continue

            if ('/*' in line):
                raise ValueError("Multi-line comments ('/* ... */') not allowed.")

            contents.append(line)

    return json.loads(' '.join(contents))


from simulation_settings import *
import numpy as np
import actions
import pickle
import datetime
from keras.models import Sequential
from keras.layers import Dense
import keras.models
from keras.callbacks import CSVLogger
import random
import pickle

state_mode = 'simple_state'

def custom_metric(state_action_a, state_action_b):
    dist_list = list()
    weights = ((1/5000), (1/5000), (1/180), (1/5), (1/5), 1.0, 1.0)
    for vars in zip(state_action_a, state_action_b, weights):
        var_dist = np.float(abs((vars[0] - vars[1])*vars[2]))
        dist_list.append(var_dist)
    dist = np.average(dist_list)
    #TODO Use fixed divisors for ref distance..avoid zero
    return dist

def get_nn(obj):
    if obj:
        model = keras.models.load_model(obj)
    else:
        # create model
        model = Sequential()
        if state_mode == 'simple_state':
            model.add(Dense(20, input_shape=(5,), activation='relu'))
        else:
            model.add(Dense(20, input_shape=(7,), activation='relu'))
        model.add(Dense(20, activation='relu'))
        model.add(Dense(20, activation='relu'))
        model.add(Dense(1, activation='linear'))
        # Compile model
        # sgd = optimizers.SGD(lr=1, decay=0, momentum=0.9, nesterov=True)
        # rmsprop = optimizers.RMSprop(lr=0.001)
        model.compile(loss='mean_squared_error', optimizer='adam')
        # plot_model(model, to_file='model.png')
    return model

class Learner(object):
    exploring = None

    def __init__(self, file_to_save='agents/agent_'+datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
                 load_saved_regression=False,
                 r_m_=None, nn_=False):
        self.rw_mp = r_m_
        self.debug = True
        self.current_step = 0
        self.batch_list = list()
        self.nn_flag = nn_
        if self.nn_flag:
            self.learner = get_nn(load_saved_regression)
        else:
            pass
        self.end_states = dict()
        self.discount_factor = 0.8
        self.mode = self.mode = 'angle_only'
        self.states = list()
        self.act = list()
        self.rewards = list()
        self.states_p = list()
        self.q_target = list()
        r_mode = '__'
        self.file = None
        self.samples = None
        if self.rw_mp:
            r_mode = self.rw_mp.reward_mode
        self.file = file_to_save + self.learner.__class__.__name__ + '_r_' + r_mode+'_disc_'+str(self.discount_factor)
        self.logger = CSVLogger(self.file + 'log', separator=';', append=True)

    def add_tuples(self, tuples_list):
        self.batch_list = self.batch_list + tuples_list

    def set_up_agent(self):
        print("Batch size: ", len(self.batch_list))
        self.states = [list(k[0]) for k in self.batch_list]
        if self.mode == 'angle_only':
            self.act = [(x[1][0]) for x in self.batch_list]
        else:
            self.act = [(x[1]) for x in self.batch_list]
        self.rewards = np.asarray([x[3] for x in self.batch_list], dtype=np.float64)
        self.states_p = [list(k[2]) for k in self.batch_list]
        self.end_states = [(x[4]) for x in self.batch_list]
        self.q_target = self.rewards
        self.states = np.array(self.states)
        self.act = np.array(self.act)
        self.samples = np.column_stack((self.states, self.act))
        print("Current batch size: ", len(self.samples))

    def save_batch(self):
        with open(self.file + '_batch',
                  'wb') as outfile:
            pickle.dump(self.batch_list, outfile)

    def fqi_step(self, max_iterations, debug=False):
        stop_flag = False
        for it in range(max_iterations):
            self.current_step += 1
            print("FQI_iteration: ", it)
            self.learner.fit(self.samples, self.q_target, batch_size=300, verbose=1, epochs=1000,
                             callbacks=[self.logger])
            if not self.nn_flag:
                sc = self.learner.score(self.samples, self.q_target)
                print("Score: ",sc)
            if self.discount_factor > 0:
                maxq_prediction = np.asarray([self.find_max_q(state_p,i)[0] for i,state_p in enumerate(self.states_p)])
                self.q_target = self.rewards + self.discount_factor*maxq_prediction
            else:
                self.q_target = self.rewards
            if self.nn_flag:
                self.learner.save(self.file+'it'+str(self.current_step)+'.h5')
            else:
                with open(self.file+'it'+str(it), 'wb') as outfile:
                    pickle.dump(self.learner, outfile)
            if stop_flag:
                break

    def find_max_q(self, state_p, i):
        qmax = -float('Inf')
        choice_list = list()
        if not i in self.end_states or self.end_states[i] == 0:
            for action in action_space.action_combinations:
                if self.mode == 'angle_only':
                    state_action = np.append(state_p, action[0])
                else:
                    state_action = np.append(state_p, action)
                state_action = np.reshape(state_action, (1, -1))
                qpred = self.learner.predict(state_action, batch_size=1, verbose=1)[0][0]
                print('Q value and respective action: ', qpred, action)
                if qpred > qmax:
                    qmax = qpred
                    choice_list = [action]
                elif qpred == qmax:
                    choice_list.append(action)
        else:
            print('final')
            qmax = 0
            choice_list = action_space.action_combinations
        return qmax, choice_list

    def select_action(self, state):
        qmax, choice_list = self.find_max_q(state,-1)
        selected_action = random.choice(choice_list)
        print("Max",qmax)
        print(selected_action[0])
        print(selected_action[1])
        return selected_action

if __name__ == '__main__':
    with open('agent20180408200244', 'rb') as infile:
        agent_obj = pickle.load(infile)
        agent = Learner(load_saved_regression=agent_obj, action_space_name='only_rudder_action_space')
        action = agent.select_action((7977.5731952, 4594.6156251, -103.49968, -2.909885, -0.6988991, 0.0005474))
        print(action)


import Queue as queue
import time

prio_queue = queue.PriorityQueue()
prio_queue.put((2, time.time(), 'super blah'))
time.sleep(0.1)
prio_queue.put((1, time.time(), 'This thing would come after Some Thing if we sorted by this text entry'))
time.sleep(0.1)
prio_queue.put((1, time.time(), 'Some thing'))
time.sleep(0.1)
prio_queue.put((5, time.time(), 'blah'))

while not prio_queue.empty():
    item = prio_queue.get()
    print(item)

"""
(1, 1412382774.606068, 'This thing would come after Some Thing if we sorted by this text entry')
(1, 1412382774.70722, 'Some thing')
(2, 1412382774.504914, 'super blah')
(5, 1412382774.808372, 'blah')
"""


def solution(s):
    stack = []
    for elem in s:
        if elem == '(':
            stack.append(elem)
        elif len(stack) > 0 and elem == ')':
            stack.pop()
        else:
            return False

    if len(stack) == 0:
        answer = True
    else:
        answer = False
    return answer

if __name__ == '__main__':
    solution(input())


#transform the training data into the following nonlinear feature vector:
#(1,x1,x2,x1x2,x21,x22)
#Find the vector w~ that corresponds to the solution of Linear Regression,
#and take it for classification.
#Which of the following hypotheses is closest to the one you find using
#Linear Regression on the transformed input?

import numpy as np
import random
from random import shuffle

def trainData(n):
	data = []
	for i in range(n):
		row = []
		x1 = random.uniform(-1,1)
		x2 = random.uniform(-1,1)
		row.append(1)
		row.append(x1)
		row.append(x2)
		row.append(x1*x2)
		row.append(x1*x1)
		row.append(x2*x2)
		data.append(row)
	return data

def sign(n):
	if n <=0:
		return -1
	else:
		return 1

def getOutput(data):
	y = []
	for i in data:
		x1 = i[1]
		x2 = i[2]
		value = sign(x1*x1+x2*x2-0.6)
		rand = random.uniform(0,1)
		if rand<=0.1:
			value = -1*value
		y.append(value)
	return y

def getLinearRegressionWeight(data,ouput):
	weight = np.dot(np.linalg.pinv(data),output)
	return weight

data = trainData(1000)
output = getOutput(data)
weight = getLinearRegressionWeight(data,output)
print(weight)


"""
(4) Crea una funcion que nos devuelva numeros pares.
"""
def num_par (numero):
    if numero % 2 == 0:
        print(f"El numero: {numero}, es par")
    else:
        print(f"El numero: {numero}, es impar")
def run():
    numero = int(input("Ingresa un numero entero: "))
    num_par(numero)
if __name__ == "__main__":
    run()


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

import platform
from setuptools import setup, find_packages

PACKAGE_NAME = 'mattapi'
PACKAGE_VERSION = '0.99.03'

INSTALL_REQUIRES = [
'coloredlogs==10.0',
'pyautogui==0.9.41',
'python-dateutil==2.8.0',
'opencv-python==4.0.0.21',
'pytesseract==0.2.6',
'numpy==1.16.1',
'image==1.5.27',
'pyperclip==1.7.0',
'packaging==19.0',
'pynput==1.4.2',
'gitpython==2.1.11',
'pytest==5.0.1',
'pygithub==1.43.8',
'bugzilla==1.0.0',
'mozinfo==1.0.0',
'mozinstall==2.0.0',
'mozdownload==1.26',
'mozversion==2.1.0',
'mozlog==4.2.0',
'mozrunner==7.4.0',
'mss==4.0.1',
'more-itertools==5.0.0',
'psutil==5.6.3',
'funcy==1.11'
]

if platform.system() == "Linux":
    INSTALL_REQUIRES.append('xlib')

TESTS_REQUIRE = [
]

DEV_REQUIRES = [
]

setup(
    name=PACKAGE_NAME,
    version=PACKAGE_VERSION,
    description='Test API Iris',
    classifiers=[
        'Environment :: Console',
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)',
        'Natural Language :: English',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: Microsoft :: Windows :: Windows 10',
        'Operating System :: Microsoft :: Windows :: Windows 7',
        'Operating System :: Microsoft :: Windows :: Windows 8',
        'Operating System :: Microsoft :: Windows :: Windows 8.1',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 3.7',
        'Topic :: Software Development :: Quality Assurance',
        'Topic :: Software Development :: Testing'
    ],
    keywords=['automation', 'testing'],
    author='Matt Wobensmith',
    author_email='itsmatt@pacbell.net',
    url='https://github.com/mwxfr/mattapi',
    download_url='https://github.com/mwxfr/mattapi/latest.tar.gz',
    license='MPL2',
    packages=find_packages(),
    python_requires='>=3.7.3',
    include_package_data=True,  # See MANIFEST.in
    zip_safe=False,
    use_2to3=False,
    install_requires=INSTALL_REQUIRES,
    tests_require=TESTS_REQUIRE,
    extras_require={'dev': DEV_REQUIRES},  # For `pip install -e .[dev]`
    entry_points={
        'console_scripts': [
            'hi = mattapi.scripts.test:test',
            'lite = mattapi.scripts.test:main',
            'iris = mattapi.scripts.main:main',
            'api = mattapi.scripts.some_test:my_test'
        ]
    }
)


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

# 1. 递归
# class Solution:
#     def merge2Lists(self, list1, list2):
#         if not list1:
#             return list2
#         if not list2:
#             return list1
#         if list1.val < list2.val:
#             tmp = self.merge2Lists(list1.next, list2)
#             list1.next = tmp
#             return list1
#         else:
#             tmp = self.merge2Lists(list1, list2.next)
#             list2.next = tmp
#             return list2
#     def mergeKLists(self, lists):
#         n = len(lists)
#         if n == 0:
#             return None
#         res_link = lists[0]
#         for i in range(n-1):
#             res_link = self.merge2Lists(res_link, lists[i+1])
#         return res_link

# 2. 非递归
from typing import List

class Solution:
    def merge2Lists(self, list1, list2):
        dummy = ListNode()
        cur = dummy
        while list1 and list2:
            if list1.val < list2.val:
                cur.next = list1
                cur = list1
                list1 = list1.next
            else:
                cur.next = list2
                cur = list2
                list2= list2.next
        if list1:
            cur.next = list1
        if list2:
            cur.next = list2
        return dummy.next

    def mergeKLists(self, lists):
        n = len(lists)
        if n == 0:
            return None
        res_link = lists[0]
        for i in range(n-1):
            res_link = self.merge2Lists(res_link, lists[i+1])
        return res_link

# 3. 优先队列
# from queue import PriorityQueue as PQ

# class Solution:
#     def mergeKLists(self, lists):
#         n = len(lists)
#         if n == 0:
#             return None
#         dummy = ListNode()
#         cur = dummy
#         pq = PQ()
#         for i in range(n):
#             if lists[i]:
#                 pq.put((lists[i].val, i, lists[i]))

#         while not pq.empty():
#             _, i, l = pq.get()
#             cur.next = l
#             cur = cur.next
#             if l.next:
#                 pq.put((l.next.val, i, l.next))

#         return dummy.next


import csv

beforeCvs = input("Düzenlenecek Cvs Adı Nedir? ")
newVerdor=input("Yeni Vendor Ne Olsun?")
newVariant=input("Yeni Variant Inventory Tracker Ne Olsun?")
saveCvs= input("Yeni Dosya Adı Ne olsun? ")
rate=input("Artış Oranı Nedir? ")

with open(saveCvs+'_editing.csv', mode='w',newline='') as yeni_dosya:
    yeni_yazici = csv.writer(yeni_dosya)
    with open(beforeCvs+'.csv','r') as csv_file:
        csv_reader = csv.reader(csv_file)
        line_count = 0
        for row in csv_reader:
            if line_count==0:
                line_count += 1
            else:
                if row[3]!="" and newVerdor!="":
                    row[3]=newVerdor
                if row[16]!="" and newVariant!="":

                    row[16]=newVariant

                if row[10]=="":

                    if row[20]!="":
                        row[20]=round(float(row[20])*(1+(float(rate)/100.00)),2)
                    if row[21]!="":
                        row[21]=round(float(row[21])*(1+(float(rate)/100.00)),2)
                else:
                    if row[22]!="":
                        row[22]=round(float(row[22])*(1+(float(rate)/100.00)),2)
                    if row[23]!="":
                        row[23]=round(float(row[23])*(1+(float(rate)/100.00)),2)

            yeni_yazici.writerow(row)


from django.http import HttpResponse
from django.template import Template, Context
from django.template import loader
from django.shortcuts import render

import os
import numpy as np
import csv
import pandas as pd
import math

clear = lambda: os.system("cls")
f = pd.read_csv("CoefAcu.csv")
pd.DataFrame(f)

reader = csv.reader(open('CoefAcu.csv'))

Materiales = {}
for row in reader:
   key = row[0]
   if key in Materiales:
       pass
   milistafloat = []
   for item in row[1:]:
       milistafloat.append(float(item))
   Materiales[key] = milistafloat

class room():
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
        self.v = x*y*z
        self.a = 2*(x*y+x*z+y*z)

    def Calcular(self,T, P, WF, WB, WL, WR, v, a, ssaW):
        self.sa    = T + P + WF + WB + WL + WR + ssaW
        self.RT60f = -0.161*v/(a*np.log(1-(self.sa/a)))
        self.RT60  = np.mean(self.RT60f)
        self.dev = (np.mean((self.RT60f-self.RT60)**2))**(1/2.0)

class wall():
    def __init__(self,Nombre,N,d1,d2):
        self.Nombre = Nombre
        self.Wall   = N
        self.Ancho  = d1
        self.Largo  = d2
        self.aW     = d1*d2

    def mat(self,m):
        self.MNombre  = m
        self.MCoefAcu = Materiales[self.MNombre]

    def saWall(self):
        self.saW = self.aW*np.array(self.MCoefAcu)

    def restaWall(self,aOW):
        self.aOW = aOW
        self.aW -= self.aOW

class objWall(wall):
    def mat(self,m):
        self.MNombre  = m
        self.MCoefAcu = Materiales[self.MNombre]

    def saWall(self ):
        self.saW = self.aW*np.array(self.MCoefAcu)

    def ssaWall(self,ssaW):
        ssaW = ssaW

def home(request):
    Index_Loader = loader.get_template('index.html')
    Index_Template = Index_Loader.render({})
    return HttpResponse(Index_Template)

def RT60(request):
    clear()
    RT60_Loader = loader.get_template('RT60.html')
    RT60_Template = RT60_Loader.render({"Materiales":Materiales})
    return HttpResponse(RT60_Template)

import json
def RT60_resp(request):
    clear()
    if request.method == "GET":

        R = room (float(request.GET.get("x")),
                  float(request.GET.get("y")),
                  float(request.GET.get("z")))

        T  = wall("Techo",          "T",      R.x,R.z)
        P  = wall("Piso",           "P",      R.x,R.z)
        WF = wall("Pared Frontal",  "WF",     R.x,R.y)
        WB = wall("Pared trasera",  "WB",     R.x,R.y)
        WL = wall("Pared izquierda","WL",     R.z,R.y)
        WR = wall("Pared derecha",  "WR",     R.z,R.y)

        T.mat(request.GET.get("Material_T"))
        P.mat(request.GET.get("Material_P"))
        WF.mat(request.GET.get("Material_WF"))
        WB.mat(request.GET.get("Material_WB"))
        WL.mat(request.GET.get("Material_WL"))
        WR.mat(request.GET.get("Material_WR"))

        ssaW = np.zeros([1,6])
        objetos = {}
        sobjsaW = []

        if (request.GET.get('Extras') != None):
            Extras = json.loads(request.GET.get('Extras'))

            n = 0
            i = 0
            while i < len(Extras):
                clear()
                obj = Extras[n]

                objx = objWall( obj[1],
                                obj[2],
                                float(obj[3]),
                                float(obj[4]))

                objx.mat(obj[5])

                if   objx.Wall == "Techo":              T.restaWall(objx.aW)
                elif objx.Wall == "Piso":               P.restaWall(objx.aW)
                elif objx.Wall == "Pared Frontal":      WF.restaWall(objx.aW)
                elif objx.Wall == "Pared Trasera":      WB.restaWall(objx.aW)
                elif objx.Wall == "Pared Izquierda":    WL.restaWall(objx.aW)
                elif objx.Wall == "Pared Derecha":      WR.restaWall(objx.aW)

                objx.saWall()

                objetos[n]=[objx.Nombre,objx.Wall,objx.aW,objx.MNombre,objx.saW]
                sobjsaW.append(np.around(objx.saW,2,None).tolist())

                ssaW += np.array(objx.saW)
                n += 1
                i += 1

        else:
            Extras = None

        T. saWall()
        P. saWall()
        WF.saWall()
        WB.saWall()
        WL.saWall()
        WR.saWall()

        saTnp = np.around(T .saW,2,None)
        saPnp = np.around(P .saW,2,None)
        saWFnp = np.around(WF .saW,2,None)
        saWBnp = np.around(WB .saW,2,None)
        saWLnp = np.around(WL .saW,2,None)
        saWRnp = np.around(WR .saW,2,None)

        saT = saTnp.tolist()
        saP = saPnp.tolist()
        saWF = saWFnp.tolist()
        saWB = saWBnp.tolist()
        saWL = saWLnp.tolist()
        saWR = saWRnp.tolist()

        R.Calcular( T.saW,
                    P.saW,
                    WF.saW,
                    WB.saW,
                    WL.saW,
                    WR.saW,

                    R.v,
                    R.a,
                    ssaW )

        RT60f = np.around(R.RT60f,2,None)
        RT60f = RT60f.tolist()

    datos = {
            "x"   :R.x,
            "y"   :R.y,
            "z"   :R.z,

            "v"   :np.around(R.v,2,None),
            "a"   :np.around(R.a,2,None),

            "sT"  :np.around(T.aW,2,None),
            "sP"  :np.around(P.aW,2,None),
            "sWF" :np.around(WF.aW,2,None),
            "sWB" :np.around(WB.aW,2,None),
            "sWL" :np.around(WL.aW,2,None),
            "sWR" :np.around(WR.aW,2,None),

            "lT"  :T.Largo,
            "lP"  :P.Largo,
            "lWF" :WF.Largo,
            "lWB" :WB.Largo,
            "lWL" :WL.Largo,
            "lWR" :WR.Largo,

            "aT"  :T.Ancho,
            "aP"  :P.Ancho,
            "aWF" :WF.Ancho,
            "aWB" :WB.Ancho,
            "aWL" :WL.Ancho,
            "aWR" :WR.Ancho,

            "matT"  :T.MNombre,
            "matP"  :P.MNombre,
            "matWF" :WF.MNombre,
            "matWB" :WB.MNombre,
            "matWL" :WL.MNombre,
            "matWR" :WR.MNombre,

            "saT" : saT,
            "saP" : saP,
            "saWF" : saWF,
            "saWB" : saWB,
            "saWL" : saWL,
            "saWR" : saWR,

            "cT"  :T.MCoefAcu,
            "cP"  :P.MCoefAcu,
            "cWF" :WF.MCoefAcu,
            "cWB" :WB.MCoefAcu,
            "cWL" :WL.MCoefAcu,
            "cWR" :WR.MCoefAcu,

            "ssaW":ssaW.tolist(),
            "sobjsaW":sobjsaW,
            "Extras": Extras,

            "RT60f":RT60f,
            "dev":round(R.dev,3),

            "RT60":round(R.RT60,3)
    }

    return HttpResponse(json.dumps(datos), content_type='application/json')

class Resonador():
    def __init__(self,fr,q):
        self.fr = fr
        self.q  = q
        self.bw = fr/q
        self.fh = fr + self.bw/2
        self.fl = fr - self.bw/2
        self.RT60 = 2.2/self.bw

class Difragmatico(Resonador):
    def panelD(self, b, h, m):
        self.b = b
        self.h = h
        self.m = m
        self.d = m/(b*h)
        self.e = ((6/self.fr)**2)/self.d

class Perforado(Resonador):
    def panelP(self, b, h, g, d, p):
        self.b = b
        self.h = h
        self.g = g
        self.d = d
        self.p = p
        self.s = ((78.5*(2.54*d)**2)/p)**(1/2.0)
        self.nb = round((b/self.s)-1)
        self.nh = round((h/self.s)-1)
        self.n = self.nb*self.nh
        self.e = ((548/self.fr)**2)*(p/(g+0.8*(2.54*d)))
        self.borde_altura = (self.b - (round(self.s,2)*(self.nb-1)))/2
        self.borde_base = (self.h - (round(self.s,2)*(self.nh-1)))/2

def Paneles(request):
    clear()
    Paneles_Loader = loader.get_template('Paneles.html')
    Paneles_Template = Paneles_Loader.render({})
    return HttpResponse(Paneles_Template)

def Paneles_resp(request):

    if request.method == "GET":
        clear()

        Tipo = request.GET.get("tipo")
        if Tipo == "Difragmático":
            P = Difragmatico(   float(request.GET.get("f")),
                                float(request.GET.get("q")))

            P.panelD(   float(request.GET.get("db")),
                        float(request.GET.get("dh")),
                        float(request.GET.get("dm"))
            )

            datos = {
                "f":P.fr,
                "q":P.q,

                "bw":round(P.bw,2),
                "fh":round(P.fh,2),
                "fl":round(P.fl,2),
                "RT60":round(P.RT60,3),

                "db":P.b,
                "dh":P.h,
                "dm":P.m,
                "dd":round(P.d*100000,2),
                "de":round(P.e,2)
            }

        if Tipo == "Perforado":
            P = Perforado(   float(request.GET.get("f")),
                            float(request.GET.get("q")))

            P.panelP(   float(request.GET.get("pb")),
                        float(request.GET.get("ph")),
                        float(request.GET.get("pg")),
                        float(request.GET.get("pd")),
                        float(request.GET.get("pp")),
            )

            print(P.borde_base)
            print(P.borde_altura)

            datos = {
                "f":P.fr,
                "q":P.q,
                "bw":round(P.bw,2),
                "fh":round(P.fh,2),
                "fl":round(P.fl,2),
                "RT60":round(P.RT60,3),

                "pb":P.b,
                "ph":P.h,
                "pg":P.g,
                "pd":P.d,
                "pp":P.p,
                "pnb":P.nb,
                "pnh":P.nh,

                "pn":round(P.n),
                "ps":round(P.s,2),
                "pe":round(P.e,2),

                "borde_base":round(P.borde_base,2),
                "borde_altura":round(P.borde_altura,2)
            }

    return HttpResponse(json.dumps(datos), content_type='application/json')

bw3 = 31.25
bw2 = bw3/2**(1/3.0)
bw1 = bw2/2**(1/3.0)

Tercios_Octava = np.array([bw1,bw2,bw3])
Tercios_Octava2 = np.array([bw1,bw2,bw3])
for i in range (2,6,1):
    Tercios_Octava2 = np.array(Tercios_Octava2*2)
    Tercios_Octava  = np.concatenate((Tercios_Octava,Tercios_Octava2),axis=None)

Tercios_Octava_Low  = Tercios_Octava/2**(1/6)
Tercios_Octava_High = Tercios_Octava*2**(1/6)

n = 20

class room_modos():
    def __init__ (self, x, y, z, RT60):
        self.x = x
        self.y = y
        self.z = z
        self.d = np.array([x,y,z])
        self.RT60 = RT60
        self.v = x*y*z
        self.max = max(x,y,z)
        self.f1	 = 343/(2*self.max)
        self.f2  = 1893*(self.RT60/self.v)**(1/2.0)
        self.f3	 = self.f2*4
        self.sf  = 2000*(self.RT60/self.v)**(1/2.0)
        self.bw  = 2.2/self.RT60

    def modo_axial(self):
        self.axial = np.ones((n,3))
        for i in range(1,n+1,1):
            x = 343/2*i/self.d
            self.axial[i-1] = x*self.axial[i-1]

    def conteo(self):
        self.conteo_modos = np.zeros((4,15))

        for s in range(0,3,1):
            for e in range(0,n,1):
                for i in range(0,15,1):
                    if self.axial[e,s] > Tercios_Octava_Low[i] and self.axial[e,s] < Tercios_Octava_High[i]:
                        self.conteo_modos[s,i] += 1
        for i in range(0,15,1):
            self.conteo_modos[3,i] = self.conteo_modos[0,i] + self.conteo_modos[1,i] + self.conteo_modos[2,i]

def Modos(request):
    clear()
    Modos_Loader = loader.get_template('Modos.html')
    Modos_Template = Modos_Loader.render({})
    return HttpResponse(Modos_Template)

def Modos_resp(request):
    clear()
    if request.method == "GET":

        R = room_modos (float(request.GET.get("x")),
                  float(request.GET.get("y")),
                  float(request.GET.get("z")),
                  float(request.GET.get("RT60"))
                  )

        R.modo_axial()

        axial = np.around(R.axial,1,None)

        axial_lista = axial.tolist()

        R.conteo()

        conteo = R.conteo_modos

        conteo_lista = conteo.tolist()

        header_a = np.array([['' ,'x','y','z']])
        axial_df = pd.DataFrame(data=R.axial,index=range(1,n+1,1),columns=header_a[0,1:])
        conteo_df = pd.DataFrame(data = R.conteo_modos, index = ['x','y','z','suma'] , columns = np.round(Tercios_Octava))

        axial_orden = R.axial.flatten()
        axial_orden = np.sort(axial_orden)
        axial_orden = np.around(axial_orden,2,None)
        axial_orden = axial_orden.tolist()

        print(axial_df)
        print(conteo_df)

        datos = {
            "x":R.x,
            "y":R.y,
            "z":R.z,
            "RT60":R.RT60,

            "f1":round(R.f1),
            "f2":round(R.f2),
            "f3":round(R.f3),
            "sf":round(R.sf,2),
            "bw":round(R.bw,2),

            "axial":axial_lista,
            "conteo":conteo_lista,
            "axial_orden":axial_orden
        }

    return HttpResponse(json.dumps(datos), content_type='application/json')


#!/usr/bin/env python3

import os
import sys
import traceback
import operator

# Add the pulsar path
thispath = os.path.dirname(os.path.realpath(__file__))
psrpath = os.path.join(os.path.dirname(thispath), "modules")
sys.path.insert(0, psrpath)

import pulsar as psr
from pulsar.output import *
from pulsar.testing import *
from pulsar.math import *

from helper.SetOperations import test_set_operations

def SetComp(set1, set2):
    if len(set1) != len(set2):
        return False
    for i in range(0, len(set1)):
        if set1[i] != set2[i]:
            return False
    return True

def SetComp2(set1, set2):
    return set1 == set2

def PrintSet(s):
    string = "{} : ".format(len(s))
    for it in s:
        string += str(it)
    print(string)

def SetElement(s, i, e):
    s[i] = e

def FillUniverse(values):
    u = StringSetUniverse()
    for v in values:
        u.insert(v)
    return u

def Run():
    try:
        Alphabet="abcdefghijklmnopqrstuvwxyz"
        BadAlphabet = "ABCDE"

        tester = Tester("Testing Universe and MathSet")
        tester.print_header()

        ################################
        # Do basic testing of set stuff
        ################################
        u0 = StringSetUniverse()
        u1 = FillUniverse(Alphabet[:7])
        u2 = FillUniverse(Alphabet)
        u3 = FillUniverse(reversed(Alphabet))
        u9 = FillUniverse(Alphabet[7:])
        test_set_operations(tester, StringSetUniverse, Alphabet, BadAlphabet,
                          False, u0, u1, u2, u3, u9)

        ###############################
        # Serialization
        ###############################
        tester.test("Universe serialization - u0", True, TestSerialization_StringSetUniverse, u0)
        tester.test("Universe serialization - u1", True, TestSerialization_StringSetUniverse, u1)
        tester.test("Universe serialization - u2", True, TestSerialization_StringSetUniverse, u2)
        tester.test("Universe serialization - u3", True, TestSerialization_StringSetUniverse, u3)
        tester.test("Universe serialization - u9", True, TestSerialization_StringSetUniverse, u9)

        ###############################
        # Universe-specific stuff
        ###############################
        for idx in range(0, len(u1)):
            tester.test_value("Element {} by idx - getitem".format(idx), u1[idx], Alphabet[idx])
            tester.test_value("Element {} by idx - At".format(idx), u1.at(idx), Alphabet[idx])

        # Try inserting bad values
        tester.test("inserting 10", False, u1.insert, 10)
        tester.test("inserting None", False, u1.insert, None)

        # Modification of an element in a universe -- shouldn't be possible
        tester.test("Modification of an element in universe", False, SetElement, u1, 0, "Z")

        tester.print_results()

    except Exception as e:
      print_global_output("Caught exception in main handler. Contact the developers\n")
      traceback.print_exc()
      print_global_error("\n")
      print_global_error(str(e))
      print_global_error("\n")

psr.initialize(sys.argv, color = True, debug = True)
Run()
psr.finalize()


#!/bin/python
""" Code challenge https://www.codeeval.com/open_challenges/83/

Description:

Your program should accept as its first argument a path to a filename. Each line
in this file has a sentence
"""
import re
import sys

def beauty(source):
    """ When John was a little kid he didn't have much to do. There was no
    internet, no Facebook, and no programs to hack on. So he did the only thing
    he could... he evaluated the beauty of strings in a quest to discover the
    most beautiful string in the world.

    Given a string s, little Johnny defined the beauty of the string as the sum
    of the beauty of the letters in it. The beauty of each letter is an integer
    between 1 and 26, inclusive, and no two letters have the same beauty. Johnny
    doesn't care about whether letters are uppercase or lowercase, so that
    doesn't affect the beauty of a letter. (Uppercase 'F' is exactly as
    beautiful as lowercase 'f', for example.)

    You're a student writing a report on the youth of this famous hacker. You
    found the string that Johnny considered most beautiful. What is the maximum
    possible beauty of this string?
    """
    characters = "".join(re.findall("[a-zA-Z]+", source)).lower()
    character_map = {}
    for char in characters:
        character_map[char] = character_map.get(char, 0) + 1
    i = 26
    totals = []
    for char in sorted(character_map.values(), reverse=True):
        totals.append(char * i)
        i = i-1
    return sum(totals)

if __name__ == '__main__':
    with open(sys.argv[1]) as f:
        for line in f.readlines():
            print(str(beauty(line)))


# 2315 이현수

# <실행 방법>
# 1. main.py 파일을 실행해야한다.
# 2. 게임 설명을 보려면 1, 게임 메뉴를 고르려면 2 선택해야한다.
# 3. 유저의 이름 입력해야한다.
# 4. 게임 메뉴에서 미니게임 4개 중에 게임 선택해야한다.
# 5. 입력란에 기회와 현재 점수가 표시되어 있는 것을 고려하여 게임을 클리어해야한다.
# 6. 기회 3번이 끝나거나 총점 5점을 획득하면 게임 끝이 난다.
# 7. 성공했는지 실패했는지 결과가 출력된다.
# 8. 그만할련지 물어본다.

# <프로젝트 소개>	: 어떤 프로젝트인지 간략하게 소개
# 미니게임 4가지 중 한개씩 선택해 게임을 하여 기회 3번만에 총 점 5점이상이 되어야합니다.
# 난이도에 따라 점수가 달라 점수가 클수록 어렵습니다.

from game import *
from gugu_game import *
from rps_game import *
from updown_game import *
from baseball_game import *

print("< < < Mini Game > > >")
print("1. 게임 설명")
print("2. 게임 메뉴")
c=int(input("선택하시오.>> "))

#일단 name 초기화
g=Game("null")

#다시할수도 있기 때문에 run 생성
run = True

#게임 시작
while(run):
    if c ==1:   #1번 선택
        g.explain() #게임 설명

    if c==1 or c==2:    #1번이나 2번 선택
        print("\n<<< 게임 시작 >>>")
        name=input("이름을 입력하시오.>> ")
        g=Game(name)    #이름 등록

        for i in range(3):
            chance=3-i  #남은 기회

            #게임 메뉴
            g.kind()
            #게임 메뉴 고르기
            cg = int(input("게임을 선택하시오.(기회: "+str(chance)+"번 / 현재 점수: "+str(g.total)+")>> "))

            if cg==1:
                gg=Gugu_game(name)  #이름 등록
                gg.start()  #구구단 게임 실행
            elif cg==2:
                rg=Rps_game(name)   #이름 등록
                rg.start()  #가위바위보 게임 실행
            elif cg==3:
                ug=Updown_game(name)    #이름 등록
                ug.start()  #업다운 게임 실행
            elif cg==4:
                bg=Baseball_game(name)  #이름 등록
                bg.start()  #야구 게임 실행
            else:   #잘못 입력했을 경우
                print("잘못 입력하셨습니다. 다시 입력해주세요.")
                i-=1    #기회가 줄지 않아야 하기 때문
                continue

            #총점 5점이상일 경우
            if g.total >= 5:
                break

        #게임이 종료되며 최종결과 출력
        g.end()

    #다시 할건지 물어보고 입력받기
    how=int(input("\n"+g.name+"님 다시 하시겠습니까? (0: 다시 할래요. 1: 그만할래요.)>> "))
    if how==0:      #다시하기
        run==True       #while(True)
    elif how == 1:  #그만하기
        run=False       #while(False)
    else:   #잘못 입력했을 경우
        print("잘못 입력하셨으므로 종료합니다.")
        run=False

print("\n- End -")


"""
########################################################################################################################
# Title        : Tranform utility module
# Author       : Namrakant Tamrakar
# Created on   : 2/7/2021
# Updated on   : 4/9/2021 (latest update)
# Description  : Functions to manipulate and create transforms
                 Note: The constants will be replaced in the UI creation process using pyside2 by May 15, 2021
########################################################################################################################
"""

import maya.cmds as mc

from . import name

def makeOffsetGrp( object, prefix = ''):
    """
    Make offset group for given object

    @param object: transform object to get offset group
    @param prefix: str, prefix to name new objects
    @return: str, name of new offset group
    """

    # create offset group

    if not prefix:

        prefix = name.removeSuffix( object )

    offsetGrp = mc.group( n = prefix + 'Offset_grp', em = 1) # em= empty

    objectParents = mc. listRelatives( object, p = 1 )

    if objectParents:

        mc.parent( offsetGrp,objectParents[0] )

    # match object transform

    mc.delete( mc.parentConstraint( object, offsetGrp) )
    mc.delete( mc.scaleConstraint( object, offsetGrp) )

    # parent object under offset group

    mc.parent( object, offsetGrp )

    return offsetGrp


import pandas as pd
from horizontalView import naming_convention
import metrics

def analysis_naming_convention(endYear, startYear, percent=False):
    name = str(startYear) + "-" + str(endYear) + "horizontal"
    if percent:
        name += "Perc"
    return name

def analysis(df, endYear, startYear):
    df = df[df[naming_convention(endYear)].notnull(
    ) & df[naming_convention(startYear)].notnull()]
    horizontal = []
    horizontalPerc = []
    for index, row in df.iterrows():
        startVal = row[naming_convention(startYear)]
        endVal = row[naming_convention(endYear)]
        thisHorizontal, thisHorizontalPerc = metrics.horizontal(startVal, endVal)
        horizontal.append(thisHorizontal)
        horizontalPerc.append(thisHorizontalPerc)
    df[analysis_naming_convention(endYear, startYear)] = horizontal
    df[analysis_naming_convention(
        endYear, startYear, percent=True)] = horizontalPerc

    # https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html
    return df


"""
This module contains classes and methods for working with interleaved channels.
"""

import typing

import numpy

import redvox.api900.constants as constants
import redvox.api900.exceptions as exceptions
import redvox.api900.lib.api900_pb2 as api900_pb2
import redvox.api900.migrations as migrations
import redvox.api900.reader_utils as reader_utils
import redvox.api900.stat_utils as stat_utils

# pylint: disable=R0902
class InterleavedChannel:
    """
    This class represents an interleaved channel.

    An interleaved channel contains multiple channel types in a single payload. This is useful for situations where
    a sensor produces several values for a single timestamp. For example, a GPS will produce a LATITUDE, LONGITUDE,
    ALTITUDE, and SPEED values with every update. An interleaved channel encodes all four of those channel types
    into a single payload.

    Every channel has a field channel_types that list the channel types contained within the payload. For a GPS sensor,
    the channel_types array would look like [LATITUDE, LONGITUDE, ALTITUDE, SPEED]. The location of the channel type
    in channel_types determines the offset into the payload and the length of channel_types determines the step size.
    As such, this hypothetical GPS channel payload be encoded as:

    [LAT0, LNG0, ALT0, SPD0, LAT1, LNG1, ALT1, SPD1, ..., LATn, LNGn, ALTn, SPDn]

    This class provides methods for working with interleaved channels as well as accessing interleaved statistic values.
    """

    def __init__(self, channel: typing.Optional[typing.Union[api900_pb2.EvenlySampledChannel,
                                                             api900_pb2.UnevenlySampledChannel]] = None):
        """
        Initializes this interleaved channel object.
        :param channel: Either a protobuf evenly or unevenly sampled channel.
        note: value_means, value_medians, value_stds, and channel_type_index are only set during initialization or
            when payload is altered
        payload should only be altered by set_payload or set_deinterleaved_payload due to the extra data values that are
            required to correctly set the protobuf_channel
        """
        if channel is None:
            self.protobuf_channel = None
            self.sensor_name = None
            self.channel_types = [0]
            self.payload = [0]
            self.metadata = []
            self.value_means = []
            self.value_stds = []
            self.value_medians = []
            self.channel_type_index = []
        else:
            self.protobuf_channel: typing.Union[api900_pb2.EvenlySampledChannel,
                                                api900_pb2.UnevenlySampledChannel] = channel
            """Reference to the original protobuf channel"""

            self.sensor_name: str = channel.sensor_name
            """Provided sensor name"""

            self.channel_types: typing.List[
                typing.Union[
                    api900_pb2.EvenlySampledChannel,
                    api900_pb2.UnevenlySampledChannel]] = reader_utils.repeated_to_list(channel.channel_types)
            """List of channel type constant enumerations"""

            self.payload: numpy.ndarray = reader_utils.extract_payload(channel)
            """This channels payload as a numpy array of either floats or ints"""

            self.metadata: typing.List[str] = reader_utils.repeated_to_list(channel.metadata)
            """This channels list of metadata"""

            self.value_means: numpy.ndarray = reader_utils.repeated_to_array(channel.value_means)
            """Interleaved array of mean values"""

            self.value_stds: numpy.ndarray = reader_utils.repeated_to_array(channel.value_stds)
            """Interleaved array of standard deviations of values"""

            self.value_medians: numpy.ndarray = reader_utils.repeated_to_array(channel.value_medians)
            """Interleaves array of median values"""

            self.channel_type_index: typing.Dict[api900_pb2.ChannelType, int] = {self.channel_types[i]: i for
                                                                                i in
                                                                                range(
                                                                                len(
                                                                                self.channel_types))}
            """Contains a mapping of channel type to index in channel_types array"""

    def set_channel_types(self, types: typing.List[typing.Union[api900_pb2.EvenlySampledChannel,
                                                                api900_pb2.UnevenlySampledChannel]]):
        """
        sets the channel_types to the list given
        :param types: a list of channel types
        """
        del self.protobuf_channel.channel_types[:]
        for ctype in types:
            self.protobuf_channel.channel_types.append(ctype)
        self.channel_types = reader_utils.repeated_to_list(self.protobuf_channel.channel_types)
        self.channel_type_index = {self.channel_types[i]: i for i in range(len(self.channel_types))}

    def get_channel_type_names(self) -> typing.List[str]:
        """
        Returns the list of channel_types as a list of names instead of enumeration constants.
        :return: The list of channel_types as a list of names instead of enumeration constants.
        """
        return list(map(reader_utils.channel_type_name_from_enum, self.channel_types))

    def channel_index(self, channel_type: int) -> int:
        """
        Returns the index of a channel type or -1 if it DNE.
        :param channel_type: The channel type to search for.
        :return: The index of the channel or -1 if it DNE.
        """
        return self.channel_type_index[channel_type] if channel_type in self.channel_type_index else -1

    def has_channel(self, channel_type: int) -> bool:
        """
        Returns if channel type exists with in this channel.
        :param channel_type: The channel type to search for.
        :return: True if it exist, False otherwise.
        """
        return channel_type in self.channel_type_index

    def set_channel(self, channel: typing.Union[api900_pb2.EvenlySampledChannel,
                                                api900_pb2.UnevenlySampledChannel]):
        """
        Sets the protobuf channel
        :param channel: protobuf channel
        """
        self.protobuf_channel = channel
        self.sensor_name = channel.sensor_name
        self.channel_types = reader_utils.repeated_to_list(channel.channel_types)
        self.payload = reader_utils.extract_payload(channel)
        self.metadata = reader_utils.repeated_to_list(channel.metadata)
        self.value_means = reader_utils.repeated_to_array(channel.value_means)
        self.value_stds = reader_utils.repeated_to_array(channel.value_stds)
        self.value_medians = reader_utils.repeated_to_array(channel.value_medians)
        self.channel_type_index = {self.channel_types[i]: i for i in range(len(self.channel_types))}

    def has_payload(self, channel_type: int) -> bool:
        """
        Returns if channel contains a non-empty specified payload.
        :param channel_type: The channel to check for a payload for.
        :return: Whether this channel contains the specified payload.
        """
        return self.has_channel(channel_type) and len(self.payload) > 0

    def set_payload(self,
                    payload_values: typing.Union[numpy.ndarray, typing.List],
                    pl_type: constants.PayloadType,
                    should_compute_stats=True):
        """
        sets the payload to an interleaved channel with step number of arrays interleaved together.
        :param should_compute_stats: Whether the statistics should be computed or not (optional default to True)
        :param payload_values: Interleaved payload values
        :param pl_type: payload type
        """
        # if len(payload_values) < 1:
        #     raise exceptions.ReaderException("Channel must not be empty and number of arrays must not be less than
        #     1.")

        # Convert to numpy array is necessary
        payload_values = reader_utils.to_array(payload_values)

        # clear all other payloads
        self.protobuf_channel.byte_payload.ClearField("payload")
        self.protobuf_channel.uint32_payload.ClearField("payload")
        self.protobuf_channel.uint64_payload.ClearField("payload")
        self.protobuf_channel.int32_payload.ClearField("payload")
        self.protobuf_channel.int64_payload.ClearField("payload")
        self.protobuf_channel.float32_payload.ClearField("payload")
        self.protobuf_channel.float64_payload.ClearField("payload")

        # set the payload based on the type of data
        if pl_type == constants.PayloadType.BYTE_PAYLOAD:
            self.protobuf_channel.byte_payload.payload = payload_values
        elif pl_type == constants.PayloadType.UINT32_PAYLOAD:
            self.protobuf_channel.uint32_payload.payload.extend(payload_values)
        elif pl_type == constants.PayloadType.UINT64_PAYLOAD:
            self.protobuf_channel.uint64_payload.payload.extend(payload_values)
        elif pl_type == constants.PayloadType.INT32_PAYLOAD:
            self.protobuf_channel.int32_payload.payload.extend(payload_values)
        elif pl_type == constants.PayloadType.INT64_PAYLOAD:
            self.protobuf_channel.int64_payload.payload.extend(payload_values)
        elif pl_type == constants.PayloadType.FLOAT32_PAYLOAD:
            self.protobuf_channel.float32_payload.payload.extend(payload_values)
        elif pl_type == constants.PayloadType.FLOAT64_PAYLOAD:
            self.protobuf_channel.float64_payload.payload.extend(payload_values)
        else:
            raise TypeError("Unknown payload type to set.")

        if len(payload_values) < 1:
            self.payload = payload_values
        else:
            self.payload = reader_utils.extract_payload(self.protobuf_channel)

            # calculate the means, std devs, and medians
            if should_compute_stats:
                self.update_stats()

    def set_interleaved_payload(self,
                                payloads: typing.List[typing.Union[typing.List, numpy.ndarray]],
                                pl_type: constants.PayloadType,
                                should_compute_stats: bool = True):
        """
        Interleaves multiple payloads together and sets the interleaved payload.
        :param payloads: Payloads of the same length to be interleaved.
        :param pl_type: The payload type
        :param should_compute_stats: Whether or not payload stats should be calculated.
        """
        interleaved = reader_utils.interleave_arrays(list(map(reader_utils.to_array, payloads)))
        self.set_payload(interleaved, pl_type, should_compute_stats)

    def get_payload(self, channel_type: int) -> numpy.ndarray:
        """
        Returns a deinterleaved payload of a given channel type or an empty array.
        :param channel_type: The channel type to extract/deinterleave from the payload.
        :return: A numpy array of floats or ints of a single channel type.
        """
        idx = self.channel_index(channel_type)
        if idx < 0:
            return reader_utils.empty_array()
        try:
            payload: numpy.ndarray = reader_utils.deinterleave_array(self.payload, idx, len(self.channel_types))
            return migrations.maybe_get_float(payload)
        except exceptions.ReaderException:
            return reader_utils.empty_array()

    def get_payload_type(self) -> str:
        """
        Returns the internal protobuf payload type.
        :return: The internal protobuf payload type.
        """
        return reader_utils.payload_type(self.protobuf_channel)

    def get_multi_payload(self, channel_types: typing.List[int]) -> numpy.ndarray:
        """
        Returns an interleaved payload with the given channel types.
        :param channel_types: Channel types to interleave into a single payload.
        :return: A numpy array of an interleaved payload.
        """
        channel_types_len = len(channel_types)
        if channel_types_len == 0:
            return reader_utils.empty_array()
        elif channel_types_len == 1:
            return self.get_payload(channel_types[0])

        payloads = list(map(self.get_payload, channel_types))
        return reader_utils.interleave_arrays(payloads)

    def get_value_mean(self, channel_type: int) -> float:
        """
        Returns the mean value for a single channel type.
        :param channel_type: The channel type to extract the mean from.
        :return: The mean value.
        """
        idx = self.channel_index(channel_type)
        if idx < 0 or len(self.value_means) == 0:
            raise exceptions.ReaderException("mean DNE, is the payload empty?")

        return self.value_means[idx]

    def get_value_std(self, channel_type: int) -> float:
        """
        Returns the standard deviation value for a single channel type.
        :param channel_type: The channel type to extract the std from.
        :return: The standard deviation.
        """
        idx = self.channel_index(channel_type)
        if idx < 0 or len(self.value_stds) == 0:
            raise exceptions.ReaderException("std DNE, is the payload empty?")

        return self.value_stds[idx]

    def get_value_median(self, channel_type: int) -> float:
        """
        Returns the median value for a single channel type.
        :param channel_type: The channel type to extract the median from.
        :return:The median value.
        """
        idx = self.channel_index(channel_type)
        if idx < 0 or len(self.value_medians) == 0:
            raise exceptions.ReaderException("median DNE, is the payload empty?")

        return self.value_medians[idx]

    def update_stats(self):
        """
        updates mean, std and median for all values
        """
        channel = self.payload
        step = len(self.channel_types)
        del self.protobuf_channel.value_means[:]
        del self.protobuf_channel.value_stds[:]
        del self.protobuf_channel.value_medians[:]
        for i in range(step):
            std, mean, median = stat_utils.calc_utils(reader_utils.deinterleave_array(channel, i, step))
            self.protobuf_channel.value_means.append(mean)
            self.protobuf_channel.value_stds.append(std)
            self.protobuf_channel.value_medians.append(median)
        self.value_stds = reader_utils.repeated_to_array(self.protobuf_channel.value_stds)
        self.value_means = reader_utils.repeated_to_array(self.protobuf_channel.value_means)
        self.value_medians = reader_utils.repeated_to_array(self.protobuf_channel.value_medians)

    def set_sensor_name(self, name: str):
        """
        sets the sensor name
        :param name: name of sensor
        """
        self.sensor_name = name
        self.protobuf_channel.sensor_name = name

    def set_metadata(self, data: typing.List[str]):
        """
        sets the metadata
        :param data: metadata as list of strings
        """
        del self.protobuf_channel.metadata[:]
        for meta in data:
            self.protobuf_channel.metadata.append(meta)
        self.metadata = reader_utils.repeated_to_list(self.protobuf_channel.metadata)

    def metadata_as_dict(self) -> typing.Dict[str, str]:
        """
        Returns any metadata as a dictionary of key-pair values.
        :return: Any metadata as a dictionary of key-pair values.
        """
        return reader_utils.get_metadata_as_dict(self.metadata)

    def __str__(self) -> str:
        """
        Returns a string representation of this interleaved channel.
        :return: A string representation of this interleaved chanel.
        """
        return "sensor_name: {}\n" \
               "channel_types: {}\n" \
               "len(payload): {}\n" \
               "payload_type: {}".format(self.sensor_name,
                                         list(map(
                                             reader_utils.channel_type_name_from_enum,
                                             self.channel_types)),
                                         len(self.payload),
                                         reader_utils.payload_type(
                                             self.protobuf_channel))


# This script executes stress tests for DLMD as resources decrease within
# infrastructure graphs.

from functools import reduce
import networkx as nx
import pandas as pd
import numpy as np
import copy
import argparse
import time

##################
# DLMD FUNCTIONS #
##################

def shortest_and_weight(G, src, dst, weight_fn):
    # Finds the shortest path between src and dst using as cost the weight_fn
    # using Dijkstra
    # The weight_fn receives the edge enedpoints and the edge data

    path = nx.shortest_path(G, source=src, target=dst,
                            weight=weight_fn, method='dijkstra')
    path_weight = sum([weight_fn(n1,n2,G.edges[n1,n2])\
                       for n1,n2 in zip(path[:-1], path[1:])])

    return path, path_weight

def dlmd(G, SFC, PoA):
    # Executes de DLMD algorithm and yields the VF-placement for a robotic
    # service with a robot that can be attached to the PoAs.
    # The code asumes the best PoA is obtained.
    # TODO: update it to do the SNR filtering outside
    # The SFC is a graph

    # Server level function l(s)
    l = lambda s: 1 if G.nodes[s]['type'] == 'cloud' else (
            2 if G.nodes[s]['type'] == 'far_edge' else 3)

    # Obtain the edges with less than 'bw' bandwidth
    low_bw = lambda G,bw: [(n1,n2) for n1,n2,d in G.edges(data=True)\
                            if d['bandwidth'] <= bw]

    # Check the used CPUs @server=s in the deployment
    used_cpus = lambda s,dep,G,SFC: sum([SFC.nodes[vf]['cpus']\
            for vf in dep if (type(vf)!=tuple) and dep[vf]==s])

    # Dijkstra weight function using the delay and used bw
    dlmd_weight_G = lambda n1,n2,G: G.edges(data=True)[n1,n2]['delay'] +\
                                    G.edges(data=True)[n1,n2]['used_bw']
    dlmd_weight = lambda n1,n2,data: data['delay'] + data['used_bw']

    # Deployment
    deployment = {}

    # Filter the servers
    servers = [n for n,d in G.nodes(data=True) if 'type' in d and
                d['type'] in ['near_edge', 'far_edge', 'cloud']]

    # Create sorted VFs & VLs
    vfs =  sorted(SFC.nodes, reverse=True)
    vls =  list(zip(sorted(SFC.nodes, reverse=True)[:-1],
                    sorted(SFC.nodes, reverse=True)[1:]))

    hop = -1
    max_eta = 1000
    for vf in vfs:
        print('  vf:', vf)
        min_eta = max_eta
        path = []

        # Find the server deployment or steer to PoA
        for s in (servers if vf != vfs[-1] else [PoA]):
            # Check if server s has enough CPUs
            free_cpus = G.nodes[s]['cpus'] - used_cpus(s,deployment,G,SFC)
            if SFC.nodes[vf]['cpus'] > free_cpus:
                continue

            # Server weight=eta based on distance to the PoA
            try:
                _, server_poa_eta = shortest_and_weight(G=G, src=s, dst=PoA,
                                                        weight_fn=dlmd_weight)
                eta = l(s) + server_poa_eta
            # Exit if the server has no connectivity to the PoA
            except nx.exception.NetworkXNoPath as no_path:
                continue

            # link cost
            if hop >= 0:
                # Prior VF
                vf_1 = vfs[hop]

                # Prune links without enough BW
                vl_bw = SFC[vf_1][vf]['bandwidth']
                pruned_links = low_bw(G, vl_bw)
                G_pruned = copy.deepcopy(G)
                G_pruned.remove_edges_from(pruned_links)

                # Find path between (vf,vf-1)
                s_1 = deployment[vf_1]
                try:
                    path, path_eta = shortest_and_weight(
                            G=G_pruned, src=s_1, dst=s, weight_fn=dlmd_weight)
                    eta += path_eta
                except nx.exception.NetworkXNoPath as no_path:
                    path = []
                    eta += 100000

            # Select the deployment if it's better
            if eta < min_eta:
                min_eta = eta
                deployment[vf] = s
                if hop >= 0:
                    deployment[vf_1,vf] = path

        # Return if the VF could not be deployed
        if min_eta == max_eta:
            return deployment, False

        # Consume the VL bandwidth along the best deployment path
        if hop >= 0:
            for n1,n2 in zip(path[:-1], path[1:]):
                G[n1][n2]['bandwidth'] -= vl_bw
                G[n1][n2]['used_bw'] += vl_bw

        # Go to next hop in the SFC
        hop += 1

    # Check if the deployment has been completed
    completed = reduce(lambda a,b: a and b,
                       [vf in deployment for vf in SFC.nodes])

    return deployment, completed

def deployment_delay(G, deployment):
    # Computes the delay of a deployment over the graph G

    delay = 0

    for vf1,vf2 in filter(lambda k: type(k)==tuple, deployment.keys()):
        path = deployment[vf1,vf2]
        delay += sum([G[n1][n2]['delay']\
                        for n1,n2 in zip(path[:-1], path[1:])])

    return delay

def deployment_free_edge(G, G_, SFC, deployment):
    # Calculates the free edge resources at the edge
    # using the original graph G, and the stressed graph G_
    # note: the deployment must have been successfull
    # returns: free_ALL_edge, free_far_edge, free_near_edge

    n_edges = [n for n,d in G.nodes(data=True)\
                if ('type' in d) and (d['type']=='near_edge')]
    n_edge_cpus = sum([d['cpus'] for n,d in G.nodes(data=True)\
                        if ('type' in d) and (d['type']=='near_edge')])
    n_edge_cpus_ = sum([d['cpus'] for n,d in G_.nodes(data=True)\
                        if ('type' in d) and (d['type']=='near_edge')])
    f_edges = [n for n,d in G.nodes(data=True)\
                if ('type' in d) and (d['type']=='far_edge')]
    f_edge_cpus = sum([d['cpus'] for n,d in G.nodes(data=True)\
                        if ('type' in d) and (d['type']=='far_edge')])
    f_edge_cpus_ = sum([d['cpus'] for n,d in G_.nodes(data=True)\
                        if ('type' in d) and (d['type']=='far_edge')])

    # Total edge resource
    total_edge = n_edge_cpus + f_edge_cpus
    consumed_n_edge = 0
    consumed_f_edge = 0

    # Derive the resource consumption
    for vf in SFC.nodes:
        if G.nodes[deployment[vf]]['type'] == 'near_edge':
            consumed_n_edge += SFC.nodes[vf]['cpus']
        elif G.nodes[deployment[vf]]['type'] == 'far_edge':
            consumed_f_edge += SFC.nodes[vf]['cpus']
    consumed_edge = consumed_n_edge + consumed_f_edge

    # Derive free resources
    free_all_edge = (n_edge_cpus_+ f_edge_cpus_ - consumed_edge) /\
                        (n_edge_cpus + f_edge_cpus)
    free_far_edge = (f_edge_cpus_ - consumed_f_edge) / f_edge_cpus
    free_near_edge = (n_edge_cpus_ - consumed_n_edge) / n_edge_cpus

    return free_all_edge, free_far_edge, free_near_edge

def print_server_resources(G):
    # prints the CPUs of servers

    cloud_cpus, f_edge_cpus, n_edge_cpus = 0, 0, 0

    for n in G.nodes:
        if 'type' in G.nodes[n]:
            if G.nodes[n]['type'] == 'cloud':
                cloud_cpus += G.nodes[n]['cpus']
            elif G.nodes[n]['type'] == 'far_edge':
                f_edge_cpus += G.nodes[n]['cpus']
            elif G.nodes[n]['type'] == 'near_edge':
                n_edge_cpus += G.nodes[n]['cpus']

    print(f'== Server resources @{G} ==')
    print(f'{cloud_cpus}CPUs @cloud')
    print(f'{f_edge_cpus}CPUs @far edge')
    print(f'{n_edge_cpus}CPUs @near edge')

#########################
# STRESS-TEST FUNCTIONS #
#########################

def stress_network(G, p_step=0.1):
    # Stress G resources at steps of p_step percent

    stressed_networks = {0: copy.deepcopy(G)}

    # Get the server nodes
    n_edges = [n for n,d in G.nodes(data=True)\
               if 'type' in d and d['type']=='near_edge']
    f_edges = [n for n,d in G.nodes(data=True)\
               if 'type' in d and d['type']=='far_edge']
    clouds = [n for n,d in G.nodes(data=True)\
               if 'type' in d and d['type']=='cloud']

    # CPU sums
    n_edge_cpus = sum([G.nodes[s]['cpus'] for s in n_edges])
    f_edge_cpus = sum([G.nodes[s]['cpus'] for s in f_edges])
    cloud_cpus = sum([G.nodes[s]['cpus'] for s in clouds])

    for p in np.arange(p_step, 1, p_step):
        # Get the copy for this p and store it
        G_ = copy.deepcopy(G)
        stressed_networks[round(p,2)] = G_
        print(f'stress @{p}')

        # Compute #edges & CPUs to remove
        edges_to_remove = round(p * len(G.edges))
        n_edge_cpus_to_remove = round(p * n_edge_cpus)
        f_edge_cpus_to_remove = round(p * f_edge_cpus)
        cloud_cpus_to_remove = round(p * cloud_cpus)

        # Remove edge from the highest degree nodes
        for _ in range(edges_to_remove):
            nodes_deg = sorted([(n, len(G_[n])) for n in G_.nodes],
                           key=lambda x: x[1], reverse=True)
            G_.remove_edge(nodes_deg[0][0], list(G_[nodes_deg[0][0]])[0])

        # Remove near edge CPUs
        i = 0
        while n_edge_cpus_to_remove > 0:
            s = n_edges[i]
            G_.nodes[s]['cpus'] -= 1
            i = (i+1) % len(n_edges)
            n_edge_cpus_to_remove -= 1

        # Remove far edge CPUs
        i = 0
        while f_edge_cpus_to_remove > 0:
            s = f_edges[i]
            G_.nodes[s]['cpus'] -= 1
            i = (i+1) % len(f_edges)
            f_edge_cpus_to_remove -= 1

        # Remove cloud CPUs
        i = 0
        while cloud_cpus_to_remove > 0:
            s = clouds[i]
            G_.nodes[s]['cpus'] -= 1
            i = (i+1) % len(clouds)
            cloud_cpus_to_remove -= 1

    return stressed_networks

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('graphGML', type=str,
                        help='path to the infra graph GML')
    args = parser.parse_args()

    # Read the infrastructure CSV and set cell CPUs to 0
    G = nx.read_gml(args.graphGML)
    G_name = args.graphGML.split('/')[-1].split('.')[0]
    cells = [n for n,d in G.nodes(data=True)\
            if 'type' in d and d['type'] == 'cell']
    nx.set_node_attributes(G, {cell: 0 for cell in cells}, 'cpus')
    nx.set_edge_attributes(G, {e: 0 for e in G.edges}, 'used_bw')
    nx.set_edge_attributes(G, {e: 1 for e in G.edges}, 'delay')

    # Create the SFC
    SFC_len = 4
    SFC = nx.path_graph(SFC_len)
    VF_cpus = 1
    nx.set_edge_attributes(SFC, {e: 1 for e in SFC.edges}, 'bandwidth')
    nx.set_node_attributes(SFC, {n: VF_cpus for n in range(SFC_len)}, 'cpus')
    SFC.nodes[0]['cpus'] = 0 # the PoA
    print('SFC created ')

    # Store the stress-test results
    p_step = 0.01
    stress_test = {}

    # Create the stressed networks
    for p, G_ in stress_network(G, p_step).items():
        print(f'G stress: p={p} with {len(list(nx.connected_components(G_)))}')
        print_server_resources(G_)

        PoAs= [n for n,d in G_.nodes(data=True)\
                if 'type' in d and d['type']=='cell']
        stress_test[p] = {}

        # Store the available resources at this step
        av_all_edge, av_far_edge, av_near_edge =\
            deployment_free_edge(G, G_, nx.Graph(), {})
        stress_test[p][f'available_edge'] = av_all_edge
        stress_test[p][f'available_far_edge'] = av_far_edge
        stress_test[p][f'available_near_edge'] = av_near_edge

        # Deploy as the robot moves
        for PoA in PoAs:
            # Execute DLMD
            print(f' DLMD@PoA={PoA}')
            tic = time.time()
            deployment, completed = dlmd(G_, SFC, PoA)
            tac = time.time()

            # Store deployment results
            stress_test[p][f'completed_{PoA}'] = completed
            stress_test[p][f'delay_{PoA}'] =\
                deployment_delay(G, deployment) if completed else 30
            free_all_edge, free_far_edge, free_near_edge =\
                deployment_free_edge(G, G_,
                     SFC if completed else nx.Graph(), deployment)
            stress_test[p][f'free_edge_{PoA}'] = free_all_edge
            stress_test[p][f'free_far_edge_{PoA}'] = free_far_edge
            stress_test[p][f'free_near_edge_{PoA}'] = free_near_edge
            stress_test[p][f'dlmd_runtime_{PoA}'] = tac - tic

    ##################################
    # Store the stress-test in a CSV #
    ##################################
    df_dict = {p: [] for p in stress_test.keys()}
    for p in df_dict:
        columns = []

        p_completions, p_delays, p_runtimes = [], [], []
        p_free_edges, p_free_far_edges, p_free_near_edges = [], [], []

        # Specify the available resources
        df_dict[p] += [
            stress_test[p][f'available_edge'],
            stress_test[p][f'available_far_edge'],
            stress_test[p][f'available_near_edge']
        ]
        columns += [
            'available_edge',
            'available_far_edge',
            'available_near_edge'
        ]

        # Specify results for each PoA
        for PoA in PoAs:
            p_completions += [stress_test[p][f'completed_{PoA}']]
            p_delays += [stress_test[p][f'delay_{PoA}']]
            p_free_edges += [stress_test[p][f'free_edge_{PoA}']]
            p_free_far_edges += [stress_test[p][f'free_far_edge_{PoA}']]
            p_free_near_edges += [stress_test[p][f'free_near_edge_{PoA}']]
            p_runtimes += [stress_test[p][f'dlmd_runtime_{PoA}']]

            df_dict[p] += [
                stress_test[p][f'completed_{PoA}'],
                stress_test[p][f'delay_{PoA}'],
                stress_test[p][f'free_edge_{PoA}'],
                stress_test[p][f'free_far_edge_{PoA}'],
                stress_test[p][f'free_near_edge_{PoA}'],
                stress_test[p][f'dlmd_runtime_{PoA}'],
            ]
            columns += [
                f'completed_{PoA}',
                f'delay_{PoA}',
                f'free_edge_{PoA}',
                f'free_far_edge_{PoA}',
                f'free_near_edge_{PoA}',
                f'dlmd_runtime_{PoA}',
            ]

        #############
        # Get stats #
        #############
        percentiles = list(range(0, 101, 5))
        # Completion
        columns += ['completion_percentage']
        df_dict[p] += [sum(p_completions) / len(p_completions)]
        # Delay
        columns += ['delay_avg']
        df_dict[p] += [np.mean(p_delays)]
        columns += ['delay_median']
        df_dict[p] += [np.median(p_delays)]
        columns += [f'delay_percentile_{q:.2f}' for q in percentiles]
        df_dict[p] += list(np.percentile(p_delays, percentiles))
        # Free edge
        columns += ['free_edge_avg']
        df_dict[p] += [np.mean(p_free_edges)]
        columns += ['free_edge_median']
        df_dict[p] += [np.median(p_free_edges)]
        columns += ['free_edge_min']
        df_dict[p] += [min(p_free_edges)]
        columns += [f'free_edge_percentile_{q:.2f}' for q in percentiles]
        df_dict[p] += list(np.percentile(p_free_edges, percentiles))
        # Free far edge
        columns += ['free_far_edge_avg']
        df_dict[p] += [np.mean(p_free_far_edges)]
        columns += ['free_far_edge_median']
        df_dict[p] += [np.median(p_free_far_edges)]
        columns += ['free_far_edge_min']
        df_dict[p] += [min(p_free_far_edges)]
        columns += [f'free_far_edge_percentile_{q:.2f}' for q in percentiles]
        df_dict[p] += list(np.percentile(p_free_far_edges, percentiles))
        # Free near edge
        columns += ['free_near_edge_avg']
        df_dict[p] += [np.mean(p_free_near_edges)]
        columns += ['free_near_edge_median']
        df_dict[p] += [np.median(p_free_near_edges)]
        columns += ['free_near_edge_min']
        df_dict[p] += [min(p_free_near_edges)]
        columns += [f'free_near_edge_percentile_{q:.2f}' for q in percentiles]
        df_dict[p] += list(np.percentile(p_free_near_edges, percentiles))
        # run-time
        columns += [f'dlmd_runtime_percentile_{q:.2f}' for q in percentiles]
        df_dict[p] += list(np.percentile(p_runtimes, percentiles))
        columns += ['median_dlmd_runtime']
        df_dict[p] += [np.median(p_runtimes)]
        columns += ['max_dlmd_runtime']
        df_dict[p] += [max(p_runtimes)]

    # Print it all out
    for i,col in enumerate(columns):
        print('column:', i+2, '=', col)
    out = f'stress-test-{G_name}.csv'
    print('writing stress metrics at:', out)
    pd.DataFrame.from_dict(df_dict, columns=columns,
            orient='index').to_csv(out, index_label='p')


import time
import threading
from formant.sdk.agent.v1 import Client as FormantAgentClient

NO_HEARTBEAT_DISCONNECTION_THRESHOLD = 0.1
current_timer = None

def trigger_disconnected():
    print("Disconnected")

def f(message):
    global current_timer
    if current_timer is not None:
        current_timer.cancel()
    print("Received heartbeat callback at", time.time())
    print("Received heartbeat:", message)
    current_timer = threading.Timer(
        NO_HEARTBEAT_DISCONNECTION_THRESHOLD, trigger_disconnected
    )
    current_timer.start()

if __name__ == "__main__":
    fclient = FormantAgentClient(ignore_unavailable=True)
    fclient.register_teleop_heartbeat_callback(f)

    try:
        while True:
            time.sleep(0.1)
    except KeyboardInterrupt:
        exit()


#  Created by btrif Trif on 21-02-2023 , 6:02 PM.
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from src.mazes.crud import delete_user, get_user_by_username
from src.mazes.database import get_db
from src.mazes.schemas import UserBaseSchema, UserSchema
from src.mazes.utils import get_current_user

admin_router = APIRouter(
        prefix="",
        tags=[ "admin" ],
        # dependencies=[ Depends(TokenSchema) ],
        responses={
            404 : {"description" : "Not found"},
            },
        )

@admin_router.post("/admin")
async def update_admin() :
    return {"message" : "Admin getting schwifty"}

@admin_router.post("/delete_user", response_model=dict)
async def delete_username(
        user: UserBaseSchema,
        current_user: UserBaseSchema = Depends(get_current_user),
        db: Session = Depends(get_db),
        ) :
    loggedin_user = current_user.username
    print(f"loggedin_user : {loggedin_user}   {type(loggedin_user)}   ")

    if loggedin_user in {'admin'} :
        db_user = get_user_by_username(
                db,
                user_name=user.username
                )
        if db_user :
            print(f"delete_user_by_username db_user :  {db_user}")
            deleted_user = delete_user(
                    db=db,
                    user_name=user.username
                    )
            print(f"deleted_user : {deleted_user}")
        else :
            raise HTTPException(status_code=400, detail="This username does not exist")

        return {"status" : "ok", "message" : f"The user {user.username} was successfully deleted"}

    else :
        raise HTTPException(status_code=400, detail="Only administrators can delete accounts")


class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = fast = slow = ListNode(next=head)
        while fast is not None:
            fast = fast.next
            slow = slow.next
            if fast is None:
                break

            fast = fast.next

        return slow


from .models import AVGRegisterline, ExternalReference
from rest_framework import serializers

class AVGRegisterlineSerializer(serializers.ModelSerializer):
    class Meta:
        model = AVGRegisterline
        fields = '__all__'
        exclude = [ ]
        read_only_fields = []

class EmbeddedAVGRegisterlineSerializer(AVGRegisterlineSerializer):
    id = serializers.IntegerField(label='ID', required=False)

class ExternalReferenceSerializer(serializers.ModelSerializer):
    avgregisterline = EmbeddedAVGRegisterlineSerializer()
    class Meta:
        model = ExternalReference
        fields = '__all__'


from bs4 import BeautifulSoup
from urllib.request import urlopen
from os import system

if __name__ == "__main__":
    f = open("/home/palpatine/result","w")
    html = urlopen("http://vstup.info/2018/i2018i41.html")
    wordToLookFor = input("textToFind:").lower()
    bs = BeautifulSoup(html)
    print(bs.prettify())
    f.write("")
    f.write("\n<meta charset=\"UTF-8\">\n")
    blocklist = bs.find("table", {"id": "denna1"}).find("tbody").findAll("tr")
    print(len(blocklist))
    for block in blocklist:
        if block.get_text().lower().find(wordToLookFor) != -1:
            f.write(str(block).replace("href=\".", "href=\"http://vstup.info/2018/") + "\n")
            f.write("
")
    f.write("")
    f.write("")
    f.close()
    system("firefox ~/result")


#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
@author:BanShaoHuan
@file: 1.py
@time: 2018/04/29
@contact: banshaohuan@163.com
@site:
@software: PyCharm

# code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
              ┏┓      ┏┓
            ┏┛┻━━━┛┻┓
            ┃      ☃      ┃
            ┃  ┳┛  ┗┳  ┃
            ┃      ┻      ┃
            ┗━┓      ┏━┛
                ┃      ┗━━━┓
                ┃  神兽保佑    ┣┓
                ┃  永无BUG！   ┏┛
                ┗┓┓┏━┳┓┏┛
                  ┃┫┫  ┃┫┫
                  ┗┻┛  ┗┻┛
"""

import time
def timer(func):
    def wapper(*args, **kwargs):
        start_time = time.time()
        res = func(*args, **kwargs)
        stop_time = time.time()
        print('time of the program is %s' %(stop_time - start_time))
        return res
    return wapper

@timer
def cal(l):
    res = 0
    for i in l:
        time.sleep(0.01)
        res += i
    return res

# print(cal(range(100)))

def test1():
    for i in range(3):
        if i > 4:
            print(i)
            return 0
    else:
        print('this is a test')

test1()


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from voicerecog_module import *
from selenium.webdriver.common.by import By
from difflib import SequenceMatcher
import time
from selenium.webdriver.chrome.service import Service

options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")
options.add_argument('--log-level=3')
path=Service("C:\Program Files\BraveSoftware\Brave-Browser\Application\112.1.50.119")
options.binary_location = "C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"
# Load the YouTube homepage
f = open("C:\\Users\\utkar\\OneDrive\\vscode\\automation_yt oops project\\test_topics.txt", "r")
topics=f.read()
sep=(input("enter the separator :-"))[0]
search_list=list(topics.split(sep))
start_index=input("input start topic no. or say start from begin :- ")
if start_index.isdigit()==True:
    start_index=int(start_index)
else:
    start_index=1
i=start_index-1
driver = webdriver.Chrome(service=path,options=options)
for search_term in search_list[i:]:
    print(start_index,"out of",len(search_list))
    start_index+=1
    driver.get("https://www.youtube.com")
    search_box = driver.find_element(By.NAME,"search_query")
    search_box.send_keys(search_term)

    search_box.send_keys(Keys.RETURN)
    search_box.clear()
    videos = driver.find_elements(By.XPATH,"//div[@id='contents']//ytd-video-renderer")
    title_similarity_scores = {}
    top_video_element = None
    for video in videos:
                title_element = video.find_element(By.XPATH,".//a[@id='video-title']")
                title = title_element.get_attribute("title")
                similarity_score = SequenceMatcher(None, search_term.lower(), title.lower()).ratio()
                title_similarity_scores[title] = similarity_score

                if len(title_similarity_scores) > 0:
                    sorted_titles = sorted(title_similarity_scores, key=title_similarity_scores.get, reverse=True)
                    top_video_title = sorted_titles[0]
                    top_video_element = None
                    for video in videos:
                        title_element = video.find_element(By.XPATH,".//a[@id='video-title']")
                        title = title_element.get_attribute("title")
                        if title == top_video_title:
                            top_video_element = video
                            break

                    top_video_element.click()
                    time.sleep(2)
                    top_video_element.send_keys("f")
                    #driver.find_element(By.XPATH,"//*[@id='movie_player']/div[33]/div[2]/div[2]/button[9]").click()
                    break
    print("listening")
# Listen for voice commands
    while True:
        try:
            command=voice()
    # Respond to voice commands
            if "search for" in command:
                search_term = command.replace("search for ", "")
                search_box = driver.find_element(By.NAME,"search_query")
                search_box.send_keys(search_term)
                search_box.send_keys(Keys.RETURN)
                search_box.clear()
                videos = driver.find_elements(By.XPATH,"//div[@id='contents']//ytd-video-renderer")
                title_similarity_scores = {}
                top_video_element = None
                for video in videos:
                    title_element = video.find_element(By.XPATH,".//a[@id='video-title']")
                    title = title_element.get_attribute("title")
                    similarity_score = SequenceMatcher(None, search_term.lower(), title.lower()).ratio()
                    title_similarity_scores[title] = similarity_score

                    if len(title_similarity_scores) > 0:
                        sorted_titles = sorted(title_similarity_scores, key=title_similarity_scores.get, reverse=True)
                        top_video_title = sorted_titles[0]
                        top_video_element = None
                        for video in videos:
                            title_element = video.find_element(By.XPATH,".//a[@id='video-title']")
                            title = title_element.get_attribute("title")
                            if title == top_video_title:
                                top_video_element = video
                                break
                        if top_video_element:
                            top_video_element.click()
                            break
                        else:
                            Speech("Failed to select video. Please try again.")
                            break
                    else:
                        Speech("No videos found. Please try again with a different search term.")

                    try:
                        top_video_element.click()
                    except TypeError:
                        Speech("retry ")

            if "pause" in command:
                pause_button = driver.find_element(By.CSS_SELECTOR,"#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button")
                pause_button.click()
            elif "play" in command:
                if "next video" in command:
                    seek_forward_button = driver.find_element(By.CSS_SELECTOR,"#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > a.ytp-next-button.ytp-button")
                    seek_forward_button.click()
                else:
                    play_button = driver.find_element(By.CSS_SELECTOR,"#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button")
                    play_button.click()
            elif "next video" in command:

                #driver.find_element(By.CSS_SELECTOR,"#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > a.ytp-next-button.ytp-button").click()
                break
            elif "mute" in command:
                driver.find_element(By.CSS_SELECTOR,"#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > span > button").click()
            elif "exit" in command or 'later' in command :
                exit()
        except TypeError:
            pass
# Quit the browser and release the microphone resources
driver.quit()
f.close()


import numpy as np
import cv2
import time
cap=cv2.VideoCapture(0)#Read from the default web cam i.e why 0

time.sleep(3) #for the system to sleep for 3 second before the webcam starts
for i in range(30):
    retval,back=cap.read()
back=np.flip(back,axis=1) #images captured is mirror image so we need to flip it again to get the original background amd axis=1 means laterally invert image
cap=cv2.VideoCapture(0)

## detecting the red portion In each frame

while (cap.isOpened()):  ##Read every Frame from the webcam, until the camera is open
    ret,img=cap.read()
    if ret:
        img=np.flip(img,axis=1)

        ##convert the color space from BGR to HSV because BGR  cant detect colour efficiently
        hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

        ##Generat masks to detect red color
        lower_red = np.array([0,120,70])
        upper_red = np.array([10,255,255])
        mask1 = cv2.inRange(hsv,lower_red,upper_red)

        lower_red = np.array([170,120,70])
        upper_red = np.array([180,255,255])
        mask2 = cv2.inRange(hsv,lower_red,upper_red)
        mask1+=mask2

        ###Replacing the red portion with a mask image in each frame

        mask = cv2.morphologyEx(mask1, cv2.MORPH_OPEN, np.ones((5,5),np.uint8))
        img[np.where(mask==255)]=back[np.where(mask==255)]

         #Final output
        cv2.imshow("Harry Potter's invisible secret revealed",img)
    key = cv2.waitKey(1)
    if key==ord("q"):
        break
cap.release()
cv2.destroyAllWindows()


import Shape
from Shape import *
class Triangle(Shape):
    def __init__(self,size):
        Shape.__init__(self)
        self.size= size

    def draw(self):
        super().draw()
        print("Triangle Draw")
        incre=1
        for row in range(self.size):
            print("*"*incre)
            incre+=1