# 6.0002 Problem Set 5
# Graph optimization
# Name:
# Collaborators:
# Time:

#
# Finding shortest paths through MIT buildings
#
import unittest
from graph import Digraph, Node, WeightedEdge

#
# Problem 2: Building up the Campus Map
#
# Problem 2a: Designing your graph
#
# What do the graph's nodes represent in this problem? What
# do the graph's edges represent? Where are the distances
# represented?
#
# Answer: The graph's nodes represent the buildings, with edges between them the paths to get there, with the distances stored in the WeightedEdge
#

# Problem 2b: Implementing load_map
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    #Create the digraph
    mit_campus = Digraph()
    with open(map_filename, "r") as f:
        for line in f:
            #Get all values into an array
            values = line.split()
            #Create nodes for first and second value
            start_node = Node(values[0])
            end_node = Node(values[1])
            #Check if nodes are not in Digraph, if so add them
            if not mit_campus.has_node(start_node):
                mit_campus.add_node(start_node)
            if not mit_campus.has_node(end_node):
                mit_campus.add_node(end_node)
            #Create weighted Edge
            edge = WeightedEdge(start_node, end_node, values[2], values[3])
            #Add weighted edge
            mit_campus.add_edge(edge)
    return mit_campus
    print("Loading map from file...")

# Problem 2c: Testing load_map
# Include the lines used to test load_map below, but comment them out

# mit_test = load_map("test_load_map.txt")
# print(mit_test)

#
# Problem 3: Finding the Shortest Path using Optimized Search Method
#
# Problem 3a: Objective function
#
# What is the objective function for this problem? What are the constraints?
#
# Answer: The objective function is to minimise the total distance travelled while staying below the maximum distance outside.
#

# Problem 3b: Implement get_best_path
def get_best_path(digraph, start, end, path, max_dist_outdoors, best_dist, best_path):
    """
    Finds the shortest path between buildings subject to constraints.

    Parameters:
        digraph: Digraph instance
            The graph on which to carry out the search
        start: string
            Building number at which to start
        end: string
            Building number at which to end
        path: list composed of [[list of strings], int, int]
            Represents the current path of nodes being traversed. Contains
            a list of node names, total distance traveled, and total
            distance outdoors.
        max_dist_outdoors: int
            Maximum distance spent outdoors on a path
        best_dist: int
            The smallest distance between the original start and end node
            for the initial problem that you are trying to solve
        best_path: list of strings
            The shortest path found so far between the original start
            and end node.

    Returns:
        A tuple with the shortest-path from start to end, represented by
        a list of building numbers (in strings), [n_1, n_2, ..., n_k],
        where there exists an edge from n_i to n_(i+1) in digraph,
        for all 1 <= i < k and the distance of that path.

        If there exists no path that satisfies max_total_dist and
        max_dist_outdoors constraints, then return None.
    """
    #Add the str of the node that you are at to the path - can't use append as adds it to the old list (would mutate arguments passed in) even with list.copy() as it is shallow copying, would need to use list.deepcopy()
    path[0] = path[0] + [start]
    #Check if this is the right node
    if start == end:
        #If so return the current path, as well as distance of path
        print("Returned path: ", path)
        return (path[0].copy(), path[1])
    #Check if start node passed in is valid -
    # if not  class will raise a ValueError
    start_node = digraph.get_node(start)
    #Get all possible paths and loop through each of them - edge is an instance of a WeightedEdge. As passed a string need to get the node before getting associated edges
    for edge in digraph.get_edges_for_node(start_node):
        # print("path", path)
        # print(edge)
        #Destintation node
        dest = edge.get_destination()
        #Check never been to destination to avoid loops
        if dest.get_name() not in path[0]:
            #Copy as lists are objects, don't want to change the main path, incase this path is not the right one
            proposed_path = path.copy()
            #Add total distance
            proposed_path[1] += edge.get_total_distance()
            # and outdoor distance
            proposed_path[2] += edge.get_outdoor_distance()
            #Check to see if problem has been solved and the best path is smaller than the current path
            if best_dist != None and proposed_path[1] >= best_dist:
                pass
            #Check to make sure the proposed path doesn't exceed maximum distance outdoors
            elif proposed_path[2] > max_dist_outdoors:
                #move onto next branch
                pass
            else:
                #Recursively go to the end node
                end_path = get_best_path(digraph, dest.get_name(), end, proposed_path.copy(), max_dist_outdoors, best_dist, best_path)
                #Check to make sure a path was returned
                #Then check to make sure path returned has best_dist so far, first check if best_dist == None
                if end_path != None and (best_dist == None or end_path[1] < best_dist):
                    #Change best distance and best path
                    best_path, best_dist = end_path
    #Once you have gone through all the possible paths for this node, return the best path and best distance found, only if both not None
    if best_dist == None or best_path == None:
        return None
    return (best_path, best_dist)

mit_test = load_map("test_load_map.txt")
#Tests for Digraph.get_node that I added
# a = mit_test.get_node("a")
# print(a)
# print(isinstance(a, Node))

#Test of best_path - depth first search
# best_path = get_best_path(mit_test, "a", "b", [[],0,0], 10, None, None)
# print(best_path)

# Problem 3c: Implement directed_dfs
def directed_dfs(digraph, start, end, max_total_dist, max_dist_outdoors):
    """
    Finds the shortest path from start to end using a directed depth-first
    search. The total distance traveled on the path must not
    exceed max_total_dist, and the distance spent outdoors on this path must
    not exceed max_dist_outdoors.

    Parameters:
        digraph: Digraph instance
            The graph on which to carry out the search
        start: string
            Building number at which to start
        end: string
            Building number at which to end
        max_total_dist: int
            Maximum total distance on a path
        max_dist_outdoors: int
            Maximum distance spent outdoors on a path

    Returns:
        The shortest-path from start to end, represented by
        a list of building numbers (in strings), [n_1, n_2, ..., n_k],
        where there exists an edge from n_i to n_(i+1) in digraph,
        for all 1 <= i < k

        If there exists no path that satisfies max_total_dist and
        max_dist_outdoors constraints, then raises a ValueError.
    """
    best_path = get_best_path(digraph, start, end, [[],0,0], max_dist_outdoors, None, None)
    # print("BEST PATH", best_path)
    if best_path == None or best_path[1] > max_total_dist:
        raise ValueError
    return best_path[0]

# ================================================================
# Begin tests -- you do not need to modify anything below this line
# ================================================================

class Ps2Test(unittest.TestCase):
    LARGE_DIST = 99999

    def setUp(self):
        self.graph = load_map("mit_map.txt")

    def test_load_map_basic(self):
        self.assertTrue(isinstance(self.graph, Digraph))
        self.assertEqual(len(self.graph.nodes), 37)
        all_edges = []
        for _, edges in self.graph.edges.items():
            all_edges += edges  # edges must be dict of node -> list of edges
        all_edges = set(all_edges)
        self.assertEqual(len(all_edges), 129)

    def _print_path_description(self, start, end, total_dist, outdoor_dist):
        constraint = ""
        if outdoor_dist != Ps2Test.LARGE_DIST:
            constraint = "without walking more than {}m outdoors".format(
                outdoor_dist)
        if total_dist != Ps2Test.LARGE_DIST:
            if constraint:
                constraint += ' or {}m total'.format(total_dist)
            else:
                constraint = "without walking more than {}m total".format(
                    total_dist)

        print("------------------------")
        print("Shortest path from Building {} to {} {}".format(
            start, end, constraint))

    def _test_path(self,
                   expectedPath,
                   total_dist=LARGE_DIST,
                   outdoor_dist=LARGE_DIST):
        start, end = expectedPath[0], expectedPath[-1]
        self._print_path_description(start, end, total_dist, outdoor_dist)
        dfsPath = directed_dfs(self.graph, start, end, total_dist, outdoor_dist)
        print("Expected: ", expectedPath)
        print("DFS: ", dfsPath)
        self.assertEqual(expectedPath, dfsPath)

    def _test_impossible_path(self,
                              start,
                              end,
                              total_dist=LARGE_DIST,
                              outdoor_dist=LARGE_DIST):
        self._print_path_description(start, end, total_dist, outdoor_dist)
        with self.assertRaises(ValueError):
            directed_dfs(self.graph, start, end, total_dist, outdoor_dist)

    def test_path_one_step(self):
        self._test_path(expectedPath=['32', '56'])

    def test_path_no_outdoors(self):
        self._test_path(
            expectedPath=['32', '36', '26', '16', '56'], outdoor_dist=0)

    def test_path_multi_step(self):
        self._test_path(expectedPath=['2', '3', '7', '9'])

    def test_path_multi_step_no_outdoors(self):
        self._test_path(
            expectedPath=['2', '4', '10', '13', '9'], outdoor_dist=0)

    def test_path_multi_step2(self):
        self._test_path(expectedPath=['1', '4', '12', '32'])

    def test_path_multi_step_no_outdoors2(self):
        self._test_path(
            expectedPath=['1', '3', '10', '4', '12', '24', '34', '36', '32'],
            outdoor_dist=0)

    def test_impossible_path1(self):
        self._test_impossible_path('8', '50', outdoor_dist=0)

    def test_impossible_path2(self):
        self._test_impossible_path('10', '32', total_dist=100)

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


#! /usr/bin/env python3
import serial, signal, struct, rospy, time
from commands_controller import CommandsController

rospy.init_node('radio_command_node')

ser = serial.Serial()
ser.baudrate = rospy.get_param('~baud', 19200)
ser.port = rospy.get_param('~port', "/dev/serial/by-id/usb-Silicon_Labs_CP2102_USB_to_UART_Bridge_Controller_0001-if00-port0")
ser.dtr = False
ser.timeout = 0.5
ser.open()

term = b'\x00\xFF\xFF'
lenterm = len(term)
global_loop = True

# unsigned char + short int
# struct_format = "!Bh"
# unsigned char  + short_uint
struct_format = "!BH"

def stop_global_loop(signal, frame):
    global global_loop
    print("Ctrl+C captured, ending read.")
    global_loop = False

signal.signal(signal.SIGINT, stop_global_loop)

linear_speed = rospy.get_param('~linear_speed', 0.22)
angular_speed = rospy.get_param('~angular_speed', 1)

controller = CommandsController(linear_speed, angular_speed)

while global_loop:

    pack = ser.read_until(term)
    if(len(pack) > 2 and pack[-lenterm:] == term):

        pack = pack[:-lenterm]
        commands_count  = int(len(pack)/struct.calcsize(struct_format))

        for i in range(0, commands_count):
            try:
                (command, value) = struct.unpack(struct_format, pack[i*3:(i+1)*3])
                ret_data = controller.execute(command, value)

                # image echo
                pack_size = 1024
                if(command == 55 or command == 56):
                    pack_num  = int(len(ret_data)/pack_size)+1
                    for i in range(0, pack_num):
                        serial_pack = ret_data[i*pack_size:(i+1)*pack_size]
                        send_bytes = ser.write(serial_pack)
                        rospy.loginfo("Send data pack%i: %s", i, send_bytes)
                        time.sleep(0.5)

            except:
                pass


