from ROOT import *
import copy

from hist2plot_cff import *
from mcsample_cfi import *
from monitors_cfi import *

#import sys

mon = monitors
#for i,ii in enumerate(monitors):
#  #print monitors[ii]
#  mon+=monitors[ii]

mon2 = []
for i,ii in enumerate(monitors2d):
  #print monitors2d[ii]
  mon2.append(monitors2d[ii])

json = {
"file": "hist_all.root",
#"file": "hist_all2.root",
"mcsamples" : mcsamples,
"datasamples" : datasamples,
#"cuts" : ["S0","S1","S2","S3","S4","S5"],
#"cuts" : ["S0","S1","S2","S3"],
#"cuts" : ["S0","S1","S2","S3","S4","S5","S6"],
"cuts" : [
"S0mm","S1mm","S2mm","S3mm","S4mm","S5mm","S6mm","S7mm",
"S0ee","S1ee","S2ee","S3ee","S4ee","S5ee","S6ee","S7ee",
"S0em","S1em","S2em","S3em","S4em","S5em","S6em","S7em"
   ],
#"cuts" : ["S6"],

#"monitors" : monitors["jetMon3"]
"monitors" : mon,
"monitors2" : mon2
}

#########
#TH1F
f = json['file'] #TFile.Open(json['file'],"read")
#singleplotStack2(f,"MET","S2em",json['mcsamples'],json['datasamples'],False)
######
#for step in json['cuts']:
#  for mon in json['monitors']:
#    singleplotStack2(f,mon['name'],step,json['mcsamples'],json['datasamples'],False)

#########
#TH2F
#for step in json['cuts']:
#  for ii,mon in enumerate(json['monitors2']):
#    for i,mon1 in enumerate(mon):
#      for j,mon2 in enumerate(mon):
#        if i<j :
#          mon_ = mon1['name']+"_"+mon2['name']
#          plotTH2F(f,mon_,step,json['mcsamples'],json['datasamples'])

jsonLL = {
"file": "hist_all.root",
#"file": "hist_all2.root",
"mcsamples" : mcsamples,
"datasamples" : datasamples,
#"cuts" : ["S0","S1","S2","S3","S4","S5"],
#"cuts" : ["S0","S1","S2","S3"],
#"cuts" : ["S0","S1","S2","S3","S4","S5","S6"],
"cuts" : [
"S0","S1","S2","S3","S4","S5","S6","S7"
   ],
#"cuts" : ["S6"],

#"monitors" : monitors["jetMon3"]
"monitors" : mon,
"monitors2" : mon2
}

f1 = jsonLL['file'] #TFile.Open(json['file'],"read")
for step1 in jsonLL['cuts']:
  for mon1 in jsonLL['monitors']:
    singleplotStackLL2(f1,mon1['name'],step1,jsonLL['mcsamples'],jsonLL['datasamples'],False)


import glob
import os
import shutil
import re
import tkinter as tk
import tkinter.messagebox
from datetime import date
from os import rename
from pathlib import Path
from tkinter import filedialog

font_size = 15

def match_iban(search_str: str):
    m = re.search("AT[0-9]+", search_str)

    if m is None:
        return None

    return m.group(0)

def change_font_size(increase, root, frame):
    global font_size
    if increase:
        font_size += 1
    else:
        if font_size < 10:
            tkinter.messagebox.showerror(title="Fehler", message="Schriftgröße kann nicht weiter reduziert werden.")
            return
        font_size -= 1

    frame.destroy()

    # root.iconbitmap("example/path/file.ico")
    root.option_add("*Font", ('Arial', font_size))

    MainWindow(root)

