from __future__ import division
from math import atan2
import numpy as np

# Point helper methods
def is_in_bbox(point, bottom_left, upper_right):
    return (
        bottom_left[0] <= point[0]
        and upper_right[0] >= point[0]
        and bottom_left[1] <= point[1]
        and upper_right[1] >= point[1]
    )

# LineString helper methods
def ray_line_intersection(ray_origin, ray_direction, line):
    ray_array = np.array(ray_origin)
    p1_array = np.array(line[0])
    p2_array = np.array(line[1])
    v1 = ray_array - p1_array
    v2 = p2_array - p1_array
    v3 = np.array([-ray_direction[1], ray_direction[0]])

    dot = np.dot(v2, v3)

    if abs(dot) < 1e-5:
        return -1.0
    t1 = np.cross(v2, v1) / dot
    t2 = np.dot(v1, v3) / dot
    if t1 >= 0.0 and (t2 >= 0.0 and t2 <= 1.0):
        return t1

    return -1.0

def clip_segment_bbox(linestring, bottom_left, upper_right):
    new_line = []

    if len(linestring) == 2:
        t = np.array(linestring[1]) - np.array(linestring[0])
        direction = t / np.linalg.norm(t)

        origin_in = is_in_bbox(linestring[0], bottom_left, upper_right)
        destination_in = is_in_bbox(linestring[1], bottom_left, upper_right)

        if not origin_in and not destination_in:
            return new_line

        if origin_in:
            new_line.append(linestring[0])

        if origin_in and destination_in:
            new_line.append(linestring[1])
            return new_line

        else:
            t_intersections = []

            # bottom border
            border = [bottom_left, [upper_right[0], bottom_left[1]]]
            t = ray_line_intersection(linestring[0], direction, border)
            if t > -1.0:
                t_intersections.append(t)

            # left border
            border = [bottom_left, [bottom_left[0], upper_right[1]]]
            t = ray_line_intersection(linestring[0], direction, border)
            if t > -1.0:
                t_intersections.append(t)

            # right border
            border = [[upper_right[0], bottom_left[1]], upper_right]
            t = ray_line_intersection(linestring[0], direction, border)
            if t > -1.0:
                t_intersections.append(t)
            # upper border
            border = [[bottom_left[0], upper_right[1]], upper_right]
            t = ray_line_intersection(linestring[0], direction, border)
            if t > -1.0:
                t_intersections.append(t)

            t_sorted = np.sort(np.array(t_intersections))

            origin = np.array(linestring[0])
            destination = np.array(linestring[1])
            t_destination = (destination[0] - origin[0]) / direction[0]

            for intersection in t_sorted:
                if intersection < t_destination:
                    new_point = origin + direction * intersection
                    new_line.append(new_point.tolist())

            if destination_in:
                new_line.append(linestring[1])

    return new_line

def segment_segment_intersection(segment1, segment2):
    origin = np.array(segment1[0])
    destination = np.array(segment1[1])
    t = destination - origin
    direction = t / np.linalg.norm(t)

    t_intersection = ray_line_intersection(origin, direction, segment2)
    dir_factor = 1 if np.allclose(direction[0], 0) else 0
    t_destination = (destination[dir_factor] - origin[dir_factor]) / direction[
        dir_factor
    ]

    if t_intersection < t_destination and t_intersection > 0:
        return [origin + direction * t_intersection]

    return []

def triangle_area2(point_1, point_2, point_3):
    return (
        point_1[0] * point_2[1]
        - point_1[1] * point_2[0]
        + point_2[0] * point_3[1]
        - point_2[1] * point_3[0]
        + point_3[0] * point_1[1]
        - point_3[1] * point_1[0]
    )

def left(point_1, point_2, point_3):
    return triangle_area2(point_1, point_2, point_3) > 0

# Polygon helper methods

def order_clockwise(polygon, direction):

    center_x = 0
    center_y = 0

    for p in polygon:
        center_x += p[0]
        center_y += p[1]

    if len(polygon) > 0:
        center_x /= len(polygon)
        center_y /= len(polygon)

        polygon.sort(
            key=lambda x: atan2(x[1] - center_y, x[0] - center_x), reverse=direction
        )

    return polygon

def point_in_convex_polygon(point, polygon):
    for i in range(len(polygon) - 1):
        if left(point, polygon[i], polygon[i + 1]):
            return False

    return True

def polygon_polygon_intersection(poly1, poly2):
    clipped_polygon = []
    poly1 = order_clockwise(poly1[:-1], True)
    poly2 = order_clockwise(poly2[:-1], True)
    poly1.append(poly1[0])
    poly2.append(poly2[0])

    # Take points of poly1 inside poly2
    for p in poly1[:-1]:
        if point_in_convex_polygon(p, poly2):
            clipped_polygon.append(p)

    # Take points of poly1 inside poly2
    for p in poly2[:-1]:
        if point_in_convex_polygon(p, poly1):
            clipped_polygon.append(p)

    # Detect collisions
    for i in range(len(poly1) - 1):
        line1 = [poly1[i], poly1[i + 1]]
        for j in range(len(poly2) - 1):
            line2 = [poly2[j], poly2[j + 1]]
            point = segment_segment_intersection(line1, line2)
            if len(point) > 0:
                point_list = point[0].tolist()
                clipped_polygon.append(point_list)

    if len(clipped_polygon) > 0:
        clipped_polygon = order_clockwise(clipped_polygon, False)
        clipped_polygon.append(clipped_polygon[0])

    return clipped_polygon


#!/usr/bin/env python

import rospy
import os
from astar import AStarAlgorithm
import math
import numpy as np
import heapq
from PIL import Image
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
from nav_msgs.msg import Odometry

class PathFollowing:
    def __init__(self, start_pos, goal_pos):
        self.max_speed = rospy.get_param("~max_speed", 1)
        self.max_steering = rospy.get_param("~max_steering", 0.37)
        self.cmd_vel_pub = rospy.Publisher("cmd_vel", Twist, queue_size=1)
        # self.scan_sub = rospy.Subscriber('scan', LaserScan, self.scan_callback, queue_size=1)
        # self.odom_sub = rospy.Subscriber('odom', Odometry, self.odom_callback, queue_size=1)
        self.start_pos = start_pos
        self.goal_pos = goal_pos

        astar_instance = AStarAlgorithm(
            "/home/chris/catkin_ws/src/RacecarS5/racecar_behaviors/scripts/brushfire.bmp"
        )
        path, cost = astar_instance.astar(
            start_pos,
            goal_pos,
            astar_instance.m_cost,
            astar_instance.m_n,
            astar_instance.m_h,
        )

        print(
            "Le plus court chemin entre %s et %s est : %s (%d)"
            % (start_pos, goal_pos, path, cost)
        )

def main():
    rospy.init_node("path_following")
    pathFollowing = PathFollowing((315, 167), (59, 135))
    rospy.spin()

