"""Unit tests for the affine connections."""

import pytest

import geomstats.backend as gs
import geomstats.tests
from geomstats.geometry.connection import Connection
from geomstats.geometry.euclidean import EuclideanMetric
from geomstats.geometry.hypersphere import Hypersphere
from geomstats.geometry.special_orthogonal import SpecialOrthogonal
from tests.conftest import Parametrizer, TestCase
from tests.data_generation import TestData

class TestConnection(TestCase, metaclass=Parametrizer):
    class ConnectionTestData(TestData):
        def metric_matrix_test_data(self):
            smoke_data = [
                dict(
                    metric=EuclideanMetric(dim=4),
                    point=gs.array([0.0, 1.0, 0.0, 0.0]),
                    expected=gs.eye(4),
                )
            ]
            return self.generate_tests(smoke_data)

        def parallel_transport_test_data(self):
            smoke_data = [dict(dim=2, n_sample=2)]
            return self.generate_tests(smoke_data)

        def parallel_transport_trajectory_test_data(self):
            smoke_data = [dict(dim=2, n_sample=2)]
            return self.generate_tests(smoke_data)

        def exp_connection_metric_test_data(self):
            smoke_data = [
                dict(
                    dim=2,
                    tangent_vec=gs.array([[0.25, 0.5], [0.30, 0.2]]),
                    point=gs.array([[gs.pi / 2, 0], [gs.pi / 6, gs.pi / 4]]),
                ),
                dict(
                    dim=2,
                    tangent_vec=gs.array([0.25, 0.5]),
                    point=gs.array([gs.pi / 2, 0]),
                ),
            ]
            return self.generate_tests(smoke_data)

        def log_connection_metric_test_data(self):
            smoke_data = [
                dict(
                    dim=2,
                    point=gs.array([1.0, gs.pi / 2]),
                    base_point=gs.array([gs.pi / 3, gs.pi / 4]),
                ),
                dict(
                    dim=2,
                    point=gs.array([[1.0, gs.pi / 2], [gs.pi / 6, gs.pi / 3]]),
                    base_point=gs.array(
                        [[gs.pi / 3, gs.pi / 4], [gs.pi / 2, gs.pi / 4]]
                    ),
                ),
            ]
            return self.generate_tests(smoke_data)

        def geodesic_and_coincides_exp_test_data(self):
            smoke_data = [
                dict(
                    space=Hypersphere(2),
                    n_geodesic_points=10,
                    vec=gs.array([[2.0, 0.0, -1.0]] * 2),
                ),
                dict(
                    space=SpecialOrthogonal(n=4),
                    n_geodesic_points=10,
                    vec=gs.random.rand(2, 4, 4),
                ),
            ]
            return self.generate_tests(smoke_data)

        def geodesic_invalid_initial_conditions_test_data(self):
            smoke_data = [dict(space=SpecialOrthogonal(n=4))]
            return self.generate_tests(smoke_data)

        def geodesic_test_data(self):
            smoke_data = [dict(space=Hypersphere(2))]
            return self.generate_tests(smoke_data)

        def ladder_alpha_test_data(self):
            smoke_data = [dict(dim=2, n_samples=2)]
            return self.generate_tests(smoke_data)

    testing_data = ConnectionTestData()

    def test_metric_matrix(self, metric, point, expected):
        self.assertAllClose(metric.metric_matrix(point), expected)

    def test_parallel_transport(self, dim, n_samples):
        sphere = Hypersphere(dim)
        base_point = sphere.random_uniform(n_samples)
        tan_vec_a = sphere.to_tangent(gs.random.rand(n_samples, 3), base_point)
        tan_vec_b = sphere.to_tangent(gs.random.rand(n_samples, 3), base_point)
        expected = sphere.metric.parallel_transport(tan_vec_a, base_point, tan_vec_b)
        expected_point = sphere.metric.exp(tan_vec_b, base_point)
        base_point = gs.cast(base_point, gs.float64)
        base_point, tan_vec_a, tan_vec_b = gs.convert_to_wider_dtype(
            [base_point, tan_vec_a, tan_vec_b]
        )
        for step, alpha in zip(["pole", "schild"], [1, 2]):
            min_n = 1 if step == "pole" else 50
            tol = 1e-5 if step == "pole" else 1e-2
            for n_rungs in [min_n, 11]:
                ladder = sphere.metric.ladder_parallel_transport(
                    tan_vec_a,
                    base_point,
                    tan_vec_b,
                    n_rungs=n_rungs,
                    scheme=step,
                    alpha=alpha,
                )
                result = ladder["transported_tangent_vec"]
                result_point = ladder["end_point"]
                self.assertAllClose(result, expected, rtol=tol, atol=tol)
                self.assertAllClose(result_point, expected_point)

    def test_parallel_transport_trajectory(self, dim, n_samples):
        sphere = Hypersphere(dim)
        for step in ["pole", "schild"]:
            n_steps = 1 if step == "pole" else 50
            tol = 1e-6 if step == "pole" else 1e-2
            base_point = sphere.random_uniform(n_samples)
            tan_vec_a = sphere.to_tangent(gs.random.rand(n_samples, 3), base_point)
            tan_vec_b = sphere.to_tangent(gs.random.rand(n_samples, 3), base_point)
            expected = sphere.metric.parallel_transport(
                tan_vec_a, base_point, tan_vec_b
            )
            expected_point = sphere.metric.exp(tan_vec_b, base_point)
            ladder = sphere.metric.ladder_parallel_transport(
                tan_vec_a,
                base_point,
                tan_vec_b,
                n_rungs=n_steps,
                scheme=step,
                return_geodesics=True,
            )
            result = ladder["transported_tangent_vec"]
            result_point = ladder["end_point"]

            self.assertAllClose(result, expected, rtol=tol, atol=tol)
            self.assertAllClose(result_point, expected_point)

    def test_ladder_alpha(self, dim, n_samples):
        sphere = Hypersphere(dim)
        base_point = sphere.random_uniform(n_samples)
        tan_vec_a = sphere.to_tangent(gs.random.rand(n_samples, 3), base_point)
        tan_vec_b = sphere.to_tangent(gs.random.rand(n_samples, 3), base_point)

        with pytest.raises(ValueError):
            sphere.metric.ladder_parallel_transport(
                tan_vec_a,
                base_point,
                tan_vec_b,
                n_rungs=1,
                scheme="pole",
                alpha=0.5,
                return_geodesics=False,
            )

    def test_exp_connection_metric(self, dim, tangent_vec, base_point):
        sphere = Hypersphere(dim)
        connection = Connection(dim)
        point_ext = sphere.spherical_to_extrinsic(base_point)
        vector_ext = sphere.tangent_spherical_to_extrinsic(tangent_vec, base_point)
        connection.christoffels = sphere.metric.christoffels
        expected = sphere.metric.exp(vector_ext, point_ext)
        result_spherical = connection.exp(
            tangent_vec, base_point, n_steps=50, step="rk4"
        )
        result = sphere.spherical_to_extrinsic(result_spherical)

        self.assertAllClose(result, expected)

    @geomstats.tests.autograd_tf_and_torch_only
    def test_log_connection_metric(self, dim, point, base_point):
        sphere = Hypersphere(dim)
        connection = Connection(dim)
        connection.christoffels = sphere.metric.christoffels
        vector = connection.log(
            point=point, base_point=base_point, n_steps=75, step="rk4", tol=1e-10
        )
        result = sphere.tangent_spherical_to_extrinsic(vector, base_point)
        p_ext = sphere.spherical_to_extrinsic(base_point)
        q_ext = sphere.spherical_to_extrinsic(point)
        expected = sphere.metric.log(base_point=p_ext, point=q_ext)

        self.assertAllClose(result, expected, atol=1e-6)

    def test_geodesic_and_coincides_exp(self, space, n_geodesic_points, vector):
        initial_point = space.random_uniform(2)
        initial_tangent_vec = space.to_tangent(vector=vector, base_point=initial_point)
        geodesic = space.metric.geodesic(
            initial_point=initial_point, initial_tangent_vec=initial_tangent_vec
        )
        t = gs.linspace(start=0.0, stop=1.0, num=n_geodesic_points)
        points = geodesic(t)
        result = points[:, -1]
        expected = space.metric.exp(initial_tangent_vec, initial_point)
        self.assertAllClose(result, expected)

        initial_point = initial_point[0]
        initial_tangent_vec = initial_tangent_vec[0]
        geodesic = space.metric.geodesic(
            initial_point=initial_point, initial_tangent_vec=initial_tangent_vec
        )
        points = geodesic(t)
        result = points[-1]
        expected = space.metric.exp(initial_tangent_vec, initial_point)
        self.assertAllClose(expected, result)

    def test_geodesic_invalid_initial_conditions(self, space):
        initial_point = space.random_uniform(2)
        vector = gs.random.rand(2, 4, 4)
        initial_tangent_vec = space.to_tangent(vector=vector, base_point=initial_point)
        end_point = space.random_uniform(2)
        with pytest.raises(RuntimeError):
            space.bi_invariant_metric.geodesic(
                initial_point=initial_point,
                initial_tangent_vec=initial_tangent_vec,
                end_point=end_point,
            )

    def test_geodesic(self, space):
        metric = space.metric
        initial_point = space.random_uniform(2)
        vector = gs.random.rand(2, 3)
        initial_tangent_vec = space.to_tangent(vector=vector, base_point=initial_point)
        end_point = space.random_uniform(2)
        time = gs.linspace(0, 1, 10)

        geo = metric.geodesic(initial_point, initial_tangent_vec)
        path = geo(time)
        result = path.shape
        expected = (2, 10, 3)
        self.assertAllClose(result, expected)

        geo = metric.geodesic(initial_point, end_point=end_point)
        path = geo(time)
        result = path.shape
        expected = (2, 10, 3)
        self.assertAllClose(result, expected)

        geo = metric.geodesic(initial_point, end_point=end_point[0])
        path = geo(time)
        result = path.shape
        expected = (2, 10, 3)
        self.assertAllClose(result, expected)

        initial_tangent_vec = space.to_tangent(
            vector=vector, base_point=initial_point[0]
        )
        geo = metric.geodesic(initial_point[0], initial_tangent_vec)
        path = geo(time)
        result = path.shape
        expected = (2, 10, 3)
        self.assertAllClose(result, expected)


