# import graphing tools
import matplotlib
from matplotlib import style
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
import matplotlib.pyplot as plt

# haven't used this yet - need to read about it
import pandas

# for logging dates and its spendings
from datetime import datetime

#for storing data on expenditure
import pickle

import tkinter as tk
from tkinter import ttk
from tkinter import DoubleVar

from PIL import Image, ImageTk

# Create a simple database to store expenditure based on categories

# {amount, category, date}
# entry boxes/ option list for each

# main functions:

# - log spendings
# - store spendings details in dictionary
# - generate graphs and update them uppon command

# storage of spendings needs to be external to the script, otherwise it just
# gets refreshed everytime the the app is started
# use pickle module to pickle a dictionary

#strucutre of database:  (dict<tuple:dict>)
# i.e. {(date):{'food':0, 'shopping':0, etc.}, ...}

CATEGORIES = ('food', 'entertainment', 'fitness', 'rent', 'transport',
    'shopping')
UPPER_CATEG = ('Food', 'Entertainment', 'Fitness', 'Rent', 'Transport',
     'Shopping')

# The following classes form the model of the GUI

class Page(tk.Frame):
    """ Class that represents a page in the expense tracker app. Pages can be
        toggled to be hidden and shown and only one page can be displayed in the
        window.
    """
    def __init__(self, *args, **kwargs):
        """ Cosntructor """
        tk.Frame.__init__(self, *args, **kwargs)

        # Every page inherits the pickled dictionary
        self._database = {}
        self._load_database()

    def show(self):
        """ Shows the current page. """
        self.lift()

    # Every page has the dictionary loaded as an instance of itself
    def _load_database(self):
        """ Loads persistent storage containing information about expenditure."""
        with open('Expense_Tracker/expense_tracker.pickle', 'rb') as handle:
            self._database = pickle.load(handle)

class LogSpendings(Page):
    """ Page providing ability for user to log spendings into the persistent
        storage. Spendings are stored by the month in a dictionary.
    """

    def __init__(self, *args, **kwargs ):
        """ Constructor """
        Page.__init__(self, *args, **kwargs)

        self._init_vars()
        self._init_frames()
        self._init_headings()
        self._init_labels()
        self._init_entries()

        # Debugging code here
        # ----------------------------------------------
        # button = tk.Button(self, text="print_data", \
        #      command=self.print_data).pack(expand=True)
        # button2 = tk.Button(self, text="clear data", \
        #     command=self.clear_database).pack(expand=True)
        # -------------------------------------------------

        # pack all of the category frames into the page
        self._pack_frames()

        # button to log entered spendings into the database
        self._log = tk.Button(self, text="Log Spendings", \
            command=self.log_spending)\
            .pack(pady=5, padx=5, ipadx=8, ipady=2, side=tk.TOP)

    def _init_vars(self):
        """ Initialise double variables for entry widgets"""
        # initialise variables for entry widgets
        self._food = DoubleVar()
        self._entertainment = DoubleVar()
        self._fitness = DoubleVar()
        self._rent = DoubleVar()
        self._shopping = DoubleVar()
        self._transport = DoubleVar()
        return

    def _init_frames(self):
        """ Initialise frames for each spending category"""
        # create containers for each category
        self._food_frame = tk.Frame(self, background='white')
        self._ent_frame = tk.Frame(self, background='white')
        self._fitness_frame = tk.Frame(self, background='white')
        self._rent_frame = tk.Frame(self, background='white')
        self._shop_frame = tk.Frame(self, background='white')
        self._transp_frame = tk.Frame(self, background='white')
        return

    def _init_headings(self):
        """ Initialise headings for the page"""
        # Headings for the app
        self._heading = tk.Label(self, text="Expense Tracker", font=11, background='white')\
            .pack(side=tk.TOP, expand=True)
        self._subheading = tk.Label(self, \
            text="Enter your spendings and press 'Log Spendings'", background='white')\
            .pack(side=tk.TOP, expand=True)
        return

    def _pack_frames(self):
        """Pack frames (vertically stacked) into the page"""
        # pack containers into the master window
        self._food_frame.pack(side=tk.TOP, expand=True, fill=tk.X, padx=10)
        self._ent_frame.pack(side=tk.TOP, expand=True, fill=tk.X, padx=10)
        self._fitness_frame.pack(side=tk.TOP, expand=True, fill=tk.X, padx=10)
        self._rent_frame.pack(side=tk.TOP, expand=True, fill=tk.X, padx=10)
        self._shop_frame.pack(side=tk.TOP, expand=True, fill=tk.X, padx=10)
        self._transp_frame.pack(side=tk.TOP, expand=True, fill=tk.X, padx=10)
        return

    def _init_labels(self):
        """ Initialise labels for each category and pack"""
        self._food_lbl = tk.Label(self._food_frame, text="Food", background='white')\
            .pack(side=tk.LEFT, ipadx=28, padx=5, expand=True, anchor=tk.E)
        self._ent_lbl = tk.Label(self._ent_frame, text="Entertainment", background='white')\
            .pack(side=tk.LEFT, ipadx=4, padx=5, expand=True, anchor=tk.E)
        self._fitness_lbl = tk.Label(self._fitness_frame, text="Fitness", background='white')\
            .pack(side=tk.LEFT, ipadx=23, padx=5, expand=True, anchor=tk.E)
        self._rent_lbl = tk.Label(self._rent_frame, text="Rent", background='white')\
            .pack(side=tk.LEFT, ipadx=29, padx=5, expand=True, anchor=tk.E)
        self._shop_lbl = tk.Label(self._shop_frame, text="Shopping", background='white')\
            .pack(side=tk.LEFT, ipadx=16, padx=5, expand=True, anchor=tk.E)
        self._transp_lbl = tk.Label(self._transp_frame, text="Transport", background='white')\
            .pack(side=tk.LEFT, ipadx=16, padx=5, expand=True, anchor=tk.E)
        return

    def _init_entries(self):
        """ Initialise entry widgets for each category and pack"""
        self._food_entry = tk.Entry(self._food_frame, textvariable=self._food, \
            background='white') \
            .pack(side=tk.RIGHT, pady=10, padx=10, expand=True, anchor=tk.W)

        self._entertainment_entry = tk.Entry(self._ent_frame, \
             textvariable=self._entertainment, background='white')\
            .pack(side=tk.RIGHT, pady=10, padx=10, expand=True, anchor=tk.W)

        self._fitness_entry = tk.Entry(self._fitness_frame, \
             textvariable=self._fitness, background='white')\
            .pack(side=tk.RIGHT, pady=10, padx=10, expand=True, anchor=tk.W)

        self._rent_entry = tk.Entry(self._rent_frame, textvariable=self._rent, \
            background='white')\
            .pack(side=tk.RIGHT, pady=10, padx=10, expand=True, anchor=tk.W)

        self._shopping_entry = tk.Entry(self._shop_frame, \
             textvariable=self._shopping, background='white')\
            .pack(side=tk.RIGHT, pady=10, padx=10, expand=True, anchor=tk.W)

        self._transport_entry = tk.Entry(self._transp_frame, \
             textvariable=self._transport, background='white')\
            .pack(side=tk.RIGHT, pady=10, padx=10, expand=True, anchor=tk.W)
        return

# ------------------------------ DEBUGGING ---------------
    # def print_data(self):
    #     """ This method is for debugging purposes only."""
    #     print(self._database.items())
    #     print(self._database.keys())
    #     print(self._database.values())
    #     return

    # def clear_database(self):
    #     """Deletes all memory stored on database dictionary"""
    #     self._database = {}
    #     return
# --------------------------------------------------------

    def _save_database(self): # save log into persistent storage
        """ Saves current data on self._database to pickle file"""
        with open('Expense_Tracker/expense_tracker.pickle', 'wb') as handle:
            pickle.dump(self._database, handle, \
                 protocol=pickle.HIGHEST_PROTOCOL)
        return

    def log_spending(self):
        """ Retrieves entered spendings and logs the values into storage."""
        # get current month and date (this is the key)
        month = datetime.now().month
        year = datetime.now().year
        date = (month, year,)

        # add date and/or category if not exists, else add to the current
        # value stored in dict
        for category in CATEGORIES:
            amount = getattr(self, "_" + category).get()
            if self._database.get(date) is not None:
                if self._database.get(date).get(category) is not None:
                    init_amount = self._database.get(date).get(category)
                    self._database[date][category] = init_amount + amount
                else:
                    self._database[date][category] = amount
            else:
                self._database[date] = {}
                self._database[date][category] = amount

        print("Successfully saved log!")

        self._save_database()

        return

#might want to do a getter method that obtains the amount for each date

    # def view_category_spendings(self):
    #     """ View by category (histogram??) use matplotlib

    #     Can either make it appear in root window or a pop-up window"""

    #     back_btn = tk.Button(self._master, text="Back to Main Page")
    #     pass

    # def view_monthly_spendings(self):
    #     """ View total spendings by date (month) (line chart??) use matplotlib

    #     can either make it appear in root window or a pop-up window"""
    #     back_btn = tk.Button(self._master, text="Back to Main Page")
    #     pass

# need to use category names instead of numbers for the bar chart
class CategoryGraphs(Page):
    """ Page displaying current month's categorical spendings as a bar graph."""
    def __init__(self, *args, **kwargs ):
        """ Constructor of an expense tracker"""
        Page.__init__(self, *args, **kwargs)

        self._categ = {}
        self._init_graph()

        update_graph_btn = tk.Button(self, text="Update Graph", \
            command=self._update_graph)\
            .pack(expand=True, pady=5, ipadx=1, ipady=2, anchor=tk.S)
        return

    def _update_category_values(self):
        """ Retrieves current values for the month's categorical spendings."""
        # update the spendings values for each category
        (month, year,) = (datetime.now().month, datetime.now().year,)
        if self._database.get((month, year,)) is None:
            self._database[(month, year,)] = {}
        for category in CATEGORIES:
            self._categ[category] = self._database.get((month, year,)) \
                .get(category, 0)

        # update the data points for the bar graph
        self._data = []
        for category in CATEGORIES:
            self._data.append(self._categ.get(category, 0))
        return

    def _update_graph(self):
        """ Update subplot of bar graph on page. """
        self._update_category_values()
        self._a.clear()
        self._a.bar(self._rang, self._data, 0.5)
        print("updated!")
        return

    def _init_graph(self):
        """ Initialise the bar graph using matplotlib and tkinter module. """
        # Create a figure and add a subplot to the figure
        self._f = Figure(figsize=(3, 3), dpi=100)
        self._a = self._f.add_subplot(111)
        self._a.set_title("Categorical Spendings")
        self._rang = np.arange(1,7)

        self._update_category_values()

        # create a bar graph and add it tkinter canvas to be packed.
        self._a.bar(self._rang, self._data, 0.5)
        self._canvas = FigureCanvasTkAgg(self._f, self)
        self._canvas.get_tk_widget().pack(side=tk.TOP, ipady=20, fill=tk.BOTH, \
             expand=True)
        return

class MonthlyGraphs(Page):
    """ Page displaying line graph of total spendings per month"""
    def __init__(self, *args, **kwargs ):
        """ Constructor """
        Page.__init__(self, *args, **kwargs)

        self._monthly_values = []
        self._months = []
        self._init_graph()

        create_graph = tk.Button(self, text="Update Graph", \
            command=self._update_graph)\
                .pack(expand=True, pady=5, ipadx=1, ipady=2, anchor=tk.S)
        return

    def _init_graph(self):
        """ Updates the graph values to the current data stored in the
        dictionary. """
        # create figure and add subplot
        self._f = Figure(figsize=(3,3), dpi=100)
        self._a = self._f.add_subplot(111)
        self._a.set_title("Monthly Spendings")

        self._update_plot_pts()
        self._a.plot(self._months, self._monthly_values, marker='o')

        self._canvas = FigureCanvasTkAgg(self._f, self)
        self._canvas.get_tk_widget().pack(side=tk.TOP, ipady=20, fill=tk.BOTH,\
             expand=True)
        return

    def _update_graph(self):
        """ Updates the set of points to plot and plots them on the figure """
        self._update_plot_pts()
        self._a.clear()
        self._a.plot(self._months, self._monthly_values, marker='o')
        return

    def _update_plot_pts(self):
        """ Retrieves current year's months and monthly spendings and
            stores them in lists.
        """
        curr_year = datetime.now().year
        self._monthly_values = []
        self._months = []

        for i in range(1, 13):
            if self._database.get((i, curr_year,)) is not None:
                self._monthly_values.append(sum( \
                    self._database.get((i, curr_year,)).values()))
                self._months.append(i)
        return