if __name__ == "__main__":
    try:
        main()
    except rospy.ROSInterruptException:
        pass


class DatabaseConnection:

    _instance = None
    _data = None

    @classmethod
    def instance(cls):
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    def setAssignmentGrade(cls, student: str, course: str, assignment: str):
        #Estamos simulando uma entrada de dados que será salva no Banco
        cls._data = "Aluno:" + student + " , Curso: " + course + " , Grade: " + assignment

    def getAssignmentGrade(cls):
        return cls._data

if __name__ == "__main__":

    databaseObjectA = DatabaseConnection.instance()
    databaseObjectB = DatabaseConnection.instance()

    databaseObjectA.setAssignmentGrade("John", "MBA", "Grade A")

    if (databaseObjectA.getAssignmentGrade().__eq__(databaseObjectB.getAssignmentGrade())):
        print("true")


import os
import pickle
import argparse
import pandas as pd

from vocab import WordVocab

from utils import split_camel

def parse_args():

    parser = argparse.ArgumentParser("Path Vocab Generation!!")

    # 数据的路径
    parser.add_argument('--data_path', type=str, default='/.../APathCS/path_data/',help="data location")
    # 数据的类型
    parser.add_argument('--data_name', type=str, default='example', help="dataset name")
    # 语言的类型
    parser.add_argument('--lang_type', type=str, default='java', help="different code type")
    # 词典的大小
    parser.add_argument("--vocab_size", default=None, type=int)
    # 最小频率
    parser.add_argument("--min_freq", default=1, type=int)

    return parser.parse_args()

def main():
    # 参数配置
    args = parse_args()

    # /path_data/exmaple/java/
    lang_path = os.path.join(args.data_path, args.data_name, args.lang_type)

    # /data/hugang/DeveCode/PSCS/data/exmaple/java/code_path/test/java
    input_path = os.path.join(lang_path,os.path.join('code_path','train',args.lang_type))
    # /data/hugang/DeveCode/PSCS/data/exmaple/java/processed
    out_path = os.path.join(lang_path, 'processed')

    # 根据词典将token转为数字，
    f = open(os.path.join(out_path,'descr_vocab.pickle'), 'rb')
    descrs_vocab = pickle.load(f)
    print(descrs_vocab)
    f.close()

    def protoken_func(x):
        #  字符串切成列表
        split_list = split_camel(x)
        #  列表转成数字
        num_list = descrs_vocab.to_seq(split_list)
        #  拼接数字串
        return ' '.join([str(i) for i in num_list])

    '''
    id	token
    14	empty
    78	concatMapEagerDelayError
    70	offer
    23	CheckReturnValue
    '''

    #  对代码的tokens做分词处理
    tokens_paths = [os.path.join(lang_path,os.path.join('code_path', i, args.lang_type, 'tokens.csv')) for i in ['train','test']]

    for tokens_path in tokens_paths:
        # 读取csv数据
        tokens = pd.read_csv(tokens_path)
        tokens['token_cut'] = tokens['token'].apply(protoken_func)
        tokens['token_cut'] = tokens['token_cut'].astype(str)
        tokens.to_csv(tokens_path, index=False)

    #node_types 包含 path_contexts和path指定的词
    node_path = os.path.join(input_path, 'node_types.csv')
    nodes_vocab = pd.read_csv(node_path)
    nodes_vocab['node_type'] = nodes_vocab.apply(lambda x: '_'.join(x['node_type'].split()), axis=1)

    '''
               id                          node_type
           0   43             ExpressionStatement_UP
           1    3       SingleVariableDeclaration_UP
    '''

    node_idx = nodes_vocab.set_index('id').to_dict(orient='dict')
    node_dict = node_idx['node_type']

    '''
    {'node_type': {43: 'ExpressionStatement_UP',... 3: 'SingleVariableDeclaration_UP'}
    '''

    paths_path = os.path.join(input_path, 'paths.csv')
    paths = pd.read_csv(paths_path)
    #path为数字转字符，先构建字典在映射
    paths['path_tokens'] = paths.apply(lambda x: ' '.join([node_dict.get(int(i), '<unk>') for i in x['path'].split(' ')]), axis=1)

    '''
        id         path                                path_tokens
    0    308       1 2 0 0 7 5           SimpleName_UP SimpleType_UP <unk> <unk> Method...
    1    309       1 6 39 40 7 5         SimpleName_UP MethodInvocation_UP ClassInstanc...
    '''
    path_words= paths['path_tokens'].values.tolist()

    vocab = WordVocab(path_words, max_size=args.vocab_size, min_freq=args.min_freq)
    print("VOCAB SIZE:", len(vocab))

    vocab.save_vocab(os.path.join(out_path, 'path_vocab.pickle'))

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-

__title__ = "Маркировать"
__author__ = 'Tima Kutsko'
__doc__ = "Маркировка пространств или помещений"

import sys
import Autodesk
from Autodesk.Revit.DB import *
from rpw import revit, db, ui
from rpw.ui.forms import Console
from pyrevit import script

spaceList, roomList, tagList = [], [], []
doc = revit.doc

# Functions
def GetUVPoint(pt):
    if pt.GetType().ToString() == 'Autodesk.Revit.DB.XYZ':
        return Autodesk.Revit.DB.UV(pt.X, pt.Y)
    elif pt.GetType().ToString() == 'Autodesk.Revit.DB.UV':
        return Autodesk.Revit.DB.UV(pt.U, pt.V)

def CreateSpaceTag(space, uv, view):
    return doc.Create.NewSpaceTag(space, uv, view)

def CreateRoomTag(space, uv, view):
    return doc.Create.NewRoomTag(roomId, uv, view)

# Tag types
types = FilteredElementCollector(doc).OfClass(FamilySymbol)
typeTags = [t for t in types if t.ToString() == 'Autodesk.Revit.DB.Mechanical.SpaceTagType' or t.ToString() == 'Autodesk.Revit.DB.Architecture.RoomTagType']
tagTypeDict = {t.get_Parameter(BuiltInParameter.SYMBOL_FAMILY_AND_TYPE_NAMES_PARAM).AsString(): t for t in typeTags}
# Linked model
linkModels = FilteredElementCollector(doc).OfClass(Autodesk.Revit.DB.RevitLinkInstance)
linkDict = {l.Name: l for l in linkModels}
if len(typeTags) == 0 or linkModels.FirstElement() is None:
    print("В проекте не хватает данных для обработки:\n"
        "1. Нет пространств/помещений;\n"
        "2. Нет подгруженных марок для пространств/помещений (хотя бы одного типа);\n"
        "3. Нет подгруженных моделей (связей)\n"
        "Все вышеперечисленные пункты содержат типовые проекты. Вы либо работаете с маленьким объектом, либо слишком рано пытаетесь запустить программу\n"
        "Для небольших объектов достаточно стандартных инструментов Revit"
    )
    script.exit()