# Написать программу, которая отвечает на вопрос, пересекаются ли две заданные окружности на плоскости.
# Каждая окружность задается координатами центра и радиусом.
import math
R1 = float(input("введите радиус первой окружности R1 = "))
R2 = float(input("введите радиус второй окружности R2 = "))
print("введите координаты центра A первой окружности : ")
x1 = float(input('x1='))
y1 = float(input('y1='))
print("введите координаты центра B второй окружности: ")
x2 = float(input('x2='))
y2 = float(input('y2='))
# AB расстояние между центрами двух окружностей
AB = float(math.sqrt((x2-x1)**2+(y2-y1)**2))
# print (AB)
# R1R2sum сумма радиусов
R1R2sum = float(R1+R2)
R1R2min = (math.fabs(R1-R2))
# R1R2min разница радиусов по модулю
if R1R2sum < AB :
    print('окружности не пересекаются')
elif R1R2min > AB:
    print('окружности вписанные')
else:
    print('окружности  пересекаются')


#!/usr/bin/env python
#
import sys
import os.path
import subprocess
import argparse
import xcode

def parse_args():
  parser = argparse.ArgumentParser(description = 'desc')
  parser.add_argument('-proj_dir', type=str, help='Xcode project directory.', required=True)
  parser.add_argument('-archive_path', type=str, help='*.xcarchive file path.', required=True)
  parser.add_argument('-ipa_plist', type=str, help='*.plist file path.', required=True)
  parser.add_argument('-out_ipa_dir', type=str, help='Export .ipa folder.', required=True)
  return parser.parse_args()

# python3 build_ipa.py -proj_dir "../../build/debug/iOS/xcode" -archive_path '../../build/debug/iOS/app.xcarchive' -ipa_plist 'ipa_development.plist' -out_ipa_dir '../../build/debug/iOS/ipa/' > ../../build/debug_ios_ipa.log
if __name__ == '__main__':
  args = parse_args()

  # if args.cleanup is not None:
  #   xcode.cleanup()

  ret = xcode.archive(args.proj_dir, 'Unity-iPhone', args.archive_path)
  if ret != 0: sys.exit(ret)

  ret = xcode.export_iap(args.archive_path, args.ipa_plist, args.out_ipa_dir)
  if ret != 0: sys.exit(ret)

  print('build_iap() finish.')


input_dir = "Organisms/Eretmocerus hayati/Inputs"
organism_file = "Eretmocerus hayati.txt"
landscape_file = "Carnarvon.csv"
output_dir = "Organisms/Eretmocerus hayati/Outputs"
results_file = "results.txt"
population_file = "population.txt"
save_time_steps = True
display = True
background_image = None
num_iterations = 1
num_processors = 1

#Parameters for sensitivity analysis
trajectory_file = "trajectories.txt"

r = 20 #Number of trajectories
levels = 10 #Number of breaks between min and max values
jumps = 2  #Number of jumps for oat steps
perc = 0.20 #Percentage to vary poarameters by

#Parameters to be varied
ptv = [("ips", 0, np.inf, int, [1]),
				("d50", 0, np.inf, float, range(3, 13)),
				("d99", 0, np.inf, float, range(3, 13)),
				("rep", 0, np.inf, float, range(3, 13)),
				("allee", 0, np.inf, int, [0]),
				("survivalT", 0, 1, float, range(0, 13)),
				("K", 1, np.inf, int, range(0, 4))]

#PBS resource requests
walltime = "12:00:00"
memory = "4GB"


decimal_num=input("Enter a decimal number and I shall change it to binary number : ")
binary_num=input("Enter a binary number and I shall return its decimal counterpart : ")
mydecnum=int(decimal_num)

def decimal_to_binary(num):
	binarynumlist=[]

	for i in range(32,-1,-1):
		if ((2**i)<=num):
			break

	for x in range(i, -1, -1):
		if ((2**x)>num):
			binarynumlist.append(0)

		elif ((2**x)<=num):
			num-=2**x
			binarynumlist.append(1)

	for y in range(len(binarynumlist)):
		binarynumlist[y]=str(binarynumlist[y])
	binarynumstring="".join(binarynumlist)

	return int(binarynumstring)

print (decimal_to_binary(mydecnum))

def binary_to_decimal(num):

	binarynum=int(num)
	decimalnum=0
	for i in range(32):

		decimalnum+=round((2**i)*(binarynum%10))

		binarynum=round(binarynum/10)

	return decimalnum

print (binary_to_decimal(binary_num))

assert binary_to_decimal(0) == 0, "0 to decimal should return 0"
assert binary_to_decimal(1011) == 11, "1011 to decimal should return 11"
assert binary_to_decimal(101011) == 43, "101011 to decimal should return 43"
assert binary_to_decimal(101011101) == 349, "101011101 to decimal should return 349"

assert decimal_to_binary(0) == 0, "0 to binary should return 0"
assert decimal_to_binary(5) == 101, "5 to binary should return 101"
assert decimal_to_binary(10) == 1010, "10 to binary should return 1010"
assert decimal_to_binary(113) == 1110001, "113 to binary should return 1110001"


#!/usr/bin/python
# -*- coding: utf-8 -*-

import argparse
import copy
import sys
from collections import OrderedDict, deque
from operator import mul

class Solver(object):
    def __init__(self):
        self.game_attributes = Attributes()
        self.game_board = GameBoard()

    def start_solver(self, characters, size):
        self.game_board = GameBoard.create_game_board(characters, size)
        for row in self.game_board.rows:
            for column in self.game_board.columns:
                self.game_attributes.visited_nodes.append(
                    self.game_board.game_board[row, column])
                self._solve_neighbouring_nodes(row, column)
                self.game_attributes.visited_nodes.clear()

    def _solve_neighbouring_nodes(self, row, column):
        for index in self.get_neighbour_indexes(row, column):
            if (0 <= index[0] < len(self.game_board.rows) and
                    0 <= index[1] < len(self.game_board.columns)) and \
                    self.game_board.game_board[index] not in self.game_attributes.visited_nodes:
                self.game_attributes.visited_nodes.append(
                    self.game_board.game_board[index])
                if self._is_valid_word(self._get_word()):
                    self._solve_neighbouring_nodes(index[0], index[1])
                else:
                    self.game_attributes.visited_nodes.pop()
        self.game_attributes.visited_nodes.pop()
        return

    @staticmethod
    def get_neighbour_indexes(row, column):
        return [(row - 1, column - 1), (row - 1, column),
                (row - 1, column + 1), (row, column - 1),
                (row, column + 1), (row + 1, column - 1),
                (row + 1, column), (row + 1, column + 1)]

    def _get_word(self):
        return "".join((node[2]
                        for node in self.game_attributes.visited_nodes))

    def _is_valid_word(self, word):
        if len(word) > 1:
            if self._contains(word):
                if word in self.game_attributes.set_of_valid_words:
                    self.game_attributes.found_words.update({
                        word:
                        copy.deepcopy(self.game_attributes.visited_nodes)
                    })
                return True
        return False

    def _contains(self, value):
        index = self._bisect_left(value)
        return index < len(
            self.game_attributes.list_of_valid_words_sorted
        ) and self.game_attributes.list_of_valid_words_sorted[index].startswith(value)

    def _bisect_left(self, value):
        left, right = 0, len(self.game_attributes.list_of_valid_words_sorted)
        while left < right:
            middle = (left + right) // 2
            if self.game_attributes.list_of_valid_words_sorted[middle][:len(
                    value)] < value:
                left = middle + 1
            else:
                right = middle
        return left

class Attributes(object):
    visited_nodes = deque()
    words = set()
    set_of_valid_words = set()
    list_of_valid_words_sorted = list()
    found_words = dict()

class GameBoard(object):
    game_board = OrderedDict()
    rows = range(0)
    columns = range(0)

    @classmethod
    def create_game_board(cls, characters, board_size):
        if not isinstance(board_size, tuple):
            raise TypeError("Given size must a type of tuple")
        if isinstance(characters, str):
            if len(characters) != mul(*board_size):
                raise IndexError(
                    "Given character string and size does not match!")
            cls.rows = range(0, board_size[0])
            cls.columns = range(0, board_size[1])
            start_index = 0
            for row in cls.rows:
                for column in cls.columns:
                    cls.game_board[(row,
                                    column)] = (row, column,
                                                characters[start_index])
                    start_index += 1
            return cls()
        raise TypeError("Given characters must a type of str")

class Parser(object):
    @staticmethod
    def extract_words_from_file(_file):
        if not _file:
            _file = "words.txt"
        with open(_file, 'r') as f:
            for line in f:
                Attributes.set_of_valid_words.add(line.strip())

        Attributes.list_of_valid_words_sorted = sorted(
            list(Attributes.set_of_valid_words))

def handle_commandline():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-c", "--characters", type=str, help="characters used in game board")
    parser.add_argument(
        "-s",
        "--size",
        type=int,
        default=2,
        help="the size of the game board [default: 2x2]")
    args = parser.parse_args()
    return args.characters, args.size, args.words

def print_results(found_words):
    print()
    for word in sorted(found_words.keys(), key=len, reverse=True):
        visited_nodes = found_words[word]
        print("Found word: {}, ".format(word.upper()), end='')
        print("Word path: ", end='')
        for i, node in enumerate(visited_nodes, start=1):
            if i == len(visited_nodes):
                print("({}, {})".format(node[0], node[1]), end='')
            else:
                print("({}, {}) -> ".format(node[0], node[1]), end='')
        print()

def main():
    chars, board_size, words_file = handle_commandline()
    Parser.extract_words_from_file(words_file)
    solver = Solver()
    solver.start_solver(chars, (board_size, board_size))
    print_results(solver.game_attributes.found_words)

if __name__ == '__main__':
    sys.exit(main())


import json
import re
from typing import List

from models.chess_model import ChessColors
from models.chessscom_model import ChesscomParsedGames

def create_chesscom_games_json_file(
    chesscom_parsed_games: List[ChesscomParsedGames],
    chess_color: ChessColors,
) -> None:
    games = __get_games_by_color(chesscom_parsed_games, chess_color)
    result = __get_game_result(games)
    pgn = __get_pgn(games)

    data = [
        {
            "opening": games[index]["opening"],
            "result": result[index],
            "pgn": pgn[index],
        }
        for index in range(len(games))
    ]

    with open("games.json", "w") as file:
        json.dump(data, file, indent=4, sort_keys=True)

def __get_games_by_color(
    chesscom_parsed_games: List[ChesscomParsedGames], chess_color: ChessColors
) -> List[ChesscomParsedGames]:
    data: List[ChesscomParsedGames] = []
    for game in chesscom_parsed_games:
        color: str = game["userColor"]
        if chess_color.value == ChessColors.ALL.value:
            data.append(game)
        if color == chess_color.value:
            data.append(game)
    return data

def __get_game_result(chesscom_parsed_games: List[ChesscomParsedGames]) -> List[str]:
    data: List[str] = []
    for game in chesscom_parsed_games:
        result = game["result"]
        if result in ["win", "checkmated"]:
            data.append("win")
        elif result in ["agreed", "stalemate", "repetition"]:
            data.append("equal")
        else:
            data.append("lose")

    return data