class PieGraph(Page):
    """ Page displaying pie chart of categorical spendings for current month."""
    def __init__(self, *args, **kwargs ):
        """ Constructor """
        Page.__init__(self, *args, **kwargs)

        self._percentages = []
        self._update_percentages()

        self._f = Figure(figsize=(4,4), dpi=100)
        self._a = self._f.add_subplot(111)
        self._a.set_title("Categorical Spendings")

        # only display a pie chart if there have been spendings for the month
        if len(self._percentages) != 0:
            self._a.pie(self._percentages)
            self._a.legend(CATEGORIES, loc="upper left")

        canvas = FigureCanvasTkAgg(self._f, self)
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, ipady=20, expand=True)

        create_graph = tk.Button(self, text="Update Chart", \
             command=self._update_pie)\
            .pack(expand=True, pady=5, ipadx=1, ipady=2, anchor=tk.S)
        return

    def _update_percentages(self):
        """ Updates percentages of categorical spendings for current month."""
        (month, year,) = (datetime.now().month, datetime.now().year,)
        values = []
        if self._database.get((month, year,), 0) == 0:
            self._database[(month, year,)] = {}

        # get a list of the categorical spendings for the current month
        for category in CATEGORIES:
            # add the expenditure for the category to the values list
            expenditure = self._database.get((month, year,), 0).get(category, 0)
            values.append(expenditure)
            # create a dictionary for that month of the year if there isn't one
            if expenditure == 0:
                self._database[(month, year,)][category] = 0

        total = sum(values)
        # if the total spendings is 0, set the percentages list to be empty
        if total == 0:
            self._percentages = [0,0,0,0,0,0,0]
            return "you haven't spent any money this month!"
        # otherwise, store the corresponding percentage for each category
        self._percentages = [value*100/total for value in values]
        return

    def _update_pie(self):
        """ Updates the pie graph in the page. """
        self._update_percentages()
        self._a.clear
        self._a.pie(self._percentages)
        self._a.legend(CATEGORIES)
        return

class Home(Page):
    """ Home page of application. """
    def __init__(self, *args, **kwargs ):
        """ Constructor """
        Page.__init__(self, *args, **kwargs)
        welcome = tk.Label(self, text="Welcome to the Expense Tracker App!", \
            font=12, background='white') \
                .pack(side=tk.TOP, expand=True, fill=tk.BOTH)

        # load an icon image for the home page
        load = Image.open("Expense_Tracker/Icons/analytics-icon.png")
        render = ImageTk.PhotoImage(load)
        img = tk.Label(self, image=render, background='white')
        img.image = render
        img.pack(side=tk.TOP, expand=True)

        desc = tk.Label(self, text="Click on one of the buttons below to get started.",\
             background='white').pack(side=tk.TOP, expand=True, fill=tk.BOTH)
        return

# ----------------------------------------------------------------------------
#                                  VIEW
# ---------------------------------------------------------------------------

# This is the View of the GUI
class MainView(tk.Frame):
    """ Main view for user when application is run. Contains buttons that
    direct users to different pages of the application."""

    def __init__(self, *args, **kwargs):
        """ constructor """
        tk.Frame.__init__(self, *args, **kwargs)

        self._init_pages()
        self._init_containers()
        self._place_pages()
        self._init_buttons()

        # show the home page first
        self._home.show()
        return

    def _init_pages(self):
        """ Initialise 'pages' (tk.Frame) for the application """
        # create instances of the frames I want to toggle
        self._home = Home(self, background='white')
        self._log = LogSpendings(self, background='white')
        self._category = CategoryGraphs(self, background='white')
        self._monthly = MonthlyGraphs(self, background='white')
        self._pie = PieGraph(self, background='white')
        return

    def _init_containers(self):
        """ Initialise the containers for buttons and pages."""
        # create containers for the buttons and frames
        self._buttonframe = tk.Frame(self)
        self._container = tk.Frame(self)
        self._buttonframe.pack(side=tk.TOP, fill=tk.X, expand=False)
        self._container.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        return

    def _place_pages(self):
        """ Place the 'pages' into the container."""
        # place each 'page'/frame into the container
        self._home.place(in_=self._container, x=0, relwidth=1, \
            relheight=1)
        self._log.place(in_=self._container, x=0, y=0, relwidth=1, relheight=1)
        self._category.place(in_=self._container, x=0, y=0, relwidth=1, \
            relheight=1)
        self._monthly.place(in_=self._container, x=0, y=0, relwidth=1, \
            relheight=1)
        self._pie.place(in_=self._container, x=0, y=0, relwidth=1, relheight=1)
        return

    def _init_buttons(self):
        """ Initialise buttons to toggle to different pages."""
        # buttons to toggle to the different pages
        self._log_btn = tk.Button(self, text="Log Spendings", \
            command=self._log.lift).pack(side=tk.LEFT, padx=10, pady=15, \
                 ipady=2, ipadx=1, expand=True)

        self._category_btn = tk.Button(self, text="Category Spending", \
            command=self._category.lift).pack(side=tk.LEFT, padx=10, pady=15, \
                ipady=2, ipadx=1, expand=True)
        self._month_btn = tk.Button(self, text="Monthly Spending", \
            command=self._monthly.lift)\
            .pack(side=tk.LEFT, padx=10, pady=15, ipady=2, ipadx=1, expand=True)

        self._pie_btn = tk.Button(self, text="Category Pie Chart", \
            command=self._pie.lift)\
            .pack(side=tk.LEFT, padx=10, pady=15, ipady=2, ipadx=1, expand=True)
        return

def main():
    root = tk.Tk()
    root.title("Expense Tracker")
    root.minsize(550,550)
    expense_tracker=MainView(root, background='white')
    expense_tracker.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
    root.mainloop()

if __name__ == "__main__":
    main()


import argparse
import json
from urllib.request import urlopen

def get_parser():
    """Get parser for command line arguments."""
    parser = argparse.ArgumentParser(description="URL Downloader")
    parser.add_argument("-q", "--query", dest="query", help="Query/Filter", default='-')
    parser.add_argument("-k", "--key", dest="key", help="Google API Key")
    return parser

if __name__ == '__main__':

    parser = get_parser()
    args = parser.parse_args()

    data = urlopen('https://www.googleapis.com/customsearch/v1?key={}&cx=000919482489691833361:drmpuulq2tk&q={}'.format(args.key,args.query))
    data = json.load(data)
    #print(data['items'][0]['link'])
    with open('NewsURL.txt', 'a') as f:
        for j in range(len(data['items'])):
            f.write(data['items'][j]['link']+'\n')
            print(data['items'][j]['link'])


# -*- coding: UTF-8 -*-
#
# Fibonacci search works for a sorted array.
# The All ▲lgorithms library for python
#
# Contributed by: dieterpl
# Github: @dieterpl
#

def fibonacci_search(arr, query):
    fib2, fib1 = 0, 1
    fib = fib2 + fib1
    hi = len(arr) - 1
    while fib <= hi:
        fib2 = fib1
        fib1 = fib
        fib = fib2 + fib1
    offset = -1
    while fib > 1:
        i = min(offset + fib2, hi)
        if arr[i] < query:
            fib = fib1
            fib1 = fib2
            fib2 = fib - fib1
            offset = i
        elif arr[i] > query:
            fib = fib2
            fib1 = fib1 - fib2
            fib2 = fib - fib1
        else:
            return i
    if fib1 and arr[offset + 1] == query:
        return offset + 1
    return None


import os
import numpy as np

def random_calib_data(size, path, num=100):
    for i in range(num):
        data = np.random.randn(*size).astype('f')
        filename = os.path.join(path, str(i))
        np.save(filename, data)
        print(f'save random cali data file {filename}.npy')


from .resources.quotes import quotes

class JsonStub(object):

    def __init__(self, url):
        self.url = url

    def json(self):
        param = self.url.rsplit('/', 1)[1]

        if param.isdigit():
            return {"quote": quotes[int(param)]}
        elif param == "random":
            return {"quote": quotes[2]}

        return {"quotes": quotes}


import numpy as np
import os
import math
import tensorflow as tf
from functools import partial

# resample each hypothesis given the scaling coefficients
def tf_resample_hyps(hyps, coeff_x, coeff_y):
    resampled_hyps = []
    for h in hyps:
        x_center = h[:, 0:1, :, :] / coeff_x
        y_center = h[:, 1:2, :, :] / coeff_y
        width = h[:, 2:3, :, :] / coeff_x
        height = h[:, 3:4, :, :] / coeff_y
        resampled_hyps.append(tf.concat([x_center, y_center, width, height], axis=1))
    return resampled_hyps

# create a tensorflow session and initialize the global variables
def create_session():
    tf.reset_default_graph()
    config = tf.ConfigProto(log_device_placement=False)
    config.gpu_options.per_process_gpu_memory_fraction = 0.95
    config.gpu_options.allow_growth = True
    session = tf.Session(config=config)
    session.run(tf.global_variables_initializer())
    return session

# restore the variables from a snapshot
def optimistic_restore(session, save_file, ignore_vars=None, verbose=False, ignore_incompatible_shapes=False):
    def vprint(*args, **kwargs):
        if verbose: print(*args, flush=True, ** kwargs)

    if ignore_vars is None:
        ignore_vars = []

    reader = tf.train.NewCheckpointReader(save_file)
    saved_shapes = reader.get_variable_to_shape_map()
    var_names = sorted([(var.name, var.dtype, var.name.split(':')[0]) for var in tf.global_variables()
                        if var.name.split(':')[0] in saved_shapes and not var in ignore_vars])
    restore_vars = []

    nonfinite_values = False

    with tf.variable_scope('', reuse=True):
        for var_name, var_dtype, saved_var_name in var_names:
            curr_var = [var for var in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) if saved_var_name in var.name][0]
            var_shape = curr_var.get_shape().as_list()
            if var_shape == saved_shapes[saved_var_name]:
                tmp = reader.get_tensor(saved_var_name)

                # check if there are nonfinite values in the tensor
                if not np.all(np.isfinite(tmp)):
                    nonfinite_values = True
                    print('{0} contains nonfinite values!'.format(saved_var_name), flush=True)

                if isinstance(tmp, np.ndarray):
                    saved_dtype = tf.as_dtype(tmp.dtype)
                else:
                    saved_dtype = tf.as_dtype(type(tmp))
                if not saved_dtype.is_compatible_with(var_dtype):
                    raise TypeError('types are not compatible for {0}: saved type {1}, variable type {2}.'.format(
                        saved_var_name, saved_dtype.name, var_dtype.name))

                print('restoring    ', saved_var_name)
                restore_vars.append(curr_var)
            else:
                vprint('not restoring', saved_var_name, 'incompatible shape:', var_shape, 'vs',
                       saved_shapes[saved_var_name])
                if not ignore_incompatible_shapes:
                    raise RuntimeError(
                        'failed to restore "{0}" because of incompatible shapes: var: {1} vs saved: {2} '.format(
                            saved_var_name, var_shape, saved_shapes[saved_var_name]))
    if nonfinite_values:
        raise RuntimeError('"{0}" contains nonfinite values!'.format(save_file))
    saver = tf.train.Saver(var_list=restore_vars, restore_sequentially=True)
    saver.restore(session, save_file)