# Selected planes
selection = ui.Selection()
views = [v.unwrap() for v in selection]
for view in views:
    try:
        view_type = view.ViewType
    except:
        view_type = None
    if view_type != ViewType.FloorPlan:
        ui.forms.Alert('Нужно выбирать только планы!', title='pyKPLN_Маркировка пространств/помещений', exit=True)
# Form
ComboBox = ui.forms.flexform.ComboBox
Label = ui.forms.flexform.Label
Button = ui.forms.flexform.Button
CheckBox = ui.forms.flexform.CheckBox
TextBox = ui.forms.flexform.TextBox
Separator = ui.forms.flexform.Separator
if len(selection) == 0:
    ui.forms.Alert('Выбери (выдели через shift/ctrl) в модели план(-ы) для маркировки', title='pyKPLN_Маркировка пространств/помещений', exit=True)
else:
    components = [Label("Узел ввода данных"),
            Label("1. Пространства или помещения:"),
            CheckBox('isRoom', 'Помещения', default = True),
            CheckBox('isSpace', 'Пространства'),
            Label("2. Тип марки для выбранной категории:"),
            ComboBox("tagType", tagTypeDict),
            Label("3. Связанная модель (ТОЛЬКО для помещений)?"),
            CheckBox('isLink', 'Да, модель из связанного файла', default = True),
            Separator(),
            Button("Запуск")]
    form = ui.forms.FlexForm("Маркировка помещений или пространств", components)
    form.ShowDialog()
    isSpace = form.values["isSpace"]
    isRoom = form.values["isRoom"]
    tagType = form.values["tagType"]
    isLink = form.values["isLink"]
    if isLink:
        components = [Label("Узел ввода данных"),
            Label("Выбери модель из списка (если файл связанный):"),
            ComboBox("link", linkDict),
            Separator(),
            Button("Запуск")]
        form = ui.forms.FlexForm("Маркировка помещений или пространств", components)
        form.ShowDialog()
        link = form.values["link"]

