"""
Polygon exercises:
    - __len__
    - __getitem__ (retrieve)
    - __add__
    - __iadd__
    - __mul__
    - __imul__
    - append()
    - insert()
    - extend()
    - __setitem__ (assignment)
    - __delitem__
"""
import numbers

class Point:
    """"""

    def __init__(self, x, y):
        if isinstance(x, numbers.Real) \
                and isinstance(y, numbers.Real):
            self._pt = (x, y)
        else:
            raise TypeError('Point co-ordinates must be real numbers')

    def __repr__(self):
        return f'Point(x={self._pt[0]}, y={self._pt[1]})'

    # Custom Seq p1
    def __len__(self):
        """Defines len()"""
        return len(self._pt)

    def __getitem__(self, i):
        """Defines obj[i]"""
        return self._pt[i]

class Polygon:

    def __init__(self, *pts):
        if pts:
            self._pts = [Point(*pt) for pt in pts]
        else:
            self._pts = []

    def __repr__(self):
        # Removes the square brackets in the result
        pts_str = ",".join(str(pt) for pt in self._pts)
        return f'Polygon({pts_str})'

    # Turn Polygon into a Sequence Type
    def __len__(self):
        """Defines len()"""
        return len(self._pts)

    def __getitem__(self, s):
        return self._pts[s]

    def __setitem__(self, s, other):
        """Define instance[s] = other"""
        try:
            rhs = [Point(*pt) for pt in other]
            is_single = False
        except TypeError:
            try:
                rhs = Point(*other)
                is_single = True
            except TypeError:
                raise TypeError('Invalid Point or Iterable of Points')
        if isinstance(s, int) and is_single \
                or (isinstance(s, slice) and not is_single):
            # Assignment for a slice
            self._pts[s] = rhs
        else:
            raise TypeError('Incompatible')

    # More methods
    def __add__(self, other):
        """Define p1 + p2"""
        if isinstance(other, Polygon):
            new_pts = self._pts + other._pts
            return Polygon(*new_pts)
        else:
            raise TypeError('can only concatenate with same Polygon')

    # def __iadd__(self, other):
    #     """Define p1 += p2
    #     - Mutating
    #     - p2 can be any iterables
    #     """
    #     if isinstance(other, Polygon):
    #         # The memory address of _pts will be changed
    #         points = other._pts
    #     else:
    #         # Modify for more options of right-hand-side
    #         points = [Point(*pt) for pt in other]
    #     self._pts = self._pts + points
    #     return self

    def append(self, pt):
        """Define instance.append()
        NOT need to return
        """
        pt = Point(*pt)
        self._pts.append(pt)

    def insert(self, i, pt):
        """Define instance.insert(i, pt)
        NOT need to return
        """
        self._pts.insert(i, Point(*pt))

    def extend(self, pts):
        """Define instance.extend(pts)
        NOT need to return
        """
        if isinstance(pts, Polygon):
            self._pts += pts._pts
        else:
            self._pts += [Point(*pt) for pt in pts]

    def __iadd__(self, other):
        """Define p1 += p2 (Improved from extend)
        - Mutating
        - p2 can be any iterables
        """
        self.extend(other)
        return self

    def __delitem__(self, s):
        """Define del instance[s]"""
        del self._pts[s]

    def pop(self, s):
        """Define instance.pop(s)"""
        return self._pts.pop(s)

    def clear(self):
        self._pts.clear()

# Usage
p1 = Point(10, 2.5)
print(p1)
x, y = p1
print(x, y)

# This is the beauty of using custom seq over Named Tuple
p2 = Point(*p1)

# Polygon
print('POLYGON')

p = Polygon((0, 0), Point(1, 1))
print(p)
print(p[0])
print(len(p))

print('\n CONCAT POLYGON')
p1 = Polygon((1, 1), (2, 2))
p2 = Polygon((3,3), (4, 4))
result = p1 + p2
print(result)  # New object

print('\n ICONCAT POLYGON')
print(id(p1))
p1 += p2
print(id(p1))  # Original object (Mutating)
print(p1)
print('\n ICONCAT POLYGON (Modified)')
p1 = Polygon((1, 1), (2, 2))
print(id(p1))
p1 += [(0, 0), (6, 2)]
print(id(p1))
print(p1)

print('\n Append')
p1 = Polygon((1, 1), (2, 2))
print(id(p1))
p1.append((3, 4))
print(id(p1))
print(p1)

print('\n Extend')
p1 = Polygon((0, 0), (2, 2))
p2 = Polygon((3, 3), (4, 4))
print(id(p1), p1)
print(id(p2), p2)

p1.append([10, 10])
print(id(p1), p1)

p1.insert(1, Point(-1, -1))
print(id(p1), p1)

p1.extend(p2)
print(id(p1), p1)

p1.extend([(6, 6), Point(20, 20)])
print(id(p1), p1)

print('\n Assignment of slice')
p1 = Polygon((0, 0), (2, 2))
print(id(p1), p1)
p1[0:2] = [(3, 3), Point(20, 20), [30, 30]]
print(id(p1), p1)

print('\n Assignment of value')
p1 = Polygon((0, 0), (2, 2))
print(id(p1), p1)
p1[0] = (3, 3)
print(id(p1), p1)
p1[0] = Point(-1, -1)
print(id(p1), p1)

print('\n Assignment (Modified)')
p1 = Polygon((0, 0), (2, 2))
print(id(p1), p1)
p1[0:2] = [(3, 3), [4,4]]
print(id(p1), p1)

print('\n Del/Pop (Modified)')
p1 = Polygon((0, 0), (2, 2), (3, 3))
print(id(p1), p1)
del p1[0]
print(id(p1), p1)
p1 = Polygon((0, 0), (2, 2), (3, 3))
print(id(p1), p1)
del p1[0:2]
print(id(p1), p1)
p1 = Polygon((0, 0), (2, 2), (3, 3))
print(id(p1), p1)
res = p1.pop(0)
print(res)
print(id(p1), p1)


## Say "Hello, World!" With Python
print("Hello, World!")

## Python If-Else
import math
import os
import random
import re
import sys

if __name__ == '__main__':
    n = int(input().strip())
    if n % 2 != 0:
        print("Weird")
    else:
        if (n in range(2, 6)) or (n > 20):
            print("Not Weird")
        elif n in range(6, 21):
            print("Weird")

## Arithmetic Operators
if __name__ == '__main__':
    a = int(input())
    b = int(input())
    print(a + b)
    print(a - b)
    print(a * b)

## Python: Division
if __name__ == '__main__':
    a = int(input())
    b = int(input())
    print(a // b)
    print(a / b)

## Loops
if __name__ == '__main__':
    n = int(input())
    for i in range(0, n):
        print(i**2)

## Write a function
def is_leap(year):
    leap = False

    if year % 4 == 0 and year % 100 != 0:
        leap = True
    elif year % 100 == 0 and year % 400 == 0:
        leap = True

    return leap

year = int(input())

## Print Function
if __name__ == '__main__':
    n = int(input())
    result = ""
    for i in range(1, n + 1):
        result = result + str(i)
    print(result)

## List Comprehensions
if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    print([[i, j, k]
    for i in range(0, x+1)
    for j in range(0, y+1)
    for k in range(0, z+1)
    if (i + j + k != n)])

## Find the Runner-Up Score!
if __name__ == '__main__':
    n=input()
    a=map(int,input().split())
    a=list(set(a))
    a.remove(max(a))
    print (max(a))

## Nested Lists
if __name__ == '__main__':
    arr = []
    scores = []
    for _ in range(int(input())):
        name = input()
        score = float(input())
        arr.append([name, score])
        scores.append(score)

    scores_min = min(scores)
    s = [i for i in scores if i != scores_min]
    m = min(s)
    students = []
    for i in arr:
        if i[1] == m:
            students.append(i[0])

    students.sort()
    for i in students:
        print(i)

## Finding the percentage
if __name__ == '__main__':
    n = int(input())
    student_marks = {}
    for _ in range(n):
        name, *line = input().split()
        scores = list(map(float, line))
        student_marks[name] = scores
    query_name = input()
    x = sum(student_marks[query_name])/3.0
    print(format(x, '.2f'))


import requests
import winsound
import random
import string
import urllib
import argparse

if __name__ == '__main__':
    p = argparse.ArgumentParser()
    p.add_argument('-a', dest='app_id')
    p.add_argument('-k', dest='app_key')
    p.add_argument('--tts_uri')
    p.add_argument('--tts_endpoint')
    args = p.parse_args()

    # Set your TTS Text here
    ttsText = "Hello World..."

    # Available Sources, http://dragonmobile.nuancemobiledeveloper.com/public/index.php?task=supportedLanguages
    ttsLang = "en_US"
    voice = "Susan"

    # Set a random ID via list comprehension, randomizing a-zA-Z and digits
    randomID = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(8)])

    # HTTP Request Headers
    headers = {
        "Content-Type": "text/plain",
        "Accept": "audio/x-wav"
    }

    # Use Requests to send POST message with Query String
    params = urllib.urlencode({'appId': args.app_id, 'appKey': args.app_key, 'id': randomID, 'ttsLang': ttsLang,
                               'voice': voice})
    url = '%s%s?%s' % (args.tts_uri, args.tts_endpoint, params)
    req = requests.post(url, data=ttsText, headers=headers)

    # Play file using Windows
    play_wav = winsound.PlaySound(req.content, winsound.SND_MEMORY)

    # Play file using Linux
    # https://pypi.python.org/pypi/pysox/0.3.6.alpha
    # http://stackoverflow.com/questions/8195544/how-to-play-wav-data-right-from-memory


amount = eval(input("Enter an amount, for example, 11.56: "))

remainingAmount = amount * 100

numberOfOneDollars = remainingAmount // 100
remainingAmount = remainingAmount % 100

numberOfQuarters = remainingAmount // 25
remainingAmount = remainingAmount % 25

numberOfDimes = remainingAmount // 10
remainingAmount = remainingAmount % 10

numberOfNickels = remainingAmount // 5
remainingAmount = remainingAmount % 5

numberOfPennies = remainingAmount

print("Your amount", amount, "consists of")
if numberOfOneDollars > 1:
    print("\t", numberOfOneDollars, "dollars")
elif numberOfOneDollars == 1:
    print("\t", numberOfOneDollars, "dollar")
if numberOfQuarters > 1:
    print("\t", numberOfQuarters, "quarters")
elif numberOfQuarters == 1:
    print("\t", numberOfQuarters, "quarter")
if numberOfDimes > 1:
    print("\t", numberOfDimes, "dimes")
elif numberOfDimes == 1:
    print("\t", numberOfDimes, "dime")
if numberOfNickels > 1:
    print( "\t", numberOfNickels, "nickels")
elif numberOfNickels == 1:
    print("\t", numberOfNickels, "nickel")
if numberOfPennies > 1:
    print( "\t", numberOfPennies, "pennies")
elif numberOfPennies == 1:
    print("\t", numberOfPennies, "penny")


## calculates the area of N andjacent fences
## uses recursion (python has a recursion limit)

def main():
    n, loh, low = get_input()
    l = loh.pop(0)
    print(solve(l, loh, low, 0))
    return

def get_input():
    n = int(input())
    loh = list(map(int, input().split()))  # list of N + 1 heights
    low = list(map(int, input().split()))  # list of N widths
    return n, loh, low

def solve(l, loh, low, area):
    if not loh:
        return area
    else:
        w = low.pop(0)
        r = loh.pop(0)
        area += calc_area(l, w, r)
        return solve(r, loh, low, area)

def calc_area(l, w, r):
    return w * ((l + r)/2)

