import glob
import os
import pickle
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.patches import Rectangle
from blitzcurve.utils import setup_matplotlib_dark_background
import blitzcurve.utils as utils
import sys
import blitzcurve

def run_compare(data_dir, file_list="all", name_dict= None):
    """

    Parameters
    ----------
    data_dir : str
        Path to directory with the input text files.
    file_list : str, list
        List of files to analyse.
        E.g. ["10nM-FGC1-2min_aniso.txt", "10nM-FGC2-2min_aniso.txt"]
        Default is "all", which analyses all files in folder
    name_dict : dict
        Dictionary to rename long filenames for plotting.

    Returns
    -------

    Usage
    -----
    import blitzcurve
    data_dir = r"D:\data\20180229_TRdata"
    # fit
    blitzcurve.run_fit(data_dir, figs_to_plot=figs_to_plot, testing_mode=False)
    # compare
    name_dict = {"10nM-FGC1-2min_aniso.txt": "FGC1", "10nM-FGC2-2min_aniso.txt": "FGC2", "10nM-FGC3-2min_aniso.txt": "FGC3"}
    blitzcurve.run_compare(data_dir, name_dict=name_dict)
    """

    # create object with the compare file paths
    cfp = utils.CompareFilePaths(data_dir)

    setup_matplotlib_dark_background(plt)

    fc = utils.FlourescentColours()
    csv_files = glob.glob(os.path.join(data_dir, "*.txt"))

    # drop any files not in the list
    if file_list != "all":
        for csv in csv_files:
            if os.path.basename(csv) not in file_list:
                csv_files.remove(csv)

    summ_csv = os.path.join(data_dir, "summary", "fit_summary.csv")
    df = pd.read_csv(summ_csv, index_col=0)

    df["orig_names"] = df.index

    if name_dict is not None:
        # rename the index
        df.rename(index=name_dict, inplace=True)
    else:
        # no naming dict available
        # cut off the ".txt" in the filename before plotting.
        df.index = df.index.str[:-4]

    create_barcharts = True

    if create_barcharts:
        #########################################################################
        #                   Barchart maximum anisotropy                         #
        #########################################################################
        fig, ax = plt.subplots()
        width = 0.6
        df["r_max"].plot(kind="bar", ax=ax, color=fc.blue, width=width, label="segment 1")
        ax.set_ylabel(r"$r_{max}$", fontsize=16)
        # adjust margins around bars
        ax.set_xlim(-0.6, df.shape[0] - 0.4)
        ax.set_ylim(df["r_max"].min() - 0.005, df["r_max"].max() + 0.005)
        fig.tight_layout()
        fig.savefig(cfp.barchart_r_max)
        sys.stdout.write("\n{}".format(cfp.barchart_r_max))

        #########################################################################
        #                              Barchart r_inf                           #
        #########################################################################
        fig, ax = plt.subplots()
        width = 0.6
        df["r_inf"].plot(kind="bar", ax=ax, color=fc.blue, width=width, label="segment 1")
        ax.set_ylabel(r"$r_{inf}$", fontsize=16)
        # adjust margins around bars
        ax.set_xlim(-0.6, df.shape[0] - 0.4)
        ax.set_ylim(df["r_inf"].min() - 0.005, df["r_inf"].max() + 0.005)
        fig.tight_layout()
        fig.savefig(cfp.barchart_r_inf)
        sys.stdout.write("\n{}".format(cfp.barchart_r_inf))

        #########################################################################
        #               Barchart variable a, segments 1 and 2                   #
        #########################################################################

        #generate only dataframe with a_seg1 and a_seg2
        df_a_bars = pd.concat([df["a_seg1"], df["a_seg2"]], axis=1)
        df_a_bars.columns = ["a_seg1", "a_seg2"]

        fig, ax = plt.subplots()
        width = 0.8
        df_a_bars.plot(kind="bar", ax=ax, color=[fc.blue,fc.lemon], width=width, legend=False)
        #gets handles for the legend (also gets and labels - rudimentary)
        handles, labels = ax.get_legend_handles_labels()
        #brings segment b to secondary y axis
        ax2 = ax.twinx()
        for r in ax.patches[len(df_a_bars):]:
            r.set_transform(ax2.transData)
        #defines labels
        labels = ["segment 1", "segment 2"]

        ax.set_ylabel("variable a in segment 1", color=fc.blue)
        ax.tick_params("y", colors=fc.blue)
        ax2.set_ylabel("variable a in segment 2", color=fc.lemon)
        ax2.tick_params("y", colors=fc.lemon)
        # adjust margins around bars
        ax.set_xlim(-0.6, df.shape[0] - 0.4)
        ax.set_ylim(df["a_seg1"].min() - 0.005, df["a_seg1"].max() + 0.01)
        ax2.set_ylim(df["a_seg2"].min() - 0.005, df["a_seg2"].max() + 0.01)
        fig.legend(handles,labels,ncol=2, loc="upper center", bbox_to_anchor=(0, 0.85, 1.1, .102))

        fig.tight_layout()
        fig.savefig(cfp.barchart_variable_a_png)
        sys.stdout.write("\n{}".format(cfp.barchart_variable_a_png))

        #########################################################################
        #               Barchart variable b, segments 1 and 2                   #
        #########################################################################

        #generate only dataframe with b_seg1 and b_seg2
        df_b_bars = pd.concat([df["b_seg1"], df["b_seg2"]], axis=1)
        df_b_bars.columns = ["b_seg1", "b_seg2"]

        fig, ax = plt.subplots()
        width = 0.8
        df_b_bars.plot(kind="bar", ax=ax, color=[fc.blue, fc.lemon], width=width, legend=False)
        # gets handles for the legend (also gets and labels - rudimentary)
        handles, labels = ax.get_legend_handles_labels()
        # brings segment b to secondary y axis
        ax2 = ax.twinx()
        for r in ax.patches[len(df_b_bars):]:
            r.set_transform(ax2.transData)
        # defines labels
        labels = ["segment 1", "segment 2"]

        ax.set_ylabel("variable b in segment 1", color=fc.blue)
        ax.tick_params("y", colors=fc.blue)
        ax2.set_ylabel("variable b in segment 2", color=fc.lemon)
        ax2.tick_params("y", colors=fc.lemon)
        # adjust margins around bars
        ax.set_xlim(-0.6, df.shape[0] - 0.4)
        ax.set_ylim(df["b_seg1"].min() - 0.005, df["b_seg1"].max() + 0.02)
        ax2.set_ylim(df["b_seg2"].min() - 0.005, df["b_seg2"].max() + 0.02)
        fig.legend(handles,labels,ncol=2, loc="upper center", bbox_to_anchor=(0, 0.85, 1.1, .102))

        fig.tight_layout()
        fig.savefig(cfp.barchart_variable_b_png)
        sys.stdout.write("\n{}".format(cfp.barchart_variable_b_png))

        #########################################################################
        #               Barchart variable c, segments 1 and 2 (r_inf)           #
        #########################################################################
        plt.close("all")

        # generate only dataframe with c_seg1 and r_inf
        df_c_rinf_bars = pd.concat([df["c_seg1"], df["r_inf"]], axis=1)
        df_c_rinf_bars.columns = ["c_seg1", "r_inf"]

        fig, ax = plt.subplots()
        width = 0.8
        df_c_rinf_bars.plot(kind="bar", ax=ax, color=[fc.blue, fc.lemon], width=width, legend=False)
        # gets handles for the legend (also gets and labels - rudimentary)
        handles, labels = ax.get_legend_handles_labels()
        # brings segment b to secondary y axis
        ax2 = ax.twinx()
        for r in ax.patches[len(df_c_rinf_bars):]:
            r.set_transform(ax2.transData)
        # defines labels
        labels = ["segment 1", "segment 2"]

        ax.set_ylabel("variable c in segment 1", color=fc.blue)
        ax.tick_params("y", colors=fc.blue)
        ax2.set_ylabel("variable c (r_inf) in segment 2", color=fc.lemon)
        ax2.tick_params("y", colors=fc.lemon)
        # adjust margins around bars
        ax.set_xlim(-0.6, df.shape[0] - 0.4)
        ax.set_ylim(df["c_seg1"].min() - 0.005, df["c_seg1"].max() + 0.01)
        ax2.set_ylim(df["r_inf"].min() - 0.005, df["r_inf"].max() + 0.01)

        fig.legend(handles,labels,ncol=2, loc="upper center", bbox_to_anchor=(0, 0.85, 1.1, .102))
        fig.tight_layout()
        fig.savefig(cfp.barchart_variable_c_png)
        sys.stdout.write("\n{}".format(cfp.barchart_variable_c_png))

    fig_sg, ax_sg = plt.subplots()
    fig_seg1, ax_seg1 = plt.subplots()
    fig_seg2, ax_seg2 = plt.subplots()

    for csv in csv_files:
        # paths for the output files
        p = utils.FitFilePaths(data_dir, csv)
        with open(p.fitdata_pickle, "rb") as pic:
            #fd = blitzcurve.fit.OutputFitData()
            fd = pickle.load(pic)
            print("fd.filename", fd.filename)
            #for item in [fd.fit_savgol, fd.seg1_xfit, fd.seg1_yfit, fd.seg2_xfit, fd.seg2_yfit]:
            #    assert item is not None
            if name_dict is not None:
                label = name_dict[fd.filename] if fd.filename in name_dict else fd.filename
            else:
                label = fd.filename
            ax_sg.plot(fd.time, fd.y_fit_savgol, label=label)

            ax_seg1.plot(fd.time, fd.y_fit_savgol, color="0.3", zorder=0)
            ax_seg1.plot(fd.seg1_xfit, fd.seg1_yfit, label=label)

            ax_seg2.plot(fd.time, fd.y_fit_savgol, color="0.3", zorder=0)
            ax_seg2.plot(fd.seg2_xfit, fd.seg2_yfit, label=label)

    ax_sg.set_xlabel("time (ns)")
    ax_sg.set_ylabel("anisotropy, r")
    ax_sg.legend()
    fig_sg.tight_layout()
    fig_sg.savefig(cfp.linechart_savgol)

    ax_seg1.set_xlabel("time (ns)")
    ax_seg1.set_ylabel("anisotropy, r")
    ax_seg1.legend()
    fig_seg1.tight_layout()
    fig_seg1.savefig(cfp.linechart_seg1)

    ax_seg2.set_xlabel("time (ns)")
    ax_seg2.set_ylabel("anisotropy, r")
    ax_seg2.legend()
    fig_seg2.tight_layout()
    fig_seg2.savefig(cfp.linechart_seg2)


import tkinter as tk
from tkinter import ttk
import os

from thoughts import Collection, Project, Note

# TODOS:
# TODO: Fix new project/note entry connection in entry field?
# TODO: Make note editor work when switching notes / creating notes
# TODO: Make delete options for notes, projects and collections
# TODO: Improve button design
# TODO: Improve layout
# TODO: Make color schemes