# simple wrapper for a fully connected layer with activation
def tf_full_conn(input, activation=None, **kwargs):

    k_initializer = tf.contrib.layers.variance_scaling_initializer(factor=2, mode='FAN_IN', uniform=False)
    k_regularizer = tf.contrib.layers.l2_regularizer(scale=0.0)
    b_initializer = tf.zeros_initializer

    num_output = kwargs.pop('num_output', False)
    name = kwargs.pop('name', 'conv_no_name')

    # Flatten the data to a 1-D vector for the fully connected layer
    fc1 = tf.contrib.layers.flatten(input)

    dense_out = tf.layers.dense(fc1,
                                int(num_output),
                                activation=activation,
                                kernel_initializer=k_initializer,
                                bias_initializer=b_initializer,
                                kernel_regularizer=k_regularizer,
                                trainable=True,
                                name=name)
    output = tf.reshape(dense_out, [dense_out.shape[0], dense_out.shape[1], 1, 1])
    return output

# padding a tensor
def tf_pad_input(input, pad):
    padded = tf.pad(input, [[0,0],[0,0],[pad,pad],[pad,pad]])
    return padded

# simple wrapper for a convolution layer with a default leaky_relu as activation
def tf_conv(input, activation=partial(tf.nn.leaky_relu, alpha=0.1), **kwargs):

    k_initializer = tf.contrib.layers.variance_scaling_initializer(factor=2, mode='FAN_IN', uniform=False)
    k_regularizer = tf.contrib.layers.l2_regularizer(scale=0.0)
    b_initializer = tf.zeros_initializer

    # for shared params
    dropout = kwargs.pop("dropout", False)
    if dropout: raise NotImplementedError

    kernel_size = kwargs.pop('kernel_size', False)
    num_output = kwargs.pop('num_output', False)
    stride = kwargs.pop('stride', 1)
    pad = kwargs.pop('pad', 0)
    name = kwargs.pop('name', 'conv_no_name')

    if not kernel_size:
        raise KeyError('Missing kernel size')
    if not num_output:
        raise KeyError('Missing output size')

    # layer
    # note: input might be a tuple, in which case weights are shared
    if not isinstance(input, tuple):
        conv_out = tf.layers.conv2d(tf_pad_input(input, pad),
                                num_output,
                                kernel_size,
                                strides=stride,
                                data_format='channels_first',
                                trainable=False,
                                activation=activation,
                                kernel_regularizer = k_regularizer,
                                kernel_initializer = k_initializer,
                                bias_initializer = b_initializer,
                                name=name)
        return conv_out
    else:
        outputs = []
        for i in input:
            outputs.append(tf.layers.conv2d(pad_input(i, pad),
                                num_output,
                                kernel_size,
                                strides=stride,
                                data_format='channels_first',
                                trainable=nd.scope.learn(),
                                reuse=tf.AUTO_REUSE,
                                activation=activation,
                                kernel_regularizer = k_regularizer,
                                kernel_initializer = k_initializer,
                                bias_initializer = b_initializer,
                                name=name,
                                ))

        return outputs

# Post-processing function applied on the log sigmas. This should constraint the log_sigma given (min, max).
# We use this technique to ensure stability during training (e.g, we start training by small range and we increase over time).
def tf_adjusted_sigmoid(X, min, max):
    tf.add_to_collection('log_scale_bound', max)
    const = lambda z: tf.fill(X.get_shape(), z)
    min = tf.to_float(min)
    max = tf.to_float(max)
    range = max - min
    x_scaled = tf.multiply(X, const(4.0 / range))
    sig = tf.sigmoid(x_scaled)
    sig_scaled = tf.multiply(sig, const(range))
    if min != 0:
        sig_scaled_shifted = tf.add(sig_scaled, const(min))
    else:
        sig_scaled_shifted = sig_scaled
    return sig_scaled_shifted

# wrapper function for sum(w_i * x_i)/sum(w_i)
def tf_average_weighted_norm(x, w):
    sum_w = tf.reduce_sum(w, axis=1)
    sum_w_inv = tf.pow(tf.add(sum_w, tf.fill(sum_w.get_shape(), 1e-6 / 2.0)), -1)

    x_weighted = tf.multiply(x, w)
    x_weighted_sum = tf.reduce_sum(x_weighted, axis=1)
    result = tf.multiply(x_weighted_sum, sum_w_inv)
    result = tf.expand_dims(result, axis=1)
    return result

# generates a laplacian mixture model parameters given a set of independent laplacian distributions
# this corresponds to the equations 6,7,8,9 in the paper.
def tf_get_laplace_mixture_model_from_independent_dists(samples_means, samples_log_scales, assignments):
    num_of_modes = assignments[0].shape[1]
    num_samples = len(samples_means)

    expanded_means = [tf.expand_dims(samples_means[i], axis=1) for i in range(num_samples)]
    samples_means_concat = tf.concat(expanded_means, axis=1)

    expanded_scales = [tf.expand_dims(tf.exp(samples_log_scales[i]), axis=1) for i in range(num_samples)]
    samples_b_concat = tf.concat(expanded_scales, axis=1)
    # map b (scale) to sigma^2
    samples_var_concat = tf.scalar_mul(2.0, tf.pow(samples_b_concat, 2))

    expanded_assignments = [tf.expand_dims(assignments[i], axis=1) for i in range(len(assignments))]
    assignments_adjusted = tf.nn.softmax(tf.concat(expanded_assignments, axis=1), dim=2)

    mixture_weights = []
    means = []
    log_scales = []
    for k in range(num_of_modes):
        y_ik = assignments_adjusted[:,:,k,:,:]

        w_k = tf.expand_dims(tf.reduce_mean(y_ik, axis=1), axis=1)

        mu_k_x = tf_average_weighted_norm(samples_means_concat[:,:,0,:,:], y_ik)
        mu_k_y = tf_average_weighted_norm(samples_means_concat[:,:,1,:,:], y_ik)
        mu_k = tf.concat([mu_k_x, mu_k_y], axis=1)

        # Var =E[Var()] + Var(E[])
        mu_k_repeated = tf.concat([tf.expand_dims(mu_k, axis=1) for i in range(num_samples)], axis=1)
        diff = tf.subtract(samples_means_concat, mu_k_repeated)
        diff2 = tf.pow(diff, 2)
        var_E_k_x = tf_average_weighted_norm(diff2[:,:,0,:,:], y_ik)
        var_E_k_y = tf_average_weighted_norm(diff2[:,:,1,:,:], y_ik)
        var_E_k = tf.concat([var_E_k_x, var_E_k_y], axis=1)
        E_var_k_x = tf_average_weighted_norm(samples_var_concat[:, :, 0, :, :], y_ik)
        E_var_k_y = tf_average_weighted_norm(samples_var_concat[:, :, 1, :, :], y_ik)
        E_var_k = tf.concat([E_var_k_x, E_var_k_y], axis=1)
        var_k = tf.add(E_var_k, var_E_k)
        # map sigma^2 to b
        b_k = tf.pow(tf.scalar_mul(0.5, var_k), 0.5)
        log_scale_k = tf.log(b_k)

        mixture_weights.append(w_k)
        means.append(mu_k)
        log_scales.append(log_scale_k)

    return means, log_scales, mixture_weights

def tf_assemble_lmm_parameters_independent_dists(samples_means, samples_log_scales, assignments):
    means, log_sigmas, mixture_weights = tf_get_laplace_mixture_model_from_independent_dists(samples_means, samples_log_scales, assignments)
    bounded_log_sigmas = [tf_adjusted_sigmoid(log_sigmas[i], -6, 6) for i in range(len(log_sigmas))]
    return means, bounded_log_sigmas, mixture_weights

# get a binary mask (B_i) for the object bounding box
def tf_get_mask(indices, width, height, fill_value=1.0):# shape of indices is 5
    indices = tf.to_int32(indices)
    tl_x = indices[0]
    tl_y = indices[1]
    bbox_width = indices[2]-indices[0]
    bbox_height = indices[3]-indices[1]
    ind_row = [tl_y, height - tl_y - bbox_height]
    ind_col = [tl_x, width - tl_x - bbox_width]
    padding = tf.stack([ind_row, ind_col])
    input = tf.ones([bbox_height, bbox_width]) * (fill_value + 1)
    padded = tf.expand_dims(tf.expand_dims(tf.pad(input, padding, "CONSTANT"), axis=0), axis=0)
    return padded


import sys
sys.stdin = open("./baekjoon/testcase.txt")

n = int(sys.stdin.readline())
matrix = []
for _ in range(n):
    row = list(map(int, sys.stdin.readline().split()))
    matrix.append(row)

counts = [0,0,0]

def solve(r, c, width):
    v = matrix[r][c]
    valid = True
    for i in range(r, r+width):
        for j in range(c, c+width):
            if v != matrix[i][j]:
                valid = False
                break
    if (valid):
        counts[v] += 1
    else:
        new_width = width // 3
        for i in range(0, 3):
            for j in range(0, 3):
                solve(r+i*new_width, c+j*new_width, new_width)

r, c, width = 0, 0, n
solve(r, c, width)
print(counts[-1])
print(counts[0])
print(counts[1])


from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import os
import sys
import optparse
import csv
import time
import matplotlib.pyplot as plt
# user's python files
from intelligentModel2PhaseCoord import callUppaalStratego
import detectorData
import generateRouteForTwenty
import calculateWaitingTime
import plottingPurpose

# we need to import python modules from the $SUMO_HOME/tools directory
if 'SUMO_HOME' in os.environ:
    tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
    sys.path.append(tools)
else:
    sys.exit("please declare environment variable 'SUMO_HOME'")
from sumolib import checkBinary  # noqa
import traci  # noqa

# loop and area detectors
areaDetectorFifty = detectorData.areaDetectorFifty
areaDetectorFiftySeqIndex = detectorData.areaDetectorFiftySeqIndex
loopDetectorFifity = detectorData.loopDetectorFifity
loopDetectorFiftySeqIndex = detectorData.loopDetectorFiftySeqIndex
loopAreaDetectorFifity = detectorData.loopAreaDetectorFifity
throughputLoopDetectors = detectorData.throughputLoopDetectors

totalWaitingTime = np.zeros(20,dtype=int)
tolSum =[]
phaseNS = np.zeros(20,dtype=int)
phaseWE = np.zeros(20,dtype=int) + 2
phaseToNS = np.zeros(20,dtype=int) + 1
phaseToEW = np.zeros(20,dtype=int) + 3
ic_minGreen = np.zeros(20,dtype=int) + 8
yellow = np.zeros(20,dtype=int) + 4
timeInPhase = np.zeros(20,dtype=int)
nextPhase = np.zeros(20,dtype=int)
phase = np.zeros(20,dtype=int)
count_time = [False] * 20
phaseTime = np.zeros(20,dtype=int)

# intelligent variable declaration
previousPhase = np.zeros(20,dtype=int)
maximumTimer_A = np.zeros(20,dtype=int) + 40
maximumTimer_B = np.zeros(20,dtype=int) + 40
loadCapacity = [15,20,25,30,35,45,55,75,100,120]
maxGreenTimeforLoad = [50,60,70,90,100,110,120,130,140,150]
intelligentTimer = [20,25,30,35,40,45,45,50,50,50]

trafficLightId = detectorData.trafficLightId