main()


import os
import shutil
from copy import deepcopy
import numpy as np
import matplotlib
import pynn_genn as sim
from pyNN.random import RandomDistribution
from pyNN.parameters import Sequence
from neo.io import PickleIO
from sacred import Experiment
from lib.embedding import spike_encode
from lib.data import get_inputs, separable
from lib.model import build_model, supervision, predicate
from lib.util import WeightLogger

matplotlib.use('GTK3Agg')

ex = Experiment()

@ex.config
def base_config():
    """Experiment Config"""
    # Input params
    n_class = 2
    n_epoch = 4
    downscale = 8
    input_transform = separable

    # Simulation parameters
    delta_t = 0.1
    t_snapshot = 50
    jitter = 5

    test_frac = 0.5
    sample_duration = n_class * 20 * t_snapshot
    test_duration = test_frac * sample_duration
    train_duration = (1 - test_frac) * sample_duration * n_epoch
    cooldown_duration = t_snapshot * 4

    duration = (
            train_duration  # Train period
            + cooldown_duration  # Cool down
            + test_duration  # Test period
            + t_snapshot  # Last interval
    )
    train_intervals = np.arange(0, train_duration, t_snapshot)
    test_intervals = np.arange(train_duration + cooldown_duration, duration - t_snapshot, t_snapshot)
    runs = 1
    model_type = 'unsupervised'
    tag = "muted"

    N_EKC = n_class
    INH = 100 / N_EKC
    A_PLUS = 0.01
    A_MINUS = 0.0

    # Model parameters
    model = dict(
        population={
            'n_pn': int(np.ceil(105 / downscale) ** 2),
            'n_ekc': N_EKC,
            's_ikc': 20
        },
        neuron={'tau_m': 5},
        synapse={
            0: {'weight': RandomDistribution('uniform', (5.0, 7.5)),
                'delay': 2.0},
            1: {'weight': 0.0,
                'delay': 5.0,
                'td': {
                    'A_minus': A_MINUS,
                    'A_plus': A_PLUS,
                    't_stop': train_duration,
                }},
        },
        swta=[-.75, -INH],  # 100 / neKC
        sparsity=0.1
    )

@ex.named_config
def unmuted_config():
    input_transform = None
    tag = "unmuted"

@ex.named_config
def multiclass():
    n_class = 3
    test_frac = 0.33

@ex.capture
def fetch_inputs(n_class, n_epoch, downscale, input_transform, test_frac):
    return get_inputs(
        "omniglot/python/images_background",
        n_class,
        n_epoch,
        downscale,
        test_frac=test_frac,
        transform=input_transform
    )

@ex.capture(prefix='model')
def construct_model(population, neuron, synapse, swta, sparsity):
    delta_t = sim.get_min_delay()
    return build_model(population['n_pn'], neuron, synapse, swta, delta_t, population['n_ekc'], population['s_ikc'],
                       sparsity)

# Helper
def prepare_simulation(model_type, tag, run, n_class, ekc_proj, t_snapshot):
    results_dir = f"results/{tag}_{model_type}_{n_class}"
    for pop in ["pn", "ikc", "ekc"]:
        shutil.rmtree(f"{results_dir}/data_{pop}_{run}.pickle", ignore_errors=True)
    os.makedirs(results_dir, exist_ok=True)
    weight_logger = WeightLogger(ekc_proj, t_snapshot, f"{results_dir}/weight_log.npy")
    return (
        PickleIO(f"{results_dir}/data_pn_{run}.pickle"),
        PickleIO(f"{results_dir}/data_ikc_{run}.pickle"),
        PickleIO(f"{results_dir}/data_ekc_{run}.pickle"),
        weight_logger
    )

@ex.automain
def main(n_class, model, N_EKC, INH, downscale, tag, model_type, delta_t, n_epoch, t_snapshot, jitter, train_duration,
         test_duration,
         test_frac, duration,
         cooldown_duration,
         train_intervals,
         test_intervals, runs):
    label_set = []

    for run_ix in range(runs):
        print("Run:", run_ix + 1)

        # Setup inputs
        sim.setup(delta_t)
        train_xs, train_ys, test_xs, test_ys = fetch_inputs()

        train_spikes = spike_encode(train_xs, train_ys,
                                    t_snapshot,
                                    spike_jitter=jitter)

        test_spikes = spike_encode(test_xs, test_ys,
                                   t_snapshot, offset=train_duration + cooldown_duration,
                                   spike_jitter=jitter)

        input_spikes = [Sequence(train + test) for train, test in zip(train_spikes, test_spikes)]

        # Set train spike times
        mb, projections = construct_model()
        mb.get_population('pn').record('spikes')
        mb.get_population('ekc').record('spikes')
        mb.get_population('ikc').record('spikes')
        mb.get_population('pn').set(spike_times=input_spikes)

        # Supervision
        if model_type == 'supervised':
            n = len(mb.get_population('ekc'))
            p = predicate.Predicate(lambda i, l, t: i == l)
            supervision\
                .Supervisor(p, n, off=0.0, on=5.0, t_duration=15.0, t_offset=5.0, until=train_duration)\
                .signal(train_ys, train_intervals)\
                .inject_into(mb.get_population('ekc'))

        mb.initialize(v=RandomDistribution('normal', (-65.0, 2.0)))

        # Preparations
        io_pn, io_ikc, io_ekc, weight_logger = prepare_simulation(model_type, tag, run_ix, n_class, projections[1],
                                                                  t_snapshot)

        # Run the simulation
        def logger(t):
            period = "Training" if t <= train_duration else "Testing"
            print(end='\r')
            print(f"{period}: Elapsed time:", sim.get_current_time(), "ms", end='')
            return t + t_snapshot

        print(f"Running simulation '{tag}_{model_type}' for", duration, "ms")
        sim.run(duration, callbacks=[logger, weight_logger])

        mb.get_population('ekc').write_data(io_ekc, 'spikes')
        mb.get_population('pn').write_data(io_pn, 'spikes')
        mb.get_population('ikc').write_data(io_ikc, 'spikes')

        weight_logger.save()

        label_set.append(test_ys)

        print()

        # Save weights for next epoch
        weights = projections[1].get('weight', format='array')
        sim.end()

    # Save data
    np.savez(
        f"results/{tag}_{model_type}_{n_class}_params.npz",
        runs=runs,
        train_intervals=train_intervals,
        test_intervals=test_intervals,
        duration=duration,
        t_snapshot=np.array(t_snapshot),
        labels=np.array(label_set),
        n_epoch=n_epoch,
        n_iKC=len(mb.get_population('ikc')),
        n_eKC=len(mb.get_population('ekc')),
    )


import numpy as np
import os as os
from tqdm import *
# from adam import computeS

USER_SERVICE_FILE = "book_rating_filtered.txt"
SCORE_FOLDER = "./service_score/"
SPARSE_FILE_NAME = "./sparse.npy"
ORIGIN_SPARSE_FILE_NAME = "./origin_sparse.npy"
USER_INDEX_NAME = "./user.txt"
SERVICE_INDEX_NAME = "./service.txt"
RATING_MEAN_FILE_NAME = "./mean.npy"
RATING_VAR_FILE_NAME = "./var.npy"
# TRAINING_FILE = "./train.txt"
USER2TOPIC_FILE_NAME = "./user2topic.npy"
TRAIN_RECORD_FILE = "./train_record.npy"
TEST_RECORD_FILE = "./test_record.npy"

SPARITY = 0.8

y = 10

matrix = np.loadtxt(USER_SERVICE_FILE, delimiter=',', dtype=str)
matrix = np.char.replace(matrix, "\"", "")

user_matrix = matrix[::, 0]
service = matrix[::, 1]
rating = matrix[::, 2].astype(np.int)

service_list = os.listdir(SCORE_FOLDER)

choose = np.zeros(len(service)).astype(np.bool)

for doc in service_list:
	doc = doc.replace(".txt", "")
	index = doc == service
	choose = choose | index

user_matrix = user_matrix[choose]
service = service[choose]
rating = rating[choose]

user_set = set(user_matrix)
service_set = set(service)
service_list = list(service_set)
user_list = list(user_set)

x = len(user_set)
z = len(service_list)

rating_mean = np.zeros([z, 1])
rating_var = np.zeros([z, 1])

np.seterr(divide='ignore')

for (doc, seq) in zip(service_list, range(z)):
	doc = doc.replace(".txt", "")
	index = doc == service
	rating_result = rating[index]

	rating_mean[seq] = np.mean(rating_result)
	rating_var[seq] = np.var(rating_result)

sparse_matrix = np.zeros([x, y])
sequence = 0

def load_score(file_name):
	return np.loadtxt(file_name)

def correct_rat(doc, rat):

	rat_index = service_list.index(doc)

	mean_rat = rating_mean[rat_index]
	var_rat = rating_var[rat_index]

	rat = (rat - mean_rat) / var_rat
	nan_index = np.isnan(rat)
	inf_index = np.isinf(rat)

	all_index = nan_index | inf_index
	rat[all_index] = 0

	# rat = np.nan_to_num(rat)
	# print (rat)
	return rat

def build_sparse_matrix(matrix, sparsity):

	number = len(rating)

	sample_number = np.int(number * sparsity)

	permutation = np.random.permutation(number)
	permutation_index = permutation < sample_number

	train_user_list = user_matrix[permutation_index]
	train_user_set = np.unique(train_user_list)
	train_service = service[permutation_index]
	train_rating = rating[permutation_index]

	train_record = np.zeros(matrix.shape, dtype=np.bool)
	sample_matrix = np.zeros(matrix.shape)

	for user in tqdm(train_user_set):
		index = user == train_user_list
		services = train_service[index]
		ratings = train_rating[index]

		sequence = user_list.index(user)

		basic = np.zeros(y)

		for doc, rat in zip(services, ratings):
			service_index = service_list.index(doc)
			sample_matrix[sequence, service_index] = rat
			train_record[sequence, service_index] = True

			doc_name = doc + ".txt"
			full_name = SCORE_FOLDER + doc_name
			score = load_score(full_name)
			rat = correct_rat(doc, rat)
			# print (score)
			basic += score * rat

		# basic = (basic-min_value) / (max_value - min_value)
		# sparse_matrix[sequence]

		sparse_matrix[sequence] = basic
		# print (basic)

	return sample_matrix, sparse_matrix, train_record

def build_origin_matrix():
	origin_sparse_matrix = np.zeros([x, z])
	all_record = np.zeros([x, z], dtype=np.bool)

	for user in tqdm(user_set):
		index = user == user_matrix
		services = service[index]
		ratings = rating[index]

		sequence = user_list.index(user)

		for doc, rat in zip(services, ratings):
			service_index = service_list.index(doc)
			origin_sparse_matrix[sequence, service_index] = rat
			all_record[sequence, service_index] = True

	return origin_sparse_matrix, all_record

def save_np_matrix(sparse_matrix, file_name):
	# np.savetxt(file_name, sparse_matrix)
	np.save(file_name, sparse_matrix)

def save_user_index(user_set, file_name):
	user_set = np.array(list(user_set)).reshape(-1, 1)
	np.savetxt(file_name, user_set, fmt='%s')

origin_matrix, data_record = build_origin_matrix()
sparse_matrix, user2topic_matrix, train_record = build_sparse_matrix(origin_matrix, SPARITY)

test_record = data_record ^ train_record

save_np_matrix(origin_matrix, ORIGIN_SPARSE_FILE_NAME)
save_np_matrix(sparse_matrix, SPARSE_FILE_NAME)
save_np_matrix(user2topic_matrix, USER2TOPIC_FILE_NAME)