#Main code
try:
	#main part of code
	with db.Transaction('pyKPLN_Маркировка пространств/помещений'):
		#Spaces
		if isSpace and isRoom:
			print('Выбери только одну(!) категорию')
		elif isSpace and tagType.ToString() == 'Autodesk.Revit.DB.Mechanical.SpaceTagType':
			for view in views:
				spaces = FilteredElementCollector(doc, view.Id).OfCategory(BuiltInCategory.OST_MEPSpaces).WhereElementIsNotElementType().ToElements()
				for space in spaces:
					try:
						point = space.Location.Point
						if point:
							uv = GetUVPoint(point)
							spaceTag = CreateSpaceTag(space, uv, view)
							spaceTag.SpaceTagType = tagType
					except:
						print("Элемент с Id: {} не размещен".format(space.Id))
		#Rooms
		elif isRoom and tagType.ToString() == 'Autodesk.Revit.DB.Architecture.RoomTagType':
			if isLink:
				linkDoc = link.GetLinkDocument()
				linkId = link.Id
				transformCoord = link.GetTransform()
			else:
				linkDoc = doc
			rooms = FilteredElementCollector(linkDoc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().ToElements()
			for room in rooms:
				try:
					loc = room.Location
					if loc:
						point = loc.Point
						if isLink:
							transformPoint = Autodesk.Revit.DB.Transform.OfPoint(transformCoord, point)
						else:
							transformPoint = point
						uv = GetUVPoint(transformPoint)
						for view in views:
							if isLink:
								roomId = LinkElementId(linkId, room.Id)
							else:
								roomId = LinkElementId(room.Id)
							roomTag = CreateRoomTag(roomId, uv, view.Id)
							roomTag.RoomTagType = tagType
				except:
					print("Элемент с Id: {} не размещен".format(room.Id))
		else:
			print('Не совпадает тип марки и выбранная категория')
except:
	pass


def platecalculator(weight, bar = 45,plates = [45,35,25,10,5,2.5]):
    net_weight = (weight-bar)/2.0
    required = {}
    for index, plate in enumerate(plates):
        required[plate] = net_weight//plate
        net_weight = net_weight-(plate*required[plate])

    return required


def employee(name):
    def name_and_salary(salary):
        nonlocal name
        print(f"my name is: {name}, my salary is {salary}")
        name = "Unknown"

    name_and_salary(100000)
    print(f"my name is {name}")

name = "John"
employee(name)
print(f"Global name: {name}")


import os
import sys
from fractions import Fraction
from os import remove, devnull as os_devnull, system
from random import randint
from subprocess import check_call

import numpy as np
import psutil
from numpy.linalg import svd
from sympy import Matrix

from ecmtool.mpi_wrapper import get_process_rank

def unique(matrix):
    unique_set = list({tuple(row) for row in matrix if np.count_nonzero(row) > 0})
    return np.vstack(unique_set) if len(unique_set) else to_fractions(np.ndarray(shape=(0, matrix.shape[1])))

def find_unique_inds(matrix, verbose=False, tol=1e-9):
    n_rays = matrix.shape[0]
    n_nonunique = 0
    original_inds_remaining = np.arange(n_rays)
    unique_inds = []
    counter = 0
    while matrix.shape[0] > 0:
        row = matrix[0, :]
        unique_inds.append(original_inds_remaining[0])
        if verbose:
            if counter % 100 == 0:
                mp_print("Find unique rows has tested %d of %d (%f %%). Removed %d non-unique rows." %
                         (counter, n_rays, counter / n_rays * 100, n_nonunique))
        counter = counter + 1
        equal_rows = np.where(np.max(np.abs(matrix - row), axis=1) < tol)[0]
        if len(equal_rows):
            n_nonunique = n_nonunique + len(equal_rows) - 1
            matrix = np.delete(matrix, equal_rows, axis=0)
            original_inds_remaining = np.delete(original_inds_remaining, equal_rows)
        else:  # Something is wrong, at least the row itself should be equal to itself
            mp_print('Something is wrong in the unique_inds function!!')

    return unique_inds

def relative_path(file_path):
    return os.path.join(os.path.dirname(__file__), file_path)

def open_relative(file_path, mode='r'):
    return open(relative_path(file_path), mode)

def remove_relative(file_path):
    return remove(relative_path(file_path))

def get_total_memory_gb():
    """
    Returns total system memory in GiB (gibibytes)
    :return:
    """
    return psutil.virtual_memory().total / 1024 ** 3

def get_min_max_java_memory():
    """
    Returns plausible starting and maximum virtual memory sizes in gibibytes
    for a java VM, as used to run e.g. Polco. Min is either 10% of system RAM
    or 1 gigabyte, whichever is larger. Max is 80% of system RAM.
    :return:
    """
    total = get_total_memory_gb()
    min = int(np.ceil(float(total) * 0.1))
    max = int(np.round(float(total) * 0.8))
    return min, max

def nullspace(N, symbolic=True, atol=1e-13, rtol=0):
    """
    Calculates the null space of given matrix N.
    Source: https://scipy-cookbook.readthedocs.io/items/RankNullspace.html
    :param N: ndarray
            A should be at most 2-D.  A 1-D array with length k will be treated
            as a 2-D with shape (1, k)
    :param symbolic: set to False to compute nullspace numerically instead of symbolically
    :param atol: float
            The absolute tolerance for a zero singular value.  Singular values
            smaller than `atol` are considered to be zero.
    :param rtol: float
            The relative tolerance.  Singular values less than rtol*smax are
            considered to be zero, where smax is the largest singular value.
    :return: If `A` is an array with shape (m, k), then `ns` will be an array
            with shape (k, n), where n is the estimated dimension of the
            nullspace of `A`.  The columns of `ns` are a basis for the
            nullspace; each element in numpy.dot(A, ns) will be approximately
            nullspace; each element in numpy.dot(A, ns) will be approximately
            zero.
    """
    if not symbolic:
        N = np.asarray(N, dtype='int64')
        u, s, vh = svd(N)
        tol = max(atol, rtol * s[0])
        nnz = (s >= tol).sum()
        ns = vh[nnz:].conj()
        return np.transpose(ns)
    else:
        nullspace_vectors = Matrix(N).nullspace()

        # Add nullspace vectors to a nullspace matrix as row vectors
        # Must be a sympy Matrix so we can do rref()
        nullspace_matrix = nullspace_vectors[0].T if len(nullspace_vectors) else None
        for i in range(1, len(nullspace_vectors)):
            nullspace_matrix = nullspace_matrix.row_insert(-1, nullspace_vectors[i].T)

        return to_fractions(
            np.transpose(np.asarray(nullspace_matrix.rref()[0], dtype='object'))) if nullspace_matrix \
            else np.ndarray(shape=(N.shape[0], 0))

def get_extreme_rays(equality_matrix=None, inequality_matrix=None, symbolic=True, verbose=False):
    rand = randint(1, 10 ** 6)

    if inequality_matrix is not None and inequality_matrix.shape[0] == 0:
        inequality_matrix = None

    if equality_matrix is not None and equality_matrix.shape[0] == 0:
        equality_matrix = None

    if inequality_matrix is None:
        if equality_matrix is not None:
            # inequality_matrix = np.identity(equality_matrix.shape[1])
            inequality_matrix = np.zeros(shape=(1, equality_matrix.shape[1]))
        else:
            raise Exception('No equality or inequality argument given')

    # if inequality_matrix.shape[1] < 50:
    #     if verbose:
    #         print('Using CDD instead of Polco for enumeration of small system')
    #     ineq = np.append(np.append(equality_matrix, -equality_matrix, axis=0), inequality_matrix, axis=0)
    #     for ray in get_extreme_rays_cdd(ineq):
    #         yield ray
    #     return

    # Write equalities system to disk as space separated file
    if verbose:
        print('Writing equalities to file')
    if equality_matrix is not None:
        with open_relative('tmp' + os.sep + 'eq_%d.txt' % rand, 'w') as file:
            for row in range(equality_matrix.shape[0]):
                file.write(' '.join([str(val) for val in equality_matrix[row, :]]) + '\n')

    # Write inequalities system to disk as space separated file
    if verbose:
        print('Writing inequalities to file')
    with open_relative('tmp' + os.sep + 'iq_%d.txt' % rand, 'w') as file:
        for row in range(inequality_matrix.shape[0]):
            file.write(' '.join([str(val) for val in inequality_matrix[row, :]]) + '\n')

    # Run external extreme ray enumeration tool
    min_mem, max_mem = get_min_max_java_memory()
    if verbose:
        print('Running polco (%d-%d GiB java VM memory)' % (min_mem, max_mem))

    equality_path = relative_path('tmp' + os.sep + 'eq_%d.txt' % rand)
    inequality_path = relative_path('tmp' + os.sep + 'iq_%d.txt' % rand)
    generators_path = relative_path('tmp' + os.sep + 'generators_%d.txt' % rand)
    with open(os_devnull, 'w') as devnull:
        polco_path = relative_path('polco' + os.sep + 'polco.jar')
        check_call(('java -Xms%dg -Xmx%dg ' % (min_mem, max_mem) +
                    '-jar %s -kind text -sortinput AbsLexMin ' % polco_path +
                    '-arithmetic %s ' % (' '.join(['fractional' if symbolic else 'double'] * 3)) +
                    '-zero %s ' % (' '.join(['NaN' if symbolic else '1e-10'] * 3)) +
                    ('' if equality_matrix is None else '-eq %s ' % equality_path) +
                    ('' if inequality_matrix is None else '-iq %s ' % inequality_path) +
                    '-out text %s' % generators_path).split(' '),
                   stdout=(devnull if not verbose else None), stderr=(devnull if not verbose else None))

    # Read resulting extreme rays
    if verbose:
        print('Parsing computed rays')
    with open(generators_path, 'r') as file:
        lines = file.readlines()
        rays = np.ndarray(shape=(0, inequality_matrix.shape[1]))

        if len(lines) > 0:
            number_lines = len(lines)
            number_entries = len(lines[0].replace('\n', '').split('\t'))
            rays = np.repeat(np.repeat(to_fractions(np.zeros(shape=(1, 1))), number_entries, axis=1), number_lines,
                             axis=0)

            for row, line in enumerate(lines):
                # print('line %d/%d' % (row+1, number_lines))
                for column, value in enumerate(line.replace('\n', '').split('\t')):
                    if value != '0':
                        rays[row, column] = Fraction(str(value))

    if verbose:
        print('Done parsing rays')

    # Clean up the files created above
    if equality_matrix is not None:
        remove(equality_path)

    remove(inequality_path)
    remove(generators_path)

    return rays

def binary_exists(binary_file):
    return any(
        os.access(os.path.join(path, binary_file), os.X_OK)
        for path in os.environ["PATH"].split(os.pathsep)
    )

def get_redund_binary():
    if sys.platform.startswith('linux'):
        if not binary_exists('redund'):
            raise EnvironmentError(
                'Executable "redund" was not found in your path. Please install package lrslib (e.g. apt install lrslib)')
        return 'redund'
    elif sys.platform.startswith('win32'):
        return relative_path('redund\\redund_win.exe')
    elif sys.platform.startswith('darwin'):
        return relative_path('redund/redund_mac')
    else:
        raise OSError('Unsupported operating system platform: %s' % sys.platform)

def redund(matrix, verbose=False):
    rank = str(get_process_rank())
    matrix = to_fractions(matrix)
    binary = get_redund_binary()
    matrix_path = relative_path('tmp' + os.sep + 'matrix' + rank + '.ine')
    matrix_nonredundant_path = relative_path('tmp' + os.sep + 'matrix_nored' + rank + '.ine')

    if matrix.shape[0] <= 1:
        return matrix

    with open(matrix_path, 'w') as file:
        file.write('V-representation\n')
        file.write('begin\n')
        file.write('%d %d rational\n' % (matrix.shape[0], matrix.shape[1] + 1))
        for row in range(matrix.shape[0]):
            file.write(' 0')
            for col in range(matrix.shape[1]):
                file.write(' %s' % str(matrix[row, col]))
            file.write('\n')
        file.write('end\n')

    system('%s %s > %s' % (binary, matrix_path, matrix_nonredundant_path))

    matrix_nored = np.ndarray(shape=(0, matrix.shape[1] + 1), dtype='object')

    with open(matrix_nonredundant_path) as file:
        lines = file.readlines()
        for line in [line for line in lines if line not in ['\n', '']]:
            # Skip comment and INE format lines
            if np.any([target in line for target in ['*', 'V-representation', 'begin', 'end', 'rational']]):
                continue
            row = [Fraction(x) for x in line.replace('\n', '').split(' ') if x != '']
            matrix_nored = np.append(matrix_nored, [row], axis=0)

    remove(matrix_path)
    remove(matrix_nonredundant_path)

    if verbose:
        print('Removed %d redundant rows' % (matrix.shape[0] - matrix_nored.shape[0]))

    return matrix_nored[:, 1:]

def to_fractions(matrix, quasi_zero_correction=False, quasi_zero_tolerance=1e-13):
    if quasi_zero_correction:
        # Make almost zero values equal to zero
        matrix[(matrix < quasi_zero_tolerance) & (matrix > -quasi_zero_tolerance)] = Fraction(0, 1)

    fraction_matrix = matrix.astype('object')

    for row in range(matrix.shape[0]):
        for col in range(matrix.shape[1]):
            # str() here makes Sympy use true fractions instead of the double-precision
            # floating point approximation
            fraction_matrix[row, col] = Fraction(str(matrix[row, col]))

    return fraction_matrix

def get_metabolite_adjacency(N):
    """
    Returns m by m adjacency matrix of metabolites, given
    stoichiometry matrix N. Diagonal is 0, not 1.
    :param N: stoichiometry matrix
    :return: m by m adjacency matrix
    """

    number_metabolites = N.shape[0]
    adjacency = np.zeros(shape=(number_metabolites, number_metabolites))

    for metabolite_index in range(number_metabolites):
        active_reactions = np.where(N[metabolite_index, :] != 0)[0]
        for reaction_index in active_reactions:
            adjacent_metabolites = np.where(N[:, reaction_index] != 0)[0]
            for adjacent in [i for i in adjacent_metabolites if i != metabolite_index]:
                adjacency[metabolite_index, adjacent] = 1
                adjacency[adjacent, metabolite_index] = 1

    return adjacency

def mp_print(*args, **kwargs):
    """
    Multiprocessing wrapper for print().
    Prints the given arguments, but only on process 0 unless
    named argument PRINT_IF_RANK_NONZERO is set to true.
    :return:
    """
    if get_process_rank() == 0:
        print(*args)
    elif 'PRINT_IF_RANK_NONZERO' in kwargs and kwargs['PRINT_IF_RANK_NONZERO']:
        print(*args)

def unsplit_metabolites(R, network):
    metabolite_ids = [metab.id for metab in network.metabolites]
    res = []
    ids = []

    processed = {}
    for i in range(R.shape[0]):
        metabolite = metabolite_ids[i].replace("_virtin", "").replace("_virtout", "")
        if metabolite in processed:
            row = processed[metabolite]
            res[row] += R[i, :]
        else:
            res.append(R[i, :].tolist())
            processed[metabolite] = len(res) - 1
            ids.append(metabolite)

    # remove all-zero rays
    res = np.asarray(res)
    res = res[:, [sum(abs(res)) != 0][0]]

    return res, ids

def print_ecms_direct(R, metabolite_ids):
    obj_id = -1
    if "objective" in metabolite_ids:
        obj_id = metabolite_ids.index("objective")
    elif "objective_virtout" in metabolite_ids:
        obj_id = metabolite_ids.index("objective_virtout")

    mp_print("\n--%d ECMs found--\n" % R.shape[1])
    for i in range(R.shape[1]):
        mp_print("ECM #%d:" % (i + 1))
        if np.max(R[:,
                  i]) > 1e100:  # If numbers become too large, they can't be printed, therefore we make them smaller first
            ecm = np.array(R[:, i] / np.max(R[:, i]), dtype='float')
        else:
            ecm = np.array(R[:, i], dtype='float')

        div = 1
        if obj_id != -1 and R[obj_id][i] != 0:
            div = ecm[obj_id]
        for j in range(R.shape[0]):
            if ecm[j] != 0:
                mp_print("%s\t\t->\t%.4f" % (metabolite_ids[j].replace("_in", "").replace("_out", ""), ecm[j] / div))
        mp_print("")

def normalize_columns(R, verbose=False):
    result = np.zeros(R.shape)
    number_rays = R.shape[1]
    for i in range(result.shape[1]):
        if verbose:
            if i % 10000 == 0:
                mp_print("Normalize columns is on ray %d of %d (%f %%)" %
                         (i, number_rays, i / number_rays * 100), PRINT_IF_RANK_NONZERO=True)
        largest_number = np.max(np.abs(R[:,i]))
        if largest_number > 1e100:  # If numbers are very large, converting to float might give issues, therefore we first divide by another int
            part_normalized_column = np.array(R[:, i] / largest_number, dtype='float')
            result[:, i] = part_normalized_column / np.linalg.norm(part_normalized_column)
        else:
            norm_column = np.linalg.norm(np.array(R[:, i], dtype='float'), ord=1)
            if norm_column != 0:
                result[:, i] = np.array(R[:, i], dtype='float') / norm_column
    return result

def find_remaining_rows(first_mat, second_mat, tol=1e-12, verbose=False):
    """Checks which rows (indices) of second_mat are still in first_mat"""
    remaining_inds = []
    number_rays = first_mat.shape[0]
    for ind, row in enumerate(first_mat):
        if verbose:
            if ind % 10000 == 0:
                mp_print("Find remaining rows is on row %d of %d (%f %%)" %
                         (ind, number_rays, ind / number_rays * 100))
        sec_ind = np.where(np.max(np.abs(second_mat - row), axis=1) < tol)[0]
        # for sec_ind, sec_row in enumerate(second_mat):
        #    if np.max(np.abs(row - sec_row)) < tol:
        #        remaining_inds.append(ind)
        #        continue
        if len(sec_ind):
            remaining_inds.append(sec_ind[0])
        else:
            mp_print('Warning: There are rows in the first matrix that are not in the second matrix')

    return remaining_inds

def normalize_columns_fraction(R, vectorized=False, verbose=True):
    if not vectorized:
        number_rays = R.shape[1]
        for i in range(number_rays):
            if verbose:
                if i % 10000 == 0:
                    mp_print("Normalize columns is on ray %d of %d (%f %%)" %
                             (i, number_rays, i / number_rays * 100), PRINT_IF_RANK_NONZERO=True)
            norm_column = np.sum(np.abs(np.array(R[:, i])))
            if norm_column!=0:
                R[:, i] = np.array(R[:, i]) / norm_column
    else:
        R = R / np.sum(np.abs(R), axis=0)
    return R


import scona as scn
import pandas as pd
import numpy as np
import os
import sys

def load_atlas_csv() -> pd.DataFrame:
    '''
    Functon to return freesurfer atlas with mni co-ordinates and names

    Parameters
    ----------
    None

    Returns
    -------
    atlas.csv pd.Dataframe
    '''

    try:
       path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'SCN/graphs/data')
       return pd.read_csv(f'{path}/atlas.csv')

    except Exception:

        try:
            path = os.path.join(os.getcwd(), 'SCN/graphs/data')
            return pd.read_csv(f'{path}/atlas.csv')

        except Exception:
            print(f'Unable to find atlas.csv. Looking in {os.getcwd()}')

            try:
                path = os.getcwd()
                return pd.read_csv(f'{path}/atlas.csv')

            except Exception as e:
                print('Unable to load atlas.csv due to:', e)
                print('This commonly happens with venvs or grid systems. Check where SCN is looking for the atlas.csv and put the file there.')
                sys.exit(1)