class TrafficLight:
    totalWaitingTime = 0 ; totalQueueLength = 0 ; totalCo2Emission = 0 ; totalCoEmission = 0

    def __init__(self, trlId, areaDetectors,loopDetectors,loopAreaDetectors,sInd,sIndLoop,debug):
        self.trlId = trlId
        self.areaDetectors = areaDetectors
        self.loopDetectors = loopDetectors
        self.loopAreaDetectors = loopAreaDetectors
        self.sIndex = sInd
        self.sIndexLoop = sIndLoop
        self.debug = debug
        self.direction_A = 0
        self.direction_B = 0

    def getData(self,func, dets):
        numDet = len(dets)
        res = [0] * numDet
        for deti in range(0, numDet):
            res[deti] = func(dets[deti])
        return res

    # get the arrival car list
    def getArrivalCars(self):
        indx = self.sIndex
        carsArrival = self.getData(traci.lanearea.getLastStepVehicleNumber, self.areaDetectors)
        carArrival = [ sum(carsArrival[indx[0]:indx[1]]),sum(carsArrival[indx[2]:indx[3]])
                       ,sum(carsArrival[indx[4]:indx[5]]),sum(carsArrival[indx[6]:indx[7]])]
        self.direction_A = sum(carArrival[0:2])
        self.direction_B = sum(carArrival[2:4])
        if self.debug:
            print("In Intersection %s: Arrival cars [Left Right Up Down]:%s"%(self.trlId,carArrival))
        return carArrival

    # get the jammed car list
    def getJammedCars(self):
        indx = self.sIndex
        carsJammed = self.getData(traci.lanearea.getLastStepHaltingNumber, self.areaDetectors)
        carJammed = [sum(carsJammed[indx[0]:indx[1]]), sum(carsJammed[indx[2]:indx[3]])
            , sum(carsJammed[indx[4]:indx[5]]), sum(carsJammed[indx[6]:indx[7]])]
        if self.debug:
            print("In Intersection %s: Jammed cars [Left Right Up Down]:%s" % (self.trlId, carJammed))
        return carJammed

        # get the waiting car list

    def getWaitingCars(self):
        indx = self.sIndex
        carsWaiting = self.getData(traci.lanearea.getLastStepHaltingNumber, self.areaDetectors)
        carWaiting = [sum(carsWaiting[indx[0]:indx[2]]), sum(carsWaiting[indx[2]:indx[4]])
            , sum(carsWaiting[indx[4]:indx[6]]), sum(carsWaiting[indx[6]::])]
        self.totalWaitingTime += sum(carWaiting)
        if self.debug:
            print("In Intersection %s: Jammed cars [Left Right Up Down]:%s" % (self.trlId, carWaiting))
        return carWaiting
    # get the jammed cars length in meters
    def getJammedCarsLength(self):
        indx = self.sIndex
        carsJammedLength = self.getData(traci.lanearea.getJamLengthMeters, self.areaDetectors)
        carJammedLength = [sum(carsJammedLength[indx[0]:indx[2]]), sum(carsJammedLength[indx[2]:indx[4]])
            , sum(carsJammedLength[indx[4]:indx[6]]), sum(carsJammedLength[indx[6]::])]
        self.totalQueueLength += sum(carJammedLength)
        if self.debug:
            print("In Intersection %s: Jammed cars Length [Left Right Up Down]:%s" % (self.trlId, carJammedLength))
        return carJammedLength

    # getting loop detector data for loop controller
    def getLoopDetectorData(self):
        indx = self.sIndexLoop
        carsCrossed = self.getData(traci.inductionloop.getLastStepVehicleNumber, self.loopDetectors)
        carsCrossedNow = [sum(carsCrossed[indx[0]:indx[1]]), sum(carsCrossed[indx[2]:indx[3]])
            , sum(carsCrossed[indx[4]:indx[5]]), sum(carsCrossed[indx[6]:indx[7]])]
        if self.debug:
            print("In Intersection %s: Loop detector data [Left Right Up Down]:%s" % (self.trlId, carsCrossedNow))
        return carsCrossedNow

    # minor road small lenght area detector data
    def getLoopAreaDetectorData(self):
        carsLoopArea = self.getData(traci.lanearea.getLastStepVehicleNumber, self.loopAreaDetectors)
        if self.debug:
            print("In Intersection %s: loop area detectors [Up Down]:%s" % (self.trlId, carsLoopArea))
        return carsLoopArea

    def dataForLoopController(self):
        cData = np.hstack( (self.getLoopDetectorData(),self.getLoopAreaDetectorData()) )
        return cData

    # Co2 and Co  emission calculation
    def getEmission(self):
        indx = self.sIndex
        emissionOutCo2 = 0
        emissionOutCo = 0
        carsCo2Emission = self.getData(traci.lanearea.getLastStepVehicleIDs, self.areaDetectors)
        out = list(sum(carsCo2Emission, ()))
        for i in range(len(out)):
            emissionOutCo2 += traci.vehicle.getCO2Emission(out[i])
            emissionOutCo += traci.vehicle.getCOEmission(out[i])
        self.totalCo2Emission += emissionOutCo2
        self.totalCoEmission += emissionOutCo
        if self.debug:
            pass
            # print("In Intersection %s: Co2 Emission (mg):%s" % (self.trlId, self.totalCo2Emission))
            # print("In Intersection %s: Co Emission (mg):%s" % (self.trlId, self.totalCoEmission))
        return emissionOutCo2,emissionOutCo

    def dataForIntelligentController(self):
        cIData = np.hstack(( self.getArrivalCars(),self.getJammedCars()))
        cIJammedLength = self.getJammedCarsLength()
        self.getEmission()
        return cIData,cIJammedLength

def getThroughput(func, dets):
    numDet = len(dets)
    res = [0] * numDet
    for deti in range(0,numDet):
        res[deti] = func(dets[deti])
    return res

# def motorWaiting(areaDetectors):
#     count = 0
#     vehicleIds = traci.lanearea.getLastStepVehicleIDs(areaDetectors)
#     motorId = traci.lanearea.getLastStepHaltingNumber(areaDetectors)
#     print("vehicle ids:",vehicleIds)
#     motorString = str(vehicleIds)
#     for i in vehicleIds:
#         if i.startswith("motorCycle",0,10):
#             count += 1
#     for j in vehicleIds:
#         print("vehicle waitng time:",traci.vehicle.getWaitingTime(j))
#     return count
# strategoTimer = [0,0,0,0,0]
# areaDetectors = [1,2,16,18]

greenTimer = np.arange(len(trafficLightId))
redTimer = np.arange(len(trafficLightId))

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
# ysample = random.sample(range(0, 500), 250)
# print("ysample:",ysample)
xdata = []
ydata = []
x1data = []
y1data = []

def oneTimePlotIntialization(x_end,y_end):
    plt.show()
    axes = plt.gca()
    axes.set_xlim(0, x_end)
    axes.set_ylim(0, y_end)
    line, = axes.plot(xdata, ydata, 'r-')
    line1, = axes.plot(x1data, y1data, 'g-')
    return line,line1

def plotGraph(x_data,y_data,x1_data,y1_data,line,line1):

    xdata.append(x_data)
    ydata.append(y_data)

    x1data.append(x1_data)
    y1data.append(y1_data)

    line.set_xdata(xdata)
    line.set_ydata(ydata)

    line1.set_xdata(x1data)
    line1.set_ydata(y1data)

    plt.draw()
    plt.pause(1e-17)
    time.sleep(0.1)

    # loop controllers

def extend(ext, bound, extTime):
    ext = ext + extTime
    return ext

def actuatedController(trlId, phaseNS, phaseToNS, phaseWE, phaseToEW, maxGreenNS, maxGreenEW, yellow, ic_minGreen,
                   phaseNow, timeInPhaseNow, phaseTimeNow, count_timeNow, nextPhaseNow, loopDet, areaDet):
    if phaseNow == phaseNS[trlId] or phaseNow == phaseWE[trlId]:  # we controll the green time
        traci.trafficlights.setPhaseDuration(trafficLightId[trlId], 5000)
    loopDetInfo = loopDet
    areDetInfo = areaDet
    if phaseNow == phaseWE[trlId]:  # Green in B direction
        if timeInPhaseNow >= maxGreenEW[trlId] or phaseTimeNow <= 0:
            # Goto yellow
            traci.trafficlights.setPhase(trafficLightId[trlId], phaseToNS[trlId])
            phaseNow = phaseToNS[trlId]
            nextPhaseNow = phaseNS[trlId]
            timeInPhaseNow = 0
        else:  # Check if we shoud extend the phase timer
            phaseTimeNow -= 1
            if loopDetInfo[0] >= 1 or loopDetInfo[1] >= 1:
                phaseTimeNow = extend(phaseTimeNow, maxGreenEW[trlId], 4.0)
            cars_on_AreDet = sum(areDetInfo) > 0
            if cars_on_AreDet:  # Make sure the time ticks while we stay in one phase
                phaseTimeNow += 1
        timeInPhaseNow += 1
    elif phaseNow == phaseNS[trlId]:  # Green in A direction
        if timeInPhaseNow >= maxGreenNS[trlId] or phaseTimeNow <= 0:
            # Goto yellow
            traci.trafficlights.setPhase(trafficLightId[trlId], phaseToEW[trlId])
            phaseNow = phaseToEW[trlId]
            nextPhaseNow = phaseWE[trlId]
            timeInPhaseNow = 0
        else:
            cars_on_AreDet = sum(areDetInfo) > 0
            if loopDetInfo[0] == 1 or loopDetInfo[1] == 1 or cars_on_AreDet:
                count_timeNow = True
            if count_timeNow:  # This phase is the resting phase
                if loopDetInfo[2] == 1 or loopDetInfo[3] == 1:
                    phaseTimeNow = extend(phaseTimeNow, maxGreenNS[trlId], 4.0)
                if loopDetInfo[2] == 1 or loopDetInfo[3] == 1:
                    phaseTimeNow = extend(phaseTimeNow, maxGreenNS[trlId], 4.0)
                timeInPhaseNow += 1
                phaseTimeNow -= 1
    else:  # In yellow
        if timeInPhaseNow == yellow[trlId]:
            # At the end of yellow the timeing variables are reset, the min green time is 10
            timeInPhaseNow = 0
            phaseTimeNow = ic_minGreen[trlId]
            phaseNow = nextPhaseNow
            traci.trafficlights.setPhase(trafficLightId[trlId], phaseNow)
            # traci.trafficlights.setPhaseDuration(idTL, 60)
            count_timeNow = False
        else:
            timeInPhaseNow += 1
    phase[trlId] = phaseNow
    nextPhase[trlId] = nextPhaseNow
    phaseTime[trlId] = phaseTimeNow
    timeInPhase[trlId] = timeInPhaseNow
    count_time[trlId] = count_timeNow

    # return phaseNow

def writeFile(row):
    # create file(if no file) and append data
    with open('trafficWaiting.csv', 'a') as csvFile:
        writer = csv.writer(csvFile)
        writer.writerow(row)
    csvFile.close()
def loadMaximumActuated(load):
    if load == "Case1Low":
        maxGreenEW = np.zeros(20, dtype=int) + 25
        maxGreenNS = np.zeros(20, dtype=int) + 40
    if load == "Case1Mid":
        maxGreenEW = np.zeros(20, dtype=int) + 35
        maxGreenNS = np.zeros(20, dtype=int) + 55
    if load == "Case1High":
        maxGreenEW = np.zeros(20, dtype=int) + 55
        maxGreenNS = np.zeros(20, dtype=int) + 85
    if load == "Case2":
        maxGreenEW = np.zeros(20, dtype=int) + 50
        maxGreenNS = np.zeros(20, dtype=int) + 60
    if load == "Case3":
        maxGreenEW = np.zeros(20, dtype=int) + 40
        maxGreenNS = np.zeros(20, dtype=int) + 40
    if load == "Case4":
        maxGreenEW = np.zeros(20, dtype=int) + 65
        maxGreenNS = np.zeros(20, dtype=int) + 35

    return maxGreenEW,maxGreenNS
def emissionCalculation(vehicleList,mode):
    sum = 0
    for vehId in vehicleList:
        if mode == "CO":
            sum += traci.vehicle.getCOEmission(vehId)
        if mode == "CO2":
            sum += traci.vehicle.getCO2Emission(vehId)
        if mode == "WaitingTime":
            if traci.vehicle.getSpeed(vehId) < 0.1:
                sum += 1
    return sum