def __get_pgn(chesscom_parsed_games: List[ChesscomParsedGames]) -> List[str]:
    pgns: List[str] = []
    for game in chesscom_parsed_games:
        pgn = game["pgn"]
        pgn = pgn[pgn.find("\n\n") :]  # Remove description
        pgn = pgn.replace("\n", "")
        pgn = re.sub("{.+?}", "", pgn)  # Remove time annotations
        pgn = re.sub(r"\d+\.\.\. ", "", pgn)
        pgns.append(pgn)

    return pgns


from inspect import signature
from functools import wraps

def typeassert(*ty_args, **ty_kwargs):
    def decorate(func):
        # If in optimized mode, disable type checking
        if not __debug__:
            return func

        # Map function argument names to supplied types
        sig = signature(func)
        bound_types = sig.bind_partial(*ty_args, **ty_kwargs).arguments

        @wraps(func)
        def wrapper(*args, **kwargs):
            bound_values = sig.bind(*args, **kwargs)
            # Enforce type assertions across supplied arguments
            for name, value in bound_values.arguments.items():
                if name in bound_types:
                    if not isinstance(value, bound_types[name]):
                        raise TypeError(
                            'Argument {} must be {}'.format(name, bound_types[name])
                            )
            return func(*args, **kwargs)
        return wrapper
    return decorate

# Examples

@typeassert(int, int)
def add(x, y):
    return x + y

@typeassert(int, z=int)
def spam(x, y, z=42):
    print(x, y, z)

if __name__ == '__main__':
    print(add(2,3))
    try:
        add(2, 'hello')
    except TypeError as e:
        print(e)

    spam(1, 2, 3)
    spam(1, 'hello', 3)
    try:
        spam(1, 'hello', 'world')
    except TypeError as e:
        print(e)


#!/usr/bin/env python3
"""
Defines a function that trains a model using mini-batch gradient descent
using Keras library
"""

import tensorflow.keras as K

def save_config(network, filename):
    """function to save configuration"""
    json = network.to_json()
    with open(filename, 'w+') as f:
        f.write(json)
    return None

def load_config(filename):
    """function to load configuration"""
    with open(filename, 'r') as f:
        json_string = f.read()
    model = K.models.model_from_json(json_string)
    return model


import argparse
import os
import json
import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch

# setup imports
from src.simulation.observers import ACTION_SET, FEATURE_SET
from src.data.train_utils import load_data, count_parameters
from src.data.data_filter import filter_segment_by_length
from src.data.ego_dataset import EgoDataset
from src.map_api.lanelet import MapReader
from src.simulation.simulator import InteractionSimulator
from src.simulation.observers import Observer

# model imports
from src.agents.mlp_agents import MLPAgent

# training imports
from src.algo.rl import SAC
from src.algo.rl_utils import train
from src.visualization.utils import plot_history
from src.visualization.animation import animate, save_animation

import warnings
warnings.filterwarnings("ignore")

def parse_args():
    bool_ = lambda x: x if isinstance(x, bool) else x == "True"

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--data_path", type=str, default="../interaction-dataset-master"
    )
    parser.add_argument("--exp_path", type=str, default="../exp")
    parser.add_argument("--scenario", type=str, default="DR_CHN_Merging_ZS")
    parser.add_argument("--filename", type=str, default="vehicle_tracks_007.csv")
    parser.add_argument("--checkpoint_path", type=str, default="none",
        help="if entered train agent from check point")
    # agent args
    parser.add_argument("--agent", type=str, choices=["vin", "mlp"], default="vin", help="agent type, default=vin")
    parser.add_argument("--action_set", type=str, choices=["ego", "frenet"], default="frenet", help="agent action set, default=frenet")
    parser.add_argument("--dynamics_path", type=str, default="none", help="pretrained dynamics path, default=none")
    parser.add_argument("--train_dynamics", type=bool_, default=True, help="whether to train dynamics, default=True")
    parser.add_argument("--use_tanh", type=bool_, default=False, help="whether to use tanh transformation, default=False")
    parser.add_argument("--norm_obs", type=bool_, default=False, help="whether to normalize observations for agent and algo, default=False")
    # trainer model args
    parser.add_argument("--algo", type=str, choices=["sac"], default="sac", help="training algorithm, default=sac")
    parser.add_argument("--hidden_dim", type=int, default=64, help="neural network hidden dims, default=64")
    parser.add_argument("--num_hidden", type=int, default=2, help="number of hidden layers, default=2")
    parser.add_argument("--activation", type=str, default="relu", help="neural network activation, default=relu")
    parser.add_argument("--gamma", type=float, default=0.9, help="trainer discount factor, default=0.9")
    parser.add_argument("--beta", type=float, default=0.2, help="softmax temperature, default=0.2")
    parser.add_argument("--polyak", type=float, default=0.995, help="polyak averaging factor, default=0.995")
    # data args
    parser.add_argument("--max_data_eps", type=int, default=5, help="max number of data episodes, default=10")
    parser.add_argument("--create_svt", type=bool_, default=True, help="create svt to speed up rollout, default=True")
    parser.add_argument("--min_eps_len", type=int, default=50, help="min track length, default=50")
    parser.add_argument("--max_eps_len", type=int, default=500, help="max track length, default=200")
    # training args
    parser.add_argument("--batch_size", type=int, default=100, help="training batch size, default=100")
    parser.add_argument("--buffer_size", type=int, default=1e5, help="agent replay buffer size, default=1e5")
    parser.add_argument("--epochs", type=int, default=10, help="number of training epochs, default=10")
    parser.add_argument("--steps_per_epoch", type=int, default=1000, help="number of env steps per epoch, default=1000")
    parser.add_argument("--update_after", type=int, default=3000, help="burn-in env steps, default=3000")
    parser.add_argument("--update_every", type=int, default=50, help="update every env steps, default=50")
    parser.add_argument("--log_test_every", type=int, default=10, help="steps between logging test episodes, default=10")
    parser.add_argument("--a_steps", type=int, default=10, help="actor critic steps, default=50")
    parser.add_argument("--lr", type=float, default=0.001, help="model learning rate, default=0.001")
    parser.add_argument("--decay", type=float, default=1e-5, help="weight decay, default=0")
    parser.add_argument("--grad_clip", type=float, default=1000., help="gradient clipping, default=1000.")
    parser.add_argument("--plot_history", type=bool_, default=True, help="plot learning curve, default=True")
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--save", type=bool_, default=True)
    arglist = parser.parse_args()
    return arglist

def main(arglist):
    np.random.seed(arglist.seed)
    torch.manual_seed(arglist.seed)

    df_track = load_data(arglist.data_path, arglist.scenario, arglist.filename, train=True)

    # filter episode length
    df_track["eps_id"], df_track["eps_len"] = filter_segment_by_length(
        df_track["eps_id"].values, arglist.min_eps_len
    )

    """ TODO: add code to adapt input feature set """
    # define feature set
    ego_features = ["d", "ds", "dd", "kappa_r", "psi_error_r", ]
    relative_features = ["s_rel", "d_rel", "ds_rel", "dd_rel", "loom_s"]
    feature_set = ego_features + relative_features
    assert set(ego_features).issubset(set(FEATURE_SET["ego"]))
    assert set(relative_features).issubset(set(FEATURE_SET["relative"]))

    # define action set
    if arglist.action_set == "frenet":
        action_set = ["dds", "ddd"]
    else:
        action_set = ["ax_ego", "ay_ego"]
    assert set(action_set).issubset(set(ACTION_SET))

    # compute ctl limits
    ctl_max = torch.from_numpy(df_track.loc[df_track["is_train"] == 1][action_set].max().values).to(torch.float32)
    ctl_min = torch.from_numpy(df_track.loc[df_track["is_train"] == 1][action_set].min().values).to(torch.float32)
    ctl_lim = torch.max(torch.abs(ctl_max), torch.abs(ctl_min)) * 1.2

    ego_dataset = EgoDataset(
        df_track, train_labels_col="is_train",
        max_eps=arglist.max_data_eps, create_svt=arglist.create_svt, seed=arglist.seed
    )
    obs_dim, ctl_dim = len(feature_set), 2

    print(f"feature set: {feature_set}")
    print(f"action set: {action_set}")
    print(f"data size: {len(ego_dataset)}")

    agent = MLPAgent(
        obs_dim, ctl_dim, arglist.hidden_dim, arglist.num_hidden,
        activation=arglist.activation, use_tanh=arglist.use_tanh,
        ctl_limits=ctl_lim, norm_obs=arglist.norm_obs
    )

    # init trainer
    if arglist.algo == "sac":
        model = SAC(
            agent, arglist.hidden_dim, arglist.num_hidden,
            gamma=arglist.gamma, beta=arglist.beta, polyak=arglist.polyak, norm_obs=arglist.norm_obs,
            buffer_size=arglist.buffer_size, batch_size=arglist.batch_size, a_steps=arglist.a_steps,
            lr=arglist.lr, decay=arglist.decay, grad_clip=arglist.grad_clip
        )
    print(f"num parameters: {count_parameters(model)}")
    print(model)

    # load map
    map_data = MapReader()
    map_data.parse(os.path.join(arglist.data_path, "maps", arglist.scenario + ".osm"))

    # init simulator
    observer = Observer(
        map_data, ego_features=ego_features, relative_features=relative_features,
        action_set=action_set
    )
    env = InteractionSimulator(ego_dataset, map_data, observer, max_eps_steps=arglist.max_eps_len)

    model, logger = train(
        env, model, arglist.epochs, arglist.steps_per_epoch,
        arglist.update_after, arglist.update_every,
        log_test_every=arglist.log_test_every
    )

    df_history = pd.DataFrame(logger.history)
    df_history = df_history.assign(train=1)

    # save results
    if arglist.save:
        date_time = datetime.datetime.now().strftime("%m-%d-%Y %H-%M-%S")
        exp_path = os.path.join(arglist.exp_path, "agents")
        agent_path = os.path.join(exp_path, arglist.agent)
        save_path = os.path.join(agent_path, date_time)
        test_eps_path = os.path.join(save_path, "test_episodes")
        if not os.path.exists(exp_path):
            os.mkdir(exp_path)
        if not os.path.exists(agent_path):
            os.mkdir(agent_path)
        if not os.path.exists(save_path):
            os.mkdir(save_path)
        if not os.path.exists(test_eps_path):
            os.mkdir(test_eps_path)

        # save args
        with open(os.path.join(save_path, "args.json"), "w") as f:
            json.dump(vars(arglist), f)

        # save model
        torch.save(model.state_dict(), os.path.join(save_path, "model.pt"))

        # save history
        df_history.to_csv(os.path.join(save_path, "history.csv"), index=False)

        # save history plot
        fig_history, _ =plot_history(df_history, model.plot_keys)
        fig_history.savefig(os.path.join(save_path, "history.png"), dpi=100)

        # save test episode animations
        for i, test_episode in enumerate(logger.test_episodes):
            ani = animate(map_data, test_episode["sim_states"], test_episode["track_data"])
            save_animation(ani, os.path.join(test_eps_path, f"epoch_{i+1}_ani.mp4"))

        print(f"\nmodel saved at: {save_path}")