class MainWindow:
    def __init__(self, master):
        self.log_messages = ""
        self.error_messages = ""
        self.folder_path = ""
        self.target_folder_path = ""

        self.master = master

        self.master.columnconfigure(0, weight=1)
        self.master.rowconfigure(0, weight=1)

        self.frame = tk.Frame(self.master)
        self.frame.grid(row=0, column=0, padx=50, pady=50, sticky="NSEW")

        self.frame.columnconfigure((0, 1, 2, 3), weight=1)
        self.frame.rowconfigure((0, 1, 2, 3, 4), weight=1)

        # directory input field
        self.dLabel = tk.Label(self.frame, text="Verzeichnis:  ").grid(column=0, row=0, sticky="NSEW")
        self.directoryEntry = tk.Entry(self.frame, width=80)
        self.directoryEntry.grid(column=1, row=0, sticky="")
        self.dirSelectButton = tk.Button(self.frame, text="...", command=self.select_directory)
        self.dirSelectButton.grid(column=2, row=0, sticky="")

        # output directory input field for move mode
        self.move_directory_label = tk.Label(self.frame, text="Zielverzeichnis:  ").grid(column=0, row=1, sticky="")
        self.move_directory_entry = tk.Entry(self.frame, width=80)
        self.move_directory_entry.grid(column=1, row=1, sticky="")
        self.move_dir_select_button = tk.Button(self.frame, text="...", command=self.select_move_directory)
        self.move_dir_select_button.grid(column=2, row=1, sticky="")

        # checkbox for rename mode
        self.rename_var = tk.IntVar(self.master)
        self.rename_var.set(0)
        self.rename_box = tk.Checkbutton(self.frame, text="Umbenennen", variable=self.rename_var, command=self.rename_button_action)
        self.rename_box.grid(column=0, row=2, sticky="")

        # checkbox for move mode
        self.move_var = tk.IntVar(self.master)
        self.move_var.set(1)
        self.move_box = tk.Checkbutton(self.frame, text="Kopieren", variable=self.move_var, command=self.move_button_action)
        self.move_box.grid(column=1, row=2, sticky="")

        self.move_button_action()

        # confirm button
        self.confirm = tk.Button(self.frame, text="Bestätigen", command=self.submit)
        self.confirm.grid(column=1, row=3, sticky="NSEW")

        # close button
        self.close = tk.Button(self.frame, text="Schließen", command=self.master.destroy)
        self.close.grid(column=2, row=3, sticky="")

        # increase font size
        self.increase_size_button = tk.Button(self.frame, text="+", command=lambda: change_font_size(True, self.master, self.frame))
        self.increase_size_button.grid(column=2, row=4, sticky="NSEW", padx=50, pady=10)

        # reduce font size
        self.reduce_size_button = tk.Button(self.frame, text="-", command=lambda: change_font_size(False, self.master, self.frame))
        self.reduce_size_button.grid(column=1, row=4, sticky="NSEW", padx=50, pady=10)

    def rename_button_action(self):
        self.move_var.set(0)

        self.rename_box.config(state="disabled")
        self.move_box.config(state="normal")

        self.move_directory_entry.config(state="disabled")
        self.move_dir_select_button.config(state="disabled")

        self.master.update()

    def move_button_action(self):
        self.rename_var.set(0)

        self.rename_box.config(state="normal")
        self.move_box.config(state="disabled")

        self.move_directory_entry.config(state="normal")
        self.move_dir_select_button.config(state="normal")

        self.master.update()

    def select_directory(self):
        self.folder_path = filedialog.askdirectory()
        self.directoryEntry.delete(0, "end")
        self.directoryEntry.insert(0, self.folder_path)

    def select_move_directory(self):
        self.target_folder_path = filedialog.askdirectory()
        self.move_directory_entry.delete(0, "end")
        self.move_directory_entry.insert(0, self.target_folder_path)

    def show_result_window(self):
        self.log_messages = self.log_messages.replace("/", "\\")
        self.error_messages = self.error_messages.replace("/", "\\")

        result_window = tk.Tk()
        result_window.option_add("*Font", ('Arial', font_size))
        ResultWindow(result_window, self.log_messages, self.error_messages)

        self.master.destroy()

        result_window.mainloop()

    def submit(self):
        if self.folder_path == "" or self.folder_path is None:
            tkinter.messagebox.showerror(title="Fehler", message="Verzeichnis kann nicht leer sein.")
            return

        if self.rename_var.get() == 1:

            self.iterate_rename_files(".pdf")
            self.iterate_rename_files(".xml")

        else:
            if self.target_folder_path == "" or self.target_folder_path is None:
                tkinter.messagebox.showerror(title="Fehler", message="Zielverzeichnis kann nicht leer sein.")
                return

            self.copy_files()

        self.show_result_window()

    def iterate_rename_files(self, file_ending: str):

        all_files = glob.glob(self.folder_path + "/*" + file_ending)

        if not all_files:
            self.error_messages += "No files with the ending " + file_ending + " found in the selected folder.\n"

        for file_ in all_files:
            self.rename_file(file_, file_ending)

    def rename_file(self, file_name: str, file_ending: str):
        today = date.today()
        datestamp = today.strftime("%Y%m%d")
        file_name = re.sub(pattern=".*\\\\", repl="", string=file_name)

        iban = match_iban(file_name)

        if iban is None:
            self.error_messages += "Die Datei '" + file_name + "' enthält keinen IBAN und wird nicht umbenannt.\n"

        else:
            new_name = iban + "_" + datestamp + file_ending
            try:
                rename(self.folder_path + "/" + file_name, self.folder_path + "/" + new_name)
                self.log_messages += "Die Datei '" + file_name + "' wurde in '" + new_name + "' umbenannt.\n"
            except FileExistsError:
                self.error_messages += "Die Datei '" + self.folder_path + "\\" + file_name + "' kann nicht umbenannt werden. Der resultierende Dateiname existiert bereits.\n"

    def copy_files(self):
        all_files = glob.glob(self.folder_path + "/*.pdf")

        for file in all_files:
            iban = match_iban(file)
            if iban is None:
                self.error_messages += str(file) + " wurde übersprungen.\n"
                continue
            else:
                folder_name = self.target_folder_path + "/" + iban
                if not Path(folder_name).is_dir():
                    os.mkdir(folder_name)
                shutil.copy2(file, folder_name)
                self.log_messages += str(file) + " wurde kopiert nach " + folder_name + "\n"

class ResultWindow:
    def __init__(self, master, log_messages, error_messages):
        # window definitions
        self.master = master
        self.res = tk.Frame(self.master)
        self.master.title("Nachrichten")
        self.res.pack()

        # label for error entry
        self.error_label = tk.Label(self.master, text="Fehler")
        self.error_label.pack()

        # entry to show errors and warnings
        self.error_text = tk.Text(self.master, width=200, height=10)
        self.error_text.pack()
        self.error_text.insert("end", error_messages)
        # read-only
        self.error_text.bind("<Key>", lambda e: "break")

        # label for log entry
        self.log_label = tk.Label(self.master, text="Log")
        self.log_label.pack()

        # entry to show logs
        self.log_text = tk.Text(self.master, width=200, height=10)
        self.log_text.pack()
        self.log_text.insert("end", log_messages)
        # read-only
        self.log_text.bind("<Key>", lambda e: "break")

        # close button
        self.close = tk.Button(self.master, text="Schließen", command=self.master.destroy)
        self.close.pack()