def run():
    """execute the TraCI control loop"""
    step = 0
    strategoTimerTicks = 0
    crossedCars = 0
    # load fixed and actuated timing for traffic light
    for i in range(len(trafficLightId)):
        traci.trafficlights.setProgram(trafficLightId[i],options.load)

    maxGreenEW,maxGreenNS = loadMaximumActuated(options.load)

    print("%s controller is working in %s now............." %(options.controller,options.load))
    totalWaitingTime = 0
    totalCo2 = 0.0
    totalCo = 0.0
    # line,line1 = oneTimePlotIntialization(3000,15)
    nextPhaseNow = np.arange(250).reshape(5,50)
    trafficLightObj = list()
    queueLength = 0
    waitingTime = 0
    carJam = []
    carArrv = []
    timeVerJammedCars =[]
    timeVerQueuedCars =[]
    totalCOemision = []
    totalCO2emision = []
    totalWaitingtimeFrom = []
    for i in range(20):
        trafficLightObj.append( TrafficLight(str(i), areaDetectorFifty[i], loopDetectorFifity[i], loopAreaDetectorFifity[i], areaDetectorFiftySeqIndex[i],loopDetectorFiftySeqIndex[i],False))
    # t1 = TrafficLight("1", areaDet, loopDet, loopArea, sIndex,sIndexLoop,False)
    # t2 = TrafficLight("1", areaDet, loopDet, loopArea, sIndex,sIndexLoop,False)
    # while traci.simulation.getMinExpectedNumber() > 0:
    currentIntelligentTimer = 20
    oneTimeRun = True
    previousPhase = np.zeros(20, dtype=int)
    currentLoad = 100
    stepPerLoad = []
    # while traci.simulation.getMinExpectedNumber() > 0:
    while step <= int(options.step):
        # traci.switch("static")
        # traci.simulationStep()
        # y = sum(t1.getJammedCars())
        # y1 = sum(t1.getArrivalCars())
        # # plotGraph(step, y, step, y1, line, line1)
        # intl, ql = t1.dataForIntelligentController()
        # print("Total waiting Time in Static:",t1.totalWaitingTime)
        # traci.switch("loop")
        traci.simulationStep()
        step = step + 1
        jamCarsOneStep = 0
        queueCarsOneStep = 0
# ------------------------- Output data ---------------------------------------------------------------------------
        for outdata in range(0, 20):
            jamCarsOneStep += sum(trafficLightObj[outdata].getWaitingCars())
            queueCarsOneStep += sum(trafficLightObj[outdata].getJammedCarsLength())
        timeVerJammedCars.append(jamCarsOneStep)
        timeVerQueuedCars.append(queueCarsOneStep)

        # -----------------------------------------------------------------------------------------------------
        throughput = getThroughput(traci.inductionloop.getLastStepVehicleNumber, throughputLoopDetectors)
        crossedCars = crossedCars+ sum(throughput)
        #------------------ Emission calculation ---------------------------------------
        vehIdsList = traci.vehicle.getIDList()
        totalCOemision.append(emissionCalculation(vehIdsList,"CO"))
        totalCO2emision.append(emissionCalculation(vehIdsList,"CO2"))
        totalWaitingtimeFrom.append(emissionCalculation(vehIdsList,"WaitingTime"))
        # # print("vehicle ids:",traci.vehicle.getIDList())
        # for vehId in vehIdsList:
        #     # print("Co2 emission:",traci.vehicle.getCO2Emission(vehId))
        #     # print("Co emission:", traci.vehicle.getCOEmission(vehId))
        #     totalCOemision.append(traci.vehicle.getCO2Emission(vehId))
        #     if traci.vehicle.getSpeed(vehId) < 0.1:
        #         print("Waiting time: ", traci.vehicle.getSpeed(vehId),vehId)

        # print("crossed cars",crossedCars)
        # print("\rCars passed count:  {}".format(crossedCars), end="")
        # print("\rTime Step        :  {}".format(step), end="")
        # print("\n")
        # for outdata in range(0,20):
        #     trafficLightObj[outdata].getJammedCarsLength()
        #     trafficLightObj[outdata].getArrivalCars()
        #     # trafficLightObj[outdata].getWaitingCars()
        #     # queueLength += trafficLightObj[outdata].totalQueueLength
        #     # waitingTime += trafficLightObj[outdata].totalWaitingTime
        #     # print("In Traffic light %s: %s Hours" %(outdata+1,trafficLightObj[outdata].totalWaitingTime))
        #     print("Traffic Light: %s Arrival Cars: %s " % (outdata+ 1 , trafficLightObj[outdata].getArrivalCars()))
        #     print("Traffic Light: %s Jammed Cars: %s " % (outdata + 1, trafficLightObj[outdata].getJammedCars()))
            # print("Traffic Light: %s waiting Cars: %s " % (outdata + 1, trafficLightObj[outdata].getWaitingCars()))
            # print("Traffic Light: %s Detector details: %s " % (outdata + 1, trafficLightObj[outdata].dataForLoopController()))
    #     #------------------------------------------------------------------------------------------------------

        # get the current loaded capacity

        if step % 100 == 0:

            for trfLgt in range(0, 20):
                loadInADirection = trafficLightObj[trfLgt].direction_A
                loadInBDirection = trafficLightObj[trfLgt].direction_B
                for lc in range(len(loadCapacity)):
                    if loadCapacity[lc] >= loadInADirection:
                        maximumTimer_A[trfLgt] = maxGreenTimeforLoad[lc]
                    if loadCapacity[lc] >= loadInBDirection:
                        maximumTimer_B[trfLgt] = maxGreenTimeforLoad[lc]
                        break
            for trf in range(len(trafficLightId)):
                currentLoad = currentLoad + sum(trafficLightObj[trf].getArrivalCars())
            stepPerLoad.append(currentLoad)
            for lc in range(len(loadCapacity)):
                if (loadCapacity[lc] * 30 ) >= currentLoad:
                    currentIntelligentTimer = intelligentTimer[lc]
                    currentLoad = 0
                    break
            # writing time step and load
        # ------------------------cheking purpose-----------------------------
        # for a in range(16, 17):
        #     print("cars arrival in %s is %s" % (a + 1, trafficLightObj[a].getArrivalCars()))
        #     print("cars jammed in %s is %s" % (a + 1, trafficLightObj[a].getJammedCars()))
        # print("loop dec value:",throughput)
        # print("crossed cars:",crossedCars)
        # arrr= trafficLightObj[0].getArrivalCars()
        # print("A direction Cars:",AreaOne_A)
        # print("B direction Cars:",AreaOne_B)

        # y1 = sum(t2.getJammedCars())
        # y1 = sum(t1.getArrivalCars())
        # intl,ql = t2.dataForIntelligentController()
        # print("Loop controller", t1.dataForLoopController())
        # t1.getEmission()
        # print("Inte controller",intl )
        # print("Inte controller length",ql )
        # print("Total waiting Time in Loop:",t2.totalWaitingTime)
        # print("Total waiting Time:",t1.totalQueueLength)

        # ------------------------------------ Loop Controller ------------------------------------------------------
        if options.controller == "Actuated":
         for i in range(20):

            loopDet1 = trafficLightObj[i].getLoopDetectorData()
            loopArea1 = trafficLightObj[i].getLoopAreaDetectorData()
            actuatedController(i,phaseNS,phaseToNS,phaseWE,phaseToEW,maxGreenNS,maxGreenEW,yellow,ic_minGreen,phase[i],timeInPhase[i],phaseTime[i],
                                count_time[i],nextPhase[i],loopDet1,loopArea1)
         if oneTimeRun:
            print("--------------Actuated controller is working now:------------ ")
            oneTimeRun = False

         # ------------------------------------ Intelligent Controller ------------------------------------------------------

         # calling intelligent controller
        if options.controller == "Intelligent":
         if oneTimeRun:
            print("--------------------------------Intelligent controller is working now:--------------------------------------")
            oneTimeRun = False
         for a in range(0,20):
            # print("cars arrival in %s is %s" %(a+1,trafficLightObj[a].getArrivalCars()))
            # print("cars jammed in %s is %s" %(a+1,trafficLightObj[a].getJammedCars()))
            carJam.append(trafficLightObj[a].getJammedCars())
            carArrv.append(trafficLightObj[a].getArrivalCars())

        # print("cars jammed list:",carJam)
         carsJam = []
         carsArrv = []
         for b in range(0,20):
            carsJam = carsJam + carJam[b]
            carsArrv = carsArrv + carArrv[b]
         carJam.clear()
         carArrv.clear()
         if strategoTimerTicks <= 0:
            nextPhaseNow = callUppaalStratego(carsJam,carsArrv,greenTimer,redTimer,maximumTimer_B,maximumTimer_A,previousPhase)
            print("Intelligent Timer : %s step: %s" % (currentIntelligentTimer,step))
            strategoTimerTicks = currentIntelligentTimer
            for a in range(0, 20):
                print("cars arrival,Jam in %s %s is %s phase:%s" %(a+1,trafficLightObj[a].getArrivalCars(),trafficLightObj[a].getJammedCars(),nextPhaseNow[a][0:20]))
                print("GreenTimer-A: %s GreenTimer-B: %s Max-A: %s Max-B: %s" %(redTimer[a],greenTimer[a],maximumTimer_A[a],maximumTimer_B[a]))
         else:
            for i in range(0,20):
                    traci.trafficlight.setPhase(trafficLightId[i], nextPhaseNow[i][strategoTimerTicks])
                    previousPhase[i] = nextPhaseNow[i][currentIntelligentTimer-3]
                    if nextPhaseNow[i][strategoTimerTicks] == 2:
                        greenTimer[i] += 1
                    if nextPhaseNow[i][strategoTimerTicks] == 0:
                        redTimer[i] += 1
                    if nextPhaseNow[i][strategoTimerTicks] == 3:
                        redTimer[i] = 0
                        greenTimer[i] = 0
            strategoTimerTicks -= 1

    traci.close()
    detWaitingTime = np.arange(20)
    detQueueLength = np.arange(20)
    #
    for i in range(20):
        print("In Traffic light %s: %s Hours" % (i + 1, trafficLightObj[i].totalWaitingTime))
        detWaitingTime[i] = trafficLightObj[i].totalWaitingTime
        detQueueLength[i] = trafficLightObj[i].totalQueueLength
    detWaitingTime = np.around(detWaitingTime / 3600,2)
    detQueueLength = np.around(detQueueLength/1000 ,2)
    print("Waiting time from detectors:",sum(detWaitingTime))
    print("Queue length from detectors:", sum(detQueueLength))
    print("time verses cars:",timeVerJammedCars)
    # writing required data into file
    plottingPurpose.writeToFile("trafficWaiting.csv", stepPerLoad)
    calculateWaitingTime.writingPlottingData(detWaitingTime,options.controller+"Bar",options.load)
    calculateWaitingTime.writingPlottingData(timeVerJammedCars,options.controller+"Line",options.load)
    plottingPurpose.writeResult(sum(totalCOemision), sum(totalCO2emision), sum(totalWaitingtimeFrom), sum(detQueueLength) * 1000, crossedCars / step, options.controller + options.step + "-" + options.load, True)
    sys.stdout.flush()

def get_options(controllerNameEx,cases):
    optParser = optparse.OptionParser()
    controllerName = ("Intelligent","Fixed-Time","Actuated")
    optParser.add_option("--nogui", action="store_true",
                         default=True, help="run the commandline version of sumo")
    optParser.add_option("--controller", type="string", dest="controller", default= controllerNameEx)
    optParser.add_option("--step", type="string", dest="step", default="7200")
    optParser.add_option("--load", type="string", dest="load", default=cases)
    options, args = optParser.parse_args()
    return options

# this is the main entry point of this script
if __name__ == "__main__":

    controllerName = ('Fixed-Time', 'Actuated','Intelligent')
    cases = ["Case1Low","Case1Mid","Case1High","Case2","Case3","Case4"]
    # controllerName = [controllerName[1],controllerName[2]]
    # cases = ['Case2','Case3','Case4']
    for c in cases:
        plottingPurpose.writeToFile("results/resultOfExperiments.csv", "----------------------------------------------------" + c +
                         "------------------------------------------------------")
        for i in controllerName:
            options = get_options(i,c)
    # this script has been called from the command line. It will start sumo as a
    # server, then connect and run
            if options.nogui:
                sumoBinary = checkBinary('sumo')
            else:
                sumoBinary = checkBinary('sumo-gui')
            # gerenate route for the cases
            generateRouteForTwenty.generate_routefileAhmFiftyOsm(c, "ahm2PhaseOsmFiftyLoop.rou.xml", 278)

    # first, generate the route file for this simulation
    # generate_routefile()

    # this is the normal way of using traci. sumo is started as a
    # subprocess and then the python script connects and runs
    # traci.start(["sumo", "-c", "sim1.sumocfg"], label="sim1")
    # traci.start(["sumo", "-c", "sim2.sumocfg"], label="sim2")
            traci.start([sumoBinary, "-c", "twentyJunctionsAhm/ahm2PhaseOsmLoop.sumocfg","--tripinfo-output", "results/"+options.controller+"Tripfile.xml"],label="static")
    # traci.start([sumoBinary, "-c", "twentyJunctionsAhm/ahm2PhaseOsmLoop.sumocfg", "--tripinfo-output",
    #              "twentyJunctionsAhm/tripinfoInte.xml", "--emission-output", "twentyJunctionsAhm/emiInte.xml"],label="loop")
            run()