import threading

from .fifo import BytesFIFO

class ThreadsafeBytesFIFO(BytesFIFO):
    """
    A thread-safe FIFO that can store a fixed number of bytes.
    """
    def __init__(self, init_size):
        """ Create a FIFO of ``init_size`` bytes. """
        super().__init__(init_size)
        self.lock = threading.Lock()

    def read(self, size=-1):
        """
        Read at most ``size`` bytes from the FIFO.

        If less than ``size`` bytes are available, or ``size`` is negative,
        return all remaining bytes.
        """
        self.lock.acquire()

        ret = super().read(size=size)

        self.lock.release()
        return ret

    def write(self, data):
        """
        Write as many bytes of ``data`` as are free in the FIFO.

        If less than ``len(data)`` bytes are free, write as many as can be written.
        Returns the number of bytes written.
        """
        self.lock.acquire()

        ret = super().write(data)

        self.lock.release()
        return ret

    def free(self):
        """ Return the number of bytes that can be written to the FIFO. """
        self.lock.acquire()

        size = super().free()

        self.lock.release()
        return size

    def resize(self, new_size):
        """
        Resize FIFO to contain ``new_size`` bytes. If FIFO currently has
        more than ``new_size`` bytes filled, :exc:`ValueError` is raised.
        If ``new_size`` is less than 1, :exc:`ValueError` is raised.

        If ``new_size`` is smaller than the current size, the internal
        buffer is not contracted (yet).
        """
        self.lock.acquire()

        super().resize(new_size)

        self.lock.release()


"""Tester module for TimeDecay"""

__author__ = 'Andrea Tacchetti - atacchet@room77.com - Contact: kyle@'
__copyright__ = '2013, Room77, Inc'

import datetime
import unittest

from pylib.util.time_decay import (TimeDecay, TimeStampInTheFutureError)

class TimeDecayTest(unittest.TestCase):

  def test_basic(self):
    x = 10.0
    timestamp = datetime.datetime(2013,2,27)
    today = datetime.datetime.utcnow()
    td = TimeDecay(datetime.timedelta(30))
    (new_timestamp, y) = td.update_value((timestamp, x))
    self.assertTrue(y < x)
    self.assertEqual(new_timestamp.hour, today.hour)
    self.assertEqual(new_timestamp.minute, today.minute)
    self.assertEqual(new_timestamp.second, today.second)

  def test_half_life(self):
    x = 10.0
    timestamp = datetime.datetime.utcnow()- datetime.timedelta(days=15)
    td = TimeDecay(decay_time=datetime.timedelta(15))
    (new_timestamp, y) = td.update_value((timestamp, x))
    self.assertAlmostEqual(y, 5.0)

  def test_future(self):
    x = 10.0
    timestamp = datetime.datetime.utcnow() + datetime.timedelta(days=1)
    td = TimeDecay(decay_time=datetime.timedelta(30))
    self.assertRaises(TimeStampInTheFutureError, td.update_value, (timestamp,x))

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


import pygame

screen=pygame.display.set_mode((800,600))
pygame.display.set_caption('Game')
running=True
while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
    for n in range(255):
        pygame.draw.rect(screen, (n,255,255),((n,n),(255,255)))
        pygame.draw.rect(screen,(255,n,255),((n,n),(n,n)))
    pygame.display.update()
pygame.quit()


from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import sys
import glob
import matplotlib.gridspec as gridspec
from mpl_toolkits.mplot3d import Axes3D
import os

d = 3

#Set up plotting environment
if (d == 3):
    fig = plt.figure(figsize=(10,10))
    ax1 = plt.subplot2grid((1,1), (0,0),projection='3d')
elif  (d == 2):
    fig = plt.figure(figsize=(20,10))
    ax1 = plt.subplot2grid((1,2), (0,0))
    ax2 = plt.subplot2grid((1,2), (0,1))

#Load data

#path = os.environ['IliadDir']
#data = np.loadtxt(path + 'MPDFormatData.txt')

#Load example data
data = np.loadtxt('../example_data/ExampleFormattedData.txt')

r = data[:,0]
theta = data[:,1]
phi = data[:,2]
a = data[0,3]

mm = np.sqrt(r**2 + a**2)
x = mm * np.sin(theta)*np.cos(phi)
y = mm * np.sin(theta)*np.sin(phi)
z = r  * np.cos(theta)

#Plot it

if (d == 3):
    ax1.plot(x,y,z)
    limit = max(max(x),max(y),max(z))
    ax1.set_xlim(-limit,+limit)
    ax1.set_ylim(-limit,+limit)
    ax1.set_zlim(-limit,+limit)

if (d == 2):
    ax1.plot(x,y)
    ax2.plot(x,z)

plt.rc('text', usetex=True)
plt.rc('font', family='serif')
fs = 20

plt.show()


import os
import sys
import traceback
from termcolor import cprint
from functools import wraps

def unwrap(func):
    while hasattr(func, '__wrapped__'):
        func = func.__wrapped__
    return func