if __name__ == '__main__':
    root = tk.Tk()
    root.title("File Renamer")

    # root.iconbitmap("example/path/file.ico")
    root.option_add("*Font", ('Arial', font_size))

    main_page = MainWindow(root)

    root.mainloop()


from types import MethodType
from unittest import result

import numpy as np
import cv2
from PySide2.QtWidgets import QMainWindow,QLabel
from PySide2.QtGui import QImage,QPixmap
from PySide2.QtCore import Qt,Signal,QEvent
from PIL.ImageQt import ImageQt
from pdf2image import convert_from_path

from .utils import loadUi
from .elaboration import ElaborationManager,ElaborationHandler

def dragEnterEvent(self, event):

	if event.mimeData().hasUrls:
		event.accept()
	else:
		event.ignore()

def dragMoveEvent(self, event):

	if event.mimeData().hasUrls:
		event.accept()
	else:
		event.ignore()

def dropEvent(self,event):

	if event.mimeData().hasUrls:
		event.setDropAction(Qt.CopyAction)
		filepath = event.mimeData().urls()[0].toLocalFile()
		self.set_image(filepath)
		event.accept()
	else:
		event.ignore()

def set_image(self,filepath):
	self.image = None
	self.image = convert_from_path(filepath)[0]
	self.npimg = np.array(self.image)
	image = ImageQt(self.image)
	qpimage = QPixmap.fromImage(image)
	qpimage = qpimage.scaled(556, 800,Qt.KeepAspectRatio)
	self.setPixmap(qpimage)
	self.setAlignment(Qt.AlignCenter)

class Home(QMainWindow):
	def __init__(self):
		super(Home,self).__init__()
		loadUi("./uiFiles\home.ui",self)
		self.image_label.installEventFilter(self)
		self._add_method_to_label_class(self.image_label)
		self.create_dictionary()
		self.elabManager = ElaborationManager()
		self.elabHandler = ElaborationHandler(self.elabManager.results)
		self.elabHandler.new_results.connect(self.plot_results)
		self.readButton.clicked.connect(self.read_image)
		self.elabHandler.start()

	def create_dictionary(self):
		self.image_labels = {}
		self.image_labels['nome'] = self.image_name
		self.image_labels['data'] = self.image_data
		self.image_labels['targa'] = self.image_targa
		self.image_labels['cf'] = self.image_cf
		self.image_labels['via'] = self.image_via

		self.text_labels = {}
		self.text_labels['nome'] = self.text_name
		self.text_labels['data'] = self.text_data
		self.text_labels['targa'] = self.text_targa
		self.text_labels['cf'] = self.text_cf
		self.text_labels['via'] = self.text_via

	def _add_method_to_label_class(self,label):
		label.setAcceptDrops(True)
		label.image = None
		label.npimg = None
		label.dragEnterEvent = MethodType(dragEnterEvent,label)
		label.dragMoveEvent = MethodType(dragMoveEvent,label)
		label.dropEvent = MethodType(dropEvent,label)
		label.set_image = MethodType(set_image,label)

	def plot_results(self,results):

		for key,(image,text) in results.items():
			if key == "nome":
				self.image_labels[key].setPixmap(self.imgtoqpixmap(image))
				text = text.tolist()
				text = " ".join(text)
				self.text_labels[key].setText(text)
			elif key == "via":
				self.image_labels[key].setPixmap(self.imgtoqpixmap(image))
				text = text.tolist()
				text = " ".join(text)
				self.text_labels[key].setText(text.replace("()",""))
			else:
				self.image_labels[key].setPixmap(self.imgtoqpixmap(image))
				self.text_labels[key].setText(text.replace(')',""))

	def imgtoqpixmap(self,image):
		h,w,c = image.shape
		bytesPerLine = c*w
		qimage = QImage(image,w,h,bytesPerLine,QImage.Format.Format_RGB888).scaled(250,70)
		qpimage = QPixmap.fromImage(qimage)
		return qpimage

	def read_image(self):
		if self.image_label.npimg is not None and self.elabManager is not None:
			self.elabManager.imagequeue.put(self.image_label.npimg)

	def eventFilter(self, o, e):
		if e.type() == QEvent.DragEnter: #remember to accept the enter event
			self.image_label.dragEnterEvent(e)
		if e.type() == QEvent.Drop:
			self.image_label.dropEvent(e)
			# ...
			return True
		return False #remember to return false for other event types


alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'
message = input("message for decrypting: ").upper()
number = int(input('key of decrypring: '))
text = ''
for letter in message:
    index = alphabet.find(letter)
    newIndex = index + number
    if letter in alphabet:
        text += alphabet[newIndex]
    else:
        text += letter
print(text)


import sys
import os
import argparse
import urllib
import urllib2
import json
import re
import time