#This will mainly monitor the UPS status and Internet Connection
import time
import requests
import json
from IPython.display import HTML
import tools
from ppadb.client import Client as AdbClient
import time
from bs4 import BeautifulSoup
import urllib.request
import smtplib
from influxdb import InfluxDBClient
from datetime import datetime

def Facilities_Monitoring (host, port, database,url, timeout,stop):

    #Defining json config file pathing. Change this when moving code from PC to PC.
    json_file_path = "/home/eliade/Desktop/Annealing_Alarming/Python_Grafana/conf_files/facilities_conf.json"

    #Checking if stop condition is active when first starting the code.
    if stop ():
        print("Conditions not met for facilities_mon.")

    else:
        #Enter while loop
        while(True):
            print("\n#############################\n")
            timeset=datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')

            #Opening json file and checking if it can open. Otherwise sending email
            try:
                with open(json_file_path,"r") as file:
                    json_conf = json.load(file)

            except Exception as e:
                print("Cannot open json file. Reason: "+str(e))
                tools.SendEmail_mem()

            #Establishing InfluxDB connection and checking it. Sending email if no connection:
            try:
                client = InfluxDBClient(host=host,port=port,database=database)

            except Exception as e:
                print("Could not establish connection to InfluxDB server. Reason: " + str(e))
                tools.SendEmail(json_conf,"INF")
                tools.SendEmail_mem()

            #Checking UPS activation condition (time of battery is less than 50 min. Normal functioning parameters are battery life >50 min)

            #reading value and configuring alarm flag with its specific value.
            try:

                remaining_time,mode = tools.UPS_rd(json_conf)
                json_conf["Call-Monitor_Variables"]["SEU"] = 0
                print("Mode:"+mode)
                if "L" in mode:
                    mode=1
                elif "B" in mode:
                    mode=0

                json_data=[{
                    "measurement":"UPS_Annealing_Monitor",
                    "time":timeset,
                    "fields": {
                        "mode":mode,
                        "remaining_time":remaining_time
                    }
                }]
                client.write_points(json_data)
                #Checking UPS mode
                if mode==0 and json_conf["Call-Monitor_Variables"]["UFM"]==0:
                    json_conf["Call-Monitor_Variables"]["UFM"]=1
                    #Initiating call sequence to the persons in charge as alarm is triggered. (Pause of 60 seconds between sequence calls.)
                    for phone in json_conf["Call-Monitor_Variables"]["phone_array"]:

                        for i in range(3):

                            tools.SIMCall(phone, json_conf)
                else:
                    json_conf["Call-Monitor_Variables"]["UFM"]=0

                #Checking remaining time of UPS
                if remaining_time <= json_conf["Call-Monitor_Variables"]["remaining_time_th"] and json_conf["Call-Monitor_Variables"]["UFT"]==0:

                    json_conf["Call-Monitor_Variables"]["UFT"]=1
                    #Initiating call sequence to the persons in charge as alarm is triggered. (Pause of 60 seconds between sequence calls.)
                    for phone in json_conf["Call-Monitor_Variables"]["phone_array"]:

                        for i in range(3):

                            tools.SIMCall(phone, json_conf)

                else:
                    json_conf["Call-Monitor_Variables"]["UFT"]=0

                print("UPS Remaining Time:"+str(remaining_time))

            #Sending email if connection to UPS through network failed.
            except:
                if json_conf["Call-Monitor_Variables"]["SEU"] == 0:
                    tools.SendEmail(json_conf, "UPS")
                    json_conf["Call-Monitor_Variables"]["SEU"] = 1

            #Checking internet connection
            try:
                request = requests.get(url=url,timeout=timeout)

                print("\nConnection to Internet is active!\n")
                json_conf["Call-Monitor_Variables"]["SEN"] = 0

            except(requests.ConnectionError, requests.Timeout) as exception:

                print("No Internet connection detected!\n")

                #If request variable encountered an error, in this exception we will issue a call sequence, because of internet outage.
                if (json_conf["Call-Monitor_Variables"]["CN"] == 0):

                    for phone in json_conf["Call-Monitor_Variables"]["phone_array"]:

                        for i in range(3):

                            tools.SIMCall(phone, json_conf)

                    json_conf["Call-Monitor_Variables"]["CN"]=1

            #Checking stop condition.
            if stop():
                print("Stopping Initiated for facilities_mon!")
                time.sleep(1)
                break

            #Updating json file flags for alarms
            with open(json_file_path,"w") as file:
                json.dump(json_conf, file,indent = 2)

            #Waiting time
            time.sleep(30)


from random import randint
from kivy.uix.boxlayout import BoxLayout
from kivy.core.audio import SoundLoader
from kivy.app import App
from kivy.config import Config
from kivy.uix.image import Image

Config.set('graphics', 'width', '360')
Config.set('graphics', 'height', '800')
Config.set('graphics', 'resizable', 'false')

number_correct_answers = 0
number_question = 1

question_list = [['https://zamanilka.ru/wp-content/uploads/2022/05/smeshariki-krosh-kartinki-23.jpg', 'Крош', 'Кролик', 'Зайка', 'Мики', 1],
                 ['https://mykaleidoscope.ru/x/uploads/posts/2022-09/1663635911_1-mykaleidoscope-ru-p-zloi-kar-karich-krasivo-1.jpg',
                     'Ворон', 'Кар-карыч', 'Каркун', 'Карыч', 2],
                 ['https://i.ytimg.com/vi/lPVtHWVwtWE/maxresdefault.jpg',
                     'Ежик', 'Колючка', 'Ежидзе', 'Клим', 1],
                 ['https://100-bal.ru/pars_docs/refs/131/130143/130143_html_371854c8.jpg', 'Филинн',
                  'Совунья', 'Сова', 'Совушка', 2],
                 ['https://phonoteka.org/uploads/posts/2023-03/1679946865_phonoteka-org-p-smeshariki-nyusha-oboi-krasivo-31.jpg',
                  'Мила', 'Нюша', 'Пигги', 'Свинка', 2],
                 ['http://edge2.dtlab.ru/image/screenshot/PSTGMLT014623.jpg',
                  'Бараш', 'Барашка', 'Баран', 'Баранидзе', 1],
                 ['https://webmg.ru/wp-content/uploads/2022/11/i-22-53.jpeg',
                  'Оленеш', 'Лоскут', 'Лосяш', 'Лось', 3],
                 ['https://mykaleidoscope.ru/x/uploads/posts/2022-09/1663252506_5-mykaleidoscope-ru-p-zloi-kopatich-oboi-5.jpg',
                  'Мишка', 'Медведь', 'Мишка фреди', 'Копатыч', 4],
                 ['https://flomaster.club/uploads/posts/2023-01/1674059143_flomaster-club-p-pin-smeshariki-risunok-pinterest-14.jpg',
                  'Пин', 'Пингвин', 'Пингвиша', 'Лоло', 1],
                 ['https://m.media-amazon.com/images/M/MV5BZjA1MDhiYmEtODk0ZS00NjAyLTgwYmItMjA0Y2M3ZGE5ZTNiXkEyXkFqcGdeQXVyNTc0NjY1ODk@._V1_FMjpg_UX1000_.jpg', 'Панди',
                  'Панда', 'Мила', 'Степаша', 1],
                 ['https://i.ytimg.com/vi/kkvOCjjzHp4/maxresdefault.jpg',
                  'Боба', 'Руби', 'Биба', 'Биби', 4],
                 ['https://avatars.dzeninfra.ru/get-zen_doc/5234097/pub_60f16a93a7eab75c27c7d17f_60f17de2cf9db26dda648fa1/scale_1200',
                  'Мышарик', 'Мышь', 'Крыс', 'Микки', 1],
                 ['https://i.ytimg.com/vi/WNzGSfqO5nE/maxresdefault.jpg',
                  'Железяка', 'Милли', 'Железная няня', 'Няня', 3],
                 ['https://vignette.wikia.nocookie.net/shararam-smeshi/images/a/a5/%D0%A5%D1%80%D1%83%D0%BC.png/revision/latest?cb=20180825013800&path-prefix=ru', 'Дракоша', 'Антошка', 'Хрум', 'Тимоша', 3],
                 ['https://sun9-66.userapi.com/impf/c626722/v626722802/162c7/3BqL9rlJZ5E.jpg?size=604x604&quality=96&sign=84cf662044a22014c6afa4f6d908a69a&type=album', 'Лягушка', 'Жаба', 'Лягуш', 'Шиша', 1]]

class MainWidget(BoxLayout):
    def new_question(self):
        img_result = None  # Initialize img_result to None

        if len(question_list) > 0:
            question = question_list[randint(0, len(question_list)-1)]
            self.ids['img_question'].source = question[0]
            self.ids['btn_answer1'].text = question[1]
            self.ids['btn_answer2'].text = question[2]
            self.ids['btn_answer3'].text = question[3]
            self.ids['btn_answer4'].text = question[4]
        else:
            text = '\n Результат: ' + str(number_correct_answers) + ' из 15.'
            self.ids['lbl_question'].text = text
            self.remove_widget(self.ids['img_question'])
            self.remove_widget(self.ids['layout_btns'])
            if number_correct_answers >= 12:
                text1 = 'Вы - Стильный бараш'
                self.ids['lbl_result'].text = text1
                self.ids['img_result'].source = 'source/Barash.jpg'
            elif number_correct_answers >= 9:
                text1 = 'Вы - Лосяш'
                self.ids['lbl_result'].text = text1
                self.ids['img_result'].source = 'source/Losyash.jpg'

            elif number_correct_answers >= 6:
                text1 = 'Вы - Ежидзе'
                self.ids['lbl_result'].text = text1
                self.ids['img_result'].source = 'source/Ezhidze.jpg'

            elif number_correct_answers >= 3:
                text1 = 'Вы - Крош'
                self.ids['lbl_result'].text = text1
                self.ids['img_result'].source = 'source/Krosh.jpg'

            elif number_correct_answers >= 0:
                text1 = 'Вы - Бунтующий ежик'
                self.ids['lbl_result'].text = text1
                self.ids['img_result'].source = 'source/Bunt.jpg'

            self.ids['img_result'].opacity = 1

    def btn_pressed(self, number_button):
        question: list
        for i in question_list:
            if (i[0] == self.ids['img_question'].source):
                question = i
                break  # Перебор списка, чтобы выбрать вопрос который выпал из списка
        global number_correct_answers
        global number_question
        if (number_button == question[5]):
            number_correct_answers += 1

        number_question += 1
        question_list.remove(question)
        self.new_question()

class MainApp(App):
    def build(self):
        app = MainWidget()
        app.new_question()  # вызываем new_question из build метода, когда окно приложения готово
        return app

if __name__ == '__main__':
    music = SoundLoader.load('Disco.mp3')
    music.volume = 0.1
    music.play()

    MainApp().run()


from operator import attrgetter
from exact.Solution import Solution
from exact.read_file import lopez_ibanez_blum_format