if __name__ == "__main__":
    arglist = parse_args()
    main(arglist)


from sys import exit, argv
from PySide2.QtWidgets import (QApplication, QLabel, QPushButton,
                               QVBoxLayout, QHBoxLayout, QWidget, QTableView,
                               QAbstractItemView, QHeaderView, QMenuBar, QMenu, QDockWidget, QSplitter, QSizePolicy, QMessageBox)
from PySide2.QtCore import Slot, Qt, QModelIndex, QTimer
from PySide2.QtCharts import QtCharts
from time import time

# from PySide2.QtWidgets import (QWidget)
from about import About
from hwmon_interface import get_sensor_value, get_sensor_label, get_list_of_sensors

from tablemodel import TableModel

class MyWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.sensortypes = ["in", "curr", "fan", "temp"]
        self.chartView = {}

        self.createMenu()
        self.tableModel = TableModel()

        # self.dock = QDockWidget()

        self.tableView = QTableView()
        self.tableView.setModel(self.tableModel)
        # self.tableView.setSortingEnabled(True)
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        # self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.verticalHeader().hide()
        self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableView.setSelectionMode(QAbstractItemView.SingleSelection)

        self.tableView.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.tableView.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
        # self.tableView.setSizePolicy(QSizePolicy.horizontalPolicy(ds))
        # self.dock.setWidget(self.tableView)

        self.mainLayout = QHBoxLayout()
        self.mainLayout.setMenuBar(self.menuBar)
        # self.mainLayout.addWidget(self.dock)

        self.layout = QVBoxLayout()

        self.widget = QWidget()
        self.widget.setLayout(self.layout)

        self.splitter = QSplitter()
        self.splitter.addWidget(self.tableView)
        self.splitter.addWidget(self.widget)

        self.mainLayout.addWidget(self.splitter)

        self.setLayout(self.mainLayout)

        timer = QTimer(self)
        timer.timeout.connect(self.update_sensors_values)
        timer.setInterval(1000)
        timer.start()

        for sensorType in self.sensortypes:
            chart_view = QtCharts.QChartView()
            self.layout.addWidget(chart_view)

            self.chartView[sensorType] = chart_view

        self.chartSeries = {}

        self.get_sensors()

        self.updateNumber = 0

    @Slot()
    def magic(self):
        self.update_sensors_values()

    @Slot()
    def get_sensors(self):
        sensors = get_list_of_sensors()

        for sensor in sensors:
            self.tableModel.addSensor(sensor)

            series = QtCharts.QLineSeries()
            series.setName(sensor.label)

            self.chartSeries[sensor.name] = series

            self.chartView[sensor.type].chart().addSeries(series)
            self.chartView[sensor.type].chart().createDefaultAxes()
            self.chartView[sensor.type].chart().legend().setAlignment(Qt.AlignLeft)
            self.chartView[sensor.type].chart().axisX().setRange(0, 100)
            self.chartView[sensor.type].chart().axisY().setRange(0, 0)
            self.chartView[sensor.type].show()
        #
        # for sensor in sensors:
        #     # Step 1: create the  row
        #     self.tableModel.insertRows(0)
        #
        #     # Step 2: get the index of the newly created row and use it.
        #     # to set the name
        #     ix = self.tableModel.index(0, 0, QModelIndex())
        #     self.tableModel.setData(ix, sensor.label, Qt.EditRole)
        #
        #     # Step 3: lather, rinse, repeat for the address.
        #     ix = self.tableModel.index(0, 1, QModelIndex())
        #     self.tableModel.setData(ix, sensor.current_value, Qt.EditRole)

    def update_sensors_values(self):
        for index, sensor in enumerate(self.tableModel.sensors):
            sensor.setCurrentValue(get_sensor_value(sensor.name))
            self.tableModel.dataChanged.emit(index, index, 0)

            chart = self.chartView[sensor.type].chart()
            if sensor.getScaledValue() > chart.axisY(self.chartSeries[sensor.name]).max():
                chart.axisY(self.chartSeries[sensor.name]).setMax(round(sensor.getScaledValue() + 5, -1))

            self.chartSeries[sensor.name].append(self.updateNumber, sensor.getScaledValue())

        self.updateNumber += 1

    def createMenu(self):
        self.menuBar = QMenuBar()

        self.fileMenu = QMenu("&File", self)
        self.exitAction = self.fileMenu.addAction("E&xit")
        self.exitAction.triggered.connect(self.close)

        self.menuBar.addMenu(self.fileMenu)

        self.helpMenu = QMenu("&Help", self)
        self.aboutAction = self.helpMenu.addAction("&About")
        self.aboutAction.triggered.connect(self.about)

        self.menuBar.addMenu(self.helpMenu)

    def about(self):
        # form = About()
        # form.show()
        QMessageBox.about(self, "About", "Asus sensor monitor v1")

if __name__ == "__main__":
    app = QApplication(argv)

    widget = MyWidget()
    widget.resize(800, 600)
    widget.show()
    widget.setWindowTitle("Sensor monitoring")

    exit(app.exec_())


# -*- coding: utf-8 -*-
"""
Created on Fri Apr 10 23:04:06 2020

@author: Aidan Montare (aam141@case.edu)
"""

import os
import json
import requests
from datetime import datetime, timezone

GROUPME_BASE_URL = "https://api.groupme.com/v3"

def read_secrets():
    """Reads the `secrets.json` file."""
    try:
        # We store our various secrets in an aptly named file
        with open('secrets.json', 'r') as data_file:
            return json.load(data_file)
    except FileNotFoundError:
        raise Exception("You must either provide an access token"
                        " on the commnad line or in the file"
                        " `secrets.json`")

def getAllGroupsOfUser():
    """Get all the groups of the user, and return
    the json"""

    page = 1 # page of the groups list we are looking at
    cache = []

    while True:
        request = requests.get(GROUPME_BASE_URL + "/groups",
                               params={'token': groupme_token,
                                       "omit": "memberships",
                                       "page": page})

        response = request.json()["response"]

        if request.status_code != 200:
            print("API fail with status code", request.status_code)
            break

        if not response:
            # we reached the last page
            break

        for group in response:
            cache.append(group)

        page += 1

    return cache

def identifyGroups(groups):
    """
    Print the names and IDs of all the users groups
    """

    for group in groups:
        print(group['name'], group['id'])
        if group['id'] != group['group_id']:
            raise Exception("The id and group_id fields are not"
                            " the same")

def showGroup(group_id):
    """
    Load the information about a given group
    """

    request = requests.get(GROUPME_BASE_URL + "/groups/" + target_group_id,
                               params={'token': groupme_token})

    response = request.json()["response"]

    return response

def postMessage():
    # post a message

    with open('message.json', 'r') as data_file:
        message = json.load(data_file)

    r = requests.post(GROUPME_BASE_URL + "/groups/" + target_group_id + "/messages",
                      data=json.dumps(message),
                      headers={"Content-Type": "application/json"},
                      params={'token': groupme_token})

    return r.json()["response"]

def printMessages():
    # messages are returned newest first

    print("created_at", "id", "text")
    for m in messages:
        print(m["created_at"], m["id"], m["text"])

def getMessagesInGroup():
    """
    Get all the messages in a group
    """
    all_messages = [] # the list we will collect messages in

    r = requests.get(GROUPME_BASE_URL + "/groups/" + target_group_id + "/messages",
                      params={'token': groupme_token})

    response = r.json()["response"]

    total_messages = response["count"]
    print("Total messages to be downloaded:", total_messages)

    messages = response["messages"]

    all_messages.extend(messages)

    last_id = messages[len(messages) - 1]["id"]

    print("Downloading.", end="")

    while True:
        r = requests.get(GROUPME_BASE_URL + "/groups/" + target_group_id + "/messages",
                      params={'token': groupme_token,
                              "before_id": last_id})

        if r.status_code == 304:
            # no more messages
            break

        response = r.json()["response"]
        messages = response["messages"]

        if not messages:
            break

        all_messages.extend(messages)

        last_id = messages[len(messages) - 1]["id"]
        print(".", end="")

    if len(all_messages) != total_messages:
        raise Exception("Not all messages were successfully"
                        " downloaded.")

    print(" Done.")

    return all_messages

secrets = read_secrets()

groupme_token = secrets["groupme_token"]
target_group_id = secrets["target_group_id"]

now = datetime.now(timezone.utc)

group_info = showGroup(target_group_id)

with open("./data/raw/group_info.json", 'w') as f:
    json.dump(group_info, f)

messages = getMessagesInGroup()

with open("./data/raw/messages.json", 'w') as f:
    json.dump(messages, f)

metadata = {"downloaded_at": now.isoformat()}

with open("./data/raw/metadata.json", 'w') as f:
    json.dump(metadata, f)


from odoo import api, fields, models

class ProjectProject(models.Model):
    _inherit = "project.project"

    picking_type_id = fields.Many2one(
        comodel_name="stock.picking.type",
        string="Operation Type",
        readonly=False,
        domain="[('company_id', '=', company_id)]",
        index=True,
        check_company=True,
    )
    location_id = fields.Many2one(
        comodel_name="stock.location",
        string="Source Location",
        readonly=False,
        check_company=True,
        index=True,
        help="Default location from which materials are consumed.",
    )
    location_dest_id = fields.Many2one(
        comodel_name="stock.location",
        string="Destination Location",
        readonly=False,
        index=True,
        check_company=True,
        help="Default location to which materials are consumed.",
    )
    stock_analytic_date = fields.Date(string="Analytic date")

    @api.onchange("picking_type_id")
    def _onchange_picking_type_id(self):
        self.location_id = self.picking_type_id.default_location_src_id.id
        self.location_dest_id = self.picking_type_id.default_location_dest_id.id

    def write(self, vals):
        """Update location information on pending moves when changed."""
        res = super().write(vals)
        field_names = ("location_id", "location_dest_id")
        if any(vals.get(field) for field in field_names):
            self.task_ids._update_moves_info()
        return res


import cv2
import numpy as np
from matplotlib import pyplot as plt