### Argument parser ###
parser = argparse.ArgumentParser(description="Get Wikipedia articles for a given category")
parser.add_argument("category", help="the Wikipedia category")
parser.add_argument("-l", "--language", default="en", help="the Wikipedia language (default: %(default)s)")
parser.add_argument("-d", "--days", choices=["30", "60", "90"], default="30", help="time range for stats (days) (default: %(default)s)")
parser.add_argument("-o", "--output_folder", default="output", help="the output folder (default: %(default)s)")
parser.add_argument("--no-stats", dest="no_stats", action="store_true", help="no stats queries are sent")

args = parser.parse_args()

# check if output folder exists
if not os.path.isdir(args.output_folder):
  print("")
  print("ERROR: Missing output folder")
  print("")
  sys.exit(1)

### Query to Wikipedia API ###
api_url = "http://" + args.language + ".wikipedia.org/w/api.php"
api_params = { "action" : "query",
               "list" : "categorymembers",
               "continue" : "",
               "cmtitle" : "Category:" + args.category,
               "cmlimit" : 500,
               "cmprop": "title",
               "format" : "json"
             }
try:
  params = urllib.urlencode(api_params)
  req = urllib2.Request(api_url, params)
  req.add_header("User-Agent", "python-wikipedia_stats")
  print("")
  sys.stdout.write("Querying " + args.language + ".wikipedia.org... ")
  response = urllib2.urlopen(req)
  response_content = response.read()
except Exception:
  print("")
  print("")
  print("Error querying Wikipedia API for category \"" + args.category + "\"")
  print("")
  sys.exit(1)
print("done.")

parsed_response = json.loads(response_content)

### Get stats ###
articles = parsed_response["query"]["categorymembers"]
num_articles = len(articles)
print("")
# exit if no articles have been found
if num_articles == 0:
  print("No articles found for category \"" + args.category + "\"")
  print("")
  sys.exit(1)
print(str(num_articles) + " articles found for category \"" + args.category + "\":")
print("")
# print the list of articles found
counter = 1
for article in articles:
  print(str(counter) + " | " + article["title"])
  counter += 1
print("")
print("")

if args.no_stats:
  sys.exit(1)

# query the stats url for each article, save the values in a dictionary
all_hits = {}
stats_url_base = "http://stats.grok.se/" + args.language + "/latest" + args.days + "/"
for article in articles:
  title = article["title"].encode("utf-8")
  urltitle = urllib.quote(title).replace("%20", "_").replace("%2F", "/")
  stats_url = stats_url_base + urltitle
  try:
    req = urllib2.Request(stats_url)
    req.add_header("User-Agent", "python-wikipedia_stats")
    print("Querying stats.grok.se for " + title)
    response = urllib2.urlopen(req)
    response_content = response.read()
  except Exception:
    print("EXCEPTION getting stats for: " + title)
    continue
  # find the number of hits for the given article
  regex_sentence = re.compile("has been viewed (\d+)")
  match_sentence = regex_sentence.search(response_content)
  num_hits = int(match_sentence.group(1))
  if num_hits not in all_hits:
    all_hits[num_hits] = []
  all_hits[num_hits].append([title, urltitle])
  time.sleep(2)

### Print output file sorted by the number of hits ###
category_file = urllib.quote(args.category).replace("%20", "_").replace("%2F", "/")
output_file_name = category_file + "_" + args.language + "_" + args.days + "_" + time.strftime("%Y%m%d%H%M%S") + ".csv"
output_file_path = os.path.join(args.output_folder, output_file_name)
try:
  output_file = open(output_file_path, "w")
  output_file.write("Title|URL|Hits_" + args.days + "\n")
  for key in sorted(all_hits, reverse=True):
    for article in all_hits[key]:
      output_file.write(article[0] + "|" + "http://" + args.language + ".wikipedia.org/wiki/" + article[1] + "|" + str(key) + "\n")
except Exception:
  print("")
  print("EXCEPTION writing output file for article: " + article[0])
  print("")
finally:
  output_file.close()
print("")
print("Output file: " + output_file_path)
print("")


import socket
import threading
import time