class Dumas(object):
	"""Problem implementation"""

	def __init__(self, graph):
		"""The Dumas implementation takes a graph"""
		self.graph = graph

	def __repr__(self):
		"""Return a string representation of this object that can
		be evaluated as a Python expression."""
		n_vertices = len(self.graph.vertices())
		n_edges = len(self.graph.edges())
		print_this = "N_vertices: " + str(n_vertices) + ". E_edges: " + str(n_edges)
		return 'Dumas(%s)' % print_this

	__str__=__repr__
	"""The str and repr forms of this object are the same."""

	def run(self):
		"""
		Run method initializes the problem instances and gives the first recursive call.
		Returns
		--------
		solution : Final solution (object)
		"""
		S = list(self.graph.vertices())
		end_depot = self.graph.end
		solution = self.f(S, end_depot)
		solution = self.join_solution(solution, end_depot)
		return solution

	def f(self, S, j):
		"""
		Dumas exact algorithm for the TSPTW
		Literature: http://pubsonline.informs.org/doi/pdf/10.1287/opre.43.2.367

		Parameters
		--------
			S: Subset of unvisited nodes of the solution
			j: Final node of path. Contained in S.
		Returns
		--------
			End time t of a path starting at depot node,
			passing through every node in S exactly once,
			ending at node j (contained in S).
		"""

		if len(S)==2:
			return self.base_case(S, j)
		else:
			s = list(S)
			s.remove(j)
			feasible_solutions = []
			for i in s:

				if i!=self.graph.start:

					solution = self.f(s, i)
					if solution is None:
						# if None then no solutions feasibles
						continue

					new_solution = self.join_solution(solution, i)

					if new_solution.is_feasible():
						feasible_solutions.append(new_solution)
			return self.choose_sol(feasible_solutions)

	def choose_sol(self, solutions):
		"""
		Choose the least cost solution in the feasible solutions list.
		In case the feasible solutions is empty, returns None
		Parameters
		--------
			solutions: List of feasible solutions
		Returns
		--------
			solution Solution (object)
		"""
		if len(solutions)==0:
			# No feasible solutions
			return None
		else:
			# Returns the solution with minimum solution.cost
			return min(solutions, key=attrgetter('cost'))

	def join_solution(self, solution, vertex):
		"""
		Base case.
			f({1,j}, j) = tj      if (1,j) in E (edges)
			f({1,j}, j) = Inf     otherwise

		Returns new t_j
		t_j = max {a_1 + s_1 + t_ij, a_j}
		where
		a_j <= t_j <= b_j
		"""
		t_i = solution.last_time()
		t_ij = self.graph.time_edge(solution.last_vertex(), vertex)
		a_j = vertex.time_window[0]
		t_j = max([t_i + t_ij, a_j])
		solution.add_vertex(vertex, t_j)
		return solution

	def base_case(self, S, j):
		"""Create new solution"""
		solution = Solution(self.graph, self.graph.start)
		return solution


import argparse
import os
import copy
import shutil
import time

import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets

from fblib.util.classification.utils import convert_secs2time, time_string, time_file_str, AverageMeter
from fblib.networks.classification import se_resnet, mobilenet_v2, resnet, resnext
from fblib.util.mypath import Path

def parse_args():
    def str2bool(v):
        return v.lower() in ("yes", "true", "t", "1")

    parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
    parser.add_argument('--data', default=Path.db_root_dir('Imagenet'),
                        help='path to dataset')
    parser.add_argument('--arch', '-a', metavar='ARCH', default='x50')
    parser.add_argument('-j', '--workers', default=16, type=int, metavar='N',
                        help='number of data loading workers (default: 16)')
    parser.add_argument('--epochs', default=100, type=int, metavar='N',
                        help='number of total epochs to run')
    parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
                        help='manual epoch number (useful on restarts)')
    parser.add_argument('-b', '--batch-size', default=256, type=int, metavar='N',
                        help='mini-batch size (default: 256)')
    parser.add_argument('--lr', '--learning-rate', default=0.1, type=float, metavar='LR',
                        help='initial learning rate')
    parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
                        help='momentum')
    parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float, metavar='W',
                        help='weight decay (default: 1e-4)')
    parser.add_argument('--print-freq', '-p', default=200, type=int, metavar='N',
                        help='print frequency (default: 100)')
    parser.add_argument('--resume', default='', type=str, metavar='PATH',
                        help='path to latest checkpoint (default: none)')
    parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',
                        help='evaluate model on validation set')
    parser.add_argument('--n_gpu', type=int, default=8,
                        help='number of GPUs')
    parser.add_argument('--group_norm', type=str2bool, default=False,
                        help='Group Normalization')

    args = parser.parse_args()
    args.prefix = time_file_str()

    return args

def main():
    args = parse_args()
    best_prec1 = 0

    if not args.group_norm:
        save_dir = os.path.join(Path.exp_dir(), 'imagenet', args.arch)
    else:
        save_dir = os.path.join(Path.exp_dir(), 'imagenet', args.arch + '-GN')
    if not os.path.isdir(save_dir):
        os.makedirs(save_dir)
    log = open(os.path.join(save_dir, '{}.{}.log'.format(args.arch, args.prefix)), 'w')

    # create model
    print_log("=> creating model '{}'".format(args.arch), log)

    resol = 224
    if args.arch == 'res26':
        model = resnet.resnet26(pretrained=False, group_norm=args.group_norm)
    elif args.arch == 'res50':
        model = resnet.resnet50(pretrained=False, group_norm=args.group_norm)
    elif args.arch == 'res101':
        model = resnet.resnet101(pretrained=False, group_norm=args.group_norm)
    elif args.arch == 'x50':
        model = resnext.resnext50_32x4d(pretrained=False)
    elif args.arch == 'x101':
        model = resnext.resnext101_32x4d(pretrained=False)
    elif args.arch == 'res26-se':
        model = se_resnet.se_resnet26(num_classes=1000)
    elif args.arch == 'res50-se':
        model = se_resnet.se_resnet50(num_classes=1000)
    elif args.arch == 'res101-se':
        model = se_resnet.se_resnet101(num_classes=1000)
    elif args.arch == 'mobilenet-v2':
        model = mobilenet_v2.mobilenet_v2(pretrained=False, n_class=1000, last_channel=2048)

    print_log("=> Model : {}".format(model), log)
    print_log("=> parameter : {}".format(args), log)

    if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):
        model.features = torch.nn.DataParallel(model.features, device_ids=list(range(args.n_gpu)))
        model.cuda()
    else:
        model = torch.nn.DataParallel(model, device_ids=list(range(args.n_gpu))).cuda()

    # define loss function (criterion) and optimizer
    criterion = nn.CrossEntropyLoss().cuda()

    optimizer = torch.optim.SGD(model.parameters(), args.lr,
                                momentum=args.momentum,
                                weight_decay=args.weight_decay,
                                nesterov=True)

    # optionally resume from a checkpoint
    if args.resume:
        if os.path.isfile(args.resume):
            print_log("=> loading checkpoint '{}'".format(args.resume), log)
            checkpoint = torch.load(args.resume)
            args.start_epoch = checkpoint['epoch']
            best_prec1 = checkpoint['best_prec1']
            model.load_state_dict(checkpoint['state_dict'])
            optimizer.load_state_dict(checkpoint['optimizer'])
            print_log("=> loaded checkpoint '{}' (epoch {})".format(args.resume, checkpoint['epoch']), log)
        else:
            raise ValueError("=> no checkpoint found at '{}'".format(args.resume))

    cudnn.benchmark = True

    # Data loading code
    traindir = os.path.join(args.data, 'train')
    valdir = os.path.join(args.data, 'val')
    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                     std=[0.229, 0.224, 0.225])

    train_dataset = datasets.ImageFolder(
        traindir,
        transforms.Compose([
            transforms.RandomResizedCrop(resol),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            normalize,
        ]))

    train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True,
                                               num_workers=args.workers, pin_memory=True, sampler=None)

    val_loader = torch.utils.data.DataLoader(
        datasets.ImageFolder(valdir, transforms.Compose([
            transforms.Resize(256),
            transforms.CenterCrop(resol),
            transforms.ToTensor(),
            normalize,
        ])),
        batch_size=args.batch_size, shuffle=False,
        num_workers=args.workers, pin_memory=True)

    if args.evaluate:
        validate(val_loader, model, criterion)
        return

    filename = os.path.join(save_dir, 'checkpoint.{}.{}.pth.tar'.format(args.arch, args.prefix))
    bestname = os.path.join(save_dir, 'best.{}.{}.pth.tar'.format(args.arch, args.prefix))

    start_time = time.time()
    epoch_time = AverageMeter()
    for epoch in range(args.start_epoch, args.epochs):
        lr = adjust_learning_rate(optimizer, epoch, args)

        need_hour, need_mins, need_secs = convert_secs2time(epoch_time.val * (args.epochs - epoch))
        need_time = '[Need: {:02d}:{:02d}:{:02d}]'.format(need_hour, need_mins, need_secs)
        print_log(' [{:s}] :: {:3d}/{:3d} ----- [{:s}] {:s} LR={:}'.format(args.arch, epoch, args.epochs, time_string(),
                                                                           need_time, lr), log)

        # train for one epoch
        train(train_loader, model, criterion, optimizer, epoch, log, args)

        # evaluate on validation set
        prec1 = validate(val_loader, model, criterion, log, args)

        # remember best prec@1 and save checkpoint
        is_best = prec1 > best_prec1
        best_prec1 = max(prec1, best_prec1)
        save_checkpoint({
            'epoch': epoch + 1,
            'arch': args.arch,
            'state_dict': model.state_dict(),
            'best_prec1': best_prec1,
            'optimizer': optimizer.state_dict(),
            'args': copy.deepcopy(args),
        }, is_best, filename, bestname)
        # measure elapsed time
        epoch_time.update(time.time() - start_time)
        start_time = time.time()
    log.close()

def train(train_loader, model, criterion, optimizer, epoch, log, args):
    batch_time = AverageMeter()
    data_time = AverageMeter()
    losses = AverageMeter()
    top1 = AverageMeter()
    top5 = AverageMeter()

    # switch to train mode
    model.train()

    end = time.time()
    for i, (input, target) in enumerate(train_loader):
        # measure data loading time
        data_time.update(time.time() - end)

        target_var = target.cuda(non_blocking=True)
        input_var = input.requires_grad_()

        # compute output
        output = model(input_var)
        loss = criterion(output, target_var)

        # measure accuracy and record loss
        prec1, prec5 = accuracy(output.data, target_var, topk=(1, 5))
        losses.update(loss.item(), input.size(0))
        top1.update(prec1.item(), input.size(0))
        top5.update(prec5.item(), input.size(0))

        # compute gradient and do SGD step
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        # measure elapsed time
        batch_time.update(time.time() - end)
        end = time.time()

        if i % args.print_freq == 0:
            print_log('Epoch: [{0}][{1}/{2}]\t'
                      'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
                      'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
                      'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
                      'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
                      'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
                epoch, i, len(train_loader), batch_time=batch_time,
                data_time=data_time, loss=losses, top1=top1, top5=top5), log)

def validate(val_loader, model, criterion, log, args):
    batch_time = AverageMeter()
    losses = AverageMeter()
    top1 = AverageMeter()
    top5 = AverageMeter()

    # switch to evaluate mode
    model.eval()

    end = time.time()

    with torch.no_grad():
        for i, (input_var, target) in enumerate(val_loader):
            target_var = target.cuda(non_blocking=True)

            # compute output
            output = model(input_var)
            loss = criterion(output, target_var)

            # measure accuracy and record loss
            prec1, prec5 = accuracy(output.data, target_var, topk=(1, 5))
            losses.update(loss.item(), input_var.size(0))
            top1.update(prec1.item(), input_var.size(0))
            top5.update(prec5.item(), input_var.size(0))

            # measure elapsed time
            batch_time.update(time.time() - end)
            end = time.time()

            if i % args.print_freq == 0:
                print_log('Test: [{0}/{1}]\t'
                          'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
                          'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
                          'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
                          'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
                    i, len(val_loader), batch_time=batch_time, loss=losses,
                    top1=top1, top5=top5), log)

    print_log(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f} Error@1 {error1:.3f}'.format(top1=top1, top5=top5,
                                                                                error1=100 - top1.avg), log)

    return top1.avg