save_np_matrix(train_record, TRAIN_RECORD_FILE)
save_np_matrix(test_record, TEST_RECORD_FILE)

save_user_index(user_set, USER_INDEX_NAME)
save_user_index(service_list, SERVICE_INDEX_NAME)

save_np_matrix(rating_mean, RATING_MEAN_FILE_NAME)
save_np_matrix(rating_var, RATING_VAR_FILE_NAME)

"""
origin_matrix = build_origin_matrix()

save_user_index(user_set, USER_INDEX_NAME)
save_user_index(service_list, SERVICE_INDEX_NAME)

train_matrix = build_sparse_matrix(sparse_matrix, SPARITY)
save_sparse_matrix(train_matrix, TRAINING_FILE)
"""


# Name : Sagie Baram

import numpy as np

def square_matrix_generator(n):
    """
    Generating an n on n matrix based on user input.
    also generating a result column based on user input.
    n: size of square matrix.
    """
    matrix = np.zeros((n, n))  # initializing
    b = np.zeros(n)
    for row in range(0, n):
        for col in range(0, n):
            matrix[row][col] = int(input((f"Matrix[{row}],[{col}]: ")))
        b[row] = int(input(f"b[{row}] = "))
    return matrix, b

def swapRows(matrix, r1, r2):
    if len(np.shape(matrix)) == 1:
        matrix[r1], matrix[r2] = matrix[r2], matrix[r1]
    else:
        matrix[[r1, r2], :] = matrix[[r2, r1], :]

def jacobi_method(matrix, result, variables):
    """
    Jacobi iterative method will iterate over each row in the matrix
    and will calculate it's variables to provide a new solution.

    Will not use the next solution therefore may cause additional iterations.

    matrix - assuming diagonally dominant.
    result - the result colum of the matrix (b)
    variables - the variable column (x)
    """
    size = len(matrix)
    new_vars = []  # will append the new solutions to it.
    for col in range(0, size):
        holder = result[col]
        for row in range(0, size):
            if col != row:  # if not diagonal index
                holder -= matrix[col][row] * variables[row]
                # calculating variables x**(val=0,1,2,3,...)
        new_vars.append(holder / matrix[col][col])
    # not updating yr+1/zr+1 with xr+1 etc
    # divide by dominant diagonal
    return new_vars  # returns the updated values.

def guassian_seidel_method(matrix, result, variables):
    """
    Guassian-seidel iterative method will iterate over each row in the matrix
    and will calculate it's variables to provide a new solution.
    It will use the next solution of any non 0 variable from that row.

    Will deliver the result with less iterations than Jacobi iterative method.

    matrix - assuming diagonally dominant.
    result - the result colum of the matrix (b)
    variables - the variable column (x)
    """

    size = len(matrix)
    var = list(variables)
    for col in range(0, size):
        holder = result[col]
        for row in range(0, size):
            if col != row:  # if not diagonal index
                holder -= matrix[col,row] * var[row]
                # calculating variables x**(val=0,1,2,3,...)
        var[col] = holder / matrix[col,col]
        # updating yr+1/zr+1 with xr+1 etc
        # divide by dominant diagonal
    return var  # returns the updated values.

def linear_system_iterative_method(iterative_method, matrix, result, xr, epsilon):
    """
      linear_system_iterative_method is an iterative method used to solve a system of
      linear equations. Can be applied to any matrix with non-zero elements
      on the diagonals, convergence is only guarenteed if the matrix is either
      strictly diagonally dominant (D), or symmetric and positive definite.
      this function will check if the given matrix is diagonally dominant.

      Analytic example using Jacobi iterative method:

      4X + 2Y = 2          ===>  Xr+1 = (2-2*Yr-0*Zr)/4
      2X + 10Y + 4Z = 6    ===>  Yr+1 = (6-2*Xr - 4*Zr)/10
      4Y + 5Z = 5          ===>  Zr+1 = (5-0*Xr-4*Yr)/5

      Using Guassian-seidel iterative method:

      4X + 2Y = 2       ===> Xr+1 = (2-2*Yr-0*Zr)/4
      2X + 10Y + 4Z = 6 ===> Yr+1 =(6-2*Xr+1 - 4*Zr)/10
      4Y + 5Z = 5       ===> Zr+1 = (5-0*Xr+1 - 4*Yr+1)/5

        0   1   2
       ___________
    0 | 4   2   0 |
      |           |
    1 | 2  10   4 |
      |           |
    2 | 0   4   2 |
      |___________|

    """

    def check_dominant_row(matrix):
        """
        checking if given matrix has dominant row.
        """
        # for each row
        size = len(matrix)
        for i in range(0, size) :
            sum_rows = 0
            for j in range(0, size) :
                if i != j:
                    sum_rows += abs(matrix[i,j])
            if (np.abs(matrix[i,i]) < sum_rows) :
                return False
        return True

    def check_valid_matrix(matrix, result, epsilon):
        """
        swapping rows with pivot if neccessary.
        """
        print(f"Given Matrix: \n{matrix}\n Given result column:\n{result}\n")
        check = False
        n = len(matrix)
        scale = np.zeros(n)
        for i in range(n):
            scale[i] = max(np.abs(matrix[i, :]))  # entering all max values in each row to scale.

        for k in range(0, n - 1):
            pivot = (np.argmax(np.abs(matrix[k:n, k]) / scale[k:n]) + k)  # Find row containing element with largest relative size
            if abs(matrix[pivot, k]) < epsilon:
                print( "Given Matrix is singular therefor can't use an iterative method\nExiting program.")
                exit(1) # If row change is needed:
            if pivot != k:
                check = True
                print(f"Swapping row: {pivot} with row: {k}\n")
                # swapping k and pivot indexes in matrix, result(b) and max variable array.
                swapRows(result, k, pivot)  # result(b) swap
                swapRows(scale, k, pivot)  # max variable array swap
                swapRows(matrix, k, pivot)  # matrix swap

        if check is True:
            print(f"Rows were swapped to make the matrix coefficient\n")
            print(f"Given Matrix: {matrix}\n Given result column:{result}")

    def check_epsilon(epsilon, xr, xr_1):
        """
        Check_epsilon will check if the absolute value for each variable
        in solution substracted from the next solution is lower than the given
        epsilon, it will return false.
        """
        for x in range(0, len(xr)):
            if abs(xr_1[x] - xr[x]) < epsilon:
                return False
        return True

    count = 0  # Iteration count
    condition = True  # Will have check_epsilon result
    check_valid_matrix(matrix, result, epsilon)
    if check_dominant_row(matrix) is False:
        print("Given matrix isn't dominant\nExiting Program")
        exit(1)

    while condition:
        xr_1 = iterative_method(matrix, result, xr)
        x_3float = list(map(lambda y: "{:.3f}".format(y), xr_1))
        print(f"{count+1}\t{x_3float}")
        condition = check_epsilon(epsilon, xr, xr_1)
        xr = np.copy(xr_1)
        count += 1
    x_3float = list(map(lambda y: "{:.3f}".format(y), xr))
    print(f"Final solution:{x_3float}")

def main():
    # Data Input (from class)
    epsilon = 0.001  # tolerance
    x0 = np.array([0,0,0])

    # convergence = true
    conv_matrix = np.array([[3, -1, 1], [0, 1, -1], [1, 1, -2]])
    conv_result = np.array([4, -1, -3])

    # convergence = false
    no_conv_matrix = np.array([[4, 2, 0], [2, 10, 4], [0, 4, 5]])
    no_conv_result = np.array([2, 6, 5])

    print("Choose from sample data or create your own matrix:")
    print("1. Create my own")
    print("2. Use sample data (default)")
    selection = int(input("Enter selection: "))
    if selection == 1:
        size = int(input("Enter size (square matrix): "))
        matrix, result = square_matrix_generator(abs(size))
    else:
        print("Choose an example:")
        print("1. With no convergence")
        print("2. With convergence (default)")
        selection = int(input("Enter selection: "))
        if selection == 1:
            matrix, result = no_conv_matrix, no_conv_result
        else:
            matrix, result = conv_matrix, conv_result

    print("Choose an iterative method:")
    print("1. Jacobi method")
    print("2. Guassian Seidel method (default)")
    selection = int(input("Enter selection: "))
    if selection == 1:
        linear_system_iterative_method(jacobi_method, matrix, result, x0, epsilon)
    else:
        linear_system_iterative_method(guassian_seidel_method, matrix, result, x0, epsilon)

main()


import urllib.parse, urllib.request

from flask import json
def getYouDao():
    while True:
        content = input("请输入内容")
        if content == ':':
            break
        url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc"
        data = {}
        data['i'] = "i love you"
        data['type'] = 'AUTO'
        data['doctype'] = 'json'
        data['version'] ='2.1'
        data['keyfrom'] ='fanyi.web'
        data['ue'] = 'UTF-8'
        data['typoResult'] = 'true'

        #
        # data['smartresult'] = 'dict'
        # data['client'] = 'fanyideskweb'
        # data['action'] = 'FY_BY_REALTIME'

        data = urllib.parse.urlencode(data).encode("utf-8")

        #  当需要添加header之后 必须通过构建request对象来解决问题
        req = urllib.request.Request(url, data)
        req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36")
        response = urllib.request.urlopen(req)
        html = response.read().decode("utf-8")
        loads = json.loads(html)
        print(loads)
        print(type(loads))
        target =loads['translateResult']
        print(target[0][0]['tgt'])
        # print(loads)

def getBet365():
    url = "https://www.bet365.com/SportsBook.API/web?lid=10&zid=0&pd=%23AS%23B1%23&cid=99&cgid=1"
    header = {}
    header['user-agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'

    response = urllib.request.urlopen(url,header)
    with open("bet365FileLevel", "w") as f:
        text = response.read().decode("utf-8")
        f.write(text)

if __name__ == '__main__':
    getYouDao()


infinity= float('infinity')
minfinity= - infinity

class H:
	def __init__(self,inf, sup, nbins):
		self.nbins=nbins
		self.inf = inf
		self.sup = sup
		self.nbins=nbins
		self.width=sup-inf
		self.npoints=0
		self.array = [0] * nbins

	def localize(self,x):
		return int( self.nbins * (x-self.inf)/self.width )

	def add(self,x):
		self.npoints+=1
		if x  >= self.inf and  x <= self.sup :
			self.array[ self.localize(x) ] += 1

	def density(self):
		step = self.width/self.nbins
		xs  = [self.inf + k*step for k in range(self.nbins+1) ]
		xs.append(self.sup)
		ds = [ x/(self.npoints*step) for x in self.array]
		return zip( xs[:-1], xs[1:], ds )

import sys
def progressbar(f):
	width = 50
	adv = int( width * f)
	todo =  width  - adv
	sys.stdout.write( "\r[{}>{}] ({}%) done".format('='*adv, ' '*todo, int(100*f)) )
	sys.stdout.flush()

import matplotlib.pyplot as plt
def plot( n , inf, sup, nbins, rng, pl=plt.plot ):
	h=H(inf,sup,nbins)
	ndone= 0
	for x in range(n) :
		r= rng()
		h.add(r)
		ndone+=1
		progressbar(ndone/n)
	xs=[]
	ds= []
	A=h.density()

	for (inf,sup, d)  in A:
		mid = (sup + inf) /2
		#xs.extend([inf,inf,sup,sup])
	#	ds.extend([0,d,d,0])
		xs.append(mid)
		ds.append(d)

	pl(xs,ds)


from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('home', views.home, name='home'),
    path('save', views.save, name='save'),
    path('edit', views.edit, name='edit'),
    path('editform', views.editform, name='editform'),
    path('delete', views.delete,name='delete'),

]