class UdpConnection:
    def __init__(self, request_ip: str, request_port: int, response_port: int, response_buffer_size: int = 1024,
                 print_responses: bool = False, auto_connect: bool = True):
        """
        A two-way UDP connection
        :param request_ip: The IP address to send data to. If only receiving, this can be None.
        :param request_port: The UDP port to send data to. If only receiving, this can be None.
        :param response_port: The UDP port to receive data from. If only sending, this can be None.
        :param response_buffer_size: The buffer size to receive responses. Defaults to 1024 bytes.
        :param print_responses: Set to True to print responses (data and addresses). Defaults to False.
        :param auto_connect: Determines whether to automatically connect (receiver) to the UDP socket. Defaults to True
        """
        self.__socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.__request_address = (request_ip, request_port)

        # Receiver
        self.__response = None
        self.__response_listeners = []
        self.__response_port = response_port
        self.__response_buffer_size = response_buffer_size
        self.__print_responses = print_responses
        self.__running = False

        self.__receive_thread = threading.Thread(target=self.__receiver)
        self.__receive_thread.daemon = True
        if auto_connect:
            self.connect()

    def connect(self):
        if self.__running or self.__response_port is None:
            return
        self.__running = True
        self.__socket.bind(('', self.__response_port))
        self.__receive_thread.start()

    def __receiver(self):
        while self.__running:
            try:
                data, address = self.__socket.recvfrom(self.__response_buffer_size)
                if self.__print_responses:
                    print(data, address)
                self.__response = data
                listeners_to_remove = []
                for listener in self.__response_listeners:
                    if not listener(data, address):
                        listeners_to_remove.append(listener)
                for listener in listeners_to_remove:
                    self.remove_listener(listener)
            except Exception as e:
                print(e)

    def cancel(self):
        """
        Close the socket and stop the receiver thread
        """
        self.__running = False
        self.__socket.close()

    def listen(self, listener):
        """
        Listen for a response. The listener will be called with the bytes received from the socket.
        :param listener: The listener which takes two parameters (bytes and (ip, port)) and optionally returns False to stop listening.
        """
        self.__response_listeners.append(listener)

    def remove_listener(self, listener):
        """
        Remove a listener.
        :param listener: The listener to remove.
        """
        if listener in self.__response_listeners:
            self.__response_listeners.remove(listener)

    def send(self, data: bytes, wait: bool = False, timeout: float = 5, response_listener=None) -> bytes:
        """
        Send data over the UDP connection.
        :param data: The data to send (bytes)
        :param wait: True if it should wait for a response.
        :param timeout: The timeout in seconds to wait for a response.
        :param response_listener: The listener to set to receive a response (does not require wait to be True)
        :return: If waiting, it will return the latest bytes received or None if it times out. Returns None if not waiting.
        """
        start_time = time.time()

        if wait:
            # Clear the previous response
            self.__response = None

        if response_listener is not None:
            self.listen(response_listener)
        self.__socket.sendto(data, self.__request_address)

        if not wait:
            return None

        # Wait for a response
        while self.__response is None:
            if time.time() - start_time > timeout:
                return None
            time.sleep(0.1)

        return self.__response


import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
import math

import utils
import hydra
import kornia
import wandb

from replay_buffer import PrioritizedReplayBuffer