def save_checkpoint(state, is_best, filename, bestname):
    torch.save(state, filename)
    if is_best:
        shutil.copyfile(filename, bestname)

def adjust_learning_rate(optimizer, epoch, args):
    """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
    lr = args.lr * (0.1 ** (epoch // 30))
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr
    return lr

def accuracy(output, target, topk=(1,)):
    """Computes the precision@k for the specified values of k"""
    maxk = max(topk)
    batch_size = target.size(0)

    _, pred = output.topk(maxk, 1, True, True)
    pred = pred.t()
    correct = pred.eq(target.view(1, -1).expand_as(pred))

    res = []
    for k in topk:
        correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
        res.append(correct_k.mul_(100.0 / batch_size))
    return res

def print_log(print_string, log):
    print("{}".format(print_string))
    log.write('{}\n'.format(print_string))
    log.flush()

if __name__ == '__main__':
    main()


import torch
import torch.nn.functional as F

from ..builder import LOSSES
from .base import BaseWeightedLoss

@LOSSES.register_module()
class CrossEntropyLoss(BaseWeightedLoss):
    """Cross Entropy Loss.

    Support two kinds of labels and their corresponding loss type. It's worth
    mentioning that loss type will be detected by the shape of ``cls_score``
    and ``label``.
    1) Hard label: This label is an integer array and all of the elements are
        in the range [0, num_classes - 1]. This label's shape should be
        ``cls_score``'s shape with the `num_classes` dimension removed.
    2) Soft label(probablity distribution over classes): This label is a
        probability distribution and all of the elements are in the range
        [0, 1]. This label's shape must be the same as ``cls_score``. For now,
        only 2-dim soft label is supported.

    Args:
        loss_weight (float): Factor scalar multiplied on the loss.
            Default: 1.0.
        class_weight (list[float] | None): Loss weight for each class. If set
            as None, use the same weight 1 for all classes. Only applies
            to CrossEntropyLoss and BCELossWithLogits (should not be set when
            using other losses). Default: None.
    """

    def __init__(self, loss_weight=1.0, class_weight=None):
        super().__init__(loss_weight=loss_weight)
        self.class_weight = None
        if class_weight is not None:
            self.class_weight = torch.Tensor(class_weight)

    def _forward(self, cls_score, label, **kwargs):
        """Forward function.

        Args:
            cls_score (torch.Tensor): The class score.
            label (torch.Tensor): The ground truth label.
            kwargs: Any keyword argument to be used to calculate
                CrossEntropy loss.

        Returns:
            torch.Tensor: The returned CrossEntropy loss.
        """
        if cls_score.size() == label.size():
            # calculate loss for soft label

            assert cls_score.dim() == 2, 'Only support 2-dim soft label'
            assert len(kwargs) == 0, \
                ('For now, no extra args are supported for soft label, '
                 f'but get {kwargs}')

            lsm = F.log_softmax(cls_score, 1)
            if self.class_weight is not None:
                self.class_weight = self.class_weight.to(cls_score.device)
                lsm = lsm * self.class_weight.unsqueeze(0)
            loss_cls = -(label * lsm).sum(1)

            # default reduction 'mean'
            if self.class_weight is not None:
                # Use weighted average as pytorch CrossEntropyLoss does.
                # For more information, please visit https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html # noqa
                loss_cls = loss_cls.sum() / torch.sum(
                    self.class_weight.unsqueeze(0) * label)
            else:
                loss_cls = loss_cls.mean()
        else:
            # calculate loss for hard label

            if self.class_weight is not None:
                assert 'weight' not in kwargs, \
                    "The key 'weight' already exists."
                kwargs['weight'] = self.class_weight.to(cls_score.device)
            loss_cls = F.cross_entropy(cls_score, label, **kwargs)

        return loss_cls

@LOSSES.register_module()
class BCELossWithLogits(BaseWeightedLoss):
    """Binary Cross Entropy Loss with logits.

    Args:
        loss_weight (float): Factor scalar multiplied on the loss.
            Default: 1.0.
        class_weight (list[float] | None): Loss weight for each class. If set
            as None, use the same weight 1 for all classes. Only applies
            to CrossEntropyLoss and BCELossWithLogits (should not be set when
            using other losses). Default: None.
    """

    def __init__(self, loss_weight=1.0, class_weight=None):
        super().__init__(loss_weight=loss_weight)
        self.class_weight = None
        if class_weight is not None:
            self.class_weight = torch.Tensor(class_weight)

    def _forward(self, cls_score, label, **kwargs):
        """Forward function.

        Args:
            cls_score (torch.Tensor): The class score.
            label (torch.Tensor): The ground truth label.
            kwargs: Any keyword argument to be used to calculate
                bce loss with logits.

        Returns:
            torch.Tensor: The returned bce loss with logits.
        """
        if self.class_weight is not None:
            assert 'weight' not in kwargs, "The key 'weight' already exists."
            kwargs['weight'] = self.class_weight.to(cls_score.device)
        loss_cls = F.binary_cross_entropy_with_logits(cls_score, label,
                                                      **kwargs)
        return loss_cls


import numpy as np
import glob
import cv2
import time

#긴급상황호출
gin=0
def gin(_gin=1) :
    global gin
    gin=_gin
    nomal(8)

def nomal(sc) :
    sc=sc+6
    global src
    src = glob.glob('./img/man*.jpg')
    print(src)
    # 만약에 그이상의 시간을 넣었을때 예외처리
    cnt = len(src)
    if sc > cnt:
        sc = cnt - 1
    print(sc)
    sinho(sc)

def teapong() :
    global src
    src = glob.glob('./img/wind*.jpg')
    sinho()

def ston() :
    global src
    src = glob.glob('./img/ston*.jpg')
    sinho()

def sinho(sc=1) :

    gin=0
    idx = sc

    while True:

        img = cv2.imread(src[idx])

        if img is None: # 이미지가 없는 경우
            print('이미지없음')
            break
        resize_img = cv2.resize(img, dsize=(0, 0), fx=0.12, fy=0.1, interpolation=cv2.INTER_AREA)
        height, width = img.shape[:2]
        # 가로 ,세로
        mat = np.float32([[1, 0, 0], [0, 1, 1]])
        tran = cv2.warpAffine(resize_img, mat, (width, height))

        cv2.namedWindow('tran', cv2.WND_PROP_FULLSCREEN)
        cv2.setWindowProperty('tran', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)

        cv2.imshow("tran", tran)
        if cv2.waitKey(1000) >= 0: # 1초 동안 사진보여주는데 만약에 키보드 입력이 있으면 종료
            break

        # 사진을 다 보면 첫번째 사진으로 돌아감
        idx -= 1
        if idx < 0:
            idx = sc

        #긴급 신호를 받았을시에
        if gin==1 :
            if idx<=8 :
                idx+=5
                gin=0

    cv2.destroyAllWindows()

#test
# teapong()
# ston()
#teapong()

# def test() :
#     nomal(8)
#     time.sleep(3)
#     gin()
#
#
# test()


from tendril.authn.auth0 import Auth0PythonClient
from tendril.authn.auth0 import management_api
from tendril.authn.auth0 import is_m2m_client
from tendril.config import AUTH0_AUDIENCE_ID
from tendril.config import AUTH0_AUDIENCE

from tendril.utils import log
logger = log.get_logger(__name__, log.DEBUG)

@management_api
def get_resource_servers(auth0: Auth0PythonClient):
    return auth0.resource_servers

def get_resource_server():
    return get_resource_servers().get(AUTH0_AUDIENCE_ID)

def get_current_scopes():
    return {x['value']: x['description'] for x in get_resource_server()['scopes']}

def commit_scopes(scopes):
    logger.debug("Patching scopes on Auth0")
    rs = get_resource_servers()
    rs.update(AUTH0_AUDIENCE_ID,
              {'scopes': [{'value': k, 'description': v}
                          for k, v in scopes.items()]})

@management_api
def get_user_scopes(user_id, auth0: Auth0PythonClient):
    if is_m2m_client(user_id):
        logger.warn("Auth0 M2M client scopes must be manually managed.")
        return None
    return [x['permission_name'] for x in
            auth0.users.list_permissions(user_id, per_page=100)['permissions']]

@management_api
def add_user_scopes(user_id, scopes, auth0: Auth0PythonClient):
    if is_m2m_client(user_id):
        logger.warn("Auth0 M2M client scopes must be manually managed.")
        return None
    return auth0.users.add_permissions(
        user_id,
        [{"resource_server_identifier": AUTH0_AUDIENCE,
          "permission_name": x} for x in scopes])

@management_api
def remove_user_scopes(user_id, scopes, auth0: Auth0PythonClient):
    if is_m2m_client(user_id):
        logger.warn("Auth0 M2M client scopes must be manually managed.")
        return None
    return auth0.users.remove_permissions(
        user_id,
        [{"resource_server_identifier": AUTH0_AUDIENCE,
          "permission_name": x} for x in scopes])


##10-3

filepath = "files/guestbook.txt"

with open(filepath, 'a') as txt_file:
    while True:
        name = input('What is your name: ')

        if name == 'quit':
            quit()
        else:
            print("Hello " + name + ", Welcome!" )
            txt_file.write("My name is " + name + "\n")


n=int(input())

arr=[]
for i in range(n):
    arr.append(list(map(int,input().split())))

v=[]
ans=10000000000000
for i in range(n):
    v.append(i)

def dfs(idx,cnt,k):
    global ans
    if cnt==k:
        sum1,sum2=0,0
        start,link=[],[]
        for i in range(len(v)):
            if s[i]==1:
                start.append(i)
            else:
                link.append(i)

        for i in range(len(start)):
            for j in range(len(start)):
                sum1+=arr[start[i]][start[j]]

        for i in range(len(link)):
            for j in range(len(link)):
                sum2+=arr[link[i]][link[j]]
        #print(start,link)
        #print(sum1,sum2)
        ans=min(ans,abs(sum1-sum2))
        return

    for i in range(idx,len(v)):
        s[i]=1
        dfs(i+1,cnt+1,k)
        s[i]=0

for k in range(1,n//2+1):
    s=[0]*len(v)
    dfs(0,0,k)

print(ans)


import logging
from persistence import get_cursor
from models import Operators

LOGGER = logging.getLogger(__name__)

def update_balance(change: float, username: str, operator: Operators):
    with get_cursor() as cursor:
        LOGGER.debug('Requested to change balance of %s by %s', username, change)
        if operator == Operators.INCREMENT:
            LOGGER.debug('Incrementing balance')
            query = "UPDATE users SET balance = balance + %s WHERE username = %s;"
        else:
            LOGGER.debug('Decrementing balance for %s by %s', username, change)
            query = "UPDATE users SET balance = balance - %s WHERE username = %s;"
        cursor.execute(query,
            (
                change,
                username
            )
        )

def update_shares_owned(change: int, username: str, symbol: str, operator: Operators):
    if operator == Operators.INCREMENT:
        LOGGER.debug('Allocating %s shares to %s for symbol %s', change, username, symbol)
        query = """INSERT INTO shares_owned_by_user (company_symbol, username, shares_owned)
                           VALUES(%s, %s, %s)
                           ON CONFLICT (company_symbol, username)
                           DO UPDATE
                           SET shares_owned = shares_owned_by_user.shares_owned + EXCLUDED.shares_owned"""
    else:
        LOGGER.debug('Deallocating %s shares to %s for symbol %s', change, username, symbol)
        query = """INSERT INTO shares_owned_by_user (company_symbol, username, shares_owned)
                    VALUES(%s, %s, %s)
                    ON CONFLICT (company_symbol, username)
                    DO UPDATE
                    SET shares_owned = shares_owned_by_user.shares_owned - EXCLUDED.shares_owned"""
    with get_cursor() as cursor:
        cursor.execute(query, (symbol, username, change))

def get_shares_portfolio(username: str):
    with get_cursor() as cursor:
        LOGGER.debug('Getting shares owned for %s', username)
        query = """SELECT company_symbol, shares_owned FROM shares_owned_by_user
                WHERE username = %s
                ORDER BY company_symbol;"""
        cursor.execute(query, (username,))
        return cursor.fetchall()