def load_centroids() -> np.float64:
    '''
    Function to return centroids from freesurfer atlas.

    Parameters
    ----------
    None

    Returns
    -------
    array of np.float64 values representing x, y, z co-ordinates in MNI space
    '''

    atlas_df = load_atlas_csv()
    return atlas_df[['x.mni', 'y.mni', 'z.mni']].to_numpy()

def load_names() -> list:
    '''
    Function to return names from freesurfer atlas.

    Parameters
    ----------
    None

    Returns
    -------
    list str values of name of brain regions
    '''

    atlas_df = load_atlas_csv()
    return list(atlas_df['name'])

def create_graphs(data: pd.DataFrame, names: list, centroids: np.float64, threshold: int) -> dict:
    '''
    Function to create a correlation matrix, graph and thresholded graph.
    Wrapper around multiple scona functions.

    Parameters
    -----------------------------------------------------
    data: pandas dataframe object with the data for graph.
    names: list object. Names of brain regions.
    centroids. Numpy array. Co-ordinates for names (x,y,z)
    threshold: int, optional. Level to threshold the graph at.

    Returns
    -------------------------------------------------------------------
    results: dict object. Dictionary of corr_matrix (correlation matrix),
             graph (graph unthresholded) and graph_threshold (thresholded graph)
    '''

    residuals_df = scn.create_residuals_df(data, names)
    corr_matrix = scn.create_corrmat(residuals_df, method='pearson')
    graph = scn.BrainNetwork(
        network=corr_matrix, parcellation=names, centroids=centroids)
    graph_threshold = graph.threshold(threshold)

    results = {

        'corr_matrix': corr_matrix,
        'graph': graph,
        'graph_threshold': graph_threshold

    }

    return results