import turtle

window=turtle.Screen()

window.bgcolor("gray")

brad=turtle.Turtle()
brad.speed(0)

def square():
	for i in range(0,4,1):
		brad.forward(100)
		brad.left(90)

for i in range(1,100,1):
	square()
	brad.left(10)

window.exitonclick()


 # -*- coding: utf-8 -*-
"""
Created on Tue Jul 16 11:00:32 2019

@author: utente
"""

import numpy as np
import os
import cv2

def read_categories_dict(filename):
    d={}
    with open(filename) as f:
        for line in f:
            (key,val1,val2,val3) = line.split()
            d[int(key)]=[val1,val2,val3]
    return d

def load_and_resize(dirpath):

    x_test=[]

    for img in os.listdir(dirpath):
        image_file=cv2.imread(dirpath+'/'+img)

        if image_file is not None:
            resized=cv2.resize(image_file,(32,32))
            x_test.append(resized)

        else: print('Error')
    return np.array(x_test)

def format_time(seconds):
    if seconds < 400:
        s = float(seconds)
        return "%.1f seconds" % (s,)
    elif seconds < 4000:
        m = seconds / 60.0
        return "%.2f minutes" % (m,)
    else:
        h = seconds / 3600.0
        return "%.2f hours" % (h,)


from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
import numpy as np
import torchvision
from torchvision import transforms, datasets, models
import os
import cv2

class ResidualBlock(nn.Module):
    def __init__(self, input_channels, output_channels, stride=1):
        super(ResidualBlock, self).__init__()
        self.input_channels = input_channels
        self.output_channels = output_channels
        self.stride = stride
        self.bn1 = nn.BatchNorm2d(input_channels)
        self.relu = nn.ReLU(inplace=True)
        self.conv1 = nn.Conv2d(input_channels, int(output_channels/4), 1, 1, bias = False)
        self.bn2 = nn.BatchNorm2d(int(output_channels/4))
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv2d(int(output_channels/4), int(output_channels/4), 3, stride, padding = 1, bias = False)
        self.bn3 = nn.BatchNorm2d(int(output_channels/4))
        self.relu = nn.ReLU(inplace=True)
        self.conv3 = nn.Conv2d(int(output_channels/4), output_channels, 1, 1, bias = False)
        self.conv4 = nn.Conv2d(input_channels, output_channels , 1, stride, bias = False)
    def forward(self, x):
        residual = x
        out = self.bn1(x)
        out1 = self.relu(out)
        out = self.conv1(out1)
        out = self.bn2(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn3(out)
        out = self.relu(out)
        out = self.conv3(out)
        if (self.input_channels != self.output_channels) or (self.stride !=1 ):
            residual = self.conv4(out1)
        out += residual
        return out

class AttentionModule(nn.Module):
    def __init__(self, in_channels, out_channels, size1, size2, size3):
        super(AttentionModule, self).__init__()
        self.first_residual_blocks = ResidualBlock(in_channels, out_channels)
        self.trunk_branches = nn.Sequential(
            ResidualBlock(in_channels, out_channels),
            ResidualBlock(in_channels, out_channels)
        )
        self.mpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.softmax1_blocks = ResidualBlock(in_channels, out_channels)
        self.skip1_connection_residual_block = ResidualBlock(in_channels, out_channels)
        self.mpool2 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.softmax2_blocks = ResidualBlock(in_channels, out_channels)
        self.skip2_connection_residual_block = ResidualBlock(in_channels, out_channels)
        self.mpool3 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.softmax3_blocks = nn.Sequential(
            ResidualBlock(in_channels, out_channels),
            ResidualBlock(in_channels, out_channels)
        )
        self.interpolation3 = nn.UpsamplingBilinear2d(size=size3)
        self.softmax4_blocks = ResidualBlock(in_channels, out_channels)
        self.interpolation2 = nn.UpsamplingBilinear2d(size=size2)
        self.softmax5_blocks = ResidualBlock(in_channels, out_channels)
        self.interpolation1 = nn.UpsamplingBilinear2d(size=size1)
        self.softmax6_blocks = nn.Sequential(
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_channels, out_channels , kernel_size = 1, stride = 1, bias = False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_channels, out_channels , kernel_size = 1, stride = 1, bias = False),
            nn.Sigmoid()
        )
        self.last_blocks = ResidualBlock(in_channels, out_channels)
    def forward(self, x):
        x = self.first_residual_blocks(x)
        out_trunk = self.trunk_branches(x)
        out_mpool1 =  self.mpool1(x)
        out_softmax1 = self.softmax1_blocks(out_mpool1)
        out_skip1_connection = self.skip1_connection_residual_block(out_softmax1)
        out_mpool2 = self.mpool2(out_softmax1)
        out_softmax2 = self.softmax2_blocks(out_mpool2)
        out_skip2_connection = self.skip2_connection_residual_block(out_softmax2)
        out_mpool3 = self.mpool3(out_softmax2)
        out_softmax3 = self.softmax3_blocks(out_mpool3)
        #
        out_interp3 = self.interpolation3(out_softmax3)
        # print(out_skip2_connection.data)
        # print(out_interp3.data)
        out = out_interp3 + out_skip2_connection
        out_softmax4 = self.softmax4_blocks(out)
        out_interp2 = self.interpolation2(out_softmax4)
        out = out_interp2 + out_skip1_connection
        out_softmax5 = self.softmax5_blocks(out)
        out_interp1 = self.interpolation1(out_softmax5)
        out_softmax6 = self.softmax6_blocks(out_interp1)
        out = (1 + out_softmax6) * out_trunk
        out_last = self.last_blocks(out)
        return out_last

class ResidualAttentionModel(nn.Module):
    def __init__(self):
        super(ResidualAttentionModel, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias = False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True)
        )
        self.mpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.residual_block1 = ResidualBlock(64, 256)
        self.attention_module1 = AttentionModule(256, 256, (56,56), (28,28), (14,14))
        self.residual_block2 = ResidualBlock(256, 512, 2)
        self.attention_module2 = AttentionModule(512, 512, (28,28), (14,14), (7,7))
        self.residual_block3 = ResidualBlock(512, 1024, 2)
        self.attention_module3 = AttentionModule(1024, 1024, (14,14), (7,7), (4,4))
        self.residual_block4 = ResidualBlock(1024, 2048, 2)
        self.residual_block5 = ResidualBlock(2048, 2048)
        self.residual_block6 = ResidualBlock(2048, 2048)
        self.mpool2 = nn.Sequential(
            nn.BatchNorm2d(2048),
            nn.ReLU(inplace=True),
            nn.AvgPool2d(kernel_size=7, stride=1)
        )
        self.fc = nn.Linear(2048,170)
    def forward(self, x):
        out = self.conv1(x)
        out = self.mpool1(out)
        # print(out.data)
        out = self.residual_block1(out)
        out = self.attention_module1(out)
        out = self.residual_block2(out)
        out = self.attention_module2(out)
        out = self.residual_block3(out)
        # print(out.data)
        out = self.attention_module3(out)
        out = self.residual_block4(out)
        out = self.residual_block5(out)
        out = self.residual_block6(out)
        out = self.mpool2(out)
        out = out.view(out.size(0), -1)
        out = self.fc(out)
        return out

import tensorflow as tf
import pathlib
data_dir = '/home/celso//ResidualAttentionNetwork-pytorch/Residual-Attention-Network/downloads'
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*.jpg')))
# Image Preprocessing
transform = transforms.Compose([
    transforms.Scale(224),
    transforms.ToTensor()])

transform2 = transforms.Compose([
    transforms.Resize([224,224],),
    transforms.ToTensor()])

train_dataset2 = datasets.CIFAR10(root='./data/',
                               train=True,
                               transform=transform,
                               download=True)

test_dataset2 = datasets.CIFAR10(root='./data/',
                              train=False,
                              transform=transform2)

train_data = datasets.ImageFolder('/home/celso//ResidualAttentionNetwork-pytorch/Residual-Attention-Network/downloads', transform=transform2)
train_size = int(0.8 * len(train_data))
test_size = len(train_data) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(train_data, [train_size, test_size])

#gerenciamento de informaçoes dinamico e

# Data Loader (Input Pipeline)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=20,
                                           shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                          batch_size=20,
                                          shuffle=False)

classes = np.array([item.name for item in data_dir.glob('*') if item.name != "LICENSE.txt"])

model = ResidualAttentionModel().cuda()
print(model)

lr = 0.001
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)

# Training
for epoch in range(100):
    for i, (images, labels) in enumerate(train_loader):
        images = Variable(images.cuda())
        # print(images.data)
        labels = Variable(labels.cuda())

        # Forward + Backward + Optimize
        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        #print("step i = ",i)
        if (i+1) % 100 == 0:
            print ("Epoch [",epoch+1,"/","80], Iter [",i+1,"/",500,"] Loss: ",loss.data)
    # Decaying Learning Rate
    if (epoch+1) % 20 == 0:
        lr /= 3
        optimizer = torch.optim.Adam(model.parameters(), lr=lr)

# Save the Model
torch.save(model.state_dict(), 'model.pkl')

# Test
correct = 0
total = 0
#
class_correct = list(0. for i in range(170))
class_total = list(0. for i in range(170))

for images, labels in test_loader:
    images = Variable(images.cuda())
    labels = Variable(labels.cuda())
    outputs = model(images)
    _, predicted = torch.max(outputs.data, 1)
    total += labels.size(0)
    correct += (predicted == labels.data).sum()
    #
    c = (predicted == labels.data).squeeze()
    for i in range(4):
        label = labels.data[i]
        class_correct[label] += c[i]
        class_total[label] += 1

print('Accuracy of the model on the test images: %d %%' % (100 * correct / total))

# class_correct = list(0. for i in range(10))
# class_total = list(0. for i in range(10))
# for data in testloader:
#     images, labels = data
#     outputs = model(Variable(images.cuda()))
#     _, predicted = torch.max(outputs.data, 1)
#     c = (predicted == labels).squeeze()
#     for i in range(4):
#         label = labels[i]
#         class_correct[label] += c[i]
#         class_total[label] += 1

for i in range(10):
    print('Accuracy of %5s : %2d %%' % (
        classes[i], 100 * class_correct[i] / class_total[i]))


# -*- coding: utf-8 -*-
from django.urls import path, register_converter
from shared.utils import BigIntConverter
from . import views

app_name = 'taxonomy'
register_converter(BigIntConverter, 'bigint')

urlpatterns = [
    # ------------------------------------------------------------------------#
    # Tasks
    path('tasks/update-taxon/', views.update_taxon, name="task-update-taxon"),
    # ------------------------------------------------------------------------#
    # Species
    path('species/', views.TaxonListView.as_view(), name='taxon-list'),
    path('species/<bigint:name_id>/', views.TaxonDetailView.as_view(), name='taxon-detail'),
    # ------------------------------------------------------------------------#
    # Communities
    path('communities/', views.CommunityListView.as_view(), name='community-list'),
    path('communities/<int:pk>/', views.CommunityDetailView.as_view(), name='community-detail'),
]


from __future__ import print_function
import os
os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from catSNN import spikeLayer, transfer_model, SpikeDataset ,load_model, fuse_module, transfer_model_sequence,fuse_bn_recursively
import catSNN
class AddGaussianNoise(object):
    def __init__(self, mean=0., std=1.):
        self.std = std
        self.mean = mean

    def __call__(self, tensor):
        return tensor + torch.randn(tensor.size()) * self.std + self.mean

    def __repr__(self):
        return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)