def compara(S1, S2, D1, D2, D3):

    hist_S1 = cv2.calcHist([S1], [0], None, [256], [0, 256])
    hist_S2 = cv2.calcHist([S2], [0], None, [256], [0, 256])
    hist_D1 = cv2.calcHist([D1], [0], None, [256], [0, 256])
    hist_D2 = cv2.calcHist([D2], [0], None, [256], [0, 256])
    hist_D3 = cv2.calcHist([D3], [0], None, [256], [0, 256])

    #correl: mais proximo de 1
    #chisqr: mais proximo de 0
    #bhatta: mais proximo de 0

    Correl = np.array([cv2.compareHist(hist_S1, hist_S1, cv2.HISTCMP_CORREL), cv2.compareHist(hist_S1, hist_S2, cv2.HISTCMP_CORREL),
    cv2.compareHist(hist_S1, hist_D1, cv2.HISTCMP_CORREL), cv2.compareHist(hist_S1, hist_D2, cv2.HISTCMP_CORREL), cv2.compareHist(hist_S1, hist_D3, cv2.HISTCMP_CORREL)])

    Chisqr = np.array([cv2.compareHist(hist_S1, hist_S1, cv2.HISTCMP_CHISQR), cv2.compareHist(hist_S1, hist_S2, cv2.HISTCMP_CHISQR),
    cv2.compareHist(hist_S1, hist_D1, cv2.HISTCMP_CHISQR), cv2.compareHist(hist_S1, hist_D2, cv2.HISTCMP_CHISQR), cv2.compareHist(hist_S1, hist_D3, cv2.HISTCMP_CHISQR)])

    Bhatta = np.array([cv2.compareHist(hist_S1, hist_S1, cv2.HISTCMP_BHATTACHARYYA), cv2.compareHist(hist_S1, hist_S2, cv2.HISTCMP_BHATTACHARYYA),
    cv2.compareHist(hist_S1, hist_D1, cv2.HISTCMP_BHATTACHARYYA), cv2.compareHist(hist_S1, hist_D2, cv2.HISTCMP_BHATTACHARYYA), cv2.compareHist(hist_S1, hist_D3, cv2.HISTCMP_BHATTACHARYYA)])

    plt.figure()
    plt.suptitle("CORRELAÇÃO", fontsize = 20)
    plt.subplot(2, 5, 1), plt.imshow(S1, cmap='gray'), plt.title("%.5f" % (Correl[0])), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 5, 2), plt.imshow(S2, cmap='gray'), plt.title("%.5f" % (Correl[1])), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 5, 3), plt.imshow(D1, cmap='gray'), plt.title("%.5f" % (Correl[2])), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 5, 4), plt.imshow(D2, cmap='gray'), plt.title("%.5f" % (Correl[3])), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 5, 5), plt.imshow(D3, cmap='gray'), plt.title("%.5f" % (Correl[4])), plt.xticks([]), plt.yticks([])

    plt.figure()
    plt.suptitle("CHI-SQUARE", fontsize = 20)
    plt.subplot(2, 5, 1), plt.imshow(S1, cmap='gray'), plt.title("%.1f" % (Chisqr[0])), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 5, 2), plt.imshow(S2, cmap='gray'), plt.title("%.1f" % (Chisqr[1])), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 5, 3), plt.imshow(D1, cmap='gray'), plt.title("%.1f" % (Chisqr[2])), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 5, 4), plt.imshow(D2, cmap='gray'), plt.title("%.1f" % (Chisqr[3])), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 5, 5), plt.imshow(D3, cmap='gray'), plt.title("%.1f" % (Chisqr[4])), plt.xticks([]), plt.yticks([])

    plt.figure()
    plt.suptitle("BHATTACHARYYA", fontsize = 20)
    plt.subplot(2, 5, 1), plt.imshow(S1, cmap='gray'), plt.title("%.5f" % (Bhatta[0])), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 5, 2), plt.imshow(S2, cmap='gray'), plt.title("%.5f" % (Bhatta[1])), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 5, 3), plt.imshow(D1, cmap='gray'), plt.title("%.5f" % (Bhatta[2])), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 5, 4), plt.imshow(D2, cmap='gray'), plt.title("%.5f" % (Bhatta[3])), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 5, 5), plt.imshow(D3, cmap='gray'), plt.title("%.5f" % (Bhatta[4])), plt.xticks([]), plt.yticks([])

imagem1 = cv2.imread("trabalho7/cachorro.jpg")
imagem1 = cv2.cvtColor(imagem1, cv2.COLOR_BGR2GRAY)

imagem2 = cv2.imread("trabalho7/cachorro2.jpg")
imagem2 = cv2.cvtColor(imagem2, cv2.COLOR_BGR2GRAY)

imagem3 = cv2.imread("trabalho7/pato.jpg")
imagem3 = cv2.cvtColor(imagem3, cv2.COLOR_BGR2GRAY)

imagem4 = cv2.imread("trabalho7/dinossauro.jpg")
imagem4 = cv2.cvtColor(imagem4, cv2.COLOR_BGR2GRAY)

imagem5 = cv2.imread("trabalho7/macaco.jpg")
imagem5 = cv2.cvtColor(imagem5, cv2.COLOR_BGR2GRAY)

altura, largura = imagem2.shape

imagem1 = cv2.resize(imagem1, (largura, altura))
imagem3 = cv2.resize(imagem3, (largura, altura))
imagem4 = cv2.resize(imagem4, (largura, altura))
imagem5 = cv2.resize(imagem5, (largura, altura))

compara(imagem1, imagem2, imagem3, imagem4, imagem5)

plt.show()


import codecs
import collections
import enum

import tensorflow as tf  # pytype: disable=import-error

# Values for padding, unknown words and a root.
PAD = '<p>'
PAD_ID = 0

UNKNOWN = '<u>'
UNKNOWN_ID = 1

ROOT = '<r>'
ROOT_ID = 2

class CoNLLAttributes(enum.Enum):
  """CoNLL attributre names and indices.

  A UD CoNLL file looks like:
  1    They     they    PRON    PRP    Case=Nom|Number=Plur       2    nsubj
  2    buy      buy     VERB    VBP    Number=Plur|PTense=Pres    0    root
  3    books    book    NOUN    NNS    Number=Plur                2    obj
  4    .        .       PUNCT   .      _                          2    punct

  For details, please see: http://universaldependencies.org/format.html.
  """

  ID = 0
  FORM = 1
  LEMMA = 2
  UPOS = 3
  XPOS = 4
  FEATS = 5
  HEAD = 6
  DEPREL = 7

def create_vocabs(filename, max_num_forms=100000):
  """Loads corpus and create vocabulary lists.

  Args:
    filename: file name of a corpus.
    max_num_forms: maximum number of tokens included.

  Returns:
    Dictionary containing named vocab dictionaries.

  """
  form_counter = collections.Counter()
  xpos_counter = collections.Counter()
  with tf.io.gfile.GFile(filename, 'rb') as f:
    for line in codecs.getreader('utf-8')(f):
      line = line.strip()
      split = line.split('\t')
      if not line.startswith('#') and split[0]:
        form_counter[split[CoNLLAttributes.FORM.value]] += 1
        xpos_counter[split[CoNLLAttributes.XPOS.value]] += 1

  special_tokens = {PAD: PAD_ID, UNKNOWN: UNKNOWN_ID, ROOT: ROOT_ID}

  # create word form vocab
  vocabs = {'forms': {}, 'xpos': {}}
  vocabs['forms'].update(special_tokens)
  vocabs['forms'].update(
      {
          form[0]: id
          for id, form in enumerate(
              form_counter.most_common(max_num_forms), start=ROOT_ID + 1
          )
      }
  )

  # create xpos vocab
  vocabs['xpos'].update(special_tokens)
  vocabs['xpos'].update(
      {
          tag[0]: id
          for id, tag in enumerate(
              xpos_counter.most_common(), start=ROOT_ID + 1
          )
      }
  )

  return vocabs

def create_token(token, attributes, vocabs):
  """Map for a token a selected subset of attributes to indices.

  Input example: CoNLL 09 representation for a token.
    ['Ms.', 'ms.', 'ms.', 'NNP', '_', '2', 'TITLE]
  Output example: Indices as defined in self._attributes, e.g., [word form,
    part-of-speech tag, and head].
    [1025, 3, 1]

  Args:
    token: CoNLL token attributes.
    attributes: selected attributes.
    vocabs: dictionary of vocabs.

  Returns:
    List of attribute ids for a token, e.g. [1025, 3] with word id and pos id.

  Raises:
    ValueError: CoNLL attribute requested but not covered by mapping.
  """
  selected_attributes = []
  for attribute in attributes:
    index = attribute.value
    if attribute == CoNLLAttributes.FORM:
      selected_attributes.append(vocabs['forms'].get(token[index], UNKNOWN_ID))
    elif attribute == CoNLLAttributes.XPOS:
      selected_attributes.append(vocabs['xpos'].get(token[index], UNKNOWN_ID))
    elif attribute == CoNLLAttributes.HEAD:
      selected_attributes.append(int(token[index]))
    else:
      raise ValueError(
          'CoNLL index %s not covered by mapping.' % str(attribute.name)
      )
  return selected_attributes

def create_sentence_with_root(attributes, vocabs):
  """Create a sentence containing a root.

  Args:
    attributes: attributes extracted from token.
    vocabs: dictionary of vocabs.

  Returns:
    A list representing a sentence containing the root only,
    e.g., [[2, 1, 0]] for root word, unknown xpos, and head 0.
  """
  # Create the token properties of an artificial root node.
  token_properties = [ROOT for _ in range(12)]  # CoNLL 09 has 12 columns.
  token_properties[CoNLLAttributes.ID.value] = '0'
  token_properties[CoNLLAttributes.HEAD.value] = '0'
  token = create_token(token_properties, attributes, vocabs)
  if len(token) == 1:
    token = token[0]
  return [token]

def sentences_from_conll_data(
    corpus_filename, vocabs, attributes, max_sentence_length=1000
):
  """Load and returns conll data in list format.

  Args:
    corpus_filename: filename of corpus.
    vocabs: dictionary of vocabs
    attributes: list of conll attributes to include into the batch
    max_sentence_length: cut off sentences longer as max tokens

  Yields:
      A sentence as a list of tokens while tokens are lists of attributes.
  """
  with tf.io.gfile.GFile(corpus_filename, 'rb') as f:
    sentence = create_sentence_with_root(attributes, vocabs)
    for line in codecs.getreader('utf-8')(f):
      line = line.strip()
      if line.startswith('#'):
        continue
      split = line.split('\t')
      if split[0]:  # Not an empty line, process next token:
        if len(sentence) < max_sentence_length:
          if len(attributes) == 1:
            sentence.append(create_token(split, attributes, vocabs)[0])
          else:
            sentence.append(create_token(split, attributes, vocabs))
      else:  # Sentences start with an empty line, yield sentence:
        yield sentence

        # Reset sentence.
        sentence = create_sentence_with_root(attributes, vocabs)
    if len(sentence) > 1:  # sentences does not only contain a root.
      yield sentence

def sentence_dataset_dict(
    filename,
    vocabs,
    attributes_input,
    attributes_target,
    batch_size,
    bucket_size,
    repeat=None,
    prefetch_size=tf.data.experimental.AUTOTUNE,
):
  """Combines sentences into a dataset of padded batches.

  Args:
    filename: file name of a corpus.
    vocabs: dictionary of dictionaries to map from strings to ids.
    attributes_input: attributes for the input.
    attributes_target: target attributes empty targets is not included.
    batch_size: the size of a batch.
    bucket_size: the size of a bucket.
    repeat: number of times the dataset is repeated.
    prefetch_size: prefetch size of the data.

  Returns:
    Returns dataset as dictionary containing the data as key value pairs.
  """
  data_keys = ['inputs']
  if attributes_target:
    data_keys.append('targets')

  def generator():
    """Generator to create the data."""
    input_generator = sentences_from_conll_data(
        filename, vocabs, attributes_input, max_sentence_length=bucket_size
    )

    if attributes_target:
      target_generator = sentences_from_conll_data(
          filename, vocabs, attributes_target, max_sentence_length=bucket_size
      )

    for inputs in input_generator:
      data = {'inputs': inputs}
      if attributes_target:
        data['targets'] = next(target_generator)
      yield data

  output_types = {k: tf.float32 for k in data_keys}
  output_shapes = {k: (None,) for k in data_keys}
  dataset = tf.data.Dataset.from_generator(
      generator, output_types=output_types, output_shapes=output_shapes
  )

  # cache the dataset in memory and repeat.
  dataset = dataset.cache()
  dataset = dataset.repeat(repeat)

  # static padding up to bucket size.
  padded_shapes = {k: [bucket_size] for k in data_keys}
  dataset = dataset.padded_batch(
      batch_size=batch_size, padded_shapes=(padded_shapes)
  )

  dataset = dataset.prefetch(prefetch_size)
  return dataset