def watch(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print('\n')
        func_name_stdout = f'{func.__code__.co_filename} -> {func.__name__}: Line number {func.__code__.co_firstlineno}'
        cprint(func_name_stdout, 'blue', 'on_white')

        args_stdout = ""
        if args:
            args_stdout += f"args: {args}"
        if kwargs:
            args_stdout += f"kwargs: {kwargs}"
        if args_stdout:
            cprint(args_stdout, 'blue', 'on_white')

        response = None
        try:
            response = func(*args, **kwargs)
        except Exception as e:
            traceback.print_exc()

        return response
    return wrapper


#! /usr/bin/env python
##
import requests
import re
import time
import pickle
import logging
import sys

from telegram.ext import Updater, CommandHandler
from telegram.bot import Bot

ADMIN_USERNAME = 'USERNAME_WITHOUT_@'
BOT_TOKEN = 'FULLTOKENHEREPLS'

bot_help_message = '''\
/subscribe yes - Subscribes to GCTF Scoreboard.
/subscribe no - Unsubscribes to GCTF Scoreboard.'''

logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.INFO)

def save_scoreboard(scoreboard):
    with open('scoreboard.txt', 'w') as file:
        pickle.dump(scoreboard, file)

def load_scoreboard():
    try:
        with open('scoreboard.txt', 'r') as file:
            scoreboard = pickle.load(file)
            return scoreboard
    except IOError:
        return set()

def load_subscribers():
    try:
        with open('subscribers.txt', 'r') as file:
            return pickle.load(file)
    except IOError:
        return set()

bot = Bot(token=BOT_TOKEN)
updater = Updater(bot=bot)
subscribers = load_subscribers()

def send_subscribe(bot, update, args):
    if len(args) > 0:
        if args[0] == 'yes':
            subscribers.add(update.message.chat_id)
            bot.sendMessage(chat_id=update.message.chat_id, text="You've been subscribed to GCTF's Scoreboard.")
            print("%s has subscribed to GCTF Scoreboard." % update.message.chat_id)
        elif args[0] == 'no':
            subscribers.remove(update.message.chat_id)
            bot.sendMessage(chat_id=update.message.chat_id, text="You've been unsubscribed from GCTF's Scoreboard.")
            print("%s has unsubscribed from GCTF Scoreboard." % update.message.chat_id)
        elif args[0] == 'list' and update.message.from_user.username == 'LFlare':
            message = ''
            for subscriber in subscribers:
                message += str(subscriber) + '\n'
            bot.sendMessage(chat_id=update.message.chat_id, text=message)
        elif args[0] == 'unsub' and update.message.from_user.username == 'LFlare':
            remove_id = int(args[1])
            try:
                subscribers.remove(remove_id)
                bot.sendMessage(chat_id=update.message.chat_id, text='%d has been removed!' % remove_id)
            except KeyError:
                bot.sendMessage(chat_id=update.message.chat_id, text='%d cannot be found!' % remove_id)
    else:
        bot.sendMessage(chat_id=update.message.chat_id, text=bot_help_message)
    print(args)

    with open('subscribers.txt', 'w') as file:
        pickle.dump(subscribers, file)

def send_scoreboard(bot, update):
    print('Sending scoreboard to %s' % update.message.chat_id)
    telegram_message = ""
    for placing in sorted(scoreboard):
        telegram_message += '%d - %s - %d' % (placing[0], placing[1], placing[2]) + "\n"
    bot.send_message(chat_id=update.message.chat_id, text=telegram_message)
    print('Sent.')

def send_ping(bot, update):
    print('Replying pong to %s' % update.message.chat_id)
    bot.send_message(chat_id=update.message.chat_id, text="pong")
    print('Replied')

def compare_scoreboards(a, b):
    difference = a ^ b

    if len(difference) != 0:
        return True
    return False

updater.dispatcher.add_handler(CommandHandler('subscribe', send_subscribe, pass_args=True))
updater.dispatcher.add_handler(CommandHandler('scoreboard', send_scoreboard))
updater.dispatcher.add_handler(CommandHandler('ping', send_ping))
updater.start_polling()