def initialize_weights(model):
    for m in model.modules():
        if isinstance(m, nn.Conv2d):
            nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='relu')
            # nn.init.normal_(m.weight, 0, 0.1)
            if m.bias is not None:
                nn.init.constant_(m.bias, 0)
        elif isinstance(m, nn.Linear):
            nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='relu')
            # nn.init.normal_(m.weight, 0, 0.1)
            if m.bias is not None:
                nn.init.constant_(m.bias, 0)

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.model = self._make_layers()
        self.fc = nn.Linear(512, 10, bias=True)
        self.model.apply(initialize_weights)

    def forward(self, x):
        out = self.model(x)
        out = out.view(-1,512)
        out = self.fc(out)
        return out

    def _make_layers(self):
        layers = []
        cfg = [(64,1), (128,1), (256,1) ,(256,2), (256,1), (512,1),(512,2),'M']

        layers += [nn.Conv2d(3, 32, 3, 1, 1, bias=True), catSNN.Clamp(max = 1)]
        in_channels = 32
        for x in cfg:
            if x == 'M':
                layers += [nn.AvgPool2d(kernel_size=8, stride=8)]
            else:
                layers += [nn.Conv2d(in_channels,2*in_channels,1,1,0,bias = True),catSNN.Clamp(max = 1)]
                layers += [nn.Conv2d(2*in_channels,2*in_channels,3,x[1],1,bias=True, groups=2*in_channels),catSNN.Clamp(max = 1)]
                layers += [nn.Conv2d(2*in_channels,x[0],1,1,0,bias = True),catSNN.Clamp(max = 1)]
                in_channels = x[0]
        return nn.Sequential(*layers)

class CatNet(nn.Module):
    def __init__(self,  T):
        super(CatNet, self).__init__()
        self.snn = catSNN.spikeLayer(T)
        self.T = T
        self.model = self._make_layers()
        self.fc = self.snn.dense(512,10,bias = True)

    def forward(self, x):
        out = self.model(x)
        out = self.fc(out)
        out = self.snn.sum_spikes(out)/self.T
        return out

    def _make_layers(self):
        layers = []
        cfg = [(64,1), (128,1), (256,1) ,(256,2), (256,1), (512,1),(512,2),'M']
        layers += [self.snn.conv(3, 32, 3,1,1 ,bias=True),self.snn.spikeLayer()]
        in_channels = 32
        for x in cfg:
            if x == 'M':
                layers += [self.snn.pool(8)]
            else:
                layers += [self.snn.conv(in_channels,2*in_channels,1,1,0,bias = True),
                           self.snn.spikeLayer()]
                layers += [self.snn.conv(2*in_channels,2*in_channels,3,x[1],1,bias=True, groups=2*in_channels),
                           self.snn.spikeLayer()]
                layers += [self.snn.conv(2*in_channels,x[0],1,1,0,bias = True),
                           self.snn.spikeLayer()]
                in_channels = x[0]
        # layers += [self.snn.sum_spikes_layer()]
        return nn.Sequential(*layers)

def train(args, model, device, train_loader, optimizer, epoch):
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        #onehot = torch.nn.functional.one_hot(target, 10)
        optimizer.zero_grad()
        output = model(data)
        loss = F.cross_entropy(output, target)
        loss.backward()
        optimizer.step()
        if batch_idx % args.log_interval == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))
            if args.dry_run:
                break
def test(model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            #onehot = torch.nn.functional.one_hot(target, 10)
            output = model(data)
            test_loss += F.cross_entropy(output, target, reduction='sum').item()  # sum up batch loss
            pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
            print(pred.eq(target.view_as(pred)).sum().item())
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)

    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

def main():
    # Training settings
    parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
    parser.add_argument('--batch-size', type=int, default=16, metavar='N',
                        help='input batch size for training (default: 64)')
    parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
                        help='input batch size for testing (default: 1000)')
    parser.add_argument('--epochs', type=int, default=3, metavar='N',
                        help='number of epochs to train (default: 14)')
    parser.add_argument('--lr', type=float, default=1, metavar='LR',
                        help='learning rate (default: 1.0)')
    parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
                        help='Learning rate step gamma (default: 0.7)')
    parser.add_argument('--no-cuda', action='store_true', default=False,
                        help='disables CUDA training')
    parser.add_argument('--dry-run', action='store_true', default=False,
                        help='quickly check a single pass')
    parser.add_argument('--seed', type=int, default=1, metavar='S',
                        help='random seed (default: 1)')
    parser.add_argument('--log-interval', type=int, default=10, metavar='N',
                        help='how many batches to wait before logging training status')
    parser.add_argument('--save-model', action='store_true', default=False,
                        help='For Saving the current Model')
    parser.add_argument('--T', type=int, default=500, metavar='N',
                        help='SNN time window')
    parser.add_argument('--resume', type=str, default=None, metavar='RESUME',
                        help='Resume model from checkpoint')

    args = parser.parse_args()
    use_cuda = not args.no_cuda and torch.cuda.is_available()

    torch.manual_seed(args.seed)

    device = torch.device("cuda" if use_cuda else "cpu")

    kwargs = {'batch_size': args.batch_size}
    if use_cuda:
        kwargs.update({'num_workers': 1,
                       'pin_memory': True,
                       'shuffle': True},
                     )

    transform=transforms.Compose([
        transforms.ToTensor(),
        #transforms.Normalize((0.1307,), (0.3081,))
        ])
    transform_train = transforms.Compose([
        transforms.RandomCrop(32, padding=4),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        AddGaussianNoise(std=0.01)
        ])

    transform_test = transforms.Compose([
        transforms.ToTensor()
        #transforms.Normalize(mean, std)
        ])

    dataset1 = datasets.CIFAR10('../data', train=True, download=True,
                       transform=transform_train)
    dataset2 = datasets.CIFAR10('../data', train=False,
                       transform=transform_test)
    snn_dataset = SpikeDataset(dataset2, T = args.T)
    train_loader = torch.utils.data.DataLoader(dataset1,**kwargs)
    test_loader = torch.utils.data.DataLoader(dataset2, **kwargs)
    snn_loader = torch.utils.data.DataLoader(snn_dataset, batch_size=1, shuffle=False)

    model = Net().to(device)
    snn_model = CatNet(args.T).to(device)

    if args.resume != None:
        load_model(torch.load(args.resume), model)

    optimizer = optim.Adadelta(model.parameters(), lr=args.lr)

    scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
    for epoch in range(1, args.epochs + 1):
        train(args, model, device, train_loader, optimizer, epoch)
        #test(model, device, train_loader)
        test(model, device, test_loader)
        scheduler.step()
    #model = fuse_bn_recursively(model)
    transfer_model(model, snn_model)
    test(snn_model, device, snn_loader)

    #if args.save_model:

if __name__ == '__main__':
    main()


def D():
    n , m = map(int,input().split())
    c = {i:[] for i in range(1,n+1)}
    ans = [0]*(n)
    for _ in range(m):
        a , b = map(int , input().split())
        c[a].append(b)

    m = -float('inf')
    maximos = []
    for j in c:
        m = max(len(c[j]), m)
    for i in range(1,n+1):
        if(len(c[i])==m): maximos.append(i)
    for i in range(1,n+1):
        ans[i-1]+= (m-1)*n
        aux = -float('inf')
        for x in maximos:
            aux2 = float('inf')
            for j in c[x]:
                aux2 = min(aux2,(j-x)%n)

            aux = max(aux, (x-i)%n+aux2 )
        ans[i-1]+=aux

    print(*ans)

D()


import glob
import logging
import os
import random
import sys
from pathlib import Path
import pickle

import numpy as np
from scipy import spatial, ndimage, misc
import torch

from lib.constants.dataset_sets import HEAD_CATS_SCANNET_200, COMMON_CATS_SCANNET_200, TAIL_CATS_SCANNET_200
from lib.dataset import VoxelizationDataset, DatasetPhase, str2datasetphase_type
from lib.pc_utils import read_plyfile, save_point_cloud
from lib.transforms import InstanceAugmentation
from lib.utils import read_txt, fast_hist, per_class_iu

from lib.constants.scannet_constants import *
from lib.datasets.preprocessing.utils import box_intersect

import MinkowskiEngine as ME