from ast import While, main
from asyncio.windows_events import NULL
from cgi import print_arguments
import random
import string
import csv
from xml.dom.minidom import Element

#Result counter variables
comp_wins = 0
player_wins = 0
ties = 0

#Function for player choice
def Choose_Option():
    while True: #While loop fixes bug of game results not being displayed when elif conditions not met
        user_choice = input("ROCK, PAPER, OR SCISSORS?: ")
        if len(user_choice) < 1: #Prevents crash if nothing is entered
            print("\nQUIT TRYING TO BREAK MY CODE. DO IT RIGHT THIS TIME.  ಠ╭╮ಠ\n")
        elif (user_choice.lower()[0] == "r"):
            user_choice = "r"
        elif (user_choice.lower()[0] == "p"):
            user_choice = "p"
        elif (user_choice.lower()[0] == "s"):
            user_choice = "s"
        else:
            print("\nQUIT TRYING TO BREAK MY CODE. DO IT RIGHT THIS TIME.  ಠ╭╮ಠ\n")
        return user_choice
    pass #Breaks out of while loop, goes to Play_Again()

#Function for computer choice
def Computer_Option():
    comp_choice = random.randint(1, 3)
    if comp_choice == 1:
        comp_choice = "r"
    elif comp_choice == 2:
        comp_choice = "p"
    elif comp_choice == 3:
        comp_choice = "s"
    return comp_choice

#Function for replay
def Play_Again():
    user_choice = input("PLAY AGAIN? (Y/N)")
    if len(user_choice) < 1: #Prevents crash if nothing is entered
        print("\nQUIT TRYING TO BREAK MY CODE. DO IT RIGHT THIS TIME.  ಠ╭╮ಠ\n")
        Play_Again()
    elif (user_choice.lower()[0] == "y"):
        return
    elif (user_choice.lower()[0] == "n"):
        print("\n***GOODBYE***\n")
        f = open("test_file.csv", "w", newline="") #'w' will overwrite the information in the file
        tup1 = ("Player Wins", player_wins)
        writer = csv.writer(f)
        writer.writerow(tup1)
        tup2 = ("Computer Wins", comp_wins)
        writer = csv.writer(f)
        writer.writerow(tup2)
        tup3 = ("Ties", ties)
        writer = csv.writer(f)
        writer.writerow(tup3)
        f.close()
        quit()
    else:
        print("\nQUIT TRYING TO BREAK MY CODE. DO IT RIGHT THIS TIME.  ಠ╭╮ಠ\n")
        Play_Again()

#First function called: a main menu of sorts
def Opening_Choice():
        user_choice = input("\n1 TO START GAME\n2 TO SEE PREVIOUS SCOREBOARD\n>>>")
        if user_choice == "1":
            print("\nLET'S GO:")
        elif user_choice == "2":
            file = open("test_file.csv", "r")
            data = list(csv.reader(file, delimiter=","))
            file.close()
            print(data)
            Opening_Choice()
        elif len(user_choice) < 1:
            print("\nQUIT TRYING TO BREAK MY CODE. DO IT RIGHT THIS TIME.  ಠ╭╮ಠ\n")
            Opening_Choice()
        else:
            print("\nQUIT TRYING TO BREAK MY CODE. DO IT RIGHT THIS TIME.  ಠ╭╮ಠ\n")
            Opening_Choice()

#Game or previous scores choice
print("********\nWELCOME:\n********")
Opening_Choice()

#Main method loop
while __name__ == "__main__":

    #Choice function calls
    #Fixes bug by allowing a direct return to the Choose_Option function (fixes recursion problem)
    print("")
    user_choice = Choose_Option()
    while True:
        if len(user_choice) < 1: #Prevents crash on null values
            user_choice = Choose_Option()
        elif (user_choice.lower()[0] != "r" and user_choice.lower()[0] != "p" and user_choice.lower()[0] != "s"): #Handles str, int, and special exceptions
            user_choice = Choose_Option()
        else:
            break
    comp_choice = Computer_Option()
    print("")

    #Outcomes for games
    if user_choice == "r":
        if comp_choice == "r":
            print("****************\nRESULT:\nPLAY: ROCK\nCOMP: ROCK\nOUTC: TIE\n****************\n")
            ties += 1

        elif comp_choice == "p":
            print("****************\nRESULT:\nPLAY: ROCK\nCOMP: PAPER\nOUTC: LOSS\n****************\n")
            comp_wins += 1

        elif comp_choice == "s":
            print("****************\nRESULT:\nPLAY: ROCK\nCOMP: SCISSORS\nOUTC: WIN\n****************\n")
            player_wins += 1

    elif user_choice == "p":
        if comp_choice == "r":
            print("****************\nRESULT:\nPLAY: PAPER\nCOMP: ROCK\nOUTC: WIN\n****************\n")
            player_wins += 1

        elif comp_choice == "p":
            print("****************\nRESULT:\nPLAY: PAPER\nCOMP: PAPER\nOUTC: TIE\n****************\n")
            ties += 1

        elif comp_choice == "s":
            print("****************\nRESULT:\nPLAY: PAPER\nCOMP: SCISSORS\nOUTC: LOSS\n****************\n")
            comp_wins += 1

    elif user_choice == "s":
        if comp_choice == "r":
            print("****************\nRESULT:\nPLAY: SCISSORS\nCOMP: ROCK\nOUTC: LOSS\n****************\n")
            comp_wins += 1

        elif comp_choice == "p":
            print("****************\nRESULT:\nPLAY: SCISSORS\nCOMP: PAPER\nOUTC: WIN\n****************\n")
            player_wins += 1

        elif comp_choice == "s":
            print("****************\nRESULT:\nPLAY: SCISSORS\nCOMP: SCISSORS\nOUTC: TIE\n****************\n")
            ties += 1

    #Scoreboard
    print("****************")
    print("PLAY WINS: " + str(player_wins))
    print("COMP WINS: " + str(comp_wins))
    print("TIES: " + str(ties))
    print("****************")

    #Replay function call
    Play_Again()
    #END OF LOOP


import argparse
import contextlib
import os.path
import subprocess
import sys

SEPARATOR = "\n<!-- DEMO TABLE MARKER -->\n"
HTML_INDENT = 2
LINK_DEFAULT_TEXT = "demo"
TRUE_TEXT = "yes"

class HtmlBuilder:
    def __init__(self, indent=None):
        self.html = []
        self.indent_amount = indent
        self.indent_level = 0
        self.add_count = 0

    def add(self, data, one_line=False):
        self.add_count += 1
        if one_line:
            self.html[-1] += data
        else:
            if self.indent_amount:
                indent = " " * (self.indent_amount * self.indent_level)
                data = indent + data

            self.html.append(data)

    @contextlib.contextmanager
    def element(self, name, attrs={}, only_with_attrs=False):
        """Open (and automatically) close an HTML element"""
        if only_with_attrs and not attrs:
            yield
            return

        attrs_str = " ".join(f"{name}='{value}'" for name, value in attrs.items())
        if attrs_str:
            attrs_str = " " + attrs_str

        self.add(f"<{name}{attrs_str}>")
        self.indent_level += 1
        initial_len = len(self.html)
        try:
            yield
        finally:
            self.indent_level -= 1
            closing = f"</{name}>"
            self.add(f"</{name}>", one_line=len(self.html) == initial_len)

    def string(self):
        sep = "" if self.indent_amount is None else "\n"
        return sep.join(self.html)

class T:
    def __init__(self, text=None, link=None, details=None):
        if text is None:
            if link is None:
                raise ValueError("must specify at least one of 'text' and 'link'")

            text = LINK_DEFAULT_TEXT

        self.text = text
        self.link = link
        self.details = details

    @staticmethod
    def textify(inp):
        if not inp:
            return None
        elif inp is True:
            return T(TRUE_TEXT)
        elif isinstance(inp, list):
            return [T.textify(x) for x in inp]
        elif isinstance(inp, T):
            return inp

        return T(inp)

    def link_is_valid_relative(self, base_dir):
        if self.link is None:
            return True

        if os.path.isabs(self.link):
            # absolute links aren't allowed
            return False

        if self.link.lower().startswith("http"):
            # github (and other website) links aren't allowed either
            return False

        return os.path.exists(os.path.join(base_dir, self.link))

    def to_html(self):
        html = HtmlBuilder()

        title_attr = {"title": self.details} if self.details else {}
        href_attr = {"href": self.link} if self.link else {}

        # add a span if we need details (hover) text, and an link if there's a link
        with html.element("span", title_attr, only_with_attrs=True):
            with html.element("a", href_attr, only_with_attrs=True):
                html.add(self.text)

        return html.string()

def validate_links(element, base_dir, invalid):
    # traverse over the collection(s) to find the T's and check their links, collecting them in
    # `invalid`.
    if element is None:
        pass
    elif isinstance(element, T):
        if not element.link_is_valid_relative(base_dir):
            invalid.append(element.link)
    elif isinstance(element, list):
        for sub in element:
            validate_links(sub, base_dir, invalid)
    elif isinstance(element, Algorithm):
        for sub in element.columns.values():
            validate_links(sub, base_dir, invalid)
    else:
        raise ValueError(f"unsupported element in link validation {element!r}")

def cell_html(html, cell):
    if not cell:
        return

    if isinstance(cell, list):
        for contents in cell:
            # multiple elements? space them out
            html.add(contents.to_html(), one_line=False)
    else:
        html.add(cell.to_html(), one_line=True)

def build_html(headings, algorithms):
    builder = HtmlBuilder(indent=2)

    builder.add(
        f"<!-- autogenerated by {__file__}, edit that file instead of this location -->"
    )
    with builder.element("table"):
        with builder.element("tr"):
            for heading in headings:
                with builder.element("th"):
                    builder.add(heading.to_html(), one_line=True)

        for algorithm in algorithms:
            with builder.element("tr"):
                for heading in headings:
                    with builder.element("td"):
                        cell_html(builder, algorithm.columns[heading])

    return builder.string()

# Columns
ALGORITHM = T("Algorithm")
HETEROGENEOUS = T("Heter.", details="Heterogeneous graphs")
DIRECTED = T("Dir.", details="Directed")
WEIGHTED = T("EW", details="Edge weights")
TEMPORAL = T("T", details="Time-varying or temporal graphs")
FEATURES = T("NF", details="Node features")
NC = T("NC", link="node-classification/README.md", details="Node classification")
LP = T("LP", link="link-prediction/README.md", details="Link prediction")
RL = T("RL", link="embeddings/README.md", details="Representation learning")
INDUCTIVE = T("Ind.", details="Inductive")
GC = T("GC", link="graph-classification/README.md", details="Graph classification")