while True:
    print('\nRetrieving scoreboard...')
    data = requests.get('https://www.spgame.site/scoreboard').text
    data = re.findall('(?s)(?:
)(.*)(?:
)', data)[0].split('\n')

    newscoreboard = set()
    for line in data:
        try:
            place = int(re.findall('(?:
)([0-9]+)', line)[0])
            name = str(re.findall('([a-zA-Z0-9\s/|!]+)', line)[0])
            score = int(re.findall('(?:	)([0-9]+)(?:	)', line)[0])
            team = (place, name, score)
            newscoreboard.add(team)
        except IndexError:
            pass

    scoreboard = load_scoreboard()
    if compare_scoreboards(newscoreboard, scoreboard):
        print('Change detected!')

        telegram_message = ''
        for placing in sorted(scoreboard - newscoreboard):
            telegram_message += '%d - %s - %d' % (placing[0], placing[1], placing[2]) + "\n"
        telegram_message += '=+=+=\n'
        for placing in sorted(newscoreboard - scoreboard):
            telegram_message += '%d - %s - %d' % (placing[0], placing[1], placing[2]) + "\n"

        for subscriber in subscribers:
            bot.send_message(chat_id=subscriber, text=telegram_message)

        save_scoreboard(newscoreboard)
    else:
        print(list(newscoreboard - scoreboard))

    try:
        for i in range(5):
            sys.stdout.write('\rSleeping... %d_' % (5 - i))
            sys.stdout.flush()
            time.sleep(1)
    except KeyboardInterrupt:
        continue


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 19 16:19:24 2016

@author: alec
"""

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

import load_scan as lscan
import plotting.format_plots_tkagg as fp
import cwesr_plot_single_fit as cpsf

scannum = 1597

scan_params_path = '/Users/alec/UCSB/cofeb_analysis_data/ta/'+str(scannum)+'/scan_parameters.json'
with open(scan_params_path, 'r') as fread:
    scan_params = json.load(fread)

fileName = scan_params['fileName']
numAvg = scan_params['numAvg']
startFileNum = scan_params['startFileNum']
res = scan_params['xres']

scanFolder = '/Users/alec/UCSB/scan_data/'
dataPath = scanFolder+str(scannum)+'-esrdata/'+fileName

def plot_point_fit(event):
    if event.dblclick:
        xp = int(np.round(event.xdata))
        yp = int(np.round(event.ydata))
        filenum = yp*res*2 + xp + startFileNum
        filePath = dataPath+str(filenum).zfill(6)+'_'+str(numAvg)+'.txt'
        cpsf.cwesr_plot_single_fit(filePath,filenum)
        print(filenum)

data = lscan.load_ff(scanFolder+str(scannum)+'-esrdata/fitdata.txt',res,res,fieldangle=True,
                     printNVCalcError=True)

plt.close('all')

fig, ax = plt.subplots()
im = plt.imshow(data[0])
cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
fp.format_plot(plt,fwidth=500,fheight=550)
plt.show()

cid = fig.canvas.mpl_connect('button_press_event', plot_point_fit)


# Pylot: mfrankie Maja

FILE = 'data/scrabblewords.txt'
FILE2 = 'data/some_output.txt'

# We will always use a 'with' statement for opening files.
# That's an example of a so-called 'context manager'.

def read_and_print_lines(n_max=10):
    """Read the first n lines from FILE  and print them out."""

    with open(FILE, 'r') as fdin:
        # The 'fdin' is of type FileObject.
        # It has several methods, and you can simply iterate over it like a list.
        n = 0

        with open(FILE2, 'a') as fdout:

            for line in fdin:
                n += 1
                line = line.strip()
                if line:
                    print(line, file=fdout)
                if n == n_max:
                    break

read_and_print_lines(100)


# -*- coding：utf-8 -*-
import pytest
import allure
#单元自动化测试脚本
@allure.feature("这是加法的计算器，加数{0}与加数{1}相加功能")
def add_caculator(num1,num2):
    sum=num1+num2
    return sum
@allure.feature("加法的计算器测试")
@allure.description("这是加法的计算器，测试加法的各种情况是否正确")
@allure.severity("critical")
@allure.story("正确的测试用例")
@allure.issue("http://59.110.52.156:8081/zentao/my-bug.html","曾经的bug")
@allure.testcase("http://59.110.52.156:8081/zentao/my-testtask.html","这是加法测试用例")
@pytest.mark.parametrize("num1,num2,result",[[1,2,3],[2,3,5],[5,5,10],[6,2,8]],ids=["10以内","10以外","负数","小数"])
def test_coculator(num1,num2,result):
    with allure.step("第一步：调用加法方法"):
        sum=add_caculator(num1,num2)
    with allure.step("第二步：断言加法运算结果与预期结果是否一致"):
        assert  sum==num1+num2

@allure.description("这是加法的计算器，测试加法的各种无效是否正确")
@allure.severity("normal")
@allure.story("无效的测试用例")
@allure.testcase("http://59.110.52.156:8081/zentao/my-testtask.html")
@pytest.mark.parametrize("num1,num2,result", [[1, '2', 3], [2, '', 5], [-5, '#@wg.,,,,,', -1], [6, 'root', 8]],
                             ids=["字符串数字", "空格", "特殊字符", "字母"])
def test_add_caculator_error(num1,num2,result):
    with allure.step("如果错误截图"):
        allure.attach.file("1.png",
                           attachment_type=allure.attachment_type.PNG)
    with allure.step("html网页的漂亮"):
        allure.attach("这是我们要测试的加法",
                      "这是个网页", allure.attachment_type.HTML)
    with allure.step("执行了"):
        sum=add_caculator(num1,num2)
        allure.attach("加数1+加数2=", f"{0}+{1}={2}")
        assert sum ==result


import random
random.seed()
arr=[]
def sel_sort(arr1):
    for i in range(len(arr1)):
        min=arr1[i]
        for j in range (i,len(arr1)):
            if min>arr1[j]:
                min=arr1[j]
                k=j
        tmp=arr1[i]
        arr1[i]=min
        arr1[k]=tmp
    return(arr1)

def ins_sort(arr2):
    for i in range (1,len(arr2)):
        j=i
        while j>0:
            if arr2[j]<arr2[j-1]:
                tmp=arr2[j-1]
                arr2[j-1]=arr2[j]
                arr2[j]=tmp
            j-=1
    return(arr2)

def bubble_sort(arr3):
    length=len(arr3)
    for i in range (len(arr3)):
        for j in range (1,length):
            if arr[j-1]>arr[j]:
                tmp=arr[j]
                arr[j]=arr[j-1]
                arr[j-1]=tmp
        length-=1
    return(arr3)
def quick_sort(arr4, st, end):
    pivot=arr4[round((st+end)/2)]
    i=st
    j=end
    while i<=j:
        while arr[i]<pivot:
            i+=1
        while arr[j]>pivot:
            j-=1
        if i<=j:
            tmp=arr4[i]
            arr4[i]=arr4[j]
            arr4[j]=tmp
            i+=1
            j-=1
            if st<j:
                quick_sort(arr4, st, j)
            if i<end:
                quick_sort(arr4, i, end)
    return (arr4)

def merge_sort(arr5):
    if len(arr5)<2:
        return arr5
    mid=round(len(arr5)/2)
    left=merge_sort(arr5[:mid])
    right=merge_sort(arr5[mid:])
    return merge(left, right)

def merge(left, right):
    res=[]
    i=0
    j=0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            res.append(left[i])
            i+=1
        else:
            res.append(right[j])
            j+=1
    res+=left[i:]
    res+=right[j:]
    return res

def heap_sort(arr6):
    def heap(arr6,m,n):
        nel=arr6[m]
        while 2*m+1<n:
            child=2*m+1
            if child+1 < n and arr6[child] < arr6[child+1]:
                child+=1
            if nel>=arr6[child]:
                break
            arr6[m]=arr6[child]
            m=child
            arr[m]=nel
    l1=len(arr6)
    for i in range(l1//2-1,-1,-1):
        heap(arr6, i, l1)
    for i in range(l1-1,0,-1):
        tmp=arr6[i]
        arr6[i]=arr6[0]
        arr6[0]=tmp
        heap(arr6,0,i)
    return (arr6)

def bucket_sort(arr7):
    MAX=max(arr7)
    length=len(arr7)
    size=MAX/length
    bucket = [[] for _ in range(length)]
    for i in range(length):
        div=int(arr7[i]/size)
        if div != length:
            bucket[div].append(arr7[i])
        else:
            bucket[length -1].append(arr7[i])
    for i in range (length):
        bubble_sort(bucket[i])
    res=[]
    for i in range(length):
        res=res+bucket[i]
    return(res)

def radix_sort(arr8):
    m=1
    r=10
    beginning=True
    while beginning:
        beginning = False
        bucket=[[], [], [], [], [], [], [], [], [], []]
        for i in arr8:
            pos=i%r//m
            bucket[pos].append(i)
            if not beginning and pos >0:
                beginning=True
        arr8=[]
        for i in bucket:
            for j in i:
                arr8.append(j)
        r*=10
        m*=10
    return(arr8)

for i in range (50):
    losowana = random.randrange(1,51)
    arr.append(losowana)
print(arr)

print("\nSelection sort\n",sel_sort(arr))
print("\nInsertion sort\n",ins_sort(arr))
print("\nBubble sort\n",bubble_sort(arr))
print("\nQuick sort\n",quick_sort(arr,0,len(arr)-1))
print("\nMerge sort\n",merge_sort(arr))
print("\nHeap sort\n",heap_sort(arr))
print("\nBucket sort\n",bucket_sort(arr))
print("\nRadix sort\n", radix_sort(arr))


from prefect.storage import GitHub
from prefect.run_configs import ECSRun
from prefect.executors import DaskExecutor
from prefect import task, Flow, Parameter
import prefect

STORAGE = GitHub(repo="lauralorenz/fourteen-oh", ref="main", path="/14-fargate-executor.py")

RUN_CONFIG = ECSRun(
	run_task_kwargs={
		#"networkMode":"awsvpc",
		#"taskDefinition":"14-fargate",
		"cluster":"prefect-demo-cluster",
	 	"networkConfiguration": {'awsvpcConfiguration': {'assignPublicIp': 'ENABLED', 'subnets': ['subnet-7410175c'], 'securityGroups': []}},
 		#"executionRoleArn": "arn:aws:iam::136638793011:role/ecsTaskExecutionRole"
 		},
	task_role_arn="arn:aws:iam::136638793011:role/prefect-demo-fargate-task-role",
	image='prefecthq/prefect:0.14.0',
	memory="512",
	cpu="256")

EXECUTOR = DaskExecutor()

@task
def hi():
   logger = prefect.context.get('logger')
   logger.info("Hello!")

with Flow("prefect-14-dask", storage=STORAGE, run_config=RUN_CONFIG, executor=EXECUTOR) as flow:
	hi()

flow.register("14-demo")

#########
# agent #
#########

if __name__ == '__main__':
	from prefect.agent.ecs.agent import ECSAgent

	AGENT = ECSAgent(#labels=["s3-flow-storage"],
		#cpu="256",
		#memory="512",
		cluster="prefect-demo-cluster",
		#networkConfiguration={'awsvpcConfiguration': {'assignPublicIp': 'ENABLED', 'subnets': ['subnet-7410175c'], 'securityGroups': []}},
		task_role_arn="arn:aws:iam::136638793011:role/prefect-demo-fargate-task-role",
	 	#executionRoleArn="arn:aws:iam::136638793011:role/ecsTaskExecutionRole"
	 	)

	AGENT.start()


import tkinter as tk
from Interface import StartPage
from vark import varkQuestionnaire
from HM import HMQuestionnaire
from Analysis import IndividualAnalysisPage, TotalIndividualAnalysisPage, TotalAnalysisPage
from UserDetails import UserDetails
from Storage import Storage

# This is our controller class, it loads each frame for later use
# It holds the variables from each frame: user details, vark score, HM score, etc.
# It can then submit the details to the database (using the storage module) at the end.

class ControlMe(tk.Tk):

	def __init__(self, *args, **kwargs):

		# Variables for user details

		self.nameVar = ""
		self.yearVar = ""
		self.progVar = ""

		# Variables for HM score

		self.activistVar = 0
		self.theoristVar = 0
		self.pragmatistVar = 0
		self.reflectorVar = 0

		# Variables for VARK score

		self.visualVar = 0
		self.auditoryVar = 0
		self.readwriteVar = 0
		self.kinestheticVar = 0

		tk.Tk.__init__(self, *args, **kwargs)

		container = tk.Frame(self) # Set up a container frame
		container.pack(side="top", fill="both", expand= True)

		container.grid_rowconfigure(0, weight=1)
		container.grid_columnconfigure(0, weight=1)

		self.frames = {} # Hold the frames here

		for F in (HMQuestionnaire, varkQuestionnaire, StartPage, IndividualAnalysisPage, TotalIndividualAnalysisPage, TotalAnalysisPage, UserDetails): # Populate self.frames{}

			frame = F(container, self)
			self.frames[F] = frame
			frame.grid_forget()

		self.show_frame(StartPage) # The starting frame must show first

	# Add ALL data to database in one go

	def addData(self):
		Storage.addData(self, self.nameVar, self.yearVar, self.progVar, self.visualVar, self.auditoryVar,
			self.readwriteVar, self.kinestheticVar, self.activistVar, self.theoristVar, self.pragmatistVar, self.reflectorVar)

	def returnResults(self):
		individualData = (self.nameVar, self.activistVar, self.theoristVar, self.pragmatistVar, self.reflectorVar,
			self.visualVar, self.auditoryVar, self.readwriteVar, self.kinestheticVar)
		return individualData

	def setUpAnalysis(self, controller):
		frameSelf = self.frames[IndividualAnalysisPage]
		IndividualAnalysisPage.retrieveResults(frameSelf, controller)

	# Functions used to grab the variables from the other frames

	# User Details

	def add_name(self, cont):
		frame = self.frames[cont]
		self.nameVar = frame.getName()

	def add_year(self, cont):
		frame = self.frames[cont]
		self.yearVar = str(frame.getYear())

	def add_prog(self, cont):
		frame = self.frames[cont]
		self.progVar = frame.getProg()

	# HM Questionnaire

	def add_activist(self, cont):
		frame = self.frames[cont]
		self.activistVar = frame.getActivistScore()

	def add_theorist(self, cont):
		frame = self.frames[cont]
		self.theoristVar = frame.getTheoristScore()

	def add_pragmatist(self, cont):
		frame = self.frames[cont]
		self.pragmatistVar = frame.getPragmatistScore()

	def add_reflector(self, cont):
		frame = self.frames[cont]
		self.reflectorVar = frame.getReflectorScore()

	# VARK Questionnaire

	def add_visual(self, cont):
		frame = self.frames[cont]
		self.visualVar = frame.getVisualScore()

	def add_auditory(self, cont):
		frame = self.frames[cont]
		self.auditoryVar = frame.getAuditoryScore()

	def add_readwrite(self, cont):
		frame = self.frames[cont]
		self.readwriteVar = frame.getReadWriteScore()

	def add_kinesthetic(self, cont):
		frame = self.frames[cont]
		self.kinestheticVar = frame.getKinestheticScore()

	# Testing function

	def print_data(self):
		print("User ID:" + self.nameVar)
		print("Year:" + self.yearVar)
		print("Programme:" + self.progVar)

		print("Activist Score:" + str(self.activistVar))
		print("Theorist Score:" + str(self.theoristVar))
		print("Pragmatist Score:" + str(self.pragmatistVar))
		print("Reflector Score:" + str(self.reflectorVar))

		print("Visual Score:" + str(self.visualVar))
		print("Auditory Score:" + str(self.auditoryVar))
		print("Read/Write Score:" + str(self.readwriteVar))
		print("Kinesthetic Score:" + str(self.kinestheticVar))

	# Show frame function

	def show_frame(self, cont):
		frame = self.frames[cont]
		frame.grid(row=0, column=0, sticky="nsew")
		frame.tkraise()

	def hide_frame(self, cont):
		frame = self.frames[cont]
		frame.grid_forget()

# Page one

app = ControlMe()
app.mainloop()


class ImageEntity:
    """Image entity"""

    __slots__ = (
        'id',
        'url',
        'sku',
    )

    def __init__(self, _id: int = None, _url: str = None, _sku: int = None):
        """
        Конструктор
        Args:
            _id: ID
            _url: Адрес
            _sku: Артикул
        """
        self.id = _id
        self.url = _url
        self.sku = _sku


# -*- coding: utf-8 -*-
'''
@File  : handleCase.py
@Date  : 2019/1/15/015 18:24
'''
from common.parseExc import *
from common.config import CASEPATH
from common.log import Log
from common.config import CASENAME
import json

# 去掉换行符
def quchu_n(str):
    str = str.replace("\n", "")
    return str

class HandleCase(object):
    def __init__(self):
        # 实例parseExc对象
        self.log = Log()
        self.pe = PaserExc(CASEPATH, 0)

    # 总用例数
    def get_totals(self):
        return self.pe.get_nrows() - 1

    # 处理检查点中数据
    def handle_checkPoint(self, item):
        global key, value
        checkPints = {}
        key, value = item.split("=")
        if ":" in value:
            value = value.replace(":", "：")
        if "." in key:
            temp = {}
            key1 = (str(key).split("."))[0]  # payload.coin类型的集合点解析
            key2 = (str(key).split("."))[1]
            temp[key2] = value
            checkPints[key1] = temp
        else:
            checkPints[key] = value
        return checkPints

    # 处理关联参数
    def handle_related_params(self, item):
        related_params = []
        if ";" in item:
            for i in item.split(";"):
                if "." in i:
                    related_params.append(i.split("."))
                else:
                    related_params.append(i)
        elif "." in item:
            related_params.append(item.split("."))
        else:
            related_params.append(item)
        return related_params

    # 处理每条用例的数据格式
    def handle_data(self, datas):
        global cid, apiId, describe, host, expect, method, params, checkPints, relatedApi, relatedParams
        checkPints = {}
        # relatedParamsInfo = {}
        if isinstance(datas, dict):
            cid = int(datas["caseId"])
            apiId = int(datas["apiId"])
            describe = str(quchu_n(datas["caseDescribe"]))
            host = str(quchu_n(datas["apiHost"]))
            expect = str(datas["expect"])
            method = str(datas["method"])
            params = str(datas["params"])
            relatedParams = str(datas["relatedParams"])
            if expect:
                if expect.split(";")[-1] != "":
                    for item in expect.split(";"):
                        checkPints.update(self.handle_checkPoint(item))
                else:
                    checkPints = self.handle_checkPoint(expect.replace(";", ""))
                datas["expect"] = checkPints
            else:
                datas["expect"] = {}
            return datas
        else:
            raise Exception("参数错误，所传参数datas必须是字典")

    # 获得所有测试用例
    def get_cases(self):
        values = []
        cases = []
        result = []
        rowValues = self.pe.get_row()[1:]
        for row in rowValues:
            values.append(dict(zip(CASENAME, row)))
        # 去掉不执行的用例
        for case in values:
            if case["isExcute"] == "y" or case["isExcute"] == "Y" or case["isExcute"] == "":
                cases.append(case)
            case.pop("isExcute")
        # 转换用例字段的数据格式
        for case in cases:
            case["caseId"] = int(case["caseId"])
            case["apiId"] = int(case["apiId"])
            case["caseDescribe"] = quchu_n(str(case["caseDescribe"]))
            case["apiHost"] = quchu_n(str(case["apiHost"]))
            case["params"] = quchu_n(case["params"])
            case["apiHeaders"] = quchu_n(case["apiHeaders"])
            case["method"] = quchu_n(case["method"])
            if isinstance(case["relatedApi"], float):
                case["relatedApi"] = int(case["relatedApi"])
            else:
                case["relatedApi"] = None
            case["relatedParams"] = quchu_n(case["relatedParams"])
            case["relatedParams"] = self.handle_related_params(case["relatedParams"])
            case["expect"] = quchu_n(case["expect"])
            self.handle_data(case)
            result.append(case)
        return result

if __name__ == '__main__':
    a = 'code;c.code'
    s = HandleCase()
    j=s.get_cases()[0]
    l=j["relatedParams"]


import discord
from discord.ext import commands

from main import HelpCenterBot
from .utils import checkers, misc
from .utils.i18n import use_current_gettext as _

class HelpCommand(commands.HelpCommand):
    def __init__(self) -> None:
        """Help command will allow the user to see the command list and ask for specific help for each commands."""
        super().__init__(command_attrs={
            'description': _("Show bot commands.")
        })
        self.add_check(checkers.authorized_channels_check)

    async def on_help_command_error(self, ctx: commands.Context, error: Exception) -> None:
        print(error)

    async def send_error_message(self, error: Exception) -> None:
        embed = discord.Embed(
            title=_("An error occurred."),
            description=error,
            color=misc.Color.black().discord
        )
        await self.context.send(embed=embed)

    async def send_bot_help(self, mapping) -> None:
        """Show the bot commands."""
        prefix = "\\" if str(self.context.bot.user.id) in self.context.prefix  else self.context.prefix
        embed = discord.Embed(
            title=_("Here are my commands:"),
            description="\n".join([f"`{prefix}{cmd.name}` : {_(cmd.description)}" for cmd in self.context.bot.commands if not cmd.hidden]),
            color=misc.Color.grey_embed().discord
        )
        await self.context.send(embed=embed)

    async def send_command_help(self, command: commands.Command) -> None:
        """Show help for a specific command."""
        if command.hidden:
            return self.command_not_found(command.name)

        embed = discord.Embed(
            title=f"{command.name}",
            description=command.description,
            color=misc.Color.grey_embed().discord
        )
        embed.add_field(
            name="Usage:",
            value=command.usage
        )
        await self.context.send(embed=embed)

    async def command_not_found(self, string: str) -> None:
        """Message if the command is not found."""
        return _("The command {string} way not found.").format(string)

def setup(bot: HelpCenterBot) -> None:
    bot.help_command = HelpCommand()
    bot.logger.info("Extension [help] loaded successfully.")


from redis import Redis
from rq import SimpleWorker, Queue
from llib import DogFetch
from birdDog import findbird
from birdDog import speak
from birdDog import chewbird
from llib.cmdutil import cmdutil
import click
import os

def myip():
    myip = cmdutil.subprocess_cmd('ec2metadata --local-ipv4')
    return(myip)

def findTheBird(dataSet, entityId, productId, redisServer):
    redisURL='redis://' + redisServer
    queue = Queue('bird', connection=Redis.from_url(redisURL))
    queue.enqueue(findbird, dataSet, entityId, productId, timeout=1800)

def pleaseSpeak(requestor, redisServer):
    redisURL='redis://' + redisServer
    queue = Queue('bird', connection=Redis.from_url(redisURL))
    queue.enqueue(speak, requestor, timeout=1800)

def chewTar(bucket, tarfile, redisServer):
    redisURL='redis://' + redisServer
    queue = Queue('bird', connection=Redis.from_url(redisURL))
    queue.enqueue(chewbird, bucket, tarfile, timeout=1800)

def huntEmUp(path,row, product):
    """ this gets a path row for a given product/dataset """
    pup = DogFetch('dogTrainer')

    entlist = pup.hunt(path=path, row=row, product=product)
    redis = pup.redis
    #redis = myip()
    pup.logi('redis = %s' % redis)
    print('redis = %s' % redis)
    cnt=0;
    for it in entlist:
        print(it)
        myid = it[0]
        myprod = it[1]
        if (cnt < 24):
            findTheBird(dataSet = product, entityId=myid, productId=myprod, redisServer=redis)
        cnt = cnt + 1

    pup.logi('Count = %s' % cnt)

def get_todo_list(bucket):
    print (bucket)
    print (bucket)
    filelist= []
    print (' scene list initializing ...')
    cmd = 'aws s3 ls --recursive %s/tar > /data/listings/tarlist.txt' % bucket
    os.system(cmd)
    file = open('/data/listings/tarlist.txt')
    for line in file:
        line = line.rstrip()
        if 'tar/' in line:
            tarfile = line.split()[3]
            filelist.append(tarfile)

    return (filelist)

def chewEmUp(bucket):
    pup = DogFetch('dogTrainer')
    redis = pup.redis
    bucket = pup.cog_bucket
    #pup.logi('chewEmUp, redis = %s' % redis)
    #pleaseSpeak('dogTrainer-chewEmUp', redis)
    list = get_todo_list(bucket)
    cnt=0;
    for item in list:
        print(item)
        if (cnt < 24):
            chewTar(bucket, item, redis)
            cnt = cnt + 1

@click.group()
def cli():
    """this script runs a pack of dogs -
    retrievers  get a bunch of tar files from EarthExplorer
    policeDogs chew these tar balls up and make cogs
    all of this goes in the cloud in an S3 bucket"""
    pass

@cli.command()
@click.option('--path', default='46', help="WRS PATH (path)", required=True)
@click.option('--row', default='28', help="WRS ROW (row)", required=True)
@click.option('--product', default='LANDSAT_ETM_C1', help=" other codes here LANDSAT_ETM_C1 (product)", required=True)
def retrieve(path, row, product):
    """ find a list of files and start the pack of retrievers via the job queue"""

    print ("retrieve started ")
    huntEmUp(path,row, product)

@cli.command()
@click.option('--bucket', default='CHSBUCKETHERE', help="This is the name of the AWS S3 Bucket (bucket)", required=True)

def makecogs(bucket):
    """ make cogs - this takes a bucket of tarballs and makes cogs via a pack of policeDogs"""

    print ("makecogs started ")
    chewEmUp(bucket)


import logging
import azure.functions as func
import yake
import json

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    try:
        body = json.dumps(req.get_json())
    except ValueError:
        return func.HttpResponse(
             "Invalid body",
             status_code=400
        )

    if body:
        result = compose_response(body)
        return func.HttpResponse(result, mimetype="application/json")
    else:
        return func.HttpResponse(
             "Invalid body",
             status_code=400
        )

def compose_response(json_data):
    values = json.loads(json_data)['values']

    # Prepare the Output before the loop
    results = {}
    results["values"] = []

    for value in values:
        output_record = transform_value(value)
        if output_record != None:
            results["values"].append(output_record)
    return json.dumps(results, ensure_ascii=False)

## Perform an operation on a record
def transform_value(value):
    try:
        recordId = value['recordId']
    except AssertionError  as error:
        return None

    # Validate the inputs
    try:
        assert ('data' in value), "'data' field is required."
        data = value['data']
        assert ('content' in data), "'content' field is required in 'data' object."
        # assert ('text2' in data), "'text2' field is required in 'data' object."
    except AssertionError  as error:
        return (
            {
            "recordId": recordId,
            "errors": [ { "message": "Error:" + error.args[0] }   ]
            })

    try:
            # if text:
        language = "nl"
        max_ngram_size = 3

        deduplication_thresold = 0.9
        deduplication_algo = 'seqm'
        windowSize = 1
        numOfKeywords = 20

        custom_kw_extractor = yake.KeywordExtractor(lan=language, n=max_ngram_size, dedupLim=deduplication_thresold, dedupFunc=deduplication_algo, windowsSize=windowSize, top=numOfKeywords, features=None)
        keywords = custom_kw_extractor.extract_keywords(value['data']['content'])

        keywords = sorted(keywords, key=lambda tup: tup[1],reverse=True)

        keyslist= [tup[0] for tup in keywords]
        valuelist = [tup[1] for tup in keywords]

        # Here you could do something more interesting with the inputs

    except:
        return (
            {
            "recordId": recordId,
            "errors": [ { "message": "Could not complete operation for record." }   ]
            })

    return ({
            "recordId": recordId,
            "data": {
                "keywords": keyslist,
                "keywordscores":valuelist
                    }
            })

    # text = req.params.get('text')
    # ngram = req.params.get('ngram')
    # nkey = req.params.get('nkey')
    # if not text:
    #     try:
    #         req_body = req.get_json()
    #     except ValueError:
    #         pass
    #     else:
    #         text = req_body.get('text')

    # if text:
    #     language = "nl"
    #     if ngram:
    #         max_ngram_size = int(ngram)
    #     else:
    #         max_ngram_size = 3

    #     deduplication_thresold = 0.9
    #     deduplication_algo = 'seqm'
    #     windowSize = 1
    #     if nkey:
    #         numOfKeywords = int(nkey)
    #     else:
    #         numOfKeywords = 20

    #     custom_kw_extractor = yake.KeywordExtractor(lan=language, n=max_ngram_size, dedupLim=deduplication_thresold, dedupFunc=deduplication_algo, windowsSize=windowSize, top=numOfKeywords, features=None)
    #     keywords = custom_kw_extractor.extract_keywords(text)

    #     # for kw in keywords:
    #     #     print(kw)

    #     return func.HttpResponse(str(dict(keywords)))
    # else:
    #     return func.HttpResponse(
    #          "Please pass a text on the query string or in the request body",
    #          status_code=400
    #     )


"""
Created on Mon Feb  4 23:06:53 2019

@author: Robert Marc
"""

import numpy as np
import matplotlib.pyplot as plt

def draw_squares(ax,d,p,s):
    if d > 0:
        ax.plot(p[:,0],p[:,1],color = 'k')
        shrink = s/4                                #Shrink value for the corner squares of the current square.
        j = len(p)-2                                #Counter for number of corner squares
        for i in range(4):                          #For and while loop for drawing the corner squares for the current level
            while j >= 0:
                nd = np.array([[p[j,0]-shrink,p[j,1]-shrink],[p[j,0]-shrink,p[j,1]+shrink],  #Builds array for coordinates of next square
                               [p[j,0]+shrink,p[j,1]+shrink],[p[j,0]+shrink,p[j,1]-shrink],
                               [p[j,0]-shrink,p[j,1]-shrink]])
                draw_squares(ax,d-1,nd,s/2)                                                  #Calls for a corner square to be drawn, and that square's corner squares if need be
                j -= 1

plt.close("all")
orig_size = 1000
p = np.array([[0,0],[0,orig_size],[orig_size,orig_size],[orig_size,0],[0,0]])
fig, ax = plt.subplots()
draw_squares(ax,4,p,orig_size)
ax.set_aspect(1.0)
ax.axis('off')
plt.show()
fig.savefig('squares.png')


def isPythagoras(a,b,c):
    if a**2 + b**2 == c**2:
        print ('true')
    else:
        print('False')
        return

isPythagoras(3,4,5)
isPythagoras(5,9,12)
isPythagoras(8,6,10)
isPythagoras(7,8,11)


# -*- coding: utf-8 -*-
"""
Author: Visura Pathirana

This script will create directories and write and place matlab script

"""

# import packages
import numpy as np
import os
import sys
from shutil import copyfile

depletion_range = np.linspace(0, 3650, num=101)

DepletionTime = []
maxPowerVal = []
fullWidthHalfMax = []
avgTempMax = []
avgTempGrapMax = []
react_fb_tot_pcmMax = []
react_fb_f_pcmMax = []
react_fb_g_pcmMax = []

for i in depletion_range:

	work_path = "../depl"'{:.0f}'.format(i)
	result_file = "%s/sim_results.txt" %work_path
	line_dat = np.genfromtxt(result_file, delimiter = ',')
	DepletionTime.append(line_dat[0])
	maxPowerVal.append(line_dat[1])
	fullWidthHalfMax.append(line_dat[2])
	avgTempMax.append(line_dat[3])
	avgTempGrapMax.append(line_dat[4])
	react_fb_tot_pcmMax.append(line_dat[5])
	react_fb_f_pcmMax.append(line_dat[6])
	react_fb_g_pcmMax.append(line_dat[7])

	if i%365 == 0:
		power_results = "power_data"+'{:.0f}'.format(i)+".mat"
		temp_results = "temp_data"+'{:.0f}'.format(i)+".mat"
		react_results = "react_data"+'{:.0f}'.format(i)+".mat"

		powerCopy = "cp "+ work_path + "/" + power_results + " ../scripts/results"
		os.system(powerCopy)

		tempCopy = "cp "+ work_path + "/" + temp_results + " ../scripts/results"
		os.system(tempCopy)

		reactCopy = "cp "+ work_path + "/" + react_results + " ../scripts/results"
		os.system(reactCopy)

orig_stdout = sys.stdout
output_file  = open('all_depl_results.m', 'w+')
sys.stdout = output_file

print('depletion_time =', DepletionTime,';\n')
print('maxPowerVal = ', maxPowerVal,';\n')
print('FWHM = ', fullWidthHalfMax,';\n')
print('avgTempMax = ', avgTempMax,';\n')
print('avgTempGrapMax = ', avgTempGrapMax,';\n')
print('react_fb_tot_pcmMax = ', react_fb_tot_pcmMax,';\n')
print('react_fb_f_pcmMax = ', react_fb_f_pcmMax,';\n')
print('react_fb_g_pcmMax = ', react_fb_g_pcmMax,';\n')

sys.stdout = orig_stdout
output_file.close()


import math
import os
import shutil
import time
from threading import Timer

import torch
import torch.nn.utils
import torch.utils.data

from utils.accuracy_fn import default_accuracy_fn
from utils.label import DoNothingLabelTransformer

class AverageMeter(object):
    """Computes and stores the average and current value"""

    def __init__(self):
        self.val = 0.
        self.avg = 0.
        self.sum = 0.
        self.count = 0.
        self.reset()

    def reset(self):
        self.val = 0.
        self.avg = 0.
        self.sum = 0.
        self.count = 0.

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

class Trainer(object):
    def __init__(self, initial_lr=1e-3, model=None, loss_fn=None, optimizer=None,
                 train_loader=None, validation_loader=None, test_loader=None,
                 lr_decay_rate=5, model_store_path="checkpoints", gpu_id=-1,
                 label_transformer=DoNothingLabelTransformer(),
                 half_float=False, accuracy_fn=default_accuracy_fn, print_interval=1, top_k=(1,)):
        if gpu_id < 0:
            self.device = torch.device("cpu")
        else:
            os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
            self.device = torch.device("cuda")
            torch.backends.cudnn.benchmark = True

        self.lr = initial_lr
        self.lr_decay = lr_decay_rate
        self.half_float = half_float
        self.train_loader = train_loader
        self.validation_loader = validation_loader
        self.test_loader = test_loader
        self.label_transformer = label_transformer
        self.model = model.to(self.device) if not half_float else model.to(self.device).half()
        self.criterion = loss_fn.to(self.device)
        self.accuracy_fn = accuracy_fn
        self.optimizer = optimizer
        self.print_interval = print_interval
        self.metric = dict()
        self.metric['train_loss'] = 0.
        self.metric['validation_loss'] = 0.
        self.model_path = model_store_path
        if self.model_path and not os.path.exists(self.model_path):
            os.makedirs(self.model_path)

        if 1 not in top_k:
            top_k.append(1)
        self.top_k = top_k
        for K in top_k:
            self.metric['train_prec@top' + str(K)] = 0.
            self.metric['validation_prec@top' + str(K)] = 0.

        self.print_str = self._print_format()
        self.stopped = False

        def check_stop(trainer):
            if not os.path.exists('command.txt'):
                Timer(10.0, check_stop, args=[trainer], kwargs=None).start()
                return
            with open('command.txt', 'r') as order:
                line = order.readline()
                if line.find('stop') >= 0:
                    trainer.stopped = True
                else:
                    Timer(10.0, check_stop, args=[trainer], kwargs=None).start()

        Timer(10.0, check_stop, args=[self], kwargs=None).start()

    def _print_format(self):
        print_str = 'Epoch[{0}]: [{1}/{2}]\t' \
                    'ETA {3:.2f}\t' \
                    'Time {batch_time.val:.3f}({batch_time.avg:.3f})\t' \
                    'Data {data_time.val:.3f}({data_time.avg:.3f})\t' \
                    'Loss {loss.val:.4f}({loss.avg:.4f})\t'
        if self.accuracy_fn is None:
            return print_str
        for k in self.top_k:
            print_str = print_str + 'Prec@' + str(k) + ' {metric[top' + str(k) + '].val:.2%}({metric[top' + str(
                k) + '].avg:.2%})\t'
        return print_str

    def _adjust_learning_rate(self, optimizer, epoch):
        lr = self.lr * (0.1 ** (epoch // self.lr_decay))
        for param_group in optimizer.param_groups:
            param_group['lr'] = lr
        print("*" * 10, '==> lr =', lr, "*" * 10)

    def _save_checkpoint(self, epoch, is_best, file_prefix='checkpoint'):
        state = {
            'epoch': epoch,
            'state_dict': self.model.state_dict(),
            'optimizer': self.optimizer.state_dict(),
            'train_prec@top1': self.metric['train_prec@top1'],
            'validation_prec@top1': self.metric['validation_prec@top1'],
            'train_loss': self.metric['train_loss'],
            'validation_loss': self.metric['validation_loss'],
        }
        filename = '{filePrefix}-{epoch}-val_prec_{precTop1:.3f}-loss_{loss:.3f}.pth' \
            .format(filePrefix=file_prefix, epoch=epoch,
                    precTop1=state['validation_prec@top1'],
                    loss=state['validation_loss'])
        file_path = os.path.join(self.model_path, filename)
        torch.save(state, file_path)
        if is_best:
            shutil.copyfile(file_path, os.path.join(self.model_path, 'model_best.pth.tar'))
        print(">> model saved >>", file_path)

    def run(self, epochs=5, resume=None, valid=True):
        epoch = 0
        if resume is not None and os.path.exists(resume):
            checkpoint = torch.load(resume)
            epoch = checkpoint['epoch'] if self.train_loader.dataset.start_index > 0 else checkpoint['epoch'] + 1
            self.model.load_state_dict(checkpoint['state_dict'])
            self.optimizer.load_state_dict(checkpoint['optimizer'])

        best_prec = 0
        for idx in range(epoch, epochs):
            print('*' * 10, "epoch[", idx, "] training start", "*" * 10)
            self._do_run(True, idx)
            print('*' * 10, "epoch[", idx, "] training finished", "*" * 10)
            if valid:
                print('*' * 10, "epoch[", idx, "] validation start", "*" * 10)
                self._do_run(False, idx)
                print('*' * 10, "epoch[", idx, "] validation finished", "*" * 10)
            is_best = self.metric['validation_prec@top1'] > best_prec
            if is_best:
                best_prec = self.metric['validation_prec@top1']
            self._save_checkpoint(idx, is_best)
            if self.stopped:
                break
            # second epoch, reset index to  0
            self.train_loader.dataset.reset_index(False)

    def _do_run(self, train_model, epoch):
        batch_time = AverageMeter()
        data_time = AverageMeter()
        losses = AverageMeter()

        prec_topk = dict()
        for k in self.top_k:
            prec_topk['top' + str(k)] = AverageMeter()

        # switch mode
        if train_model:
            self.model.train()
            self._adjust_learning_rate(self.optimizer, epoch)
        else:
            self.model.eval()

        end = time.time()
        loader = self.train_loader if train_model else self.validation_loader
        if train_model:
            self._compute(batch_time, data_time, end, epoch, loader, losses, prec_topk, train_model)
        else:
            with torch.no_grad():
                self._compute(batch_time, data_time, end, epoch, loader, losses, prec_topk, train_model)

        for k in self.top_k:
            if train_model:
                self.metric['train_prec@top' + str(k)] = prec_topk['top' + str(k)].avg
            else:
                self.metric['validation_prec@top' + str(k)] = prec_topk['top' + str(k)].avg
        if train_model:
            self.metric['train_loss'] = losses.avg
        else:
            self.metric['validation_loss'] = losses.avg

    def _compute(self, batch_time, data_time, end, epoch, loader, losses, prec_topk, train_model):
        for i, (samples, target) in enumerate(loader):
            # measure data loading time
            data_time.update(time.time() - end)
            samples = samples.to(self.device) if not self.half_float else samples.to(self.device).half()
            if isinstance(target, torch.Tensor):
                target = target.to(self.device)

            # compute output and loss
            output = self.model(samples, target=target)
            loss = self.criterion(output, target)
            if math.isinf(loss.item()):
                continue
            losses.update(loss.item(), samples.size(0))

            # measure accuracy and record loss
            if self.accuracy_fn is not None:
                precs = self.accuracy_fn(self.label_transformer, self.top_k, output, target)
                for idx, key in enumerate(prec_topk):
                    prec_topk[key].update(precs[idx].item() if isinstance(precs[idx], torch.Tensor) else precs[idx],
                                          samples.size(0))

            # compute gradient and do SGD step
            if train_model:
                self.optimizer.zero_grad()
                loss.backward()
                # torch.nn.utils.clip_grad_norm_(self.model.parameters(), 100)
                self.optimizer.step()

            # measure elapsed time
            batch_time.update(time.time() - end)
            end = time.time()

            if i != 0 and i % self.print_interval == 0:
                left_data = len(loader) - i
                print(self.print_str.format(
                    epoch, i, len(loader), left_data * batch_time.avg,
                    batch_time=batch_time, data_time=data_time, loss=losses, metric=prec_topk), flush=True)
                if i == 0:
                    batch_time.reset()
                data_time.reset()

                if self.stopped:
                    break


import scrapy

# this is the spyder that will scrape the url(s) specified by the user and retrieve the data that they want
class Spyder(scrapy.Spider):

    name = "spyder"

    def __init__(self, *args, **kwargs):
        super(Spyder, self).__init__(*args, **kwargs)
        # set the url to be scraped
        self.start_urls = kwargs.get("urls")
        # set the target dict for this spyder
        self.target_dict = kwargs.get("target_dict")
        # set the file dict for this spider
        self.file_dict = kwargs.get("file_dict")

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, self.parse)

    def parse(self, response):
        selector_keypairs = self.target_dict[response.url]

        # create dictionary that will be the item that is yielded
        # add the url of this target to the dictionary
        item = {"url": response.url}

        # for each selector key-pair, use the key (pair[0]) as the key in item and extract the data using
        # the css selector itself (pair[1])
        for pair in selector_keypairs:
            item[pair[0]] = response.css(pair[1] + "::text").extract()

        yield item