class ScannetVoxelizationDataset(VoxelizationDataset):

    # Voxelization arguments
    CLIP_BOUND = None
    TEST_CLIP_BOUND = None
    VOXEL_SIZE = 0.05

    # Load constants for label ids
    SCANNET_COLOR_MAP = SCANNET_COLOR_MAP_20
    CLASS_LABELS = CLASS_LABELS_20
    VALID_CLASS_IDS = VALID_CLASS_IDS_20

    # Augmentation arguments
    ROTATION_AUGMENTATION_BOUND = ((-np.pi / 64, np.pi / 64), (-np.pi / 64, np.pi / 64), (-np.pi,
                                                                                np.pi))
    TRANSLATION_AUGMENTATION_RATIO_BOUND = ((-0.2, 0.2), (-0.2, 0.2), (0, 0))
    ELASTIC_DISTORT_PARAMS = ((0.2, 0.4), (0.8, 1.6))

    ROTATION_AXIS = 'z'
    LOCFEAT_IDX = 2
    NUM_LABELS = max(SCANNET_COLOR_MAP_LONG.keys())  # Will be converted to 20 as defined in IGNORE_LABELS.
    IGNORE_LABELS = tuple(set(range(NUM_LABELS)) - set(VALID_CLASS_IDS))
    IS_FULL_POINTCLOUD_EVAL = True

    # If trainval.txt does not exist, copy train.txt and add contents from val.txt
    DATA_PATH_FILE = {
        DatasetPhase.Train: 'train.txt',
        DatasetPhase.Val: 'val.txt',
        DatasetPhase.TrainVal: 'trainval.txt',
        DatasetPhase.Test: 'test.txt'
    }

    def __init__(self,
                 config,
                 prevoxel_transform=None,
                 input_transform=None,
                 target_transform=None,
                 augment_data=True,
                 elastic_distortion=False,
                 cache=False,
                 phase=DatasetPhase.Train):
        if isinstance(phase, str):
            phase = str2datasetphase_type(phase)
        # Use cropped rooms for train/val
        data_root = config.scannet_path
        if phase not in [DatasetPhase.Train, DatasetPhase.TrainVal]:
            self.CLIP_BOUND = self.TEST_CLIP_BOUND
        data_paths = read_txt(os.path.join(data_root, self.DATA_PATH_FILE[phase]))
        logging.info('Loading {}: {}'.format(self.__class__.__name__, self.DATA_PATH_FILE[phase]))
        super().__init__(
            data_paths,
            data_root=data_root,
            prevoxel_transform=prevoxel_transform,
            input_transform=input_transform,
            target_transform=target_transform,
            ignore_label=config.ignore_label,
            return_transformation=config.return_transformation,
            augment_data=augment_data,
            elastic_distortion=elastic_distortion,
            config=config)

        # Load category weights for weighted CE and Focal
        self.category_weights = torch.ones(self.NUM_LABELS)
        category_weights_path = config.scannet_path + '/' + config.category_weights
        if os.path.isfile(category_weights_path):
            with open(category_weights_path, "rb") as input_file:
                category_weights = pickle.load(input_file)
                print('Loaded category weights for CE {}'.format(category_weights_path))

            for cat_id, cat_value in category_weights.items():
                if cat_id > 0:
                    mapped_id = self.label_map[cat_id]
                    self.category_weights[mapped_id] = cat_value

        # Load instance sampling weights for instance based balancing
        self.instance_sampling_weights = np.ones(self.NUM_LABELS)
        instance_sampling_weights_path = config.scannet_path + '/' + config.instance_sampling_weights
        if os.path.isfile(instance_sampling_weights_path) and config.sample_tail_instances:
            with open(instance_sampling_weights_path, "rb") as input_file:
                instance_sampling_weights = pickle.load(input_file)
                print('Loaded instance sampling probability weights {}'.format(instance_sampling_weights_path))
            for cat_id, cat_value in instance_sampling_weights.items():
                if cat_id > 0:
                    mapped_id = self.label_map[cat_id]
                    self.instance_sampling_weights[mapped_id] = cat_value
        self.instance_sampling_weights /= self.instance_sampling_weights.sum()

        # Precompute a mapping from ids to categories
        self.id2cat_name = {}
        for id, cat_name in zip(self.VALID_CLASS_IDS, self.CLASS_LABELS):
            self.id2cat_name[id] = cat_name

        # Load the bounding boxes from all instances of the dataset
        bb_path = config.scannet_path + '/' + config.bounding_boxes_path
        if os.path.isfile(bb_path):
            with open(bb_path, 'rb') as f:
                self.bounding_boxes = pickle.load(f)

        # To use instance level augmentation like color or scale shift
        self.instance_augmentation_transform = InstanceAugmentation(config)
        self.aug_color_prob = config.instance_augmentation_color_aug_prob
        self.aug_scale_prob = config.instance_augmentation_scale_aug_prob

        # Calculate head-common-tail ids
        self.head_ids = []
        self.common_ids = []
        self.tail_ids = []
        self.frequency_organized_cats = torch.zeros(self.NUM_LABELS, 3).bool()
        for scannet_id, scannet_cat in zip(self.VALID_CLASS_IDS, self.CLASS_LABELS):
            if scannet_cat in HEAD_CATS_SCANNET_200:
                self.head_ids += [self.label_map[scannet_id]]
                self.frequency_organized_cats[self.label_map[scannet_id], 0] = True
            elif scannet_cat in COMMON_CATS_SCANNET_200:
                self.common_ids += [self.label_map[scannet_id]]
                self.frequency_organized_cats[self.label_map[scannet_id], 1] = True
            elif scannet_cat in TAIL_CATS_SCANNET_200:
                self.tail_ids += [self.label_map[scannet_id]]
                self.frequency_organized_cats[self.label_map[scannet_id], 2] = True

    def add_instances_to_cloud(self, coords, feats, labels, scene_name, transformations):

        if self.config.is_train:
            phase = 'train'
        else:
            phase = 'val'

        coords = coords.astype(int)
        voxel_scale, trans_rot = transformations

        instance_folder = self.config.scannet_path + f'/train/{phase}_instances/'
        num_instances = self.config.num_instances_to_add
        samples = np.random.choice(self.VALID_CLASS_IDS, num_instances, p=self.instance_sampling_weights)
        scene_bbs = self.bounding_boxes[scene_name]

        # Get scene dimensions
        scene_maxes = np.amax(coords, axis=0)
        scene_mins = np.amin(coords, axis=0)
        scene_dims = scene_maxes - scene_mins + 1

        # Create height map of the scene
        height_map = np.zeros((scene_dims[0], scene_dims[1])) + scene_mins[2]
        def calculate_height(coord):
            height_map[coord[0], coord[1]] = max(coord[2], height_map[coord[0], coord[1]])
        mapped_coords = coords - [scene_mins[0], scene_mins[1], 0]
        [calculate_height(coord) for coord in mapped_coords]

        # Apply a max smoothing to the height map to fill holes
        filled_height_map = ndimage.maximum_filter(height_map, size=5)  # magic number with 2cm vx size = 10cm real

        # Add sample
        for sample in samples:
            sample_cat = self.id2cat_name[sample]
            cat_path = instance_folder + sample_cat
            file = cat_path + '/' + random.choice(os.listdir(cat_path))
            inst_coords, inst_feats, inst_labels, instance_ids, _ = self.load_ply_w_path(file, scene_name)

            # Add augmentation with attributes
            if self.config.instance_augmentation is not None:
                inst_labels = np.hstack((inst_labels[:, None], np.zeros_like(inst_labels)[:, None]))  # have it with all zeros, we will augment in latent space after encoding
            if self.config.instance_augmentation == 'raw':
                inst_coords, inst_feats, inst_labels = self.augment_instances(inst_coords, inst_feats, inst_labels, instance_ids) # do the augmentation here

            # Voxelize instance too
            inst_coords, inst_feats, inst_labels, inst_vox_transform = self.voxelizer.voxelize(
                inst_coords, inst_feats, inst_labels)

            # Get instance dimensions
            sample_maxes = np.amax(inst_coords, axis=0)
            sample_mins = np.amin(inst_coords, axis=0)
            sample_dims = sample_maxes - sample_mins + 1

            # Start finding a suitable location
            centroid = np.zeros(3, dtype=int)
            iter_num = 0
            while iter_num < self.config.max_instance_placing_iterations:

                # Add random BB
                random_x = random.randint(scene_mins[0], scene_maxes[0])
                random_y = random.randint(scene_mins[1], scene_maxes[1])
                height = float(filled_height_map[random_x - scene_mins[0], random_y - scene_mins[1]]) + 0  # Add some margin (+20cm)
                centroid = np.array([random_x, random_y, int(height + sample_dims[2] / 2.)])

                random_bb = np.array([centroid - (sample_dims / 2.0), centroid + (sample_dims / 2.0)])

                # Check intersection
                is_intersects = False
                for bb_dict in scene_bbs['instances']:
                    # Load and ransform BB
                    bb = np.copy(bb_dict['bb'])
                    homo_bb = np.hstack((bb, np.ones((bb.shape[0], 1), dtype=coords.dtype)))
                    bb = homo_bb @ voxel_scale.T[:, :3]

                    if box_intersect(bb, random_bb):
                        is_intersects = True
                        break

                if not is_intersects:
                    break

                iter_num += 1

            # Push point cloud to BB location
            inst_coords = inst_coords - np.mean(inst_coords, axis=0).astype(int) + centroid

            # Append new inputs
            coords = np.concatenate((coords, inst_coords))
            feats = np.concatenate((feats, inst_feats))
            labels = np.concatenate((labels, inst_labels))

        # Finally, apply rotation augmentation
        homo_coords = np.hstack((coords, np.ones((coords.shape[0], 1), dtype=coords.dtype)))
        coords_aug = np.floor(homo_coords @ trans_rot.T[:, :3])

        # Quantize again to remove touching points
        _, unique_map = ME.utils.sparse_quantize(coords_aug, return_index=True, ignore_label=self.config.ignore_label)
        coords_aug, feats, labels = coords_aug[unique_map], feats[unique_map], labels[unique_map]

        return coords_aug, feats, labels

    def augment_instances(self, coords, feats, labels, instance_ids=None):

        # To use precomputed inds we can only update the final scene cloud in the ends
        augmented_coords = []
        augmented_feats = []
        augmented_labels = []
        inds_to_remove = []

        scene_scale = np.array([(coords[:, 0].max() - coords[:, 0].min()),
                               (coords[:, 1].max() - coords[:, 1].min()),
                               (coords[:, 2].max() - coords[:, 2].min())])

        scene_cats = np.unique(labels)
        mapped_cats = np.vectorize(lambda x: self.label_map[x])(scene_cats)
        tail_cats = self.frequency_organized_cats[:, 2].cpu().numpy()
        common_cats = self.frequency_organized_cats[:, 1].cpu().numpy()
        pc_indexes = np.arange(coords.shape[0])

        for label_id in mapped_cats:
            # Only do for valid tail categories
            if label_id != self.ignore_mask and tail_cats[label_id]:

                # point inds for certain category
                cat_inds = labels[:, 0] == self.inverse_label_map[label_id]

                # Do this for scene instance augmentation
                if instance_ids is not None:
                    scene_instances = np.unique(instance_ids[cat_inds])
                    for inst in scene_instances:
                        p_inds = cat_inds * (instance_ids == inst)
                        inst_coords, inst_feats, inst_labels = coords[p_inds], feats[p_inds], labels[p_inds]

                        # Shift color with probability
                        if random.random() < self.aug_color_prob:
                            inst_coords, inst_feats, inst_labels = self.instance_augmentation_transform.shift_color(inst_coords, inst_feats, inst_labels)

                        # Shift scale with probability
                        elif random.random() < self.aug_scale_prob:
                            inst_coords, inst_feats, inst_labels = self.instance_augmentation_transform.shift_scale(inst_coords, inst_feats, inst_labels, scene_scale)

                        augmented_coords += [inst_coords]
                        augmented_feats += [inst_feats]
                        augmented_labels += [inst_labels]
                        inds_to_remove += [pc_indexes[p_inds][:, None]]

                else:  # sampled tail inst
                    inst_coords, inst_feats, inst_labels = coords, feats, labels

                    # Shift color with probability
                    if random.random() < self.aug_color_prob:
                        inst_coords, inst_feats, inst_labels = self.instance_augmentation_transform.shift_color(inst_coords, inst_feats, inst_labels)

                    # Shift scale with probability
                    elif random.random() < self.aug_scale_prob:
                        inst_coords, inst_feats, inst_labels = self.instance_augmentation_transform.shift_scale(inst_coords, inst_feats, inst_labels, scene_scale)

                    augmented_coords += [inst_coords]
                    augmented_feats += [inst_feats]
                    augmented_labels += [inst_labels]
                    inds_to_remove += [pc_indexes[:, None]]

        # Augmentation happened, update the clouds
        if len(augmented_coords) > 0:
            augmented_coords = np.vstack(augmented_coords)
            augmented_feats = np.vstack(augmented_feats)
            augmented_labels = np.vstack(augmented_labels)
            inds_to_remove = np.vstack(inds_to_remove).flatten()

            coords = np.delete(coords, inds_to_remove, axis=0)
            feats = np.delete(feats, inds_to_remove, axis=0)
            labels = np.delete(labels, inds_to_remove, axis=0)

            coords = np.vstack((coords, augmented_coords))
            feats = np.vstack((feats, augmented_feats))
            labels = np.vstack((labels, augmented_labels))

        return coords, feats, labels

    def __getitem__(self, index):

        coords, feats, labels, instance_ids, scene_name = self.load_ply(index)
        scene_name = scene_name.split('/')[-1].split('.')[0]

        # Downsample the pointcloud with finer voxel size before transformation for memory and speed
        if self.PREVOXELIZATION_VOXEL_SIZE is not None:
            _, inds = ME.utils.sparse_quantize(coords / self.PREVOXELIZATION_VOXEL_SIZE, return_index=True)
            coords = coords[inds]
            feats = feats[inds]
            labels = labels[inds]

        # Prevoxel transformations
        if self.prevoxel_transform is not None:
            coords, feats, labels = self.prevoxel_transform(coords, feats, labels)

        # Instance based augmentation
        if self.config.instance_augmentation is not None and self.augment_data:
            labels = np.hstack((labels[:, None], np.zeros_like(labels)[:, None]))
            if self.config.instance_augmentation == 'raw':
                coords, feats, labels = self.augment_instances(coords, feats, labels, instance_ids)

        # Add balanced instances
        if self.config.sample_tail_instances and self.augment_data:
            # Don't augment yet, but apply when everything is given
            coords, feats, labels, transformations = self.voxelizer.voxelize(coords, feats, labels, augment=False)
            coords, feats, labels = self.add_instances_to_cloud(coords, feats, labels, scene_name, transformations)
        else:
            # Voxelize as usual
            coords, feats, labels, transformations = self.voxelizer.voxelize(coords, feats, labels)

        # map labels not used for evaluation to ignore_label
        if self.input_transform is not None:
            coords, feats, labels = self.input_transform(coords, feats, labels)
        if self.target_transform is not None:
            coords, feats, labels = self.target_transform(coords, feats, labels)
        if self.IGNORE_LABELS is not None:
            mapper = lambda x: self.label_map[x]
            if labels.ndim == 1:
                labels = np.vectorize(mapper)(labels)
            else:
                labels[:, 0] = np.vectorize(mapper)(labels[:, 0])

        # Use coordinate features if config is set
        if self.AUGMENT_COORDS_TO_FEATS:
            coords, feats, labels = self._augment_coords_to_feats(coords, feats, labels)

        return_args = [coords, feats, labels, scene_name]

        if self.return_transformation:
            return_args.append(transformations[1].astype(np.float32))

        return tuple(return_args)

    def get_output_id(self, iteration):
        return '_'.join(Path(self.data_paths[iteration]).stem.split('_')[:2])

    def get_classids(self):
        return self.VALID_CLASS_IDS

    def get_classnames(self):
        return self.CLASS_LABELS

    def _augment_locfeat(self, pointcloud):
        # Assuming that pointcloud is xyzrgb(...), append location feat.
        pointcloud = np.hstack(
            (pointcloud[:, :6], 100 * np.expand_dims(pointcloud[:, self.LOCFEAT_IDX], 1),
             pointcloud[:, 6:]))
        return pointcloud

    def test_pointcloud(self, pred_dir, num_labels):

        print('Running full pointcloud evaluation.')
        eval_path = os.path.join(pred_dir, 'fulleval')
        os.makedirs(eval_path, exist_ok=True)
        # Join room by their area and room id.
        # Test independently for each room.
        sys.setrecursionlimit(100000)  # Increase recursion limit for k-d tree.
        hist = np.zeros((num_labels, num_labels))
        for i, data_path in enumerate(self.data_paths):
            room_id = self.get_output_id(i)
            pred = np.load(glob.glob(pred_dir + '/*pred*%04d.npy' % i)[0])

            # Scale with voxel size
            pred[:, :3] *= self.voxelizer.voxel_size

            # pred = np.load(os.path.join(pred_dir, 'pred_%04d_%02d.npy' % (i, 0)))

            # save voxelized pointcloud predictions
            save_point_cloud(
                np.hstack((pred[:, :3], np.array([self.SCANNET_COLOR_MAP[i] for i in pred[:, -1]]))),
                f'{eval_path}/{room_id}_voxel.ply',
                verbose=False)

            fullply_f = self.data_root / data_path
            query_pointcloud = read_plyfile(fullply_f)
            query_xyz = query_pointcloud[:, :3]
            query_label = query_pointcloud[:, -1]
            # Run test for each room.
            pred_tree = spatial.KDTree(pred[:, :3], leafsize=500)
            _, result = pred_tree.query(query_xyz)
            ptc_pred = pred[result, 3].astype(int)
            # Save prediciton in txt format for submission.
            np.savetxt(f'{eval_path}/{room_id}.txt', ptc_pred, fmt='%i')
            # Save prediciton in colored pointcloud for visualization.
            save_point_cloud(
                np.hstack((query_xyz, np.array([self.SCANNET_COLOR_MAP[i] for i in ptc_pred]))),
                f'{eval_path}/{room_id}.ply',
                verbose=False)
            # Evaluate IoU.
            if self.IGNORE_LABELS is not None:
                ptc_pred = np.array([self.label_map[x] for x in ptc_pred], dtype=np.int)
                query_label = np.array([self.label_map[x] for x in query_label], dtype=np.int)
            hist += fast_hist(ptc_pred, query_label, num_labels)
        ious = per_class_iu(hist) * 100
        print('mIoU: ' + str(np.nanmean(ious)) + '\n'
                                                 'Class names: ' + ', '.join(self.CLASS_LABELS) + '\n'
                                                                                'IoU: ' + ', '.join(
            np.round(ious, 2).astype(str)))