from django.urls import path

from . import views

app_name = "hangman"
urlpatterns = [
    path('', views.play, name='play'),
    path('reset/', views.reset, name='reset'),
    path('<str:letter>/', views.shot, name='shot'),
]


import logging
import os
import sys
from argparse import ArgumentParser, FileType

from erdpy import (cli_contracts, config, dependencies, errors, facade, ide,
                   nodedebug, projects, proxy, transactions)

def setup_parser_contract(subparsers):
    parser = subparsers.add_parser("contract")
    subparsers = parser.add_subparsers()

    sub = subparsers.add_parser("new", description="Create a new Smart Contract project based on a template.")
    sub.add_argument("name")
    sub.add_argument("--template", required=True, help="the template to use")
    sub.add_argument("--directory", type=str, default=os.getcwd(), help="the parent directory of the project")
    sub.set_defaults(func=create)

    sub = subparsers.add_parser("templates", description="List the available Smart Contract templates.")
    sub.add_argument("--json", action="store_true", help="whether to print the list in JSON format")
    sub.set_defaults(func=list_templates)

    sub = subparsers.add_parser("build", description="Build a Smart Contract project using the appropriate buildchain.")
    sub.add_argument("project", nargs='?', default=os.getcwd())
    sub.add_argument("--debug", action="store_true", default=False)
    sub.add_argument("--no-optimization", action="store_true", default=False)
    sub.set_defaults(func=build)

    sub = subparsers.add_parser("deploy", description="Deploy a Smart Contract.")
    sub.add_argument("project", nargs='?', default=os.getcwd(), help="the project directory")
    sub.add_argument("--proxy", required=True, help="the URL of the proxy")
    sub.add_argument("--pem", required=True, help="the PEM file of the owner")
    sub.add_argument("--arguments", nargs='+', help="constructor arguments")
    sub.add_argument("--gas-price", default=config.DEFAULT_GAS_PRICE, help="the gas price")
    sub.add_argument("--gas-limit", required=True, help="the gas limit")
    sub.add_argument("--value", default="0", help="the value to transfer")
    sub.add_argument("--metadata-upgradeable", action="store_true", default=False, help="whether the contract is upgradeable")
    sub.add_argument("--outfile", type=FileType("w"), default=sys.stdout, help="where to save the command's output")
    sub.set_defaults(func=deploy)

    sub = subparsers.add_parser("call")
    sub.add_argument("contract")
    sub.add_argument("--proxy", required=True)
    sub.add_argument("--pem", required=True)
    sub.add_argument("--function", required=True)
    sub.add_argument("--arguments", nargs='+')
    sub.add_argument("--gas-price", default=config.DEFAULT_GAS_PRICE)
    sub.add_argument("--gas-limit", required=True)
    sub.add_argument("--value", default="0")
    sub.set_defaults(func=call)

    sub = subparsers.add_parser("upgrade")
    sub.add_argument("contract")
    sub.add_argument("project")
    sub.add_argument("--proxy", required=True)
    sub.add_argument("--pem", required=True)
    sub.add_argument("--arguments", nargs='+')
    sub.add_argument("--gas-price", default=config.DEFAULT_GAS_PRICE)
    sub.add_argument("--gas-limit", required=True)
    sub.add_argument("--value", default="0")
    sub.add_argument("--metadata-upgradeable", action="store_true", default=False)
    sub.set_defaults(func=upgrade)

    sub = subparsers.add_parser("query")
    sub.add_argument("contract")
    sub.add_argument("--proxy", required=True)
    sub.add_argument("--function", required=True)
    sub.add_argument("--arguments", nargs='+')
    sub.set_defaults(func=query)

    # TODO: arwendebug
    # node_parser = subparsers.add_parser("nodedebug")
    # group = node_parser.add_mutually_exclusive_group()
    # group.add_argument('--stop', action='store_true')
    # group.add_argument('--restart', action='store_true', default=True)
    # node_parser.set_defaults(func=do_nodedebug)

    sub = subparsers.add_parser("test")
    sub.add_argument("project", nargs='?', default=os.getcwd())
    sub.add_argument("--directory", default="test")
    sub.add_argument("--wildcard", required=False)
    sub.set_defaults(func=run_tests)

    sub = subparsers.add_parser("ide")
    sub.add_argument("workspace", nargs='?', default=os.getcwd())
    sub.set_defaults(func=run_ide)