COLUMNS = [
    ALGORITHM,
    HETEROGENEOUS,
    DIRECTED,
    WEIGHTED,
    TEMPORAL,
    FEATURES,
    NC,
    LP,
    RL,
    INDUCTIVE,
    GC,
]

class Algorithm:
    def __init__(
        self,
        algorithm,
        *,
        heterogeneous=None,
        directed=None,
        weighted=None,
        temporal=None,
        features=None,
        nc=None,
        interpretability_nc=None,
        lp=None,
        rl=None,
        inductive=None,
        gc=None,
    ):
        columns = {
            ALGORITHM: algorithm,
            HETEROGENEOUS: heterogeneous,
            DIRECTED: directed,
            WEIGHTED: weighted,
            TEMPORAL: temporal,
            FEATURES: features,
            NC: nc,
            LP: lp,
            RL: rl,
            INDUCTIVE: inductive,
            GC: gc,
        }

        self.columns = {name: T.textify(value) for name, value in columns.items()}

HETEROGENEOUS_EDGE = T("yes, edges", details="Multiple edges types and one node type")

def rl_us(link=None):
    return T("US", link=link, details="UnsupervisedSampler, using link prediction")

def rl_dgi(link="embeddings/deep-graph-infomax-cora.ipynb"):
    return T("DGI", link=link, details="DeepGraphInfomax, using mutual information")

def via_rl(link=None):
    return T(
        "via RL",
        link=link,
        details="As a downstream task by training a classifier on reprentation/embedding vectors",
    )

ALGORITHMS = [
    Algorithm(
        T("GCN", details="Graph Convolutional Network"),
        heterogeneous="see RGCN",
        features=True,
        nc=T(link="node-classification/gcn/gcn-cora-node-classification-example.ipynb"),
        interpretability_nc=T(
            link="interpretability/gcn/node-link-importance-demo-gcn.ipynb"
        ),
        lp=T(link="link-prediction/gcn/cora-gcn-links-example.ipynb"),
        rl=[rl_us(), rl_dgi()],
        inductive="see Cluster-GCN",
        gc=T(link="graph-classification/supervised-graph-classification.ipynb"),
    ),
    Algorithm(
        "Cluster-GCN",
        features=True,
        nc=T(
            link="node-classification/cluster-gcn/cluster-gcn-node-classification.ipynb"
        ),
        lp=True,
        inductive=True,
    ),
    Algorithm(
        T("RGCN", details="Relational GCN"),
        heterogeneous=HETEROGENEOUS_EDGE,
        features=True,
        nc=T(
            link="node-classification/rgcn/rgcn-aifb-node-classification-example.ipynb"
        ),
        lp=True,
    ),
    Algorithm(
        T("GAT", details="Graph ATtention Network"),
        features=True,
        nc=T(link="node-classification/gat/gat-cora-node-classification-example.ipynb"),
        interpretability_nc=T(
            link="interpretability/gat/node-link-importance-demo-gat.ipynb"
        ),
        lp=True,
        rl=[rl_us(), rl_dgi()],
    ),
    Algorithm(
        T("SGC", details="Simplified Graph Convolution"),
        features=True,
        nc=T(link="node-classification/sgc/sgc-node-classification-example.ipynb"),
        lp=True,
    ),
    Algorithm(
        T("PPNP", details="Personalized Propagation of Neural Predictions"),
        features=True,
        nc=T(
            link="node-classification/ppnp/ppnp-cora-node-classification-example.ipynb"
        ),
        lp=True,
        rl=[rl_us(), rl_dgi(link=None)],
    ),
    Algorithm(
        T("APPNP", details="Approximate PPNP"),
        features=True,
        nc=T(
            link="node-classification/ppnp/ppnp-cora-node-classification-example.ipynb"
        ),
        lp=True,
        rl=[rl_us(), rl_dgi()],
    ),
    Algorithm(
        "GraphWave",
        nc=via_rl(),
        lp=via_rl(),
        rl=T(link="embeddings/graphwave-barbell.ipynb"),
    ),
    Algorithm(
        "Attri2Vec",
        features=True,
        nc=T(
            link="node-classification/attri2vec/attri2vec-citeseer-node-classification-example.ipynb"
        ),
        lp=T(link="link-prediction/attri2vec/stellargraph-attri2vec-DBLP.ipynb"),
        rl=T(link="embeddings/stellargraph-attri2vec-citeseer.ipynb"),
    ),
    Algorithm(
        "GraphSAGE",
        heterogeneous="see HinSAGE",
        directed=T(
            link="node-classification/graphsage/directed-graphsage-on-cora-example.ipynb"
        ),
        features=True,
        nc=T(
            link="node-classification/graphsage/graphsage-cora-node-classification-example.ipynb"
        ),
        lp=T(link="link-prediction/graphsage/cora-links-example.ipynb"),
        rl=[
            rl_us(link="embeddings/embeddings-unsupervised-graphsage-cora.ipynb"),
            rl_dgi(),
        ],
        inductive=T(
            link="node-classification/graphsage/graphsage-pubmed-inductive-node-classification-example.ipynb"
        ),
    ),
    Algorithm(
        "HinSAGE",
        heterogeneous=True,
        features=True,
        nc=True,
        lp=T(link="link-prediction/hinsage/movielens-recommender.ipynb"),
        inductive=True,
    ),
    Algorithm(
        "Node2Vec",
        weighted=T(
            link="node-classification/node2vec/stellargraph-node2vec-weighted-random-walks.ipynb"
        ),
        nc=via_rl(
            link="node-classification/node2vec/stellargraph-node2vec-node-classification.ipynb"
        ),
        lp=via_rl(link="link-prediction/random-walks/cora-lp-demo.ipynb"),
        rl=T(link="embeddings/stellargraph-node2vec.ipynb"),
    ),
    Algorithm(
        "Metapath2Vec",
        heterogeneous=True,
        nc=via_rl(),
        lp=via_rl(),
        rl=T(link="embeddings/stellargraph-metapath2vec.ipynb"),
    ),
    Algorithm(
        T("CTDNE", details="Continuous-Time Dynamic Network Embeddings"),
        temporal=True,
        nc=via_rl(),
        lp=via_rl(link="link-prediction/random-walks/ctdne-link-prediction.ipynb"),
        rl=True,
    ),
    Algorithm(
        "Watch Your Step",
        nc=via_rl(link="embeddings/watch-your-step-cora-demo.ipynb"),
        lp=via_rl(),
        rl=T(link="embeddings/watch-your-step-cora-demo.ipynb"),
    ),
    Algorithm(
        "ComplEx",
        heterogeneous=HETEROGENEOUS_EDGE,
        directed=True,
        nc=via_rl(),
        lp=T(link="link-prediction/knowledge-graphs/complex.ipynb"),
        rl=True,
    ),
    Algorithm(
        "DistMult",
        heterogeneous=HETEROGENEOUS_EDGE,
        directed=True,
        nc=via_rl(),
        lp=T(link="link-prediction/knowledge-graphs/distmult.ipynb"),
        rl=True,
    ),
]

def main():
    parser = argparse.ArgumentParser(
        description="Edits or compares the table of all algorithms and their demos in `demos/README.md`."
    )
    parser.add_argument(
        "readme",
        type=argparse.FileType("r+"),
        default="demos/README.md",
        nargs="?",
        help="the location of the readme file (default: %(default)s)",
    )
    parser.add_argument(
        "--action",
        choices=["compare", "overwrite"],
        default="compare",
        help="whether to compare the table in 'readme' against what would be generated, or to overwrite the table with a new one (default: %(default)s)",
    )
    args = parser.parse_args()

    def error(message, edit_fixit=False):
        formatted = f"Error while generating algorithm table for `{args.readme.name}`: {message}"
        if edit_fixit:
            formatted += f"\n\nTo fix, edit `{__file__}` as appropriate and run it like `python {__file__} --action=overwrite` to overwrite existing table with new one."

        print(formatted, file=sys.stderr)

        try:
            subprocess.run(
                [
                    "buildkite-agent",
                    "annotate",
                    "--style=error",
                    "--context=demo_table",
                    formatted,
                ]
            )
        except FileNotFoundError:
            # no agent, so probably on buildkite, and so silently no annotation
            pass

        sys.exit(1)

    base_dir = os.path.dirname(args.readme.name)

    invalid_links = []
    validate_links(COLUMNS, base_dir, invalid_links)
    validate_links(ALGORITHMS, base_dir, invalid_links)

    if invalid_links:
        formatted = "\n".join(f"- `{link}`" for link in invalid_links)
        error(
            f"expected all links in algorithm specifications in `{__file__}` to be relative links that are valid starting at `{base_dir}`, but found {len(invalid_links)} invalid:\n\n{formatted}",
            edit_fixit=True,
        )

    new_table = build_html(COLUMNS, ALGORITHMS)

    file_contents = args.readme.read()
    parts = file_contents.split(SEPARATOR)
    if len(parts) != 3:
        error(
            f"expected exactly two instances of `{SEPARATOR.strip()}` on their own lines in `{args.readme.name}`, found {len(parts) - 1} instances."
        )

    prefix, current_table, suffix = parts

    if args.action == "compare":
        if new_table != current_table:
            error(
                f"existing table in `{args.readme.name}` differs to generated table; was it edited manually?",
                edit_fixit=True,
            )

    elif args.action == "overwrite":
        file_chunks = [prefix, SEPARATOR, new_table, SEPARATOR, suffix]

        args.readme.seek(0)
        args.readme.write("".join(file_chunks))

        # delete any remaining content
        args.readme.truncate()

if __name__ == "__main__":
    main()


import requests
import re
import json
url = input("请输入要下载的抖音视频地址!\n")
userAgent = "Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Mobile Safari/537.36"
header = {
    "Referer": "https://v.douyin.com/",
    'User-Agent': userAgent,
}
#获取要下载的视频id
r = requests.get(url, headers=header)
url = r.url
id = url.split("video/")[1].split("/?")[0]
url = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=" + id
r = requests.get(url, headers=header)
video = json.loads(r.content)["item_list"][0]
url = video["video"]["play_addr"]["url_list"][0]
url = url.replace("playwm", "play")
#开始下载
r = requests.get(url, headers=header)
with open(video["desc"] + ".mp4", "wb") as code:
    code.write(r.content)
    print("下载成功")
input("按下回车退出程序")


from configparser import ConfigParser
import os