class ThoughtsApp:
    def __init__(self, app_folder: str):
        self.app_folder = app_folder
        self.collections = dict()
        self.collection_frames = dict()
        self.projects_frames = dict()
        self.notes_frames = dict()
        self.action_frames = dict()
        self.project_entries = dict()

        self.active_project = None
        self.active_note = None
        self.note_edditor = None
        self.new_collection_entry = None
        self.create_new_note_button = None
        self.new_collection_pop_up = None
        self.collection_name_entry = None
        self.create_new_project_button = None

        # Draw the main frame and
        self.root = tk.Tk()
        self.root.geometry('850x450')
        self.root.minsize(850, 450)
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)

        # Add notebook structure where each notebook corresponds to a
        # collection
        self.notebook = ttk.Notebook(self.root)
        self.notebook.grid(row=0, column=0, sticky='nsew')
        self.notebook.bind("<<NotebookTabChanged>>", self.handle_last_tab_selection)

        # Append all collections based on folders in the path
        # Notice, this is NOT robust to outside temporing with the files
        collection_folders = os.listdir(app_folder)
        for collection_name in collection_folders:
            self.add_collection_page(collection_name=collection_name, first_insert=True)
        # Add a an extra frame which purpose is to add new frames
        self.notebook.add(tk.Frame(), text="+")

        self.root.title("Thoughts")
        self.root.geometry('1600x900')
        self.root.protocol("WM_DELETE_WINDOW", self.clean_up)
        self.root.mainloop()

    def add_new_collection_from_entry(self, *args):
        collection_name = self.new_collection_entry.get()
        if collection_name not in self.collections.keys():
            self.new_collection_entry.destroy()
            self.add_collection_page(collection_name=collection_name)
        else:
            tab_id = list(self.collections.keys()).index(collection_name)
            self.notebook.select(tab_id)

    def add_collection_page(self, collection_name, first_insert=False):
        if first_insert:
            index = len(self.notebook.tabs())
        else:
            index = len(self.notebook.tabs()) - 1
        collection_frame = ttk.Frame(self.notebook)
        collection_frame.grid_rowconfigure(0, weight=1)
        collection_frame.grid_columnconfigure(2, weight=1)

        projects_frame = tk.Label(collection_frame,
                                  text="ProjectsFrameHere",
                                  anchor=tk.CENTER)
        projects_frame.grid(row=0, column=0, sticky="nsew")

        notes_frame = tk.Label(collection_frame, text="NotesFrameHere",
                               anchor=tk.CENTER)
        notes_frame.grid(row=0, column=1, sticky="nsew")

        action_frame = tk.Label(collection_frame, text="ActionFrameHere",
                                anchor=tk.CENTER)
        action_frame.grid(row=0, column=2, columnspan=3, rowspan=2,
                          sticky="nsew")
        if first_insert:
            self.notebook.add(collection_frame, text=collection_name)
        else:
            self.notebook.insert(index, collection_frame, text=collection_name)

        self.collections.update({collection_name: Collection(
            folder=app_folder, name=collection_name)})
        self.collection_frames.update({collection_name: collection_frame})
        self.projects_frames.update({collection_name: projects_frame})
        self.notes_frames.update({collection_name: notes_frame})
        self.action_frames.update({collection_name: action_frame})

        # Add selection buttons to the projects frame
        for key in self.collections[collection_name].projects.keys():
            # Notice, by assigning the button project_name in a lambda
            # the project_name becomes fixed
            # and thus references the actual project name
            project_button = tk.Button(
                master=projects_frame,
                text=key,
                activebackground="lightgrey",
                bg="grey",
                command=lambda project_name=key: self.project_button_click(
                    project_name)
            )
            project_button.pack(fill='both')

        # Add a "create new project" button
        self.add_create_new_project_button(collection_name=collection_name, projects_frame=projects_frame)

    def add_create_new_project_button(self, collection_name, projects_frame):
        self.create_new_project_button = tk.Entry(
            master=projects_frame,
            text="New Project Name",
        )
        self.create_new_project_button.bind(sequence='<Return>', func=self.add_new_project)
        self.create_new_project_button.pack(fill='both')
        self.project_entries.update({collection_name: self.create_new_project_button})

    def add_new_project(self, *args):
        project_name_entry = self.project_entries[self.active_collection.name]
        new_project_name = project_name_entry.get()
        project_name_entry.destroy()

        self.active_collection.add_project(project_name=new_project_name)
        self.add_project_button(
            project_name=new_project_name,
            project_frame=self.projects_frames[self.active_collection.name]
        )
        # Add a "create new project" button
        self.add_create_new_project_button(collection_name=self.active_collection.name,
                                           projects_frame=self.projects_frames[self.active_collection.name])

    def add_project_button(self, project_name, project_frame):
        project_button = tk.Button(
            master=project_frame,
            text=project_name,
            activebackground="lightgrey",
            bg="grey",
            command=lambda project_name=project_name: self.project_button_click(
                project_name)
        )
        project_button.pack(fill='both')

    def clean_up(self):
        if self.note_edditor is not None:
            self.active_note.update_text(self.note_edditor.get(1.0, tk.END))

        self.root.destroy()

    @property
    def active_collection(self):
        collection_position_id = self.notebook.index("current")
        return self.collections[list(self.collections.keys())[collection_position_id]]

    def project_button_click(self, project_name):
        if self.active_note is not None:
            print("Remember to save note!")

        # Deselect the current note
        self.active_note = None

        # Clear current notes frame
        for widgets in self.notes_frames[self.active_collection.name].winfo_children():
            widgets.destroy()

        # Add notes button for the selected project
        self.active_project = self.active_collection.projects[project_name]

        for key in self.active_project.notes.keys():
            # Notice, by assigning the button project_name in a lambda,
            # the project_name becomes fixed
            # and thus references the actual project name
            note_button = tk.Button(
                master=self.notes_frames[self.active_collection.name],
                text=key,
                activebackground="lightgrey",
                bg="grey",
                command=lambda note_name=key: self.note_button_click(note_name)
            )
            note_button.pack(fill='both')

        # Add a note button to add a new note
        self.add_create_new_note_button(notes_frames=self.notes_frames[self.active_collection.name])

    def add_create_new_note_button(self, notes_frames):
        self.create_new_note_button = tk.Entry(
            master=notes_frames,
            text="New Project Name",
        )
        self.create_new_note_button.bind(sequence='<Return>', func=lambda x=notes_frames: self.add_new_note_from_entry(notes_frame=x))
        self.create_new_note_button.pack(fill='both')

    def add_new_note_from_entry(self, notes_frame, *args):
        new_note_name = self.create_new_note_button.get()
        self.add_new_note(note_name=new_note_name, notes_frames=notes_frame)
        self.create_new_note_button.destroy()
        self.add_create_new_note_button(notes_frames=notes_frame)

    def add_new_note(self, note_name, notes_frames):
        # Notice, by assigning the button project_name in a lambda,
        # the project_name becomes fixed
        # and thus references the actual project name
        note_button = tk.Button(
            master=notes_frames,
            text=note_name,
            activebackground="lightgrey",
            bg="grey",
            command=lambda x=note_name: self.note_button_click(x)
        )
        self.active_project.add_note(name=note_name)
        note_button.pack(fill='both')

    def note_button_click(self, note_name):
        # Clear the old editor
        if self.note_edditor is not None:
            self.active_note.update_text(self.note_edditor.get(1.0, tk.END))
            self.note_edditor.destroy()

        # Get the note text and make a new editor
        self.note_edditor = tk.Text(
            self.action_frames[self.active_collection.name]
        )
        # TODO: Check whether notes are saved correctly
        self.active_note = self.active_project.notes[note_name]
        self.note_edditor.insert(tk.INSERT, self.active_note.text)
        self.note_edditor.pack()

    def handle_last_tab_selection(self, *args):
        if self.notebook.select() == self.notebook.tabs()[-1]:
            self.popupwin()

    def insert_new_collection_fan(self):
        new_collection_name = self.collection_name_entry.get()
        index = len(self.notebook.tabs()) - 1
        self.add_collection_page(collection_name=new_collection_name)
        self.notebook.select(index)
        self.close_pop_up_window()

    def close_pop_up_window(self):
        self.new_collection_pop_up.destroy()

    def popupwin(self):
        # Create a Toplevel window
        self.new_collection_pop_up = tk.Toplevel(self.root)
        self.new_collection_pop_up.geometry("750x250")

        # Create an Entry Widget in the Toplevel window
        self.collection_name_entry = tk.Entry(self.new_collection_pop_up,
                                              width=25)

        self.collection_name_entry.pack()

        # Create a Button to print something in the Entry widget
        tk.Button(
            self.new_collection_pop_up,
            text="Ok",
            command=lambda: self.insert_new_collection_fan()
        ).pack(pady=5, side=tk.TOP)

        # Create a Button Widget in the Toplevel Window
        button = tk.Button(
            self.new_collection_pop_up,
            text="Cancel",
            command=lambda: self.close_pop_up_window()
        )
        button.pack(pady=5, side=tk.TOP)

app_folder = "C:/test/thoughts/"
app = ThoughtsApp(app_folder=app_folder)


codpreco = [
    [1, 0.50],
    [2, 1.00],
    [3, 4.00],
    [5, 7.00],
    [9, 8.00]
    ]

print(codpreco)
finded = bool(False)

soma = 0

prod = -1
while True:
    prod = int(input('>>> [R$ {:.2f}] Código do produto: '.format(soma)))

    if prod == 0:
        break

    for i in range(len(codpreco)):
        if codpreco[i][0] == prod:
            soma = soma + codpreco[i][1]
            # print('Total a pagar R$ {:.2f}'.format(soma))
            finded = True
            break
        else:
            finded = False

    if finded == False:
        print('\n[Código inválido]\n')

print('****' * 10 + '\n')
print('Total a pagar R$ {:.2f}'.format(soma))

Introdução à programação com python/Exercícicios/Exercício 5.15.py


import requests
import datetime
import pprint
from config import open_weather_token, code_to_smile

def getWeather(city):
    try:
        r = requests.get(
            f"https://api.openweathermap.org/data/2.5/forecast?q={city}&appid={open_weather_token}"
        )
        data = r.json()
        print(data)

        city = data["name"]
        curTemp = data["main"]["temp"]
        humidity = data["main"]["humidity"]
        pressure = data["main"]["pressure"]
        windSpeed = data["wind"]["speed"]
        sunriseTime = datetime.datetime.fromtimestamp(data["sys"]["sunrise"])
        sunsetTime = datetime.datetime.fromtimestamp(data["sys"]["sunset"])
        lenthOfTheDay = sunsetTime - sunriseTime

        weatherDisc = data["weather"][0]["main"]
        if weatherDisc in code_to_smile:
            wd = code_to_smile[weatherDisc]

        print(f"***{datetime.datetime.now().strftime('%Y-%m-%d %H-%M')}***\n"
              f"{city} {wd}\nTemperature: {curTemp}°C\n"
              f"Humidity: {humidity}%\nPressure: {pressure} mmHg\n"
              f"Wind: {windSpeed} m\s\nSunrise: {sunriseTime}\n"
              f"Sunset: {sunsetTime}\nDaylight hours: {lenthOfTheDay}\n"
              f"Have a nice day!")

    except Exception as ex:
        print(ex)
        print("Check the name of the city")

def getDayWeather(city):
    try:
        r = requests.get(
            f"https://api.openweathermap.org/data/2.5/forecast?q={city}&appid={open_weather_token}"
        )
        data = r.json()
        print(data)

        city = data["name"]
        curTemp = data["main"]["temp"]
        feelsTemp = data[""]
        maxTemp = data[""]
        minTemp = data[""]
        humidity = data["main"]["humidity"]
        pressure = data["main"]["pressure"]
        windSpeed = data["wind"]["speed"]
        sunriseTime = datetime.datetime.fromtimestamp(data["sys"]["sunrise"])
        sunsetTime = datetime.datetime.fromtimestamp(data["sys"]["sunset"])
        lenthOfTheDay = sunsetTime - sunriseTime

        weatherDisc = data["weather"][0]["main"]
        if weatherDisc in code_to_smile:
            wd = code_to_smile[weatherDisc]

        print(#f"***{datetime.datetime.now().strftime('%Y-%m-%d %H-%M')}***\n"
              f"{city}\n{curTemp}°C  {wd}\n\n"
              f"Feels like: {feelsTemp}\n"
              f"Max: {maxTemp} / min: {minTemp}\n\n"
              f"\U0001F4A7 Humidity: {humidity}%\n\U0001F321 Pressure: {pressure} mmHg\n"
              f"\U0001F32C Wind: {windSpeed} m\s\n\U0001F304 Sunrise: {sunriseTime.strftime('%H:%M')}\n"
              f"\U0001F307 Sunset: {sunsetTime.strftime('%H:%M')}\n\U0000231B Daylight hours: {lenthOfTheDay}\n\n"
              f"***Have a nice day!***")

    except Exception as ex:
        print(ex)
        print("Check the name of the city")