def list_templates(args):
    json = args.json
    projects.list_project_templates(json)

def create(args):
    name = args.name
    template = args.template
    directory = args.directory

    projects.create_from_template(name, template, directory)

def build(args):
    project = args.project
    options = {
        "debug": args.debug,
        "optimized": not args.no_optimization,
        "verbose": args.verbose
    }

    projects.build_project(project, options)

def deploy(args):
    facade.deploy_smart_contract(args)

def call(args):
    facade.call_smart_contract(args)

def upgrade(args):
    facade.upgrade_smart_contract(args)

def query(args):
    facade.query_smart_contract(args)

def run_tests(args):
    projects.run_tests(args)

def run_ide(args):
    workspace = args.workspace
    ide.run_ide(workspace)

# def do_nodedebug(args):
#     stop = args.stop
#     restart = args.restart

#     if restart:
#         nodedebug.stop()
#         nodedebug.start()
#     elif stop:
#         nodedebug.stop()
#     else:
#         nodedebug.start()


# 문제 풀이 실패

# 모범 답안
n, m = map(int, input().split())

graph = [list(map(int, input())) for _ in range(n)]

# DFS로 특정 노드를 방문하고 연결된 인접 노드들 방문
def dfs(x, y):
    # 주어진 범위를 벗어나면 즉시 종료
    if x <= -1 or y <= -1 or x >= n or y >= m:
        return False
    # 현재 노드를 아직 방문하지 않았다면
    if graph[x][y] == 0:
        # 해당 노드를 방문 처리
        graph[x][y] = 1
        # 상, 하, 좌, 우를 재귀적으로 호출
        dfs(x - 1, y)
        dfs(x + 1, y)
        dfs(x, y - 1)
        dfs(x, y + 1)
        return True
    return False

# 모든 노드에 대하여 음료수 채우기
result = 0
for i in range(n):
    for j in range(m):
        # 현재 위치에서 DFS 수행
        if dfs(i, j):
            result += 1

print(result)

[이것이 코딩테스트다] 실전 문제/[DFS] 음료수 얼려먹기.py


# -*- coding: utf-8 -*-

from odoo import api, fields, models
from odoo.exceptions import ValidationError
import odoo.addons.decimal_precision as dp

import math

class StockWarehouseOrderpoint(models.Model):
    _inherit = 'stock.warehouse.orderpoint'

    def _default_of_delivery_delay(self):
        of_delivery_delay = 0
        if self.product_id and self.product_id.seller_ids:
            of_delivery_delay = self.product_id.seller_ids[0].delay
        return of_delivery_delay

    of_forecast_qty = fields.Float(string=u"Qté Prév. N", digits=dp.get_precision('Product Unit of Measure'))
    of_pace_of_sale = fields.Float(string=u"Rythme de vente", digits=(16, 2), compute='_compute_of_pace_of_sale')
    of_delivery_delay = fields.Integer(string=u"Délai de livraison", default=_default_of_delivery_delay)
    of_min_theoretical_qty = fields.Float(
        string=u"Qté mini théorique", digits=(16, 2), compute='_compute_of_min_theoretical_qty')
    of_min_stock_coef = fields.Float(string=u"Coef stock min", digits=(16, 2), default=1.0)
    of_max_stock_coef = fields.Float(string=u"Coef stock maxi", digits=(16, 2), default=1.0)

    @api.depends('of_forecast_qty')
    def _compute_of_pace_of_sale(self):
        if self.of_forecast_qty:
            self.of_pace_of_sale = 1 / (self.of_forecast_qty / 365)

    @api.depends('of_delivery_delay', 'of_pace_of_sale')
    def _compute_of_min_theoretical_qty(self):
        if self.of_pace_of_sale:
            self.of_min_theoretical_qty = self.of_delivery_delay / self.of_pace_of_sale

    @api.multi
    def compute_min_max_qty(self):
        """Calcul des quantités mini et maxi des règles de stocks"""

        for orderpoint in self:
            # On ne valorise qty min/max que si la qté min théorique est remplie
            if orderpoint.of_min_theoretical_qty:
                product_min_qty = orderpoint.of_min_theoretical_qty * orderpoint.of_min_stock_coef
                self.product_min_qty = math.ceil(product_min_qty)
                self.product_max_qty = max(math.floor(product_min_qty * orderpoint.of_max_stock_coef),
                                           self.product_min_qty)

    @api.constrains('of_min_stock_coef', 'of_max_stock_coef')
    def constraint_stock_coef(self):
        if not self.of_max_stock_coef or not self.of_min_stock_coef:
            raise ValidationError(u"Un coefficient doit toujours être supérieur à 0")
        if self.of_max_stock_coef < 1.0:
            raise ValidationError(u"Le coef de stock maxi doit toujours être supérieur ou égal a 1")

    @api.onchange('product_id')
    def onchange_product_id(self):
        of_delivery_delay = 0
        if self.product_id and self.product_id.seller_ids:
            of_delivery_delay = self.product_id.seller_ids[0].delay
        self.of_delivery_delay = of_delivery_delay


students = ["Вася", "Маша", "Петя", "Дима", "Марина", "Люба", "Коля", "Ваня"]
grades = {"Вася" : 4, "Петя" : 9, "Марина" : 8, "Люба" : 4, "Коля" : 5, "Ваня": 10}
for i in students:
    if i in grades:
        print(f"{i} оценка: {grades[i]} ")
    else:
        print(f"{i}Контрольную работу не писал(а)")

bad = []
good = []
for i in students:
    if i in grades:
        if grades[i] >= 8:
            good.append(i)
    else:
        bad.append(i)
print(good, bad)

marks = {'Mary': [5, 8, 9, 10, 3, 5, 6, 6],
        'John': [3, 3, 6, 8, 2, 1, 8, 5],
        'Alex': [4, 4, 7, 4, 7, 3, 2, 9],
        'Patricia': [2, 1, 6, 8, 2, 3, 7, 4]}
course = int(input()) - 1
total = 0
for i in marks.values():
        total += i[course]