class Config():
    def __init__(self, file_name= 'config.ini'):
        self.file_name = file_name
        self.config = ConfigParser()
        if self.file_name not in os.listdir(os.getcwd()):
            self.create_file()
        self.config.read(self.file_name, encoding="utf-8")

    def create_file(self):
        self.add_section("save")
        self.set_config("save", "file_name", "D:/Document")
        self.set_config("save", "save_file_name", "D:/Document")
        self.add_section("search")
        self.set_config("search", "file_name", "D:/Document")

    def save(self):
        """Save the configuration"""
        with open(self.file_name,"w+",encoding="utf-8") as file_obj:
            self.config.write(file_obj)

    def get_config(self, section, option):
        """"Returns the value of option in the section"""
        ret = {"ret_val":True, "data":"", "info":"normal operation"}

        if not self.config.has_option(section, option):
            ret["ret_val"] = False
            ret["info"] = "there is no section or option"
            return ret

        ret["data"] = self.config[section][option]
        return ret

    def set_config(self, section, option, value):
        """Set the value in the option of the section, if no the option, to create it """
        ret = {"ret_val":True, "data":"", "info":"normal operation"}

        if not self.config.has_section(section):
            ret["ret_val"] = False
            ret["info"] = "there is no section"
        elif not self.config.has_option(section, option):
            ret["info"] = "there is no option, but create one"

        self.config.set(section, option, value)
        self.save()
        return ret

    def add_section(self, section):
        """Add a section to the configuration"""
        ret = {"ret_val":True, "data":"", "info":"normal operation"}
        if self.config.has_section(section):
            ret["ret_val"] = False
            ret["info"] = "there has already this section"
            return ret

        self.config.add_section(section)
        self.save()
        return ret

    def remove_section(self, section):
        """Remove a section to the configuration"""
        ret = {"ret_val":True, "data":"", "info":"normal operation"}
        if not self.config.has_section(section):
            ret["ret_val"] = False
            ret["info"] = "there is no section"
            return ret

        self.config.remove_section(section)
        self.save()
        return ret

    def remove_option(self, section, option):
        """Remove a option to the configuration"""
        ret = {"ret_val":True, "data":"", "info":"normal operation"}

        if not self.config.has_option(section, option):
            ret["ret_val"] = False
            ret["info"] = "there is no section or option"
            return ret

        self.config.remove_option(section, option)
        self.save()
        return ret

if __name__ == "__main__":
    config = Config()
    print(config.get_config("db", "dbuser"))
    print(config.set_config("db", "abuse", "test2"))
    print(config.get_config("db", "dbuser"))
    print(config.get_config("db", "abuse"))
    print(config.add_section("db1"))
    print(config.set_config("db1", "name", "xiongjiageng"))
    print(config.remove_section("db1"))
    print(config.remove_option("db1", "name"))


from gamelogic import Snake, Apple
import pygame

green = (0,255,0)
red = (255,0,0)
black = (0, 0, 0)

display_width = 600
display_height = 600
FPS = 10

block_size = 20

pygame.init()
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Snake-Game") #add icon?
clock = pygame.time.Clock() # game clock

font = pygame.font.SysFont(None, 25)
def message_to_display(msg, collor):
    text = font.render(msg, True, collor)
    gameDisplay.blit(text, [display_width // 2 - 100, display_height // 2])
    pygame.display.update()

def main():
    snake = Snake(display_width // 2, display_height // 2, block_size, red,\
                  display_width, display_height)
    apple = Apple(block_size, green, display_width, display_height)
    gameRunning = True
    gameOver = False

    while gameRunning:

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN :
                if event.key == pygame.K_UP or event.key == pygame.K_w :
                    snake.go_up()
                elif event.key == pygame.K_DOWN or event.key == pygame.K_s :
                    snake.go_down()
                elif event.key == pygame.K_RIGHT or event.key == pygame.K_d :
                    snake.go_right()
                elif event.key == pygame.K_LEFT or event.key == pygame.K_a:
                    snake.go_left()
            elif event.type == pygame.QUIT:
                gameRunning = False

        snake.update()
        if  snake.outside_the_boundaries() or snake.eat_itself(): gameOver = True
        if snake.found_Apple(apple): snake.eat_aplle(apple)

        gameDisplay.fill(black)
        apple.draw(gameDisplay)
        snake.draw(gameDisplay)
        pygame.display.update()
        clock.tick(FPS)

        while gameOver:
            gameDisplay.fill(black)
            message_to_display("GAME OVER | Play again(y/n)",green)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_y:
                        gameOver = False
                        snake.reset()
                        apple.update()
                    elif event.key == pygame.K_n:
                        gameRunning = False
                        gameOver = False
                if event.type == pygame.QUIT:
                    gameRunning = False
                    gameOver = False

    pygame.quit()
    quit()

if __name__ == "__main__":
    main()


from django import template
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.html import format_html_join

from ..models import Tag

register = template.Library()

@register.simple_tag(takes_context=True)
def tagcloud(context, owner=None):
    url = reverse("social_bookmark_list")
    filters = {"bookmark__is_public": True}

    if owner is not None:
        url = reverse("social_bookmark_user", kwargs={"username": owner.username})
        filters["bookmark__owner"] = owner
    if context["user"] == owner:
        del filters["bookmark__is_public"]

    tags = Tag.objects.filter(**filters)
    tags = tags.annotate(count=models.Count("bookmark"))
    tags = tags.order_by("name").values_list("name", "count")
    fmt = '{0} ({1})' % url
    return format_html_join(", ", fmt, tags)


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

class Solution(object):
    def reverseKGroupV2(self, head, k):
        before = last_last = ListNode(0)
        before.next = left = right = head
        while True:
            count = 0
            while right is not None and count < k:
                count += 1
                right = right.next
            if count == k:
                prev, now = left, right
                for _ in range(k):
                    nex = prev.next
                    prev.next = now
                    now = prev
                    prev = nex
                last_last.next = now
                last_last = left
                left = right
            else:
                return before.next

    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or k == 1:
            return head
        new_head = head
        if self.isEnough(new_head, k):
            now_head, now_last, next_head = self.reverseK(head, k)
            new_head = now_head
            now_last.next = next_head
            last_last = now_last
            while self.isEnough(last_last.next, k):
                now_head, now_last, next_head = self.reverseK(next_head, k)
                last_last.next = now_head
                now_last.next = next_head
                last_last = now_last
        return new_head

    def isEnough(self, now_head, k):
        tmp = now_head
        for i in range(k):
            if not tmp:
                return False
            tmp = tmp.next
        return True

    def reverseK(self, head, k):
        now = head.next
        prev = head
        nex = now.next
        count = 0
        while count < k - 1:
            now.next = prev
            prev = now
            now = nex
            nex = now.next if now else None
            count += 1
        return prev, head, now

if __name__ == '__main__':
    now = head = ListNode(1)
    for i in range(2, 6):
        now.next = ListNode(i)
        now = now.next

    solu = Solution()
    head = solu.reverseKGroupV2(head, 2)
    while head is not None:
        print(head.val)
        head = head.next

src/problems/25. Reverse Nodes in k-Group.py


# Read text from a file, and count the occurence of words in that text
# Example:
# count_words("The cake is done. It is a big cake!")
# --> {"cake":2, "big":1, "is":2, "the":1, "a":1, "it":1}

def read_file_content(filename):
    # [assignment] Add your code here
    # opening the file and closing it at once after reading.
    with open(filename) as file:
        # reading the file and storing in contents
        contents = file.read()
        # printing the contents of the file
        print(contents)

def count_words():
    count = 0
    text = read_file_content("./story.txt")
    # [assignment] Add your code here
    read_text = text.read()
    woord = set(read_text.split())
    for word in woord:
        count ++ 1
    return {"as": 10, "would": 20}

read_file_content('story.txt')
count_words()


# author:Boyle time:2020/11/15
import requests
import json
from pprint import pprint

host = "http://localhost:8000"

path = "/minimalCover/inputList"
req_url = host + path
data = json.dumps({
    "F": [{
        "V": ["A"],
        "W": ["B"]
    },{
        "V": ["A"],
        "W": ["C"]
    },{
        "V": ["B"],
        "W": ["A"]
    },{
        "V": ["B"],
        "W": ["C"]
    },{
        "V": ["C"],
        "W": ["A"]
    }]
})
ret = requests.post(req_url, data=data)
pprint(json.loads(ret.content))


from __future__ import annotations

import os
import sys
import argparse

def main():
    parser = argparse.ArgumentParser(
        description="Add copyright text to the front of source files")
    parser.add_argument("--src", metavar="<path>",
                        help="Source directory.", type=str, required=True)
    parser.add_argument("--copyright", metavar="<path>",
                        help="Copyright file.", type=str, required=True)
    parser.add_argument(
        "--verbose", help="Show progress.", action="store_true")
    args = parser.parse_args()

    src_dir: str = args.src
    if not os.path.isabs(src_dir):
        src_dir = os.path.abspath(src_dir)

    copyright_file: str = args.copyright

    if not os.path.isdir(src_dir):
        print("Source directory doesn't exist.")
        sys.exit(-1)

    if not os.path.isfile(copyright_file):
        print("Copyright file doesn't exist.")
        sys.exit(-1)

    # Collect files
    source_files: list[str] = []
    for root, _, files in os.walk(src_dir):
        for file in files:
            if file.endswith((".h", ".hpp", ".cpp", ".cc")):
                source_files.append(os.path.join(root, file))

    with open(copyright_file, "r", encoding="utf-8-sig") as f:
        copyright_lines = f.readlines()

    copyright_comments = [
        "/****************************************************************************\n"]
    copyright_comments.append(" *\n")
    for line in copyright_lines:
        if not line.endswith("\n"):
            line += "\n"
        copyright_comments.append(f" * {line}")
    copyright_comments.append(" *\n")
    copyright_comments.append(
        " ****************************************************************************/\n")

    count = 0
    total = len(source_files)
    for file in source_files:
        count += 1
        if args.verbose:
            print(f"[{count}/{total}] Process {file}")

        with open(file, "r", encoding="utf-8-sig") as f:
            lines = f.readlines()

        # Find header guard and prepend the comment in front
        header_guard_found: bool = False
        is_comment: bool = False
        while len(lines) > 0:
            line = lines[0].lstrip().rstrip()

            # End of comment
            if "*/" in line and is_comment:
                is_comment = False
                del (lines[0])
                continue

            # Empty or comment
            if line == "" or is_comment:
                del (lines[0])
                continue

            if line.startswith("/*") and not is_comment:
                is_comment = True
                del (lines[0])
                continue

            if line.startswith("//"):
                del (lines[0])
                continue

            # Header guard
            if line.startswith("#ifndef") or line.startswith("#pragma"):
                header_guard_found = True

            break

        if not header_guard_found:
            continue

        with open(file, "w", encoding="utf-8") as f:
            f.writelines(copyright_comments)
            f.write("\n")
            f.writelines(lines)

if __name__ == "__main__":
    main()


import cyaron, os, string

os.system('g++ -o std -O2 ./std.cpp')

for i in range(10):

    io = cyaron.IO(file_prefix = 'rtl', data_id = i + 1)

    n = cyaron.randint(2500, 3000)
    m = cyaron.randint(1, 26)
    charset = string.ascii_lowercase[:m]
    s = cyaron.String.random(n, charset = charset)

    io.input_writeln(s)

    for j in range(m):
        io.input_writeln(charset[j], cyaron.randint(1, 100000), cyaron.randint(1, 100000))

    io.output_gen('./std')
    print('data{} generated'.format(i + 1))