def getFiveDayWeather(city):
    try:
        r = requests.get(
            f"https://api.openweathermap.org/data/2.5/forecast?q={city}&appid={open_weather_token}"
        )
        data = r.json()
        print(data)

        city = data["name"]
        maxTemp1 = data[""]
        minTemp1 = data[""]
        weatherDisc1 = data["weather"][0]["main"]
        if weatherDisc1 in code_to_smile:
            wd1 = code_to_smile[weatherDisc1]
        maxTemp2 = data[""]
        minTemp2 = data[""]
        weatherDisc2 = data["weather"][0]["main"]
        if weatherDisc2 in code_to_smile:
            wd2 = code_to_smile[weatherDisc2]
        maxTemp3 = data[""]
        minTemp3 = data[""]
        weatherDisc3 = data["weather"][0]["main"]
        if weatherDisc3 in code_to_smile:
            wd3 = code_to_smile[weatherDisc3]
        maxTemp4 = data[""]
        minTemp4 = data[""]
        weatherDisc4 = data["weather"][0]["main"]
        if weatherDisc4 in code_to_smile:
            wd4 = code_to_smile[weatherDisc4]
        maxTemp5 = data[""]
        minTemp5 = data[""]
        weatherDisc5 = data["weather"][0]["main"]
        if weatherDisc5 in code_to_smile:
            wd5 = code_to_smile[weatherDisc5]

        print(f"{city}\n\n"
              f"Today {wd1}\n"
              f"{minTemp1}°C / {maxTemp1}°C\n\n"
              f"Tomorrow {wd2}\n"
              f"{minTemp2}°C / {maxTemp2}°C\n\n"
              f" {wd3}\n"
              f"{minTemp3}°C / {maxTemp3}°C\n\n"
              f" {wd4}\n"
              f"{minTemp4}°C / {maxTemp4}°C\n\n"
              f" {wd5}\n"
              f"{minTemp5}°C / {maxTemp5}°C\n\n"
              f"***Have a nice day!***")

    except Exception as ex:
        print(ex)
        print("Check the name of the city")

def test_weather(city):
    try:
        r = requests.get(
            f"https://api.openweathermap.org/data/2.5/forecast?q={city}&appid={open_weather_token}&units=metric"
        )
        data = r.json()
        print(data)

        date = []
        maxTemp = []
        minTemp = []
        weatherDisc = []
        wd = []

        for i in data['list']:
            print(i['dt_txt'], '{0:+3.0f}'.format(i['main']['temp']), i['weather'][0]['description'])

        for i in data['list']:
            maxTemp.append(i['main']['temp_max'])
            minTemp.append(i['main']['temp_min'])
            weatherDisc.append(i['weather'][0]['main'])

        print(maxTemp[0], maxTemp[1], maxTemp[2], maxTemp[3], maxTemp[4])
        print(minTemp[0], minTemp[1], minTemp[2], minTemp[3], minTemp[4])
        print(weatherDisc[0], weatherDisc[1], weatherDisc[2], weatherDisc[3], weatherDisc[4])

        for el in weatherDisc:
            if el in code_to_smile:
                wd.append(code_to_smile[el])

        for el in wd:
            print(el)

    except:
        print ("\U00002620 Check the name of the city \U00002620 ")

def test_tomorrow(city):
    try:
        r = requests.get(
            f"https://api.openweathermap.org/data/2.5/forecast?q={city}&appid={open_weather_token}&units=metric"
        )
        data = r.json()
        pprint.pprint(data)

        date = datetime.datetime.today() + datetime.timedelta(days=1)
        curTemp = '{0:+3.0f}'.format(data["list"][1]["main"]["temp"])
        feelsTemp = '{0:+3.0f}'.format(data["list"][1]["main"]["feels_like"])
        maxTemp = '{0:+3.0f}'.format(data["list"][1]["main"]["temp_max"])
        minTemp = '{0:+3.0f}'.format(data["list"][1]["main"]["temp_min"])
        windSpeed = data["list"][1]["wind"]["speed"]

        weatherDisc = data["list"][1]["weather"][0]["main"]
        if weatherDisc in code_to_smile:
            wd = (code_to_smile[weatherDisc])

        print(
            f"*Tomorrow*\n"
            f"({date})\n\n"
            f"{city}\n{curTemp}°C  {wd}\n"
            f"Feels like: {feelsTemp}\n\n"
            f"**Min / Max**\n"
            f"{minTemp} / {maxTemp}\n\n"
            f"\U0001F32C Wind: {windSpeed} m\s\n"
            f"***Have a nice day!***")

    except:
        print ("\U00002620 Check the name of the city \U00002620 ")

def main():
    city = input("Enter the city: ")
    test_tomorrow(city)

if __name__ == '__main__':
    main()


from typing import Optional

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def maxProduct(self, root: Optional[TreeNode]) -> int:
        subtree_sums = []

        def tree_sum(root):
            if not root:
                return 0

            left_sum = tree_sum(root.left)
            right_sum = tree_sum(root.right)
            total = left_sum + root.val + right_sum

            subtree_sums.append(total)
            return total

        total = tree_sum(root)

        max_val = 0
        print(subtree_sums)
        for s in subtree_sums:
            max_val = max(max_val, s * (total-s))

        return max_val % (10**9 + 7)


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 12 13:06:07 2017
@author: Mario
"""

########################################################################
#   Cropping an image: Function to crop an image
#
#
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or    #
# at your option) any later version.                                   #
#                                                                      #
# This program is distributed in the hope that it will be useful,      #
# but WITHOUT ANY WARRANTY; without even the implied warranty of       #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        #
# GNU General Public License for more details.                         #
#                                                                      #
# You should have received a copy of the GNU General Public License    #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
########################################################################

import cv2
import numpy as np
#import matplotlib.pyplot as plt

def crop(X):

    def scale(Y):
        A=np.array(Y)
        mx=np.amax(Y)
        mn=np.amin(Y)
        A=(Y-mn)/(mx-mn)
        return np.float32(A)

    image=np.zeros(X.shape+(3,),float)
    for i in range(3): image[:,:,i]=scale(X)

    cropping = False

    def ccrop(event, x, y, flags, param):
    	global coords, cropping
    	if event == cv2.EVENT_LBUTTONDOWN:
    		coords = [(x, y)]
    		cropping = True
    	elif event == cv2.EVENT_LBUTTONUP:
    		coords.append((x, y))
    		cropping = False
    		cv2.rectangle(image, coords[0], coords[1], (0, 0, 1), 2)
    		cv2.imshow("Patient", image)

    clone = image.copy()
    cv2.namedWindow("Patient")
    cv2.setMouseCallback("Patient", ccrop)

    while True:
    	cv2.imshow("Patient", image)
    	key = cv2.waitKey(1) & 0xFF
    	if key == ord("r"):
    		image = clone.copy()
    	elif key == ord("c"):
    		break

    [x0,y0]=coords[0]
    [xf,yf]=coords[1]

    if x0 > xf:
        x0,xf = xf,x0
    elif x0 == xf:
        x0, xf= -1
    if y0 > yf:
        y0,yf = yf,y0
    elif y0 == yf:
        y0, yf= -1

    if len(coords) == 2:
        	roi = clone[y0:yf,x0:xf,:]
        	cv2.imshow("Region of Interest", roi)
        	cv2.waitKey(0)

    cv2.destroyAllWindows()

    return ((x0,y0),(xf,yf))
"""data=dicom.read_file('C:/Users/Mario/Desktop/algoritmo/pato 1/ser003img00109.dcm')

roi,image= crop(data.pixel_array)

cv2.destroyAllWindows()
axes = np.zeros((1, 3), dtype=np.object)

d=np.where(image[:,:,2] == 255)
image[d[0],d[1],2]=1