print(round(total / len(marks)))

marks = {'Mary': [5, 8, 9, 10, 3, 5, 6, 6],
         'John': [3, 3, 6, 8, 2, 1, 8, 5],
         'Alex': [4, 4, 7, 4, 7, 3, 2, 9],
         'Patricia': [2, 1, 6, 8, 2, 3, 7, 4]}
categories = {'отлично': [8, 9, 10],
              'хорошо': [6, 7],
              'удовлетворительно': [4, 5],
              'неуд': [0, 1, 2, 3]}
course = int(input()) - 1
total = 0
for i in marks.values():
        total += i[course]
for k, v in categories.items():
        if round(total / len(marks)) in v:
                print(k)

marks = {'Mary': [5, 8, 9, 10, 3, 5, 6, 6],
         'John': [3, 3, 6, 8, 2, 1, 8, 5],
         'Alex': [4, 4, 7, 4, 7, 3, 2, 9],
         'Patricia': [2, 1, 6, 8, 2, 3, 7, 4]}
mark = int(input())
c = 0
for k, v in marks.items():
        for i in v:
                if i >= mark:
                        c += 1
print(c)


import socket
import numpy as np
import struct
from time import sleep
import csv

localIP     = "192.168.1.2"
localPort   = 20001
bufferSize  = 1024
# Create a datagram socket
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# Bind to address and ip
UDPServerSocket.bind((localIP, localPort))
print("UDP server up and listening")
# Listen for incoming datagrams
bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
message = bytesAddressPair[0]
address = bytesAddressPair[1]
print(address)
while(True):
    f = open('log.txt','a')
    timestamp = str(UDPServerSocket.recvfrom(bufferSize)[0]).replace("'",'').replace('b','').replace('\\n','\r\n')
    values = str(UDPServerSocket.recvfrom(bufferSize)[0]).replace("'",'').replace('b','').replace('\\n','\r\n')
    print(timestamp)
    print(values)
    f.write(timestamp)
    f.write(values)
    sleep(0.7)
    f.close()


import unittest
from polygon import *
import turtle

# Setup the test calss and inherit the mehtods
class TestPolygon(unittest.TestCase):

    def test_sort_points(self):
        self.assertEqual(sort_points([[10,50],[50,10],[30,20]]),
                                        [[50,10],[30,20],[10,50]])
        self.assertEqual(sort_points([[10,50],[30,20],[50,10]]),
                                        [[50,10],[30,20],[10,50]])

    def test_get_angle(self):
        self.assertEqual(get_angle([50,10]), 11.309932474020215)
        # Coordinates in third quadrant
        self.assertEqual(round(get_angle([-158,-80])),297)
        # Angle is bigger than 360
        self.assertEqual(round(get_angle([221,-10])),-3)
        # Angle bigger than 360
        self.assertEqual(round(get_angle([121.66, -260.0])),-65)

    def test_sort_item(self):
        self.assertEqual(sort_item(2,[[20,30],[10,50],[50,10]]),[[50,10],[20,30],[10,50]])

if __name__ == '__main__':
    # Run the whole test
    unittest.main()


from flask.views import MethodView
from flask import request, jsonify, json

from traceback import print_exc

from block_compass.db import get_block_by_timestamp, get_chains

class Blocks(MethodView):
    def get(self):

        try:
            params = request.args.to_dict()
            timestamp = int(params['timestamp'])
            chain_ids = params.get('chain_ids')

            if chain_ids is None:
                chain_ids = [chain['id'] for chain in get_chains()]
            else:
                chain_ids = json.loads(chain_ids)

            blocks = {}
            for chain_id in chain_ids:
                blocks[chain_id] = get_block_by_timestamp(timestamp, chain_id)['number']

            return jsonify(success=True, blocks=blocks), 200

        except Exception as e:
            print_exc()
            return jsonify(success=False, message='Bad Request!'), 400


#
"""Creates vocabulary from a set of data files.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# pylint: disable=invalid-name

import sys

import tensorflow as tf

import texar as tx

Py3 = sys.version_info[0] == 3

flags = tf.flags

flags.DEFINE_string("files", "./",
                    "Path to the data files. Can be a pattern, e.g., "
                    "'/path/to/train*', '/path/to/train[12]'. Wrap the path "
                    "with quotation marks if a pattern is provided.")
flags.DEFINE_integer("max_vocab_size", -1,
                     "Maximum size of the vocabulary. Low frequency words "
                     "that exceeding the limit will be discarded. "
                     "Set to `-1` if no truncation is wanted.")
flags.DEFINE_string("output_path", "./vocab.txt",
                    "Path of the output vocab file.")
flags.DEFINE_string("newline_token", None,
                    "The token to replace the original newline token '\n'. "
                    "For example, `--newline_token '<EOS>'`. If not "
                    "specified, no replacement is performed.")

FLAGS = flags.FLAGS

def main(_):
    """Makes vocab.
    """
    filenames = tx.data.get_files(FLAGS.files)
    vocab = tx.data.make_vocab(filenames,
                               max_vocab_size=FLAGS.max_vocab_size,
                               newline_token=FLAGS.newline_token)

    with open(FLAGS.output_path, "w") as fout:
        fout.write('\n'.join(vocab).encode("utf-8"))

if __name__ == "__main__":
    tf.app.run()


import RPi.GPIO as GPIO
import time

GPIO.cleanup()

sensor = 7

GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor,GPIO.IN)

print ("IR Sensor Ready.....")

try:
    while True:
        if GPIO.input(sensor):
            print ("Object Detected")
            while GPIO.input(sensor):
                time.sleep(0.2)
        else:
            print("x")
            time.sleep(0.2)

except KeyboardInterrupt:
    GPIO.cleanup()


import contextlib, random

import numpy as np
import torch
import torch.nn.functional as F
from torch.nn.utils import parameters_to_vector as p2v

def current_val_interval(cfg, step):
    v_intervals = [(int(k), int(v)) for k, v in cfg["training"]["val_interval"].items()]
    for k, v in sorted(v_intervals, reverse=True):
        if step > k:
            return v

def resize_input(input, target, align_corners=True, mode='bilinear'):
    """Resize input to match last two dimensions of target (generally, spatial dimensions h, w)."""
    h, w = input.shape[-2:]
    ht, wt = target.shape[-2:]

    if h != ht and w != wt:
        return F.interpolate(input, size=(ht, wt), mode=mode, align_corners=align_corners)
    return input

def count(module):
    """Count total number of parameters in nn.Module."""
    return p2v(module.parameters()).numel()

def setup_seeds(seed):
    torch.backends.cudnn.deterministic = True
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)

@contextlib.contextmanager
def np_local_seed(seed):
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)

def get_trainer(cfg):
    if 'da' in cfg.training:
        from training.da_train import Trainer
    else:
        from training.train import Trainer
    return Trainer(cfg)