# from
# https://github.com/mlperf/inference/blob/master/others/edge/object_detection/ssd_mobilenet/pytorch/utils.py#L40
class Conv2d_tf(nn.Conv2d):
    """
    Conv2d with the padding behavior from TF
    """
    def __init__(self, *args, **kwargs):
        kwargs_minus_padding = dict(kwargs)
        if "padding" in kwargs_minus_padding:
            del kwargs_minus_padding["padding"]
        super(Conv2d_tf, self).__init__(*args, **kwargs_minus_padding)
        self.padding = kwargs.get("padding", "SAME")

    def _compute_padding(self, input, dim):
        input_size = input.size(dim + 2)
        filter_size = self.weight.size(dim + 2)
        effective_filter_size = (filter_size - 1) * self.dilation[dim] + 1
        out_size = (input_size + self.stride[dim] - 1) // self.stride[dim]
        total_padding = max(0, (out_size - 1) * self.stride[dim] +
                            effective_filter_size - input_size)
        additional_padding = int(total_padding % 2 != 0)

        return additional_padding, total_padding

    def forward(self, input):
        if self.padding == "VALID":
            return F.conv2d(
                input,
                self.weight,
                self.bias,
                self.stride,
                padding=0,
                dilation=self.dilation,
                groups=self.groups,
            )
        rows_odd, padding_rows = self._compute_padding(input, dim=0)
        cols_odd, padding_cols = self._compute_padding(input, dim=1)
        if rows_odd or cols_odd:
            input = F.pad(input, [0, cols_odd, 0, rows_odd])

        return F.conv2d(
            input,
            self.weight,
            self.bias,
            self.stride,
            padding=(padding_rows // 2, padding_cols // 2),
            dilation=self.dilation,
            groups=self.groups,
        )

class SEEncoder(nn.Module):
    """Convolutional encoder of pixels observations."""
    def __init__(self, obs_shape):
        super().__init__()

        self.feature_dim = 64 * 4 * 4

        self.conv1 = Conv2d_tf(obs_shape[0], 32, 5, stride=5, padding='SAME')
        self.conv2 = Conv2d_tf(32, 64, 5, stride=5, padding='SAME')

        self.outputs = dict()

    def forward(self, obs):
        obs = obs / 255.
        self.outputs['obs'] = obs

        h = torch.relu(self.conv1(obs))
        self.outputs['conv1'] = h

        h = torch.relu(self.conv2(h))
        self.outputs['conv2'] = h

        out = h.view(h.size(0), -1)
        self.outputs['out'] = out

        assert out.shape[1] == self.feature_dim

        return out

    def log(self, logger, step):
        for k, v in self.outputs.items():
            logger.log_histogram(f'train_encoder/{k}_hist', v, step)
            if len(v.shape) > 2:
                logger.log_image(f'train_encoder/{k}_img', v[0], step)

        logger.log_param(f'train_encoder/conv1', self.conv1, step)
        logger.log_param(f'train_encoder/conv2', self.conv2, step)

class Encoder(nn.Module):
    """Convolutional encoder of pixels observations."""
    def __init__(self, obs_shape):
        super().__init__()

        self.feature_dim = 64 * 11 * 11

        self.conv1 = Conv2d_tf(obs_shape[0], 32, 8, stride=4, padding='SAME')
        self.conv2 = Conv2d_tf(32, 64, 4, stride=2, padding='SAME')
        self.conv3 = Conv2d_tf(64, 64, 3, stride=1, padding='SAME')

        self.outputs = dict()

    def forward(self, obs):
        obs = obs / 255.
        self.outputs['obs'] = obs

        h = torch.relu(self.conv1(obs))
        self.outputs['conv1'] = h

        h = torch.relu(self.conv2(h))
        self.outputs['conv2'] = h

        h = torch.relu(self.conv3(h))
        self.outputs['conv3'] = h

        out = h.view(h.size(0), -1)
        self.outputs['out'] = out

        assert out.shape[1] == self.feature_dim

        return out

    def log(self, logger, step):
        for k, v in self.outputs.items():
            logger.log_histogram(f'train_encoder/{k}_hist', v, step)
            if len(v.shape) > 2:
                logger.log_image(f'train_encoder/{k}_img', v[0], step)

        logger.log_param(f'train_encoder/conv1', self.conv1, step)
        logger.log_param(f'train_encoder/conv2', self.conv2, step)
        logger.log_param(f'train_encoder/conv3', self.conv3, step)

class Intensity(nn.Module):
    def __init__(self, scale=0.1):
        super().__init__()
        self.scale = scale

    def forward(self, x):
        noise = 1.0 + (self.scale * torch.randn(
            (x.size(0), 1, 1, 1), device=x.device).clamp_(-2.0, 2.0))
        return x * noise

class Critic(nn.Module):
    """Critic network, employes double Q-learning."""
    def __init__(self, encoder_cfg, num_actions, hidden_dim, hidden_depth,
                 dueling, aug_type, image_pad, intensity_scale):
        super().__init__()

        AUGMENTATIONS = {
            'intensity':
            Intensity(scale=intensity_scale),
            'reflect_crop':
            nn.Sequential(nn.ReplicationPad2d(image_pad),
                          kornia.augmentation.RandomCrop((84, 84))),
            'crop_intensity':
            nn.Sequential(nn.ReplicationPad2d(image_pad),
                          kornia.augmentation.RandomCrop((84, 84)),
                          Intensity(scale=intensity_scale)),
            'zero_crop':
            nn.Sequential(nn.ZeroPad2d(image_pad),
                          kornia.augmentation.RandomCrop((84, 84))),
            'rotate':
            kornia.augmentation.RandomRotation(degrees=5.0),
            'h_flip':
            kornia.augmentation.RandomHorizontalFlip(p=0.5),
            'v_flip':
            kornia.augmentation.RandomVerticalFlip(p=0.5),
            'none':
            nn.Identity(),
            'all':
            nn.Sequential(nn.ReplicationPad2d(image_pad),
                          kornia.augmentation.RandomCrop((84, 84)),
                          Intensity(scale=intensity_scale),
                          kornia.augmentation.RandomRotation(degrees=5.0),
                          kornia.augmentation.RandomHorizontalFlip(p=0.5),
                          kornia.augmentation.RandomVerticalFlip(p=0.5),
                          kornia.augmentation.RandomHorizontalFlip(p=0.5),), # TODO DrQ fix this line.
        }

        assert aug_type in AUGMENTATIONS.keys()

        self.aug_trans = AUGMENTATIONS.get(aug_type)

        self.encoder = hydra.utils.instantiate(encoder_cfg)

        self.dueling = dueling
        self.num_actions = num_actions

        if dueling:
            # TODO dueling DQN, define the value and the advantage network
            self.V = utils.mlp(self.encoder.feature_dim, hidden_dim,1, hidden_depth)
            self.A = utils.mlp(self.encoder.feature_dim, hidden_dim,num_actions, hidden_depth)
            # END TODO
        else:
            self.Q = utils.mlp(self.encoder.feature_dim, hidden_dim,
                               num_actions, hidden_depth)

        self.outputs = dict()
        self.apply(utils.weight_init)

    def forward(self, obs, use_aug=False):
        if use_aug:
            obs = self.aug_trans(obs)

        obs = self.encoder(obs)

        if self.dueling:
            # TODO dueling DQN, compute the q value from the value and advantage network
            v = self.V(obs)
            a = self.A(obs)
            q = v + (a - a.mean())
            # END TODO
        else:
            q = self.Q(obs)

        self.outputs['q'] = q

        return q

    def log(self, logger, step):
        self.encoder.log(logger, step)

        for k, v in self.outputs.items():
            logger.log_histogram(f'train_critic/{k}_hist', v, step)

        M = self.A if self.dueling else self.Q
        for i, m in enumerate(M):
            if type(m) is nn.Linear:
                logger.log_param(f'train_critic/q_fc{i}', m, step)

class DRQLAgent(object):
    """Data regularized Q-learning: Deep Q-learning."""
    def __init__(self, obs_shape, num_actions, device, encoder_cfg, critic_cfg,
                 discount, lr, beta_1, beta_2, weight_decay, adam_eps,
                 max_grad_norm, critic_tau, critic_target_update_frequency,
                 batch_size, multistep_return, eval_eps, double_q,
                 prioritized_replay_beta0, prioritized_replay_beta_steps):
        self.device = device
        self.discount = discount
        self.critic_tau = critic_tau
        self.num_actions = num_actions
        self.critic_target_update_frequency = critic_target_update_frequency
        self.batch_size = batch_size
        self.eval_eps = eval_eps
        self.max_grad_norm = max_grad_norm
        self.multistep_return = multistep_return
        self.double_q = double_q
        assert prioritized_replay_beta0 <= 1.0
        self.prioritized_replay_beta0 = prioritized_replay_beta0
        self.prioritized_replay_beta_steps = prioritized_replay_beta_steps
        self.eps = 0

        self.critic = hydra.utils.instantiate(critic_cfg).to(self.device)
        self.critic_target = hydra.utils.instantiate(critic_cfg).to(
            self.device)
        self.critic_target.load_state_dict(self.critic.state_dict())

        self.critic_optimizer = torch.optim.Adam(self.critic.parameters(),
                                                 lr=lr,
                                                 betas=(beta_1, beta_2),
                                                 weight_decay=weight_decay,
                                                 eps=adam_eps)

        self.train()
        self.critic_target.train()

    def train(self, training=True):
        self.training = training
        self.critic.train(training)

    def act(self, obs):
        with torch.no_grad():
            obs = torch.FloatTensor(obs).to(self.device)
            obs = obs.unsqueeze(0).contiguous()
            q = self.critic(obs)
            action = q.max(dim=1)[1].item()
        return action

    def update_critic(self, obs, action, reward, next_obs, not_done, weights,
                      logger, step):

        with torch.no_grad():
            discount = self.discount**self.multistep_return
            if self.double_q:
                # TODO double Q learning
                # Find the target Q value based on the critic
                # and the critic target networks to find the right
                # value of target_Q
                next_Q = self.critic(next_obs, use_aug=True)
                next_action = next_Q.argmax(dim=1).unsqueeze(1)
                next_Q_target = self.critic_target(next_obs, use_aug=True)
                next_Q_target = torch.gather(next_Q_target,1,next_action)
                target_Q = reward + (not_done * discount * next_Q_target)
                # End TODO
            else:
                next_Q = self.critic_target(next_obs, use_aug=True)
                next_Q = next_Q.max(dim=1)[0].unsqueeze(1)
                target_Q = reward + (not_done * discount * next_Q)

        # get current Q estimates
        current_Q = self.critic(obs, use_aug=True)
        current_Q = current_Q.gather(1, action)

        td_errors = current_Q - target_Q
        critic_losses = F.smooth_l1_loss(current_Q, target_Q, reduction='none')
        if weights is not None:
            critic_losses *= weights

        critic_loss = critic_losses.mean()

        logger.log('train_critic/loss', critic_loss, step)
        wandb.log({"train_critic_loss":critic_loss})

        # Optimize the critic
        self.critic_optimizer.zero_grad()
        critic_loss.backward()
        if self.max_grad_norm > 0.0:
            nn.utils.clip_grad_norm_(self.critic.parameters(),
                                     self.max_grad_norm)
        self.critic_optimizer.step()

        self.critic.log(logger, step)

        return td_errors.squeeze(dim=1).detach().cpu().numpy()

    def update(self, replay_buffer, logger, step):

        prioritized_replay = type(replay_buffer) == PrioritizedReplayBuffer

        if prioritized_replay:
            fraction = min(step / self.prioritized_replay_beta_steps, 1.0)
            beta = self.prioritized_replay_beta0 + fraction * (
                1.0 - self.prioritized_replay_beta0)
            obs, action, reward, next_obs, not_done, weights, idxs = replay_buffer.sample_multistep(
                self.batch_size, beta, self.discount, self.multistep_return)
        else:
            obs, action, reward, next_obs, not_done = replay_buffer.sample_multistep(
                self.batch_size, self.discount, self.multistep_return)
            weights = None

        logger.log('train/batch_reward', reward.mean(), step)
        wandb.log({"avg_bath_reward":reward.mean()})

        td_errors = self.update_critic(obs, action, reward, next_obs, not_done,
                                       weights, logger, step)
        if prioritized_replay:
            # TODO prioritized replay buffer: update the priorities in the replay buffer using td_errors
            replay_buffer.update_priorities(idxs,abs(td_errors))
            # End TODO

        if step % self.critic_target_update_frequency == 0:
            utils.soft_update_params(self.critic, self.critic_target,
                                     self.critic_tau)


class MorseEncoder:
    """Main class of the program, you should call run() on the object"""
    def __init__(self):
        """Simply creating an empty text and the morse dictionary"""
        self.dict = {'a': '. _', 'b': '_ . . .', 'c': '_ . . .', 'd': '_ . .', 'e': '.', 'f': '. . _ .', 'g': '- - .',
                     'h': '. . . .', 'i': '. .', 'j': '. _ _ _', 'k': '_ . _', 'l': '. _ . .', 'm': '_ _', 'n': '_ .',
                     'o': '_ _ _', 'p': '. _ _ .', 'q': '_ _ . _', 'r': '. _ .', 's': '. . .', 't': '_', 'u': '. . _',
                     'v': '. . . _', 'w': '. _ _', 'x': '_ . . _', 'y': '_ . _ _', 'z': '_ _ . .', '0': '_ _ _ _ _',
                     '1': '. _ _ _ _', '2': '. . _ _ _', '3': '. . . _ _', '4': '. . . . _', '5': '. . . . .',
                     '6': '_ . . . .', '7': '_ _ . . .', '8': '_ _ _ . .', '9': '_ _ _ _ .'}
        self.text = ''

    def run(self):
        """Main method, should be called on the class' children. Detects if the input is text to encode or
         morse to decode"""
        loop = True
        while loop:
            # We loop until there is actually an entry
            self.text = input("Please enter your text to translate or your morse code to decode.")
            try:
                first = self.text[0]
            except IndexError:
                # no text was given, we pass so we loop
                pass
            else:
                loop = False
        if first == '_' or first == '.':
            # entry is morse
            self.decode()
        else:
            # entry is not morse, assuming it's text to encode
            self.encode()

    def encode(self):
        """Takes self.text as an input and returns it's corresponding morse code"""
        result = ''
        for char in self.text:
            if char in self.dict:
                result += self.dict[char] + '   '
            elif char == ' ':
                result += '       '
        print("Your text in morse will be:")
        print(result)

    def decode(self):
        """Takes a morse code as self.text as an input and return its text translation"""
        result = ''
        list_of_words = self.text.split('       ')
        for words in list_of_words:
            list_of_chars = words.split('   ')
            for char in list_of_chars:
                if char in self.dict.values():
                    result += list(self.dict.keys())[list(self.dict.values()).index(char)]
            result += ' '
        print("Your decoded text is:")
        print(result[:-1])

if __name__ == '__main__':
    """Entry point of the app"""
    morse_encoder = MorseEncoder()
    morse_encoder.run()


import turtle

def draw_square(some_turtle):
    for i in range(1, 5):
        some_turtle.forward(100)
        some_turtle.right(90)

def draw_circle(some_turtle):
    for i in range(1, 7):
        some_turtle.forward(100)
        some_turtle.right(100)
def draw_art():
    window = turtle.Screen()
    window.bgcolor("black")
    #Brad to draw squares :)
    brad = turtle.Turtle()
    brad.shape("turtle")
    brad.color("yellow")
    for i in range(1, 37):
        draw_square(brad)
        brad.right(10)
    #Angie draws circle
    angie = turtle.Turtle()
    angie.shape("turtle")
    angie.color("brown")
    angie.circle(100)
    for i in range(1, 37):
        draw_circle(angie)
        angie.right(10)

    window.exitonclick()

draw_art()


from machine import ADC, PWM, Pin
import time

PLED = PWM(Pin(25))
PLED.freq(100)
adc = ADC(Pin(26))

while True:
    valorADC = adc.read_u16()
    porc =  valorADC* 100 // 65535
    PLED.duty_u16(valorADC)
    print(f'Intensidad al {porc}%')
    time.sleep_ms(600)


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the minimumAbsoluteDifference function below.
def minimumAbsoluteDifference(arr):
    m = float("inf")

    arr.sort()
    j = 1
    for i in range(len(arr) - 1):
        temp = abs(arr[i] - arr[j])
        m = min(m, temp)
        j += 1
    return m

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    arr = list(map(int, input().rstrip().split()))

    result = minimumAbsoluteDifference(arr)

    fptr.write(str(result) + '\n')

    fptr.close()


# -*- coding: utf-8 -*-
from flask import Flask, render_template
from flask_wtf.csrf import CsrfProtect
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
sys.path.append('..')
from views import account, admin, user, setting
from extend import db
import config

DEFAULT_MODULES = (
    (account.account, ""),
    (admin.admin, "/admin"),
    (user.user, "/user"),
    (setting.setting, "/setting"),
)

def create_app():
    "main"
    app = Flask(__name__)
    # config
    app.config.from_object(config.Config)

    configure_extensions(app)
    configure_errorhandlers(app)
    configure_before_handlers(app)
    configure_template_filters(app)
    # register module

    configure_blueprint(app, DEFAULT_MODULES)
    return app

def configure_extensions(app):
    # configure extensions
    db.init_app(app)
    CsrfProtect(app)

def configure_errorhandlers(app):
    @app.errorhandler(404)
    def not_found(error):
        return render_template('404.html'), 404

def configure_before_handlers(app):
    pass

def configure_template_filters(app):
    @app.template_filter('members')
    def members_filter(s):
        s_new = ' , '.join([i[0] for i in s])
        return s_new

    @app.template_filter('week')
    def week_filter(s):
        a = [u'周一', u'周二', u'周三', u'周四', u'周五', u'周六', u'周日']
        return a[s]

def configure_blueprint(app, modules):
    for module, url_prefix in modules:
        # print module, url_prefix
        app.register_blueprint(module, url_prefix=url_prefix)


# config/settings/local.py

"""
Local settings

- Run in Debug mode

- Use console backend for emails

- Add Django Debug Toolbar
- Add django-extensions as app
"""

from .base import *

# DEBUG
# ------------------------------------------------------------------------------
DEBUG = True
TEMPLATES[0]['OPTIONS']['debug'] = DEBUG

# SECRET CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Note: This key only used for development and testing.
SECRET_KEY = 'r^rtd&Ijiajad-d=3i^5+asdadlkjk1@^10923iok)!0i8'

# django-debug-toolbar
# ------------------------------------------------------------------------------
MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ]
INSTALLED_APPS += ['debug_toolbar', 'djcelery']

DEBUG_TOOLBAR_CONFIG = {
    'DISABLE_PANELS': [
        'debug_toolbar.panels.redirects.RedirectsPanel',
    ],
    'SHOW_TEMPLATE_CONTEXT': True,
}

ALLOWED_HOSTS = ['localhost', 'peaceful-reef-87363.herokuapp.com']