class ScannetVoxelization2cmDataset(ScannetVoxelizationDataset):
    VOXEL_SIZE = 0.02

class Scannet200VoxelizationDataset(ScannetVoxelizationDataset):
    # Load constants for label ids
    SCANNET_COLOR_MAP = SCANNET_COLOR_MAP_200
    CLASS_LABELS = CLASS_LABELS_200
    VALID_CLASS_IDS = VALID_CLASS_IDS_200

    NUM_LABELS = max(SCANNET_COLOR_MAP_LONG.keys()) + 1
    IGNORE_LABELS = tuple(set(range(NUM_LABELS)) - set(VALID_CLASS_IDS))

class Scannet200Voxelization2cmDataset(Scannet200VoxelizationDataset):
    VOXEL_SIZE = 0.02


from optional import Optional

class ListNode:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next

def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
    if head == None or head.next == None:
        return head
    curr = head
    prev = None
    while curr != None:
        next_Node = curr.next
        curr.next = prev
        prev = curr
        curr = next_Node
    return prev
# Recursive Function.

def reverse_linked_list(head):
    if head is None or head.next is None:
        return head
    new_head = reverse_linked_list(head.next)
    head.next.next = head
    head.next = None
    return new_head


import pandas as pd

class PreProcessor:
    def __init__(self, f, meta_df):
        self.f = f
        self.metadata_df = meta_df
        self.file_to_docs()
        self.processed = self.preprocess()
        self.meta = self.get_meta()

    def file_to_docs(self, num_files=10):
        data = self.f.read()
        doc_split = data.split("____________________________________________________________")
        self.doc_split = doc_split[1:num_files]

    def preprocess(self,):
        ids = []
        processed = {}
        for ix, doc in enumerate(self.doc_split):
            lines = doc.splitlines()
            id = ''
            for ix, line in enumerate(lines):
                id_list = []
                #trim out irrelevant parts of document
                if 'USTC subject classification' in line:
                    processed_chunk = lines[30: ix - 3]
                #get doc_id
                if 'ProQuest document ID' in line:
                    id_list = [s for s in line.split() if s.isdigit()]
                for num in id_list:
                    id += num
            if id != '':
                processed[id] = processed_chunk
                ids.append(id)
        return processed

    def update_meta(self, id):
        meta = {}
        row = self.metadata_df[self.metadata_df['StoreId'] == int(id)]
        attr = ['Title', 'Authors', 'pubdate', 'subjects']
        comp_data = True
        for a in attr:
            val = list(row[a])
            if len(val) != 0:
                meta.update({a: val[0]})
            else:
                comp_data = False
        return meta, comp_data

    def get_meta(self,):
        ids = list(self.processed.keys())
        metadata_dict = {}
        for id in ids:
            meta_dict, comp_data = self.update_meta(id)
            if comp_data:
                metadata_dict[id] = meta_dict
        return metadata_dict


# marks = [30,40,50]
# percantage = (sum(marks)/300)*100

# marks2 = [50, 70, 60, 55]
# percantage2 = ((marks2[0] + marks2[1] + marks2[2] + marks2[3])/400)*100

# print(percantage,percantage2)

def percantage(marks):
    p = ((marks[0] + marks[1] + marks[2] + marks[3])/400)*100
    return p

marks1 = [30, 40, 50, 60]
percantage1 = percantage(marks1)

marks2 = [50, 70, 60, 55]

percantage2 = percantage(marks2)
print(percantage1,percantage2)

def fun():
    print("hello buddy")
kj=fun()


from datetime import datetime

from invian.common.utils import round_to_interval
from invian.services.controller.data.storage.redis import RedisStorage
from invian.services.controller.domains.events.entities import EventEntity

__all__ = ("EventsRepository",)

class EventsRepository:
    def __init__(self, storage: RedisStorage, interval: int) -> None:
        self.__storage = storage
        self.__interval = interval

    async def get_for_period(self, period: datetime) -> list[int]:
        return [int(payload) for payload in await self.__storage.connection.lrange(self.__get_key(period), 0, -1)]

    async def create(self, event: EventEntity) -> None:
        key = self.__get_key(event.datetime)
        await self.__storage.connection.rpush(key, event.payload)
        await self.__storage.connection.expire(key, self.__interval)

    def __get_key(self, period: datetime) -> str:
        return f"events-{int(round_to_interval(period, self.__interval).timestamp())}"


#https://www.acmicpc.net/problem/1011

import math
T=int(input())
for i in range(T):
    line=input().split()
    x=int(line[0])
    y=int(line[1])
    distance=y-x
    cap=math.ceil(distance**0.5)
    if cap*(cap-1)<distance:
        print(2*cap-1)
    else:
        print(2*cap-2)


import time
import copy
import string
import json
import requests, uuid, json

SENTENDPUNCS = ['.', '?', '!']
MAX_CHARS_PER_SUBSEG = 80
SUB_END_BUFFER = 0.5

def get_azure_translator(src, trg, subscription_key, endpoint = "https://api.cognitive.microsofttranslator.com", location = "westeurope"):
    path = '/translate'
    constructed_url = endpoint + path

    if '-' in src:
        src = src.split('-')[0]

    if '-' in trg:
        trg = trg.split('-')[0]

    params = {
        'api-version': '3.0',
        'from': src,
        'to': trg
    }

    headers = {
        'Ocp-Apim-Subscription-Key': subscription_key,
        'Ocp-Apim-Subscription-Region': location,
        'Content-type': 'application/json',
        'X-ClientTraceId': str(uuid.uuid4())
    }

    # request = requests.post(constructed_url, params=params, headers=headers, json=body)
    # response = request.json()

    def translate(string):
        request = requests.post(constructed_url, params=params, headers=headers, json=[{'text': string}])
        response = request.json()
        if request.status_code == 200:
            return response[0]['translations'][0]['text']
        else:
            print("Cannot establish connection to translator")
            print(response)
            return '~'+string+'~'

    return lambda x: translate(x)

def sec_to_srt_timestamp(sec) -> str:
    """Convert seconds to hh:mm:ss timestamp format"""
    ty_res = time.gmtime(sec)
    time_in_ms = sec * 1000
    res = time.strftime("%H:%M:%S", ty_res) + ",%03.0f"%(time_in_ms%1000)
    return res

def speaker_turns_to_srt(speaker_turns, output_path, write_speaker_id=False, txttag='rawtxt'):
    """Creates an SRT subtitle from speaker turn list"""

    out_text = ""
    for i, t in enumerate(speaker_turns):
        if not t.get(txttag):
            continue

        start_time = t['start']

        #subtitles can stay on the screen longer than the actual end timestamp
        next_t = None
        if i+1 < len(speaker_turns):
            next_t = speaker_turns[i+1]

        if next_t and t['end'] + SUB_END_BUFFER < next_t['start']:
            end_time = t['end'] + SUB_END_BUFFER
        elif next_t:
            #end_time = next_t['start']
            end_time = t['end']
        else:
            end_time = t['end'] + SUB_END_BUFFER

        out_text += str(i+1) + '\n'
        out_text += sec_to_srt_timestamp(start_time) + ' --> ' + sec_to_srt_timestamp(end_time) + '\n'

        if write_speaker_id:# and 'speaker' in t:
            out_text += '(' + t['speaker'] + ')' + SPEAKER_DELIMITER + " "

        out_text += t[txttag]
        out_text += '\n\n'

    with open(output_path, 'w', encoding='utf8') as f:
        f.write(out_text)

def get_sentend_pos(string):
    return [pos for pos, word in enumerate(string.split()) if word[-1] in SENTENDPUNCS]