fig=plt.figure(figsize=(12,6))
im=axes[0,0]=fig.add_subplot(1,3,1)
roiim=axes[0,1]=fig.add_subplot(1,3,2)
im.set_axis_off()
im.set_title('Imagen original',fontsize=10)
roiim.set_title('Regíon de interés',fontsize=10)
roiim.set_axis_off()
axes[0,0].imshow(image)
axes[0,1].imshow(roi,cmap='gray')
f=axes[0,2]=fig.add_subplot(1,3,3)
axes[0,2].hist(roi.ravel(),bins=150,color='blue')
f.set_title('Histograma de región de interés',fontsize=10)"""


import functions
import main

def functions_test():
    from transformers import BertTokenizer
    tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') # define pre-trained tokenizer
    sentence = "ok this is a TEST you'll have to watch."
    sentence = functions.preprocessW(sentence, 400, tokenizer)
    print(sentence)

if __name__ == "__main__":
    functions_test()


import logging
import os
import torch
import numpy as np
import json
from tqdm import tqdm
from functools import reduce
import pickle
from abc import ABC, abstractmethod
import tqdm as tqdm

def intersect_2d(x1, x2):
    """
    Given two arrays [m1, n], [m2,n], returns a [m1, m2] array where each entry is True if those
    rows match.
    :param x1: [m1, n] numpy array
    :param x2: [m2, n] numpy array
    :return: [m1, m2] bool array of the intersections
    """
    if x1.shape[1] != x2.shape[1]:
        raise ValueError("Input arrays must have same #columns")

    # This performs a matrix multiplication-esque thing between the two arrays
    # Instead of summing, we want the equality, so we reduce in that way
    res = (x1[..., None] == x2.T[None, ...]).all(1)
    return res

def compute_iou(bboxes1, bboxes2):
    x11, y11, x12, y12 = np.split(bboxes1, 4, axis=1)
    x21, y21, x22, y22 = np.split(bboxes2, 4, axis=1)
    xA = np.maximum(x11, np.transpose(x21))
    yA = np.maximum(y11, np.transpose(y21))
    xB = np.minimum(x12, np.transpose(x22))
    yB = np.minimum(y12, np.transpose(y22))
    interArea = np.maximum((xB - xA + 1), 0) * np.maximum((yB - yA + 1), 0)
    boxAArea = (x12 - x11 + 1) * (y12 - y11 + 1)
    boxBArea = (x22 - x21 + 1) * (y22 - y21 + 1)
    iou = interArea / (boxAArea + np.transpose(boxBArea) - interArea)
    return iou

class SceneGraphEvaluation(ABC):
    def __init__(self, result_dict):
        super().__init__()
        self.result_dict = result_dict

    @abstractmethod
    def register_container(self, mode):
        print("Register Result Container")
        pass

    @abstractmethod
    def generate_print_string(self, mode):
        print("Generate Print String")
        pass

"""
Traditional Recall, implement based on:
https://github.com/rowanz/neural-motifs
"""
class SGRecall(SceneGraphEvaluation):
    def __init__(self, result_dict):
        super(SGRecall, self).__init__(result_dict)

    def register_container(self, mode):
        # self.result_dict[mode + '_recall'] = {20: [], 50: [], 100: []}

        self.result_dict[mode + '_recall'] = {}
        for key in [5, 10, 15, 20, 25, 30, 50, 100]:
            self.result_dict[mode + '_recall'][key] = []

    def generate_print_string(self, mode):
        result_str = 'SGG eval: '
        for k, v in self.result_dict[mode + '_recall'].items():
            result_str += '    R @ %d: %.4f; ' % (k, np.mean(v))
        result_str += ' for mode=%s, type=Recall(Main).' % mode
        result_str += '\n'
        return result_str

    def calculate_recall(self, global_container, local_container, mode):
        rel_pair_idx = local_container['rel_pair_idx']
        rel_probs = local_container['rel_probs']
        gt_rels = local_container['gt_rels']
        gt_classes = local_container['gt_classes']
        gt_boxes = local_container['gt_boxes']
        pred_classes = local_container['pred_classes']
        pred_boxes = local_container['pred_boxes']
        obj_probs = local_container['obj_probs']

        iou_thres = global_container['iou_thres']

        # print('rel_pair_idx', rel_pair_idx.shape, 'obj_probs', obj_probs.shape, 'rel_probs', rel_probs.shape)
        # Sort the predicted possible based on the (sub_score*pred_score*obj_score)
        pred_rel_inds, obj_scores, rel_scores, _ = sort_the_relations(rel_pair_idx, obj_probs, torch.from_numpy(rel_probs))
        # print('pred_rel_inds', pred_rel_inds.shape, 'obj_scores', obj_scores.shape, 'rel_scores', rel_scores.shape)

        pred_rels = np.column_stack((pred_rel_inds, 1+rel_scores[:,1:].argmax(1))) # (#predted relations, (sub_id, obj_id, pred_lab))
        # print('pred_rels', pred_rels.shape)
        pred_scores = rel_scores[:,1:].max(1) # #predted relations
        # print('pred_scores',pred_scores.shape)

        # print('\ngt_rels', gt_rels.shape, 'pred_rels', pred_rels.shape)
        # print('gt_boxes',gt_boxes.shape, 'pred_boxes',pred_boxes.shape)
        # Converts (m1, (sub_id, obj_id, pred_label)) to (m1, (sub_label, obj_label, pred_label))
        # Transforms (#entities, bbox) to (#triplets, bbox)
        gt_triplets, gt_triplet_boxes, _ = _triplet(gt_rels, gt_classes, gt_boxes)
        local_container['gt_triplets'] = gt_triplets
        local_container['gt_triplet_boxes'] = gt_triplet_boxes

        pred_triplets, pred_triplet_boxes, pred_triplet_scores = _triplet(
                pred_rels, pred_classes, pred_boxes, pred_scores, obj_scores)

        # print('\ngt_triplets',gt_triplets.shape, 'pred_triplets',pred_triplets.shape)
        # print('gt_triplet_boxes',gt_triplet_boxes.shape, 'pred_triplet_boxes',pred_triplet_boxes.shape)

        # Compute recall. It's most efficient to match once and then do recall after
        pred_to_gt = _compute_pred_matches(
            gt_triplets,
            pred_triplets,
            gt_triplet_boxes,
            pred_triplet_boxes,
            iou_thres,
            phrdet=mode=='phrdet',
        )
        local_container['pred_to_gt'] = pred_to_gt

        for k in self.result_dict[mode + '_recall']:
            # the following code are copied from Neural-MOTIFS
            match = reduce(np.union1d, pred_to_gt[:k])
            # print(len(pred_to_gt[:k]), len(match), gt_rels.shape[0])
            rec_i = float(len(match)) / float(gt_rels.shape[0])
            self.result_dict[mode + '_recall'][k].append(rec_i)

        return local_container

"""
Mean Recall: Proposed in:
https://arxiv.org/pdf/1812.01880.pdf CVPR, 2019
"""
class SGMeanRecall(SceneGraphEvaluation):
    def __init__(self, result_dict, num_rel, ind_to_predicates, print_detail=False):
        super(SGMeanRecall, self).__init__(result_dict)
        self.num_rel = num_rel
        self.print_detail = print_detail
        self.rel_name_list = ind_to_predicates[1:] # remove __background__

        self.rtypes = {
            'Head': ['on', 'has', 'of', 'wearing', 'in', 'near', 'with', 'behind', 'holding'],
            'Mid': ['wears', 'above', 'sitting on', 'under', 'riding', 'in front of', 'standing on'],
            'Tail': ['attached to', 'belonging to', 'at', 'walking on', 'carrying', 'over', 'watching',
                    'hanging from', 'for', 'looking at', 'parked on', 'eating', 'laying on', 'between',
                    'covering', 'and', 'covered in', 'using', 'along', 'on back of', 'to', 'mounted on',
                    'part of', 'lying on', 'walking in', 'from', 'painted on', 'growing on', 'across',
                    'against', 'made of', 'playing', 'flying in', 'says']
        }
    def register_container(self, mode):
        #self.result_dict[mode + '_recall_hit'] = {20: [0]*self.num_rel, 50: [0]*self.num_rel, 100: [0]*self.num_rel}
        #self.result_dict[mode + '_recall_count'] = {20: [0]*self.num_rel, 50: [0]*self.num_rel, 100: [0]*self.num_rel}
        # self.result_dict[mode + '_mean_recall'] = {20: 0.0, 50: 0.0, 100: 0.0}
        # self.result_dict[mode + '_mean_recall_collect'] = {20: [[] for i in range(self.num_rel)], 50: [[] for i in range(self.num_rel)], 100: [[] for i in range(self.num_rel)]}
        # self.result_dict[mode + '_mean_recall_list'] = {20: [], 50: [], 100: []}
        # self.result_dict[mode + '_mean_recall_HMT'] = {'Head':{20: 0.0, 50: 0.0, 100: 0.0},
        #                                                 'Mid': {20: 0.0, 50: 0.0, 100: 0.0},
        #                                                 'Tail': {20: 0.0, 50: 0.0, 100: 0.0}}

        self.result_dict[mode + '_recall_hit'] = {}
        self.result_dict[mode + '_recall_count'] = {}
        self.result_dict[mode + '_mean_recall'] = {}
        self.result_dict[mode + '_mean_recall_collect'] = {}
        self.result_dict[mode + '_mean_recall_list'] = {}
        self.result_dict[mode + '_mean_recall_HMT'] = {'Head':{}, 'Mid': {}, 'Tail': {}}
        for key in [5, 10, 15, 20, 25, 30, 50, 100]:
            self.result_dict[mode + '_mean_recall'][key] = 0.0
            self.result_dict[mode + '_mean_recall_collect'][key] = [[] for i in range(self.num_rel)]
            self.result_dict[mode + '_mean_recall_list'][key] = []
            self.result_dict[mode + '_mean_recall_HMT']['Head'][key] = 0.0
            self.result_dict[mode + '_mean_recall_HMT']['Mid'][key] = 0.0
            self.result_dict[mode + '_mean_recall_HMT']['Tail'][key] = 0.0

    def generate_print_string(self, mode):
        result_str = 'SGG eval: '
        for k, v in self.result_dict[mode + '_mean_recall'].items():
            result_str += '   mR @ %d: %.4f; ' % (k, float(v))
        result_str += ' for mode=%s, type=Mean Recall.' % mode
        result_str += '\n'
        if self.print_detail:

            result_str += '----------------------- HMT ------------------------\n'
            for rtype, recalls in self.result_dict[mode + '_mean_recall_HMT'].items():
                result_str += f'SGG eval {rtype}: '
                for k, v in recalls.items():
                    result_str += '   mR @ %d: %.4f; ' % (k, float(v))
                result_str += '\n'
            result_str += '\n'
            result_str += '----------------------- Details ------------------------\n'
            for n, r in zip(self.rel_name_list, self.result_dict[mode + '_mean_recall_list'][100]):
                result_str += '({}:{:.4f}) '.format(str(n), r)
            result_str += '\n'
            result_str += '--------------------------------------------------------\n'

        return result_str

    def collect_mean_recall_items(self, global_container, local_container, mode):
        pred_to_gt = local_container['pred_to_gt']
        gt_rels = local_container['gt_rels']

        for k in self.result_dict[mode + '_mean_recall_collect']:
            # the following code are copied from Neural-MOTIFS
            match = reduce(np.union1d, pred_to_gt[:k])
            # NOTE: by kaihua, calculate Mean Recall for each category independently
            # this metric is proposed by: CVPR 2019 oral paper "Learning to Compose Dynamic Tree Structures for Visual Contexts"
            recall_hit = [0] * self.num_rel
            recall_count = [0] * self.num_rel
            for idx in range(gt_rels.shape[0]):
                local_label = gt_rels[idx,2]
                recall_count[int(local_label)] += 1
                recall_count[0] += 1

            for idx in range(len(match)):
                local_label = gt_rels[int(match[idx]),2]
                recall_hit[int(local_label)] += 1
                recall_hit[0] += 1

            for n in range(self.num_rel):
                if recall_count[n] > 0:
                    self.result_dict[mode + '_mean_recall_collect'][k][n].append(float(recall_hit[n] / recall_count[n]))

    def calculate_mean_recall(self, mode):
        no_samples_rtype = {'Head': len(self.rtypes['Head']),
                            'Mid': len(self.rtypes['Mid']),
                            'Tail':len(self.rtypes['Tail'])}
        for k, v in self.result_dict[mode + '_mean_recall'].items():
            sum_recall = 0
            num_rel_no_bg = self.num_rel - 1
            for idx in range(num_rel_no_bg):
                if len(self.result_dict[mode + '_mean_recall_collect'][k][idx+1]) == 0:
                    tmp_recall = 0.0
                else:
                    tmp_recall = np.mean(self.result_dict[mode + '_mean_recall_collect'][k][idx+1])
                self.result_dict[mode + '_mean_recall_list'][k].append(tmp_recall)
                sum_recall += tmp_recall

                for rtype, relations in self.rtypes.items():
                    if self.rel_name_list[idx] in relations:
                        self.result_dict[mode + '_mean_recall_HMT'][rtype][k] += (tmp_recall/no_samples_rtype[rtype])

            self.result_dict[mode + '_mean_recall'][k] = sum_recall / float(num_rel_no_bg)
        return

"""
Accumulate Recall:
calculate recall on the whole dataset instead of each image
"""
class SGAccumulateRecall(SceneGraphEvaluation):
    def __init__(self, result_dict):
        super(SGAccumulateRecall, self).__init__(result_dict)

    def register_container(self, mode):
        # self.result_dict[mode + '_accumulate_recall'] = {20: 0.0, 50: 0.0, 100: 0.0}
        self.result_dict[mode + '_accumulate_recall'] = {}
        for key in [5, 10, 15, 20, 25, 30, 50, 100]:
            self.result_dict[mode + '_accumulate_recall'][key] = []

    def generate_print_string(self, mode):
        result_str = 'SGG eval: '
        for k, v in self.result_dict[mode + '_accumulate_recall'].items():
            result_str += '   aR @ %d: %.4f; ' % (k, float(v))
        result_str += ' for mode=%s, type=Accumulate Recall.' % mode
        result_str += '\n'
        return result_str

    def calculate_accumulate(self, mode):
        for k, v in self.result_dict[mode + '_accumulate_recall'].items():
            self.result_dict[mode + '_accumulate_recall'][k] = float(self.result_dict[mode + '_recall_hit'][k][0]) / float(self.result_dict[mode + '_recall_count'][k][0] + 1e-10)

        return

def _triplet(relations, classes, boxes, predicate_scores=None, class_scores=None):
    """
    format relations of (sub_id, ob_id, pred_label) into triplets of (sub_label, pred_label, ob_label)
    Parameters:
        relations (#rel, 3) : (sub_id, ob_id, pred_label)
        classes (#objs, ) : class labels of objects
        boxes (#objs, 4)
        predicate_scores (#rel, ) : scores for each predicate
        class_scores (#objs, ) : scores for each object
    Returns:
        triplets (#rel, 3) : (sub_label, pred_label, ob_label)
        triplets_boxes (#rel, 8) array of boxes for the parts
        triplets_scores (#rel, 3) : (sub_score, pred_score, ob_score)
    """
    sub_id, ob_id, pred_label = relations[:, 0], relations[:, 1], relations[:, 2]
    try:
        triplets = np.column_stack((classes[sub_id], pred_label, classes[ob_id]))
    except:
        print(relations)
        print(classes, sub_id, ob_id)

        print(classes.shape, sub_id.shape, ob_id.shape)
        assert False
    triplet_boxes = np.column_stack((boxes[sub_id], boxes[ob_id]))

    triplet_scores = None
    if predicate_scores is not None and class_scores is not None:
        triplet_scores = np.column_stack((
            class_scores[sub_id], predicate_scores, class_scores[ob_id],
        ))

    return triplets, triplet_boxes, triplet_scores

def _compute_pred_matches(gt_triplets, pred_triplets,
                 gt_boxes, pred_boxes, iou_thres, phrdet=False):
    """
    Given a set of predicted triplets, return the list of matching GT's for each of the
    given predictions
    Return:
        pred_to_gt [List of List]
    """
    # This performs a matrix multiplication-esque thing between the two arrays
    # Instead of summing, we want the equality, so we reduce in that way
    # The rows correspond to GT triplets, columns to pred triplets
    keeps = intersect_2d(gt_triplets, pred_triplets)
    gt_has_match = keeps.any(1)
    # print('\ngt_pred_triplet_CM ', keeps.shape)
    # print('#gt_with_pred_match ', np.where(gt_has_match)[0].shape, 'gt_idx_pred_match ', keeps[gt_has_match].shape)

    # Iterate over the GT triplets that matches with the predicted triplets
    pred_to_gt = [[] for x in range(pred_boxes.shape[0])]
    for gt_ind, gt_box, keep_inds in zip(np.where(gt_has_match)[0],
                                         gt_boxes[gt_has_match],
                                         keeps[gt_has_match],
                                         ):
        # Extract all the predicted boxes that match the current GT triplet
        boxes = pred_boxes[keep_inds]

        # Of these pred boxes filter the ones that satisfies the IOU condition the current GT bboxe
        if phrdet:
            # Evaluate where the union box > 0.5
            gt_box_union = gt_box.reshape((2, 4))
            gt_box_union = np.concatenate((gt_box_union.min(0)[:2], gt_box_union.max(0)[2:]), 0)

            box_union = boxes.reshape((-1, 2, 4))
            box_union = np.concatenate((box_union.min(1)[:,:2], box_union.max(1)[:,2:]), 1)

            inds = compute_iou(gt_box_union[None], box_union)[0] >= iou_thres
        else:

            sub_iou = compute_iou(gt_box[None,:4], boxes[:, :4])[0]
            obj_iou = compute_iou(gt_box[None,4:], boxes[:, 4:])[0]

            inds = (sub_iou >= iou_thres) & (obj_iou >= iou_thres)

        # print(np.where(keep_inds)[0], np.where(keep_inds)[0][inds])

        for i in np.where(keep_inds)[0][inds]:
            pred_to_gt[i].append(int(gt_ind))
    # print('pred_to_gt ', len(pred_to_gt))
    return pred_to_gt

def evaluate_relation_of_one_image(groundtruth, prediction, global_container, evaluator, mode):

    # Traditional Metric with Graph Constraint
    # NOTE: this is the MAIN evaluation function, it must be run first (several important variables need to be update)
    local_container = evaluator['eval_recall'].calculate_recall(global_container, local_container, mode)

    # GT Pair Accuracy
    evaluator['eval_pair_accuracy'].calculate_recall(global_container, local_container, mode)
    # Mean Recall
    evaluator['eval_mean_recall'].collect_mean_recall_items(global_container, local_container, mode)

    return

def sort_the_relations(rel_pair_idx, obj_class_prob, rel_class_prob):

    # print('rel_pair_idx ', rel_pair_idx.shape, 'obj_class_prob ', obj_class_prob.shape, 'rel_class_prob ', rel_class_prob.shape)
    # Getting the object ids from the object probabilities ignoring the background
    obj_scores, obj_pred = obj_class_prob[:, 1:].max(dim=1)
    obj_pred = obj_pred + 1 # adding 1 as the background was ignored in previous step

    # sorting triples according to score production
    # Splitting the obj_scores into sub and obj based on the rel_pair_idx
    obj_scores0 = obj_scores[rel_pair_idx[:, 0]]
    obj_scores1 = obj_scores[rel_pair_idx[:, 1]]
    # print('obj_scores0 ', obj_scores0.shape, 'obj_scores1 ', obj_scores1.shape)
    # Getting the relation ids from the relation probabilities ignoring the N/R
    rel_scores, rel_class = rel_class_prob[:, 1:].max(dim=1)
    rel_class = rel_class + 1 # adding 1 as the N/R was ignored in previous step
    # print('rel_scores ', rel_scores.shape, 'rel_class ', rel_class.shape)

    # TODO Kaihua: how about using weighted some here?  e.g. rel*1 + obj *0.8 + obj*0.8
    triple_scores = rel_scores * obj_scores0 * obj_scores1
    _, sorting_idx = torch.sort(triple_scores.view(-1), dim=0, descending=True)
    rel_pair_idx = rel_pair_idx[sorting_idx] # (#rel, 2)

    rel_class_prob = rel_class_prob[sorting_idx]# (#rel, #rel_class)
    rel_labels = rel_class[sorting_idx] # (#rel, )

    return rel_pair_idx, obj_scores.numpy(), rel_class_prob.numpy(), rel_labels.numpy()

if __name__ == "__main__":

    # with open('metrics/local_container.pkl', "rb") as input_file:
    #     local_container = pickle.load(input_file)
    with open('metrics/ind_to_predicates.pkl', "rb") as input_file:
        ind_to_predicates = pickle.load(input_file)
    # with open('metrics/groundtruths.pkl', "rb") as input_file:
    #     groundtruths = pickle.load(input_file)
    # with open('metrics/predictions.pkl', "rb") as input_file:
    #     predictions = pickle.load(input_file)

    modes = ['predcls', 'sgcls', 'sgdet']
    result_dict = {}

    # prepare all inputs
    global_container = {}
    global_container['zeroshot_triplet'] = None
    global_container['result_dict'] = result_dict
    global_container['mode'] = modes[0]
    global_container['multiple_preds'] = False
    global_container['num_rel_category'] = 51
    global_container['iou_thres'] = 0.5
    global_container['attribute_on'] = False
    global_container['num_attributes'] = 201

    num_rel_category = 51
    result_dict = {}
    # tradictional Recall@K
    eval_recall = SGRecall(result_dict)
    eval_recall.register_container(mode=modes[0])
    mean_recall = SGMeanRecall(result_dict, num_rel_category, ind_to_predicates, print_detail=True)
    mean_recall.register_container(mode=modes[0])

    for _ in range(10):

        # Keep creating local containers with the predictions
        local_container = eval_recall.calculate_recall(global_container, local_container, modes[0])

        mean_recall.collect_mean_recall_items(global_container, local_container, mode=modes[0])

    mean_recall.calculate_mean_recall(mode = modes[0])

    string = eval_recall.generate_print_string(mode = modes[0])
    string += mean_recall.generate_print_string(mode = modes[0])

    print(string)


#values = ['valor', 10, 4, 6, 9, 8, 3, 10, 2]
#weights = ['peso', 10, 5, 1, 3, 3, 4, 3, 1]

#values = ['valor', 15, 10, 9, 5]
#weights = ['peso', 1, 5, 3, 4]

values = ['valor', 10, 40, 30, 50]
weights = ['peso', 5, 4, 6, 3]

def knapsack(values, weights, n, m):
    f = {}
    for g in range(m + 1):
        f[0, g] = 0

    for i in range(1, n + 1):
        for g in range(m + 1):
            if weights[i] <= g:
                f[i, g] = max(
                    values[i] + f[i - 1, g - weights[i]], f[i - 1, g])
            else:
                f[i, g] = f[i - 1, g]
    return f[n, m]

print(knapsack(values, weights, 4, 10))


import transformnet
import extractnet
import numpy as np
import tensorflow as tf
import PIL.Image as Image
import os
from config import *
import uuid
import shutil
import config

def traingen(dirpath):
    flist = os.listdir(dirpath)
    np.random.shuffle(flist)
    cursor = 0
    while cursor<len(flist):
        batchfn = flist[cursor:cursor+batchsize]
        cursor+=batchsize
        ims = []
        for fn in batchfn:
            im = Image.open(os.path.join(dirpath, fn))
            im = im.resize((224, 224), Image.ANTIALIAS)
            im = np.array(im) / 255.
            ims.append(im)
        yield np.array(ims)

sess = tf.Session()
# model1
input = tf.placeholder(dtype='float32', shape=(None, None, None, 3),name="input")
synthesizetensor = transformnet.transform(input)
predcontenttensor, predstyletensors = extractnet.extract(synthesizetensor,prefix="A")
# model2
contenttensor, styletensors = extractnet.extract(input,prefix="B")

styleim = Image.open(styleimg)
#styleim = styleim.resize((224, 224), Image.ANTIALIAS)
styleim = np.expand_dims(np.array(styleim) / 255., axis=0)
styles = sess.run(styletensors,feed_dict={input:styleim})
grams = []
for style in styles:
    style = np.squeeze(style)
    style = np.transpose(style,[2,0,1])
    channelnum = style.shape[0]
    style = np.resize(style,(channelnum,-1))
    styletranspose = np.transpose(style,[1,0])
    gram = np.matmul(style,styletranspose)/style.shape[1]
    grams.append(gram)
loss = tf.reduce_sum((predcontenttensor-contenttensor)**2)/tf.cast(tf.size(contenttensor[0]),dtype=tf.float32)
for predstyletensor,truthgram in zip(predstyletensors,grams):
    predstyletensor = tf.transpose(predstyletensor,[0,3,1,2])
    shape = tf.shape(predstyletensor)
    predstyletensor = tf.reshape(predstyletensor,shape=[shape[0],shape[1],-1])
    grampred = tf.matmul(predstyletensor,predstyletensor,transpose_b=True)/tf.cast(tf.shape(predstyletensor)[2],dtype=tf.float32)
    loss+=30*tf.reduce_sum((grampred-truthgram)**2)/truthgram.size/len(config.styletensors)
loss/=batchsize
trainop = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(loss)
saver = tf.train.Saver()
#sess.run(tf.global_variables_initializer())
saver.restore(sess,modelpath)

def train():
    for ep in range(epoch):
        testims = next(traingen(testpath))
        minerr = 999999999
        argminerr = -1
        errorrec = []
        for i, batchims in enumerate(traingen(trainpath)):
            _, losstrain = sess.run([trainop, loss], feed_dict={input: batchims})
            print(losstrain)
            if i % 5 == 0:
                synthesizeimgs, lossval = sess.run([synthesizetensor, loss], feed_dict={input: testims})
                errorrec.append(lossval)
                print("validate loss:"+str(lossval))
                if len(errorrec) - argminerr > 100:
                    return
                list(map(os.unlink, (os.path.join(savepath, f) for f in os.listdir(savepath))))
                for im in synthesizeimgs:
                    im = np.uint8(im*255)
                    Image.fromarray(im).save(os.path.join(savepath, str(uuid.uuid4()) + ".jpg"))
                if lossval < minerr:
                    minerr = lossval
                    argminerr = len(errorrec) - 1
                    saver.save(sess,modelpath)

train()

# tf.summary.scalar('cc',loss)
# merged = tf.summary.merge_all()
# train_writer = tf.summary.FileWriter(r"D:\Users\yl_gong\Desktop\log",
#                                       sess.graph)
# sess.run(tf.global_variables_initializer())
# im = Image.open(testimg)
# im = np.expand_dims(np.array(im)/255.,axis=0)
# summary = sess.run(merged,feed_dict={input:im})
# train_writer.add_summary(summary, 0)


def download_file_from_google_drive(id, destination):
    '''
    Function Author: @turdus-merula, from https://stackoverflow.com/questions/25010369/wget-curl-large-file-from-google-drive/39225039#39225039

    Docstring Author: Harry Hawkes (GH: @hph220), Lehigh Class of 2020

    Purpose: A solution for sharing large files with your group or future users.

    Solution:
    1. Upload (compressed) files to Lehigh Google Drive. (A non-Lehigh google drive
    will work too, but has limitations on space.)

    2. Turn on sharing for the file by right clicking it and selecting "get shareable link",
    but you don't need to give edit access.

    3. Turn on sharing for users outside of Lehigh University, but you don't need to give
    edit access.

    4. Get the ID from the sharing link (found at the end of the sharing URL), you'll need to
    put that into your code.

    5. In your file that uses this data:

        import os
        from download_file_from_google_drive import download_file_from_google_drive

        # download the file to your computer if you haven't already

        filepath_to_download_to = 'my_big_file.csv' # replace with your preferred name/path
        if not os.path.exists(filepath_to_download_to)
            download_file_from_google_drive(<put the ID here>, filepath_to_download_to)

        # open it
        <open the file, exact method depends on file type>
    '''

    import requests

    def get_confirm_token(response):
        for key, value in response.cookies.items():
            if key.startswith('download_warning'):
                return value

        return None

    def save_response_content(response, destination):
        CHUNK_SIZE = 32768

        with open(destination, "wb") as f:
            for chunk in response.iter_content(CHUNK_SIZE):
                if chunk: # filter out keep-alive new chunks
                    f.write(chunk)

    URL = "https://docs.google.com/uc?export=download"

    session = requests.Session()

    response = session.get(URL, params = { 'id' : id }, stream = True)
    token = get_confirm_token(response)

    if token:
        params = { 'id' : id, 'confirm' : token }
        response = session.get(URL, params = params, stream = True)

    save_response_content(response, destination)

if __name__ == "__main__":
    import sys
    if len(sys.argv) is not 3:
        print("Usage: python google_drive.py drive_file_id destination_file_path")
    else:
        # TAKE ID FROM SHAREABLE LINK
        file_id = sys.argv[1]
        # DESTINATION FILE ON YOUR DISK
        destination = sys.argv[2]
        download_file_from_google_drive(file_id, destination)


# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 16:11:04 2019

@author: Admin
"""

import numpy as np
def weight_prune(model,pruning_perc):
    all_weights=[]
    for p in model.parameters():
        if len(p.data.size())==4:
            all_weights+=list(p.cpu().data.abs().numpy().flatten())
    threshold=np.percentile(np.array(all_weights),pruning_perc)

    masks=[]
    for p in model.parameters():
        if len(p.data.size())==4:
            pruned_index=p.data.abs()>threshold
            masks.append(pruned_index.float())
    return masks


#coding:utf-8

"""
ID:          index.alter-05
TITLE:       ALTER INDEX - INACTIVE FOREIGN KEY
DESCRIPTION:
FBTEST:      functional.index.alter.05
"""

import pytest
from firebird.qa import *

init_script = """CREATE TABLE pk( a INTEGER NOT NULL,
                CONSTRAINT pkindx PRIMARY KEY(a)
              );
commit;
CREATE TABLE fk( a INTEGER NOT NULL,
                 CONSTRAINT fkindx FOREIGN KEY(a) REFERENCES pk(a)
              );
commit;"""

db = db_factory(init=init_script)

test_script = """ALTER INDEX fkindx INACTIVE;"""

act = isql_act('db', test_script)

expected_stderr = """Statement failed, SQLSTATE = 27000
unsuccessful metadata update
-ALTER INDEX FKINDX failed
-action cancelled by trigger (2) to preserve data integrity
-Cannot deactivate index used by an integrity constraint
"""

@pytest.mark.version('>=3.0')
def test_1(act: Action):
    act.expected_stderr = expected_stderr
    act.execute()
    assert act.clean_stderr == act.clean_expected_stderr


import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from tensorflow.keras import layers, Sequential, Input, Model, initializers
from tensorflow.keras.layers import Reshape, Dense, Flatten
import utilities.metrics
from models.utilities import custom_loss, custom_loss_UV
from utilities.metrics import MatrixSparsity, MatrixSparsity_SVD
from utilities.plot import plot_matrices

# #%%
# import sys

# sys.path.append('/Users/ericbrunner/git/denise/')
# print(sys.path)

# #%%

class NeuralNet:
    def __init__(self, dim, output_dim, lr=0.001, batch_size=64, n_epochs=30, valid_split=0.2,
                 loss='mean_absolute_error', metrics=None):
        self.dim = dim
        self.input_dim = dim * (dim + 1) / 2  # n * (n+1) / 2
        self.output_dim = output_dim  # tuple (n, k)

        self.batch_size = batch_size
        self.n_epochs = n_epochs
        self.valid_split = valid_split

        self.lr = lr
        self.optimizer = tf.keras.optimizers.Adam(learning_rate=self.lr)
        self.loss = loss
        self.metrics = metrics
        self._create_network()

        self.history = None

    def _create_network(self):
        self.model = Sequential()
        self.model.add(layers.Dense(self.dim * 2, activation="relu"))
        self.model.add(layers.Dense(self.dim * 2, activation="relu"))
        self.model.add(layers.Dense(self.dim * 2, activation="relu"))
        self.model.add(layers.Dense(self.output_dim[0] * self.output_dim[1]))
        self.model.add(layers.Reshape(self.output_dim))  # to matrix
        # self.model.add(Shrink(self.dim))

    def compile(self):
        self.model.compile(optimizer=self.optimizer,
                           loss=self.loss,
                           metrics=self.metrics
                           )

    def train(self, X, y):
        self.compile()

        self.history = self.model.fit(X, y,
                                      batch_size=self.batch_size,
                                      epochs=self.n_epochs,
                                      validation_split=self.valid_split,
                                      )
        self.model.summary()

    def save_weights(self, path):
        self.model.save_weights(filepath=path)

    def load_weights(self, path):
        x = np.zeros((1, int(self.input_dim)))
        self.model(x)
        self.model.load_weights(path)

    def plot_metrics(self, metrics):
        for metric in metrics:
            self._plot_one_metric(metric=metric)

    def _plot_one_metric(self, metric):
        train_metrics = self.history.history[metric]
        val_metrics = self.history.history['val_' + metric]
        epochs = range(1, len(train_metrics) + 1)
        plt.plot(epochs, train_metrics)
        plt.plot(epochs, val_metrics)
        plt.title('Training and validation ' + metric)
        plt.xlabel("Epochs")
        plt.ylabel(metric)
        plt.legend(["train_" + metric, 'val_' + metric])
        plt.savefig(f'plots/{metric}.pdf')
        plt.show()

    def evaluate(self, M_test, dim, path, color_code_min=None, color_code_max=None, i=0):
        if len(M_test.shape) == 2:
            M_test = M_test[None, :, :]

        # Convert
        M_tris = list()
        for m in M_test:
            tri_M = m[np.triu_indices(m.shape[0])]
            M_tris.append(tri_M)
        M_tris = np.array(M_tris)
        U_pred = self.predict(X=M_tris)

        matrix_sparsity = MatrixSparsity(dim=dim)
        matrix_sparsity.update_state(M_true=M_test, U_pred=U_pred)
        sparsity_test = matrix_sparsity.result()

        # Plot one example
        fig = plot_matrices(M_test[0], U_pred=U_pred[0], vmin=color_code_min, vmax=color_code_max)
        plt.savefig(f'{path}denise_output_{i}.pdf')
        fig.show()
        return sparsity_test, U_pred

    def predict(self, X):
        return self.model.predict(X)

class Shrink(tf.keras.layers.Layer):
    def __init__(self, dim):
        super(Shrink, self).__init__()
        self.dim = float(dim)

    def call(self, inputs, **kwargs):
        return tf.multiply(tf.abs(inputs) - 1/tf.sqrt(self.dim), tf.sign(inputs))

class NeuralNet_SVD:
    def __init__(self, dim, rank, lr=0.001, batch_size=64, n_epochs=30, iterations=10, valid_split=0.2,
                 loss='mean_absolute_error', metrics=None):
        self.dim = dim # tuple (n,m)
        self.n = dim[0]
        self.m = dim[1]
        self.rank = rank
        self.output_dim_U = (self.n,self.rank)  # tuple (n, k)
        self.output_dim_V = (self.m,self.rank)  # tuple (m, k)

        self.batch_size = batch_size
        self.n_epochs = n_epochs
        self.iterations = iterations
        self.valid_split = valid_split

        self.lr = lr
        self.optimizer = tf.keras.optimizers.Adam(learning_rate=self.lr)
        self.loss = custom_loss_UV(self.n)
        self.metrics = metrics
        self.model = self._create_network()

        self.history = None

    def _create_network(self):
        input_tensor = Input(shape=(self.n,self.m), name='Input')
        UV = Flatten()(input_tensor)
        # U = Dense(self.n // 2, activation='relu', name='U1')(UV)
        # U = Dense(self.n // 2, activation='relu',name='U2')(U)
        # U = Dense(self.n // 2, activation='relu',name='U3')(U)
        U = Dense(self.n*self.m, activation='relu', name='U1')(UV)
        U = Dense(self.n*self.m//2, activation='relu',name='U2')(U)
        U = Dense(self.n*self.m, activation='relu',name='U3')(U)
        U = Dense(self.output_dim_U[0] * self.output_dim_U[1], name='U4')(U)
        U = Reshape(self.output_dim_U)(U)

        # V = Dense(self.m // 2, bias_initializer="zeros", activation='relu', name='V1')(UV)
        # V = Dense(self.m // 2, activation='relu',name='V2')(V)
        # V = Dense(self.m // 2, activation='relu',name='V3')(V)
        V = Dense(self.n*self.m, bias_initializer="zeros", activation='relu', name='V1')(UV)
        V = Dense(self.n*self.m//2, activation='relu',name='V2')(V)
        V = Dense(self.n*self.m, activation='relu',name='V3')(V)
        V = Dense(self.output_dim_V[0] * self.output_dim_V[1], name='V4')(V)
        V = Reshape(self.output_dim_V)(V)
        UV = tf.concat([U,V], axis=-2)
        model = Model(inputs=input_tensor, outputs=UV)
        return model

    def compile(self):
        self.model.compile(optimizer=self.optimizer,
                           loss=self.loss,
                           metrics=self.metrics
                           )

    def train(self, X, y):
        self.compile()

        history = []
        for k in range(self.iterations):
            print('-----')
            print(f'Iteration {k}')
            print('-----')
            for x in ['U1','U2','U3','U4']:
                self.model.get_layer(x).trainable = True
            for x in ['V1','V2','V3','V4']:
                self.model.get_layer(x).trainable = False
            history.append(
                self.model.fit(X, y,
                    batch_size=self.batch_size,
                    epochs=self.n_epochs,
                    validation_split=self.valid_split,
                    verbose=1
                    )
                )
            for x in ['U1','U2','U3','U4']:
                self.model.get_layer(x).trainable = False
            for x in ['V1','V2','V3','V4']:
                self.model.get_layer(x).trainable = True
            history.append(
                self.model.fit(X, y,
                    batch_size=self.batch_size,
                    epochs=self.n_epochs,
                    validation_split=self.valid_split,
                    verbose=1
                    )
                )
        self.history = history
        self.model.summary()

    def save_weights(self, path):
        self.model.save_weights(filepath=path)

    def load_weights(self, path):
        # x = np.zeros((1, int(self.n), int(self.m)))
        # self.model(x)
        self.model.load_weights(path)

    def plot_metrics(self, metrics):
        for metric in metrics:
            self._plot_one_metric(metric=metric)

    def _plot_one_metric(self, metric):
        train_metrics = [x for hist in self.history for x in hist.history[metric]]
        val_metrics = [x for hist in self.history for x in hist.history['val_' + metric]]
        epochs = range(1, len(train_metrics) + 1)
        plt.plot(epochs, train_metrics)
        plt.plot(epochs, val_metrics)
        plt.title('Training and validation ' + metric)
        plt.xlabel("Epochs")
        plt.ylabel(metric)
        plt.legend(["train_" + metric, 'val_' + metric])
        plt.savefig(f'plots/SVD_{metric}.pdf')
        plt.show()

    def evaluate(self, M_test, dim):
        if len(M_test.shape) == 2:
            M_test = M_test[None, :, :]

        UV_pred = self.predict(X=M_test)

        matrix_sparsity = MatrixSparsity_SVD(dim=dim)
        matrix_sparsity.update_state(M_true=M_test, UV_pred=UV_pred)
        sparsity_test = matrix_sparsity.result()

        # Plot one example
        fig = plot_matrices(M_test[0], UV_pred=UV_pred[0])
        plt.savefig('plots/SVD_denise_output.pdf')
        fig.show()
        return sparsity_test, UV_pred

    def predict(self, X):
        return self.model.predict(X)


import turtle
import pandas

counter = 0
screen = turtle.Screen()
screen.title("US STATES GAMES")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)

us_data = pandas.read_csv("50_states.csv")
state_names = us_data['state']
state_names = state_names.tolist()

def get_user_answer():
    return screen.textinput(title=f"{counter} out of 50 done", prompt="Name another state").title()

def mark_on_map(answer_text):
    t=turtle.Turtle()
    t.hideturtle()
    t.penup()
    selected_state = us_data[us_data.state == answer_text]
    t.goto(int(selected_state.x),int(selected_state.y))
    t.write(answer_text)

already_answered = []

while True:
    answer_text =  get_user_answer()
    if(answer_text == 'Exit'):
        break
    if answer_text in state_names and answer_text not in already_answered:
        counter += 1
        mark_on_map(answer_text)
        already_answered.append(answer_text)
        print("correct")
    if counter == 50:
        print("all 50 done")
        break

missed_states = [st for st in state_names if st not in already_answered]

df = pandas.DataFrame({"States" : missed_states})
df.to_csv("states_to_learn.csv")


from msdi_io import *
import numpy as np
from skimage.feature import hog
from librosa.feature import mfcc
from os import listdir
import json, pickle

_msdi_path = 'msdi'
orientation_hog_img = 8
P=Q=3

def contructing_img_feature(img):
    hog_vector, _ = hog(img, orientations=orientation_hog_img, pixels_per_cell=(img.shape[0]//P, img.shape[1]//Q),
        cells_per_block=(1, 1), visualize=True, multichannel=True)
    return hog_vector

def contructing_tram_feature(tram):
    return np.sum(tram, axis=0)

def building_data():
    labels = get_label_list()
    msdi = get_msdi_dataframe(_msdi_path)
    with open('bag_of_words.json', 'r') as fp:
        bag_of_words = json.load(fp)
    dataset = []
    for index in range(len(msdi)):
        entry = msdi.loc[index] # index in the data file
        set = get_set(entry) # train/val/test
        track_id = get_track_id(entry) # track ID

        tram = load_mfcc(entry, _msdi_path) # load mfcc
        tram_feature = contructing_tram_feature(tram) # audio features

        img = load_img(entry, _msdi_path) # get image
        img_feature = contructing_img_feature(img) # img features

        entry_label = get_label(entry) # instance label

        # bag_of_words in the dict. I built it before

        info = {
            'id' : track_id,
            'instance_set' : set,
            'label' : labels.index(entry_label),
            'audio' : tram_feature,
            'image' : img,
            'hog' : img_feature,
            'bag_of_words': np.asarray(bag_of_words[track_id]) if track_id in bag_of_words.keys() else None
        }

        dataset.append(info)
    return dataset

#print(load_mfcc_dicts()["mfcc_A.npz"].keys())

dataset = building_data()
#filehandler = open("dataset.txt","wb")
#pickle.dump(dataset,filehandler)


from pulp import *
problem = LpProblem("Controlling Air Pollution", LpMinimize)

# Create Variables
num_abate = 6
x = LpVariable.dicts("x",list(range(num_abate)),0 , 1) # x >= 0
annual_cost = [8,10,7,6,11,9]
reduct_req = [60,150,125]
emiss_rate = [[12,9,25,20,17,13],
              [35,42,18,31,56,49],
              [37,53,28,24,29,20]]

# Objective Function
problem += lpSum([annual_cost[i] * x[i] for i in range(num_abate)])

# Constraint
c1 = lpSum([emiss_rate[0][j] * x[j] for j in range(len(emiss_rate[0]))]) >= reduct_req[0]
c2 = lpSum([emiss_rate[1][j] * x[j] for j in range(len(emiss_rate[1]))]) >= reduct_req[1]
c3 = lpSum([emiss_rate[2][j] * x[j] for j in range(len(emiss_rate[2]))]) >= reduct_req[2]

problem += c1
problem += c2
problem += c3

print(problem)
problem.solve()
print(value(problem.objective))
for i in range(num_abate) :
    print(value(x[i]))


from zope.interface import Interface
from zope.container.constraints import contains
from jpl.mcl.protocol import _
from plone.app.textfield import RichText
from zope import schema

class IAsserter(Interface):
    '''An object that describes subjects with a known predicate and a given object'''
    def characterize(obj):
        '''Characterize some subject using a known predicate for complementary ``obj``.  Returns a sequence of doubles
        containing a predicate URI (a URIRef) and an appropriate Literal or URIRef object.'''

class IOrgan(Interface):
    '''An object that describes an Organ'''

class IProtocolFolder(Interface):
    '''Study folder.'''
    contains('jpl.mcl.protocol.protocol.IProtocol', 'jpl.mcl.protocol.interfaces.IProtocolFolder')
    title = schema.TextLine(
        title=_(u'Title'),
        description=_(u'Descriptive name of this folder.'),
        required=True,
    )
    description = RichText(
        title=_(u'Description'),
        description=_(u'A short summary of this folder.'),
        required=False,
    )
    rdfDataSource = schema.TextLine(
        title=_(u'RDF Data Source'),
        description=_(u'URL to a source of Resource Description Format data that mandates the contents of this folder.'),
        required=False,
    )


from spiketimes.simulate import (
    homogeneous_poisson_process,
    imhomogeneous_poisson_process,
)
import numpy as np
import pytest

class Testhomogeneous:
    def test_num_output_samples(self):
        rate = 4
        n_time_units = 30
        n_bootstrap_replicates = 1000
        expected = int(rate * n_time_units)
        actual = int(
            np.mean(
                np.array(
                    [
                        len(homogeneous_poisson_process(rate, n_time_units))
                        for _ in range(n_bootstrap_replicates)
                    ]
                )
            )
        )
        assert np.absolute(actual - expected) < 5

    def test_output_shape(self):
        expected = 1
        actual = int(len(homogeneous_poisson_process(4, 10, 0).shape))
        assert actual == expected

class TestImhomogeneous:
    def test_num_output_samples(self):
        time_1 = 30
        time_2 = 20
        rate_1 = 2
        rate_2 = 3
        time_rate = [(time_1, rate_1), (time_2, rate_2)]
        n_bootstrap_replicates = 1000
        expected = int((time_1 * rate_1) + (time_2 * rate_2))
        actual = int(
            np.mean(
                np.array(
                    [
                        len(imhomogeneous_poisson_process(time_rate))
                        for _ in range(n_bootstrap_replicates)
                    ]
                )
            )
        )
        assert np.absolute(actual - expected) < 5

    def test_output_shape(self):
        expected = 1
        actual = len(imhomogeneous_poisson_process([(1, 2), (2, 1)]).shape)
        assert actual == expected


import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy.crawler import Request
import os
import logging

class SerieASpidermatch(scrapy.Spider):
    name = "Serie A"
    start_urls = ["https://www.booking.com/"]

    def start_requests(self):
        for d in [URLS]:
            yield Request(d,callback=self.parse)

    def parse(self, response):
        card = response.xpath('//*[@id="outer-edito-content"]/div[3]/main/div[3]/div[2]/div[1]/div/div')
        for i in card:
            winner = i.css('div.TeamScore__name TeamScore__team--winner').get()
            looser = i.css('TeamScore__name TeamScore__team--looser').get()
            score = i.css('TeamScore__score TeamScore__score--ended').getall()
            dic = {
                'winner': winner , 'looser': looser , 'score': score
            }

            yield dic

# Define a filename
filename = "serie_A_scrap_matches.json"

# Remove previous file if it allready exist
if filename in os.listdir('src/'):
        os.remove('src/' + filename)

# Define the settings for the crawler process
process = CrawlerProcess(settings = {
    # simulate browser
    'USER_AGENT': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:98.0) Gecko/20100101 Firefox/98.0',
    # display regular errors
    'LOG_LEVEL': logging.INFO,
    "FEEDS": {
        'src/' + filename : {"format": "json"},
    }
})

# Initiate crawler
process.crawl(SerieASpidermatch)
process.start()


"""Runs a single episode to compare step durations across batch sizes.
"""

import ml_collections
import numpy as np
from configs.trial_config import trial_config

def get_config():
    config = ml_collections.ConfigDict()
    config.experiment_name = 'mlp_batch_sizes'
    config.trials = []
    for param in [64, 128, 256, 512, 1024]:
        trial = trial_config('MLP')
        trial.epochs = 1
        trial.batch_size = param
        trial.trial_name = f'batch_size_{param}'
        config.trials.append(trial)
    config.lock()
    return config


import cv2 as cv
import argparse
import matplotlib.pyplot as plt
import math
import numpy as np
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'

from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer, ColorMode
from detectron2.data import MetadataCatalog
from detectron2 import model_zoo
from detectron2.projects.deeplab import add_deeplab_config

import warnings
warnings.filterwarnings('ignore')
import torch
import imutils

parser = argparse.ArgumentParser('run video')
parser.add_argument('-v', '--video_dir', type = str, help ='video directory')
parser.add_argument('-yaml', '--config_yaml', type = str, help ='config yaml file')
args = parser.parse_args()

def run_video(video_dir, config_yaml):

    cfg = get_cfg()
    cfg.merge_from_file(model_zoo.get_config_file(config_yaml))
    cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
    cfg.INPUT.CROP.ENABLED = False
    cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(config_yaml)
    cfg.MODEL.DEVICE = 'cuda'
    predictor = DefaultPredictor(cfg)

    # run video
    cap = cv.VideoCapture(video_dir)   #for webcam: 0 if single, if multiple: choose for e.g 1; if no rto -> video_dir

    width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
    size =(width, height)
    fourcc= cv.VideoWriter_fourcc(*"MP4V")

    # VideoWriter for output video
    video_writer = cv.VideoWriter(video_dir[:-4] +'_output.mp4', fourcc, 20.0, size)

    while True:
        isTrue, frame = cap.read()
        if isTrue:
#             frame = imutils.resize(frame, width=640, height=480)
            panoptic_seg, segments_info = predictor(frame)["panoptic_seg"]

            v = Visualizer(frame[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1)
            output = v.draw_panoptic_seg_predictions(panoptic_seg.to("cpu"), segments_info)

            # get labels for panoptic seg
            thing_classes = [i['category_id'] for i in segments_info if i['isthing'] == True]
            stuff_classes = [i['category_id'] for i in segments_info if i['isthing'] == False]

            thing_names = MetadataCatalog.get(cfg.DATASETS.TRAIN[0]).thing_classes
            stuff_names = MetadataCatalog.get(cfg.DATASETS.TRAIN[0]).stuff_classes
            pred_class_names = list(map(lambda x: thing_names[x], thing_classes)) + list(map(lambda x: stuff_names[x], stuff_classes))

            # display and save result
            cv.cvtColor(output.get_image()[:, :, ::-1], cv.COLOR_BGR2RGB)
            cv.imshow('result', output.get_image()[:, :, ::-1])
            video_writer.write(output.get_image()[:, :, ::-1])
            cv.waitKey(1)

        else:
            break

    cap.release()
    video_writer.release()
    cv.destroyAllWindows()

if __name__=='__main__':
    run_video(args.video_dir, args.config_yaml)


import pandas as pd
from constants import AVAILABLE_ASSETS
from player import Player
from utils import object_name

class Game(object):

    state = 'running'

    def __init__(self):
        self.player = None

    def create_player(self, name=None):
        player = Player(name=name)
        self.player = player

    def get_player(self):
        return self.player

    def get_assets(self):
        df = pd.DataFrame(list(self.player.get_assets()))
        df.columns = ["Owned Assets"]
        df.applymap(lambda x: object_name(x))
        print(df)
        return df

    def list_assets(self):
        df = pd.DataFrame(list(AVAILABLE_ASSETS.keys()))
        df.columns = ["Assets"]
        df.applymap(lambda x: object_name(x))
        print(df)
        return df

    def list_player_inventory(self):
        shop = self.player.get_inventory()
        if shop == {}:
            print('You have no ores mined')
            return

        print(f"{self.player.name}'s Shop")
        tildes = "~" * len(self.player.name) + "~~~~~"

        "Item Name", "Quantity"
        print(df)

        return len(shop)

    def display_available_commands(self):
        print('Available commands: ')
        print('1. mine')
        print('2. balance')
        print('3. close')
        print('4. buy')
        print('5. sell')

if __name__ == '__main__':
    g = Game()
    g.create_player("Cyber")
    player = g.get_player()

    while g.state == 'running':
        g.display_available_commands()
        command = input('Enter command: ')
        if command.lower() == 'mine':
            player.mine()
        elif command.lower() == 'balance':
            balance = player.get_account_balance()
            print(balance)
        elif command.lower() == 'close':
            g.state = 'not running'
        elif command.lower() == 'buy':
            g.list_assets()
            asset_to_buy = input("Enter the name of the asset you want to buy: ")
            player.buy_asset(asset_to_buy)
        elif command.lower() == 'sell':
            available_items = g.list_player_inventory()
            if not available_items or available_items == 0:
                continue
            ore = input("Enter the ore you want to sell: ")
            quantity = int(input(f"Enter the number of units of {ore} you want to sell: "))
            player.sell_from_shop(ore, quantity)
        else:
            print('Invalid input, please try again.')


from bs4 import BeautifulSoup
from lxml.etree import tostring
import lxml.html
from src.parser import Parser

class Extractor(object):
    """
    Extract data from HtmlElement
    Data includes:
        - Link
        - Author
        - Title
        - Text/Description
        - Price
        - Image
        - Date time
        - Rating
        - Comments
    """
    def __init__(self, node, type='a'):
        """
        doc: html source
        type: 'a' => article; 'c' => comment
        """
        self.type = type
        self.root = node

    def get_title_for_article(self):
        """Fetch the article title and analyze it

        Assumptions:
        - title tag is the most reliable (inherited from Goose)
        - h1, if properly detected, is the best (visible to users)
        - og:title and h1 can help improve the title extraction
        - python == is too strict, often we need to compare filtered
          versions, i.e. lowercase and ignoring special chars

        Explicit rules:
        1. title == h1, no need to split
        2. h1 similar to og:title, use h1
        3. title contains h1, title contains og:title, len(h1) > len(og:title), use h1
        4. title starts with og:title, use og:title
        5. use title, after splitting
        """
        title = ''
        text_title = Parser.find_elements_by_tag(self.root, 'title')[0].text

        h1s = Parser.find_elements_by_tag(self.root, 'h1') or []
        h1s_text = Parser.rejoin_group_text([h1.text for h1 in h1s])
        if h1s_text:
            h1s_text.sort(key=len, reverse=True)
            h1_title = h1s_text[0]

            if len(h1_title) <= 5:
                h1_title = ''

        fb_title = (

        )


#!/usr/bin/env python3
from eye import *
import time
import random
import math

angular_base_speed = 45  # initial angular BASE speed in degrees per second, i.e. deg/s. For use in Proportional!
angular_speed = 0  # initial angular speed in degrees per second, i.e. deg/s.
angular_error = 0  # initial angular error. For use in Proportional!
linear_speed = 400  # initial linear speed in millimeter per second, i.e. mm/s.
max_range = 5000  # the maximum range (distance) that the robot can sense/see, e.g. 15000 mm is 15 meters
ASPEED = 100
THRES = 225

def main():
    LCDMenu("", "", "", "END")
    curr_time = 0
    tot_time = 0
    dn_0 = ""
    min_scan_0 = 0
    isScared = 0
    while True:
        temp_time = time.strftime('%S')
        if curr_time != temp_time:
            curr_time = temp_time
            LCDSetPrintf(0, 45, "Time elapsed: %d secs", tot_time)
            tot_time = tot_time + 1
            sec = tot_time % 30 #90
            min_scan = max_range  # put a very high scan value (distance) initially at each step/scan, 15000 mm is 15 meters
            min_scan_index = 0  # initial (at each step/scan) index is 0, i.e. rear of robot
            heading_to_turn = 0  # initial (at each step/scan) heading to turn is 0 degree, i.e. no need to turn!
            LCDSetPrintf(1, 45, "COCKROACH - Light off")
            scan = LIDARGet()
            for i in range(0, 360):  # read 360-degrees range around the robot
                LCDLine(i, 250 - int(scan[i] / 10), i, 250, BLUE)
                if scan[i] <= min_scan:
                    LCDSetPrintf(
                        2, 45, "NEW min detected: %d mm", scan[i]
                    )  # just to check the minimum reading
                    min_scan = scan[i]
                    min_scan_index = i
            # mark the minimum reading on the plot, using yellow line
            LCDLine(min_scan_index, 250 - int(min_scan / 10), min_scan_index, 250, YELLOW)
            LCDLine(180, 0, 180, 250, RED)  # straight, 0 degrees
            LCDLine(90, 0, 90, 250, GREEN)  # left, -90 degrees
            LCDLine(270, 0, 270, 250, GREEN)  # right, +90 degrees
            LCDSetPrintf(19, 0, "            -90             0             +90")
            if sec <= 10: #60
                dn = "Light off"
                if isScared == 0:
                    if min_scan < max_range:  # something is within detectable range
                        LCDSetPrintf(6, 45, "Something detected!")
                        if min_scan_index == 180:  # heading is exactly at front!
                            heading_to_turn = 0
                        elif min_scan_index < 180:
                            heading_to_turn = 180 - min_scan_index
                            heading_to_turn = heading_to_turn * 1  # turn left, +ve angle
                        elif min_scan_index > 180:
                            heading_to_turn = min_scan_index - 180
                            heading_to_turn = heading_to_turn * -1  # turn right, -ve angle
                        else:  # error? remain heading 0
                            heading_to_turn = 0
                        # just checking if min_scan actually has the minimum distance scanned
                        if min_scan == min(scan):
                            LCDSetPrintf(3, 45, "LIDAR min dist scanned: %d mm", min_scan)
                            LCDSetPrintf(4, 45, "LIDAR index of min dist: %d", min_scan_index)
                            LCDSetPrintf(5, 45, "Heading to turn: %d degrees", heading_to_turn)
                        # Proportional turn: the further the heading to turn,
                        # the faster the angular speed should be, vice-versa.
                        angular_error = abs(heading_to_turn) - angular_base_speed
                        angular_speed = angular_error + angular_base_speed
                        if heading_to_turn != 0:  # only turn if the heading to turn is NOT right in-front!
                            VWTurn(heading_to_turn, angular_speed)  # angular_speed should be Proportional, now!
                            VWWait()  # OPTIONAL: can remove for this scenario, for now
                        # RE-INIT angular variables
                        angular_error = 0
                        angular_speed = 0
                        # move straight forward, as far as the minimum distance scanned.
                        VWStraight(min_scan, linear_speed)
                    else:  # NOTHING is within detectable range
                        LCDSetPrintf(6, 45, "Something NOT detected!")
                        VWSetSpeed(0, 0)  # just stay put, i.e. Stop!
                else:
                    isScared = isScared - 1
                    if isScared == 0:
                        VWStraight(2000, linear_speed)
                        VWWait()
            else:
                dn = "Light on"
                LCDSetPrintf(1, 45, "COCKROACH - Light  on")
                if sec == 11: #61 # first second of daytime
                    VWTurn(180, ASPEED)
                    VWWait()
                    isScared = 0
                else:
                    if isScared != 5:
                        left = int(scan[90] > THRES)
                        front = int(scan[180] > THRES)
                        right = int(scan[270] > THRES)
                        print(left, front, right)
                        if front != 1 and right != 1:
                            VWTurn(135, ASPEED)  # turn anticlockwise
                            VWWait()
                            isScared = 5
                        elif front != 1 and left != 1:
                            VWTurn(-135, ASPEED)  # turn clockwise
                            VWWait()
                            isScared = 5
                        elif front == 1:
                            VWStraight(scan[180]-(THRES-1), linear_speed)
                            VWWait()
                        elif front != 1:
                            if left == 1 and right == 1: #left < right # turn right
                                if scan[90] < scan[270]:  #left < right #turn left
                                    angle = 90
                                else:
                                    angle = -90
                                VWTurn(angle, ASPEED)
                                VWWait()
                            elif scan[90] < scan[270]: #left < right # turn right
                                angle = int(math.degrees(math.atan(scan[180] / scan[90])) + 90)
                                VWTurn(-angle, ASPEED)
                                VWWait()
                            else:  # turn left
                                angle = int(math.degrees(math.atan(scan[180] / scan[270])) + 90)
                                print(scan[180], scan[270], angle)
                                VWTurn(angle, ASPEED)
                                VWWait()
        if dn != dn_0:
            dn_0 = dn
            print(dn_0)
            AUBeep()
        key = KEYRead()
        if key == KEY4:
            return 0

main()


from concurrent import futures
import time
import grpc
import os
import prometheus_client

import recognizer_pb2_grpc as grpc_proto
import recognizer_pb2 as proto
import recognizer
import metrics

class Servicer(grpc_proto.FaceRecognizerServicer):
    RECOGNIZE_HISTOGRAM = metrics.request_latency_histogram.labels(
        'recognize_faces')

    @RECOGNIZE_HISTOGRAM.time()
    def RecognizeFaces(self, request, context):

        faces = recognizer.recognize(request.url)
        proto_faces = []
        for face in faces:
            area = face['area']
            encoding = face['encoding']
            proto_face = proto.Face(x=area['x'], y=area['y'], width=area['width'],
                                    height=area['height'], encoding=encoding)
            proto_faces.append(proto_face)

        metrics.request_counter.labels('recognize_faces').inc()

        return proto.RegognizeResponse(faces=proto_faces)

def serve():

    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

    grpc_proto.add_FaceRecognizerServicer_to_server(
        Servicer(),
        server
    )

    server.add_insecure_port('[::]:' + os.environ['GRPC_PORT'])

    server.start()

    try:
        while True:
            time.sleep(60 * 60 * 24)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    prometheus_client.start_http_server(int(os.environ['METRICS_PORT']))
    serve()


import numpy as np
import tensorflow as tf
m = 100000
batch_size = 64
epochs = 100
learning_rate = 0.001
x_data = np.random.rand(m,2)
y_data = (x_data.sum(axis=1, keepdims=1)>1).astype(np.float32)

w1 = tf.Variable(tf.random_normal((2,4),stddev=1,seed=1))
b1 = tf.Variable(tf.zeros((4,)))
w2 = tf.Variable(tf.random_normal((4,1),stddev=1,seed=1))
b2 = tf.Variable(tf.zeros(1,))

x = tf.placeholder(tf.float32,shape=(None,2),name="input-x")
y = tf.placeholder(tf.float32,shape=(None,1),name="input-y")

a  = tf.nn.relu(tf.matmul(x, w1) + b1)
y_ = tf.nn.relu(tf.matmul(a, w2) + b2)

loss = -tf.reduce_mean(y*tf.log(tf.clip_by_value(y_, clip_value_min=1e-10, clip_value_max=1.0))
                       + (1-y)*tf.log(tf.clip_by_value(1-y_, clip_value_min=1e-10, clip_value_max=1.0)))
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    for epoch in range(epochs):
        start = 0
        while start < m:
            end = min(m,start+batch_size)
            sess.run(optimizer,feed_dict={x:x_data[start:end], y:y_data[start:end]})
            start = end
        y_pred = sess.run(y_,feed_dict={x:x_data})
        precision = ((y_pred>0.5)==(y_data>0.5)).astype(np.float32).sum()/m
        print("epoch ",epoch,sess.run(loss,feed_dict={x:x_data,y:y_data}),precision)
        #print("w1:",sess.run(w1))
        #print("w2:",sess.run(w2))


"""
This is the simplified version of the `py_arduino.py` script.
It reads serial data from arduino and prints it to console.
The arduino has to be connected to the computer via USB.
"""

import argparse
import time

import serial

def main():
    """reads serial data from arduino and prints it to console"""

    ap = argparse.ArgumentParser()
    ap.add_argument(
        "-c", "--commport", required=True, help="Arduino's communication port"
    )
    args = ap.parse_args()
    commport = args.commport

    ser = serial.Serial(commport, 9600, timeout=10)

    while True:
        if ser.in_waiting:
            line = ser.readline().decode("utf-8").rstrip()
            print(line)
        time.sleep(1)

if __name__ == "__main__":
    main()