def fix_word_offsets(wt, fix_by_sec):
    fixed = copy.deepcopy(wt)
    for w in fixed:
        newval = int(w['Offset'] - fix_by_sec * 10000000)
        w['Offset'] = newval
    return fixed

def optimal_split_text(text, max_char):
    split_segments = []
    current_segment = ""
    tokens = text.split()
    for w in tokens:
        if w[-1] in string.punctuation and len(current_segment + " " + w) > max_char*0.7:
            current_segment += w
            split_segments.append(current_segment)
            current_segment = ""
        elif len(current_segment + " " + w) < max_char:
            current_segment += w + " "
            continue
        else:
            split_segments.append(current_segment[:-1])
            current_segment = w + " "
    if current_segment:
        split_segments.append(current_segment)
    return split_segments

def split_long_turn(turn, texttag, max_chars=MAX_CHARS_PER_SUBSEG, debug=False):
    newturns = []
    if debug: print("split_long_turn:", texttag, turn[texttag])
    text_segments = optimal_split_text(turn[texttag], max_chars)
    if debug: print("split_long_turn:text_segments", text_segments)
    fullcharlen=len(turn[texttag])
    start = turn['start']
    at_token = 0
    for seg in text_segments:
        if debug: print(">>", seg)
        no_tokens = len(seg.split())
        segcharlen = len(seg)
        duration = turn['end'] - turn['start']
        ratio = segcharlen / fullcharlen

        respective_duration = duration * segcharlen / fullcharlen
        end = start + respective_duration
        end_token = at_token+no_tokens

    #     fix_by_sec = 0 #TODO if necessary
    #     wordtiming = fix_word_offsets(turn['wordtiming'][at_token:end_token], fix_by_sec)

        splitturn = {'start': start,
                     'end': start + respective_duration,
                     'speaker': turn['speaker']}

        splitturn[texttag] = seg

        if debug: print(">>", splitturn['start'], splitturn['end'])

        start = end
        at_token = end_token

        newturns.append(splitturn)
    return newturns

def segment_turns(turns, max_chars=MAX_CHARS_PER_SUBSEG, translator_func=None, debug=False):
    sentturns = []
    sentturns_translated = []
    for turn in turns:
        turnstart = turn['start']
        if debug: print(">>>", turnstart)
        if debug: print(turn['puncdtext'])
        sentends = get_sentend_pos(turn['puncdtext'])
        if debug: print(sentends)
        prevsentendindex = 0
        for sentendindex in sentends:
            if debug: print("from", prevsentendindex, "to", sentendindex)
            puncdtext = ' '.join(turn['puncdtext'].split()[prevsentendindex:sentendindex+1])
            rawtext = ' '.join(turn['rawtext'].split()[prevsentendindex:sentendindex+1])

            sentstart = turnstart + turn['wordtiming'][prevsentendindex]['Offset']/10000000
            sentend = turnstart + turn['wordtiming'][sentendindex]['Offset']/10000000 + turn['wordtiming'][sentendindex]['Duration']/10000000

            fix_by_sec = sentstart - turnstart
            wordtiming = fix_word_offsets(turn['wordtiming'][prevsentendindex:sentendindex+1], fix_by_sec)
            #wordtiming = turn['wordtiming'][prevsentendindex:sentendindex+1]

            sentturn = {'start': sentstart,
                 'end': sentend,
                 'speaker': turn['speaker'],
                 'toolong':None,
                 'rawtext': rawtext,
                 'puncdtext': puncdtext,
                 'wordtiming': wordtiming }

            if debug: print(sentturn['start'], sentturn['end'])
            if debug: print(sentturn['puncdtext'])

            if translator_func:
                translated = translator_func(puncdtext)

                sentturn['translated'] = translated
                if debug: print(sentturn['translated'])

                sentturns_translated.extend(split_long_turn(sentturn, 'translated', max_chars, debug))

            sentturns.extend(split_long_turn(sentturn, 'puncdtext', max_chars))

            prevsentendindex = sentendindex+1
            if debug: print()
    return sentturns, sentturns_translated


import torch
import albumentations
from PIL import Image
import numpy as np

class Shopee_Dataset:
    def __init__(self, img_paths, labels=None, augmentations=None):
        self.img_paths = img_paths
        self.labels = labels
        self.augmentations = augmentations

    def __len__(self):
        return len(self.img_paths)

    def __getitem__(self, idx):
        img_path = self.img_paths[idx]
        if self.labels is not None:
            label = self.labels[idx]

        image = Image.open(img_path)
        image = np.array(image)

        # Image augmentations
        if self.augmentations is not None:
            augmented = self.augmentations(image=image)
            image = augmented["image"]

        image = np.transpose(image, (2, 0, 1)).astype(np.float32)
        return (
            {
                "image": torch.tensor(image, dtype=torch.float),
                "label": torch.tensor(label, dtype=torch.long),
            }
            if label is not None
            else {
                "image": torch.tensor(image, dtype=torch.float),
                "label": torch.tensor(-1),
            }
        )


import os
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
import gol
import logging

from config import setup_config
from dataset.dataset import BaseDataset
from dataset.sampler import MetaTaskSampler
from torchvision import transforms
from model.registry import MODEL, FINETUNING
from model.finetune.dara_finetuning import DaraFinetuning
from utils import PerformanceMeter, TqdmHandler, AverageMeter, accuracy

class Tester(object):
    """Test a model from a config which could be a training config.
    """

    def __init__(self):
        self.config = setup_config()
        self.report_one_line = True
        self.logger = self.get_logger()
        self.set_gol()

        # set device. `config.experiment.cuda` should be a list of gpu device ids, None or [] for cpu only.
        self.device = self.config.experiment.cuda if isinstance(self.config.experiment.cuda, list) else []
        if len(self.device) > 0:
            os.environ['CUDA_VISIBLE_DEVICES'] = ','.join([str(i) for i in self.device])
            self.logger.info(f'Using GPU: {self.device}')
        else:
            self.logger.info(f'Using CPU!')

        # build dataloader and model
        self.transformer = self.get_transformer(self.config.dataset.transformer)
        self.collate_fn = self.get_collate_fn()
        self.dataset = self.get_dataset(self.config.dataset)
        self.dataloader = self.get_dataloader(self.config.dataset)
        self.logger.info(f'Building model {self.config.model.name} ...')
        self.model = self.get_model(self.config.model)
        self.model = self.to_device(self.model, parallel=True)
        self.logger.info(f'Building model {self.config.model.name} OK!')
        self.finetuning = self.get_finetuning(self.config)

        # build meters
        self.performance_meters = self.get_performance_meters()
        self.average_meters = self.get_average_meters()

    def set_gol(self):
        gol._init()
        gol.set_value('is_ft', False)
        gol.set_value('use_transform', self.config.model.use_transform)

    def get_logger(self):
        logger = logging.getLogger()
        logger.handlers = []
        logger.setLevel(logging.INFO)

        screen_handler = TqdmHandler()
        screen_handler.setFormatter(logging.Formatter('[%(asctime)s] %(message)s'))
        logger.addHandler(screen_handler)
        return logger

    def get_performance_meters(self):
        return {
            metric: PerformanceMeter() for metric in ['acc']
        }

    def get_average_meters(self):
        return {
            meter: AverageMeter() for meter in ['acc']
        }

    def get_model(self, config):
        """Build model in config
        """
        name = config.name
        model = MODEL.get(name)(config)
        return model

    def load_model(self, config):
        """Load model in config
        """
        assert 'load' in config and config.load != '', 'There is no valid `load` in config[model.load]!'
        state_dict = torch.load(config.load, map_location='cpu')
        state_dict.pop('cat_mat')
        self.model.load_state_dict(state_dict, strict=False)

    def get_finetuning(self, config):
        """Get finetuning method
        """
        name = config.model.finetuning
        finetuning = FINETUNING.get(name)(config.dataset, self.model)
        return finetuning

    def get_transformer(self, config):
        return transforms.Compose([
            transforms.Resize(size=config.resize_size),
            transforms.CenterCrop(size=config.image_size),
            transforms.ToTensor(),
            transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
        ])

    def get_collate_fn(self):
        return None

    def get_dataset(self, config):
        path = os.path.join(config.meta_dir, 'test.txt')
        return BaseDataset(config.root_dir, path, transform=self.transformer)

    def get_dataloader(self, config):
        way = config.way
        shot = config.shot
        trial = config.trail
        return DataLoader(self.dataset, batch_sampler=MetaTaskSampler(self.dataset, way=way, shot=shot, trial=trial),
                          num_workers=config.num_workers, pin_memory=False)

    def to_device(self, m, parallel=False):
        if len(self.device) == 0:
            m = m.to('cpu')
        elif len(self.device) == 1 or not parallel:
            m = m.to(f'cuda:{self.device[0]}')
        else:
            m = m.cuda(self.device[0])
            m = torch.nn.DataParallel(m, device_ids=self.device)
        return m

    def get_model_module(self, model=None):
        """get `model` in single-gpu mode or `model.module` in multi-gpu mode.
        """
        if model is None:
            model = self.model
        if isinstance(model, torch.nn.DataParallel):
            return model.module
        else:
            return model

    def test(self):
        self.logger.info(f'Testing model from {self.config.model.load}')
        self.validate()
        self.performance_meters['acc'].update(self.average_meters['acc'].avg)
        self.report()

    def validate(self):
        val_bar = tqdm(self.dataloader, ncols=100, total=self.config.dataset.trail)
        for data in val_bar:
            self.task_validate(data)
            val_bar.set_description(f'Testing')
            val_bar.set_postfix(acc=self.average_meters['acc'].avg)

    def task_validate(self, data):
        self.load_model(self.config.model)
        images, labels = self.to_device(data['img']), self.to_device(data['label'])

        self.finetuning.meta_finetuning(images, self.config.finetuning.epoch)

        way = self.config.dataset.way
        shot = self.config.dataset.shot
        query_shot = self.config.dataset.query_shot

        query = images[way*shot:]
        target = torch.LongTensor([i // query_shot for i in range(query_shot * way)]).cuda()

        with torch.no_grad():
            logits = self.model(query)
            acc = accuracy(logits, target, 1)
            self.average_meters['acc'].update(acc, query.size(0))

    def report(self):
        metric_str = '  '.join([f'{metric}: {self.performance_meters[metric].current_value:.2f}'
                                for metric in self.performance_meters])
        self.logger.info(metric_str)

if __name__ == '__main__':
    tester = Tester()
    tester.test()


"""empty message

Revision ID: d6366ab8ecee
Revises:
Create Date: 2021-10-15 19:11:59.105088

"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils

# revision identifiers, used by Alembic.
revision = 'd6366ab8ecee'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('category',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(), nullable=True),
    sa.Column('slug', sa.String(), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('slug')
    )
    op.create_index(op.f('ix_category_id'), 'category', ['id'], unique=False)
    op.create_table('product',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(), nullable=True),
    sa.Column('description', sa.Text(), nullable=True),
    sa.Column('url', sqlalchemy_utils.types.url.URLType(), nullable=True),
    sa.Column('price', sa.DECIMAL(scale=2), nullable=True),
    sa.Column('available', sa.Boolean(), nullable=True),
    sa.Column('create_date', sa.Date(), nullable=True),
    sa.Column('updated_date', sa.DateTime(), nullable=True),
    sa.Column('slug', sa.String(), nullable=True),
    sa.Column('category_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['category_id'], ['category.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('slug')
    )
    op.create_index(op.f('ix_product_id'), 'product', ['id'], unique=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_product_id'), table_name='product')
    op.drop_table('product')
    op.drop_index(op.f('ix_category_id'), table_name='category')
    op.drop_table('category')
    # ### end Alembic commands ###