import os
import sys
import math
import matplotlib
import re
import argparse
import numpy as np
matplotlib.use("Agg")
import matplotlib.pyplot as plt
colormap = plt.get_cmap('tab10')
matplotlib.rcParams['axes.prop_cycle'] = matplotlib.cycler(color=[colormap(k) for k in [0,1,2,8,6,5,4,3]])
plt.rcParams.update({'font.size': 14})
adaQueryCnt = 0
c=5
def T(origNbrVar):
    intermediate = math.sqrt(pow(2,c))
    k = intermediate - 1 / intermediate
    prob = 1 - 1 / pow(k, 2)
    alpha = math.log(2) * ((prob - 0.5) ** 2) / (2 * prob)
    delta= 0.01
    return int(math.ceil(math.log(origNbrVar)*math.log(1.0/delta)/alpha))
beta = math.log10(1e5)

parser = argparse.ArgumentParser("Generate graphical representation of data")
parser.add_argument('-d', '--dir', type=str, help="path to the folder where you place all the results")
parser.add_argument('-x', '--xAxis', type=int, help="the x axis of the images, whether use varying problem sizes(0) or coupling strength(1) as x axis")
parser.add_argument('-gt', '--groundtruth', type=int, help="the index of the method which provides ground truth")
parser.add_argument('-r', '--repeat', type=int, help="")
parser.add_argument('-e', '--experiment', type=int, help="")
args = parser.parse_args()

def wish(fp):
    with open(fp, 'r') as f:
        lines = f.readlines()
        nbvar = int(lines[0].split()[0])
        weights = []
        for i in range(1, len(lines)):
            weights.append(float(lines[i].split()[0]))
        # for i in range(len(weights), nbvar):
        #     weights.append(weights[-1])
        # print(weights)
        curmax = weights[0]
        if curmax == float("-inf"):
            return 0

        # wind = len(weights) - 2
        # while wind >=0:
        #     if weights[wind] == float("-inf"):
        #         wind -= 1
        #     else:
        #         break
        # for i in range(wind, len(weights) - 1):
        #     weights[i] = weights[wind] * (len(weights) - 2 - i) / (len(weights) - 2 - wind)
        # print(weights)
        W = 1
        nbbar = 1
        for i in range(1, nbvar+1):
            W += pow(10, weights[i] - curmax) * nbbar
            nbbar = nbbar * 2

        W = math.log10(W) + curmax
        # print("Queries made by wish = {:d}".format(nbvar+1))
        # print ("Log10 Partition function by wish = {:.12f}".format(W))
        return W

def getValue(mlist, queried, index):
    if queried[index]:
        return mlist[index]
    global adaQueryCnt
    print("query depth = {}, res = {}".format(index, mlist[index]))
    adaQueryCnt += 1
    queried[index] = True
    return mlist[index]

def binarySearch(weights, queried, bcap, wnode, inter, beta, l, r):
    print("Binary Search left={}, right={}".format(l, r))
    def isninf(a):
        return a == float('-inf')
    if r == l + 1:
        # stop condition 1
        bcap[l] = getValue(weights, queried, l)
        bcap[r] = getValue(weights, queried, r)
        if not isninf(bcap[l]) and not isninf(bcap[r]):
            wnode[l] = bcap[l]
            wnode[r] = bcap[r]
            inter[l] = (bcap[l] + bcap[r]) / 2
        else:
            pass
    else:
        upperbound = max(l - c, 0)
        lowerbound = min(r + c, len(wnode) - 1)
        bcap[upperbound] = getValue(weights, queried, upperbound)
        bcap[lowerbound] = getValue(weights, queried, lowerbound)
        if not isninf(bcap[upperbound]) and not isninf(bcap[lowerbound]):
            if bcap[upperbound] >= beta + bcap[lowerbound]:
                mid = int((l + r) / 2)
                binarySearch(weights, queried, bcap, wnode, inter, beta, mid, r)
                binarySearch(weights, queried, bcap, wnode, inter, beta, l, mid)
            else:
                val = (bcap[upperbound]+bcap[lowerbound]) / 2
                    # print(val)
                    # print(upperbound)
                    # print(wnode[upperbound])
                    # print(lowerbound)
                    # print(wnode[lowerbound])
                for i in range(l, r):
                    inter[i] = val
                for i in range(l, r+1):
                    wnode[i] = val
        elif isninf(bcap[upperbound]) and isninf(bcap[lowerbound]):
            pass
        else:
            # if wnode[l] <= beta + wnode[r] and isninf(wnode[l]):
            #     wnode[l] = wnode[r]
            mid = int((l + r) / 2)
            binarySearch(weights, queried, bcap, wnode, inter, beta, mid, r)
            binarySearch(weights, queried, bcap, wnode, inter, beta, l, mid)

def adawish(fp, beta):
    global adaQueryCnt
    adaQueryCnt = 0
    ninf = float('-inf')
    with open(fp, 'r') as f:
        lines = f.readlines()
        nbvar = int(lines[0].split()[0])
        weights = []
        for i in range(1, len(lines)):
            weights.append(float(lines[i].split()[0]))

        # reverMax = weights[-1]
        # i = len(weights) - 2
        # while i > 0:
        #     if weights[i] > reverMax:
        #         reverMax = weights[i]
        #     elif weights[i] == float('-inf'):
        #         weights[i] = reverMax
        #     i -= 1

        # for i in range(len(weights), nbvar):
        #     weights.append(weights[-1])
        # print(weights)
        wnode = [ninf] * (nbvar+1)
        bcap = [ninf] * (nbvar+1)
        interval = [ninf] * nbvar
        queried = [False] * (nbvar+1)
        nbbar = 0
        # wnode[0] = getValue(weights, queried, 0)
        # wnode[-1] = getValue(weights, queried, nbvar)
        binarySearch(weights, queried, bcap, wnode, interval, beta, 0, nbvar)

        reverseMaxVal = ninf
        indItr = nbvar
        while indItr >= 0:
            if wnode[indItr] == ninf:
                wnode[indItr] = reverseMaxVal
            else:
                reverseMaxVal = max(wnode[indItr], reverseMaxVal)
            if indItr > 0:
                if interval[indItr-1] == ninf:
                    interval[indItr-1] = reverseMaxVal
                else:
                    reverseMaxVal = max(interval[indItr-1], reverseMaxVal)
            indItr -= 1

        curmax = wnode[0]
        if curmax == float("-inf"):
            return 0
        print(interval)
        print(wnode)
        print(adaQueryCnt)

        W = pow(10, wnode[-1] - curmax)
        for i in range(nbvar):
            W += pow(10, interval[i]- curmax) * nbbar
            W += pow(10, wnode[i] - curmax)
            nbbar = nbbar * 2 + 1

        W = math.log10(W) + curmax
        print("Queries made by adawish = {:d}".format(adaQueryCnt))
        print ("Log10 Partition function by adawish = {:.12f}".format(W))
        return W

markers = ['o', '2', '+', 'D', 'h', '*', 's', 'p', 'x']
linestyles = ['--', '-.', '-', '--', '-.', '-', '-.', ':', '--']
# colors = ['xkcd:chocolate brown', 'orange', 'green', 'white', 'xkcd:salmon pink', 'xkcd:rust orange', 'xkcd:cerulean']
method = ["GroundTruth", "BP", "TRWBP", "MeanField", "HAK", "DIS", "WMC", "WISH", "AdaWISH"]
abbreviations = ["jt","_bp", "trwbp", "mf",  "hak", "_dis", "wmc"]
# method = ["(Loopy) Blief Propagation", "Tree-Reweighted Blief Propagation", "Mean Field", "Junction Tree", "WISH", "AdaWish"]
# abbreviations = ["_bp", "trwbp", "mf", "jt"]

if __name__ == "__main__":
    regrex_nbvar = re.compile(r"var([0-9]+)")
    regrex_cplst = re.compile(r"w([0-9.]+)")
    regrex_repeat = re.compile(r"w[0-9.]+_([0-9]+)_")
    regrex_token = []
    for abbr in abbreviations:
        regrex_token.append(re.compile(abbr))
    xs = [[] for i in method]
    ys = [[] for i in method]
    qs = [[], []]
    for file in sorted(os.listdir(args.dir)):
        print(file)
        hasFoundMethod = False
        for index in range(len(abbreviations)):
            if hasFoundMethod:
                break
            if regrex_token[index].search(file) != None:
                hasFoundMethod = True
                # get y axis plot data
                f = open(args.dir+file, 'r')
                res = float(f.readlines()[0])
                f.close()
                ys[index].append(res)

                # get x axis plot data
                if args.xAxis == 0:
                    nbvar = int(regrex_nbvar.search(file).group(1))
                    xs[index].append(nbvar)
                elif args.xAxis == 1:
                    coupling = float(regrex_cplst.search(file).group(1))
                    xs[index].append(coupling)
                else:
                    pass
        if not hasFoundMethod:
            ys[-2].append(wish(args.dir+file))
            nbvar = int(regrex_nbvar.search(file).group(1))
            qs[-2].append((nbvar+1) * T(nbvar))
            ys[-1].append(adawish(args.dir+file, beta))
            qs[-1].append(adaQueryCnt * T(nbvar))

            # get x axis plot data
            if args.xAxis == 0:
                nbvar = int(regrex_nbvar.search(file).group(1))
                xs[-2].append(nbvar)
                xs[-1].append(nbvar)
            elif args.xAxis == 1:
                coupling = float(regrex_cplst.search(file).group(1))
                xs[-2].append(coupling)
                xs[-1].append(coupling)
            else:
                pass

    for mind in range(len(method)):
        data_len = -1
        if method[mind] == "GroundTruth":
            data_len = 8
            continue
        elif method[mind] == "HAK":
            data_len = 6
        else:
            data_len = 11
        # print(xs)
        # print(ys[mind][curInd[mind]:curInd[mind]+data_len])
        plt.plot(xs[mind], ys[mind], marker=markers[mind], linestyle=linestyles[mind])
        # curInd[mind] += data_len
    # plt.legend(method)
    jtind = method.index("GroundTruth")
    plt.plot(xs[jtind], ys[jtind], marker=markers[jtind], linestyle=linestyles[jtind], label=method[jtind])
    plt.xlabel("#Variables",size=20)
    plt.ylabel("Log Partition Estimation",size=20)
    plt.xticks(xs[-2], xs[-2])
    plt.legend(fontsize=20)
    plt.tick_params(labelsize=20)
    plt.savefig("/tmp/cliqueestimation.pdf")

    plt.figure()
    plt.tick_params(labelsize=20)
    plt.xlabel("#Variables",size=20)
    plt.ylabel("#MAP Queries(x10^3)",size=20)
    plt.xticks(xs[-2], xs[-2])

    qs = np.array(qs,dtype=np.float64)
    qs = np.true_divide(qs,1000)

    plt.bar(xs[-2], qs[-2], width=1.6, label="WISH")
    plt.bar(xs[-1], qs[-1], width=1.6, label="AdaWISH")
    plt.savefig("/tmp/clique_qry.pdf")
    queryRateArr = np.divide(qs[-1], qs[-2])
    print(queryRateArr)
    print(np.median(queryRateArr))
    print(np.average(queryRateArr))


import bpy

from ...data import mesh
from ..test_mixin import TestMixin

class TestAddMesh(TestMixin):
    "Test adding mesh to the scene"

    bl_idname = "chiro_ue4.test_op_add_mesh"
    bl_label = "Test | Add mesh"

    @classmethod
    def poll(cls, ctx):
        return True

    def _run(self):
        # assert 'root' not in bpy.data.objects

        self.log('Polling the operator ...')
        assert bpy.ops.chiro_ue4.op_add_mesh.poll()
        self.log('Polling the operator ... SUCCESS')

        self._run_option()

        for option in mesh.get_options_generator()(self):
            self._run_option(option)

    def _run_option(self, option=None):
        self.log("Calling the operator with option '{}' ...".format(option if option else 'Default'))

        with self.notice_created_objects() as keys:
            if option:
                bpy.ops.chiro_ue4.op_add_mesh(mesh_option=option[0])
            else:
                bpy.ops.chiro_ue4.op_add_mesh()

        assert len(keys) == 1
        key = list(keys)[0]
        assert bpy.data.objects[key].type == 'MESH'

        self.log('Calling the operator ... SUCCESS')

        bpy.data.objects.remove(bpy.data.objects[key])


import os
import pandas as pd
from openpyxl import load_workbook
import xlsxwriter
from datetime import datetime, date, time
import xlrd

class save_data():
    def __init__(self, now, Code, State, Score, Speed, model):
        self.now = now
        self.Code = Code
        self.State = State
        self.Score = Score
        self.Speed = Speed
        self.model = model
        self.path = './output/Info/' + self.model + "/" + self.model + "_" + self.now.strftime("%m") + \
                    self.now.strftime("%Y") + '.xlsx'
        self.path2 = r'./output/Info/' + self.model + "/" + self.model + "_" + self.now.strftime("%m") + \
                     self.now.strftime("%Y") + '.xlsx'
        self.message = self.save_xlsx()

    def save_xlsx(self):
        while True:
            # try:
            if not os.path.isfile(self.path):
                # dataframe Name and Age columns
                df = pd.DataFrame(columns=["Date", "Time", "Code", "State", "Score", "Speed"])
                # Create a Pandas Excel writer using XlsxWriter as the engine.
                writer = pd.ExcelWriter(self.path, engine='xlsxwriter')

                # Convert the dataframe to an XlsxWriter Excel object.
                df.to_excel(writer, index=False)
                worksheet = writer.sheets['Sheet1']
                worksheet.set_column('A:A', 20)
                worksheet.set_column('B:B', 10)
                worksheet.set_column('C:C', 30)

                # Close the Pandas Excel writer and output the Excel file.
                writer.save()

            reader = pd.read_excel(self.path)
            df = pd.DataFrame([[self.now.strftime("%d %B %Y"), self.now.strftime("%X"),
                                self.Code, self.State, self.Score, self.Speed]],
                              columns=["Date", "Time", "Code", "State", "Score", "Speed"])

            with pd.ExcelWriter(self.path, engine="openpyxl", mode="a", date_format='dd mmmm yyyy') as writer:
                # try to open an existing workbook
                writer.book = load_workbook(self.path)

                # copy existing sheets
                writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)

                df.to_excel(writer, index=False, header=False, startrow=len(reader) + 1)
                # Close the Pandas Excel writer and output the Excel file.
                writer.save()
                return None
            # break
            # except Exception as e:
            #     s = str(e)
            #     print(s)
            #     message = "The action can't be completed because the file is open in another tab!\nClose file and try " \
            #               "again... "
            #     return message
            #     raise
            #     break

if __name__ == "__main__":
    now = datetime.now()
    today = datetime.today()
    save_data(now, "abc", "abc", 1.2, 1.2, "abc")


import cPickle
import itertools
import numpy
import paddle.v2.dataset.common
import tarfile

__all__ = ['train100', 'test100', 'train10', 'test10', 'convert']

URL_PREFIX = 'https://www.cs.toronto.edu/~kriz/'
CIFAR10_URL = URL_PREFIX + 'cifar-10-python.tar.gz'
CIFAR10_MD5 = 'c58f30108f718f92721af3b95e74349a'
CIFAR100_URL = URL_PREFIX + 'cifar-100-python.tar.gz'
CIFAR100_MD5 = 'eb9058c3a382ffc7106e4002c42a8d85'

def reader_creator(filename, sub_name):
    def read_batch(batch):
        data = batch['data']
        labels = batch.get('labels', batch.get('fine_labels', None))
        assert labels is not None
        for sample, label in itertools.izip(data, labels):
            yield (sample / 255.0).astype(numpy.float32), int(label)

    def reader():
        with tarfile.open(filename, mode='r') as f:
            names = (each_item.name for each_item in f
                     if sub_name in each_item.name)

            for name in names:
                batch = cPickle.load(f.extractfile(name))
                for item in read_batch(batch):
                    yield item

    return reader

def train100():
    """
    CIFAR-100 training set creator.

    It returns a reader creator, each sample in the reader is image pixels in
    [0, 1] and label in [0, 99].

    :return: Training reader creator
    :rtype: callable
    """
    return reader_creator(
        paddle.v2.dataset.common.download(CIFAR100_URL, 'cifar', CIFAR100_MD5),
        'train')

def test100():
    """
    CIFAR-100 test set creator.

    It returns a reader creator, each sample in the reader is image pixels in
    [0, 1] and label in [0, 9].

    :return: Test reader creator.
    :rtype: callable
    """
    return reader_creator(
        paddle.v2.dataset.common.download(CIFAR100_URL, 'cifar', CIFAR100_MD5),
        'test')

def train10():
    """
    CIFAR-10 training set creator.

    It returns a reader creator, each sample in the reader is image pixels in
    [0, 1] and label in [0, 9].

    :return: Training reader creator
    :rtype: callable
    """
    return reader_creator(
        paddle.v2.dataset.common.download(CIFAR10_URL, 'cifar', CIFAR10_MD5),
        'data_batch')

def test10():
    """
    CIFAR-10 test set creator.

    It returns a reader creator, each sample in the reader is image pixels in
    [0, 1] and label in [0, 9].

    :return: Test reader creator.
    :rtype: callable
    """
    return reader_creator(
        paddle.v2.dataset.common.download(CIFAR10_URL, 'cifar', CIFAR10_MD5),
        'test_batch')

def fetch():
    paddle.v2.dataset.common.download(CIFAR10_URL, 'cifar', CIFAR10_MD5)
    paddle.v2.dataset.common.download(CIFAR100_URL, 'cifar', CIFAR100_MD5)

def convert(path):
    """
    Converts dataset to recordio format
    """
    paddle.v2.dataset.common.convert(path, train100(), 1000, "cifar_train100")
    paddle.v2.dataset.common.convert(path, test100(), 1000, "cifar_test100")
    paddle.v2.dataset.common.convert(path, train10(), 1000, "cifar_train10")
    paddle.v2.dataset.common.convert(path, test10(), 1000, "cifar_test10")


from typing import List

class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        prev_index = 0
        cur_length = 0
        output = []
        for cur_index in range(len(words)):
            cur_length += len(words[cur_index]) + 1
            if cur_length - 1 > maxWidth:

                words_lengths = cur_length - 1 - len(words[cur_index]) - cur_index + prev_index
                spaces_needed = max(cur_index - prev_index - 1,1)
                spaces_lengths = maxWidth - words_lengths
                spaces = [spaces_lengths//spaces_needed*" "for _ in range(spaces_needed)]+[""]
                if spaces_needed > 0:
                    for i in range(spaces_lengths%spaces_needed):
                        spaces[i] += " "
                newline = ""
                for i,j in zip(words[prev_index:cur_index],spaces):
                    newline+=i+j
                output.append(newline)
                cur_length = len(words[cur_index]) + 1
                prev_index = cur_index
        return output + [" ".join(words[prev_index:]).ljust(maxWidth)]

x = Solution()
print( x.fullJustify(["What","must","be","acknowledgment","shall","be"],16) )


def main():
    time = input("What time is it? (HH:MM or H:MM): ")
    total_time = convert(time)

    if 7.0 <= total_time <= 8.0:
        print("breakfast time")
    elif 12.0 <= total_time <= 13.0:
        print("lunch time")
    elif 18.0 <= total_time <= 19.0:
        print("dinner time")

def convert(time):
    if ":" in time:
        hours, minutes = map(int, time.split(":"))
    else:
        if len(time) == 3:
            hours = int(time[0])
            minutes = int(time[1:])
        elif len(time) == 4:
            hours = int(time[:2])
            minutes = int(time[2:])
        else:
            return "Invalid time format"

    total_time = hours + minutes / 60
    return total_time

if __name__ == "__main__":
    main()


from __future__ import annotations
import sys, os
import numpy as np
from scipy.optimize import linprog
from scipy.linalg import LinAlgWarning
from typing import List, Tuple, Union
import warnings

warnings.filterwarnings(action="ignore", category=LinAlgWarning, module="scipy")
warnings.filterwarnings(action="ignore", category=RuntimeWarning, module="scipy")

sys.path.append(os.path.dirname(__file__))
from grasp_functions import is_grasp_valid
from class_jacobian import Jacobian
from class_grasp import Grasp

def friction_form_closure(grasp: "Grasp") -> Tuple(int, np.ndarray):
    G = grasp.Gt.transpose()
    L = grasp.l
    if not is_grasp_valid(grasp):
        return 0, np.zeros((L,))
    nc = grasp.nc

    F = grasp.F
    e = []
    for i in range(nc):
        e.append([1, 0, 0])
    e = np.array(e).flatten()

    obj = np.concatenate((-1 * np.ones((1, 1)), np.zeros((1, L))), axis=1).flatten()

    lhs_ineq = np.block(
        [
            [np.ones((F.shape[0], 1)), -F],
            [np.zeros(1), e],
        ]
    )

    rhs_ineq = np.concatenate(
        (np.zeros((1, F.shape[0])), 10 * nc * np.ones((1, 1))), axis=1
    ).flatten()

    lhs_eq = np.concatenate((np.zeros((6, 1)), G), axis=1)

    rhs_eq = np.zeros((6, 1)).flatten()

    bnd_d = (0, None)
    bnd_lambda = (None, None)

    bnd = []
    bnd.append(bnd_d)

    for i in range(L):
        bnd.append(bnd_lambda)
    try:
        opt = linprog(
            c=obj,
            A_ub=lhs_ineq,
            b_ub=rhs_ineq,
            A_eq=lhs_eq,
            b_eq=rhs_eq,
            bounds=bnd,
            method="revised simplex",
        )
    except Exception:
        pass
    if opt.success and abs(opt.fun) != 0:
        lambdas = []
        for i, var in enumerate(opt.x, 0):
            if i == 0:
                pass
            else:
                lambdas.append(var)
        return abs(opt.fun), np.array(lambdas)
    return 0, np.zeros((L,))

def force_closure(grasp: "Grasp", jacobian: "Jacobian") -> bool:
    assert isinstance(jacobian, Jacobian), "jacobian argument must be of type Jacobian"
    L = grasp.l
    if not friction_form_closure(grasp)[0]:
        print(
            "Force Closure does not Exist because Friction Form Closure does not Exist"
        )
        return False
    nc = grasp.nc
    G = grasp.Gt.transpose()
    Jt = jacobian.J.transpose()
    e = []
    E = np.array([1, 0, 0]).reshape(1, 3)
    for _ in range(nc):
        e.append([1, 0, 0])
        Etemp = np.concatenate(
            (np.zeros((1, E.shape[1])).flatten(), np.array([1, 0, 0]))
        ).reshape(1, E.shape[1] + 3)
        E = np.concatenate((E, np.zeros((E.shape[0], 3))), axis=1)
        E = np.concatenate((E, Etemp), axis=0)
    e = np.array(e).flatten()
    E = E[0:-1, 0:-3]
    obj = np.concatenate((-1 * np.ones((1, 1)), np.zeros((1, L))), axis=1).flatten()

    lhs_ineq = np.block(
        [
            [np.ones((E.shape[0], 1)), -E],
            [-1 * np.ones(1), np.zeros((1, L))],
            [np.zeros(1), e],
        ]
    )

    rhs_ineq = np.concatenate(
        (np.zeros((1, E.shape[0] + 1)), 10 * nc * np.ones((1, 1))), axis=1
    ).flatten()

    lhs_eq = np.block(
        [
            [np.zeros((6, 1)), G],
            [np.zeros((jacobian.nq, 1)), Jt],
        ]
    )
    print(lhs_eq)
    rhs_eq = np.zeros((6 + jacobian.nq, 1)).flatten()

    bnd = [(None, None)]

    opt = linprog(
        c=obj,
        A_ub=lhs_ineq,
        b_ub=rhs_ineq,
        A_eq=lhs_eq,
        b_eq=rhs_eq,
        bounds=bnd,
        method="revised simplex",
    )
    if opt.success and abs(opt.fun) == 0:
        print("Force Closure Exist")
        return True
    else:
        print("Force Closure does not Exist")
        return False

def alpha_from_direction(
    grasp: "Grasp", d_ext: List, fc_max: int = 1
) -> Union[float, np.ndarray]:
    G = grasp.get_Gt().transpose()
    L = grasp.l
    if not is_grasp_valid(grasp):
        return -2, np.zeros((L,))

    if not isinstance(d_ext, np.ndarray):
        d_ext = np.array(d_ext)

    F = grasp.F
    lF = F.shape[0]

    obj = np.zeros((L + 1, 1))
    obj[0] = -1

    # 0*alpha - F*fc <= F*fa (F*fc > -F*fa)

    # print("L =", L)
    fa = np.zeros((L,))
    # step = 4 if grasp.type == "SF" else 3

    # for i in range(0, L, step):
    #     fa[i] = grasp.contact_points[i // step].fa

    pos = 0
    for cp in grasp.contact_points:
        print(cp)
        fa[pos] = cp.fa
        pos += 4 if cp.type.startswith("SF") else 3

    lhs_ineq = np.concatenate((np.zeros((lF, 1)), -F), axis=1)
    rhs_ineq = (F @ fa).flatten()

    # dWext*alpha + G*fc = 0
    lhs_eq = np.concatenate(
        (
            d_ext.reshape(6, 1),
            G,
        ),
        axis=1,
    )
    rhs_eq = np.zeros((6,))

    lower_bound = []
    for val in grasp.contact_points:
        lower_bound.append(val.fa)

    bnd = []
    bnd.append((0, None))  # alpha

    for i in range(L):
        if i % 3 == 0:
            bnd.append((None, fc_max))  # fcn
        else:
            bnd.append((None, None))  # fct
    try:
        opt = linprog(
            c=obj,
            A_ub=lhs_ineq,
            b_ub=rhs_ineq,
            A_eq=lhs_eq,
            b_eq=rhs_eq,
            bounds=bnd,
            method="revised simplex",
        )
    except Exception:
        return -1, np.zeros((L,))
    else:
        if opt.success:
            return opt.x[0], opt.x[1:]
        else:
            return 0, np.zeros((L,))

def forces_from_perturbation(grasp: Grasp, perturbation: List) -> Union(float, List):
    L = grasp.l
    if not is_grasp_valid(grasp):
        return np.zeros((L,))

    if not isinstance(perturbation, np.ndarray):
        perturbation = np.array(perturbation)

    G = grasp.Gt.transpose()
    F = grasp.F
    lF = np.shape(F)[0]

    # min(z)
    obj = np.zeros((L + 1, 1))
    obj[0] = 1

    # -F*fc <= 0 (F*fc > 0)
    # fc - z <= (fc <= z)
    fcn_coef = np.zeros((L, L))
    for i in range(L):
        fcn_coef[i, i] = 1 if not i % 1 else 0  # when one equiv to eye
    lhs_ineq = np.block([[np.zeros((lF, 1)), -F], [-1 * np.ones((L, 1)), fcn_coef]])
    rhs_ineq = np.zeros((lF + L,))
    # G*fc = -g (G*fc + alpha*dext = 0)
    lhs_eq = np.concatenate((np.zeros((6, 1)), G), axis=1)
    rhs_eq = -perturbation

    bnd = []
    bnd.append((0, None))
    bnd_fcn = (0.1, None)
    bnd_fct = (None, None)

    for i in range(L):
        if i % 3 == 0:
            bnd.append(bnd_fcn)
        else:
            bnd.append(bnd_fct)

    opt = linprog(
        c=obj,
        A_ub=lhs_ineq,
        b_ub=rhs_ineq,
        A_eq=lhs_eq,
        b_eq=rhs_eq,
        bounds=(None, None),
        method="revised simplex",
    )

    if opt.success:
        return opt.x[1:]
    return np.zeros((L,))

def main():
    val = (
        __file__.replace(os.path.dirname(__file__), "")[1:]
        + " is meant to be imported not executed"
    )
    print(f"\033[91m {val}\033[00m")

if __name__ == "__main__":
    main()


import yaml

def assetList(yamlFile):
    with open(yamlFile) as f:
        dict = yaml.load(f, Loader=yaml.FullLoader)

        fullYaml = dict

        videoInfo = []
        videoList = list(dict["Project"]["assets"]["video"].keys())

        def videoListInfo():
            for i in range(len(videoList)):
                videoInfo.append(dict["Project"]["assets"]["video"][videoList[i]])
            return videoInfo

        videoListInfo()

        audioInfo = []
        audioList = list(dict["Project"]["assets"]["audio"].keys())

        def audioListInfo():
            for i in range(len(audioList)):
                audioInfo.append(dict["Project"]["assets"]["audio"][audioList[i]])
            return audioInfo

        audioListInfo()

        imageInfo = []
        imageList = list(dict["Project"]["assets"]["image"].keys())

        def imageListInfo():
            for i in range(len(imageList)):
                imageInfo.append(dict["Project"]["assets"]["image"][imageList[i]])
            return imageInfo

        imageListInfo()

        textInfo = []
        textList = list(dict["Project"]["assets"]["text"].keys())

        def textListInfo():
            for i in range(len(textList)):
                textInfo.append(dict["Project"]["assets"]["text"][textList[i]])
            return textInfo

        textListInfo()

    output = dict["Project"]["export"]

    return (
        [videoList, audioList, imageList, textList],
        [videoInfo, audioInfo, imageInfo, textInfo],
        [output],
        [fullYaml],
    )

# print(assetList("test.yaml"))


import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("life_expectancy_years.csv", index_col = "country")

returnRows = lambda: df.shape[0]+1
returnCols = lambda: df.shape[1]+1
yearsSpan = lambda: df.head(0).columns
findOldestYear = lambda: yearsSpan().max()
findNewestYear = lambda: yearsSpan().min()
southAfricaMax = lambda: df.loc['South Africa'].max()
southAfricaMin = lambda: df.loc['South Africa'].min()
southAfricaMaxYear = lambda: df.loc['South Africa'].idxmax()
southAfricaMinYear = lambda: df.loc['South Africa'].idxmin()
maxCountry2018 = lambda: df[findOldestYear()].idxmax()
minCountry2018 = lambda: df[findOldestYear()].idxmin()
over50YearsOldCountriesOld = lambda: len([i for i in df[findOldestYear()][df[findOldestYear()] > 50]])
over50YearsOldCountriesNew = lambda: len([i for i in df[findNewestYear()][df[findNewestYear()] > 50]])

def returnNewandOldStats(oldestYear, newestYear):
	newAndOldStats = df[[oldestYear, newestYear]].describe()
	return newAndOldStats[1::]

print("1. How many rows and columns does this data set have? \n")
print("The data set has " + str(returnRows()) + " rows and " + str(returnCols()) + " columns\n")

print("2. What years does the data span? \n")
print("The years covered by the data set are: " + str(yearsSpan()) + "\n")

print("3. For the oldest year and the newest year, what are the following summary statistics: mean, std, min, max, 25% quartile, 50% quartile, 75% quartile? \n")
print("The summary statistics from the oldest year and newest year are shown as below" + str(returnNewandOldStats(findNewestYear(),findOldestYear())) + '\n')

print("4. What were the min and max values for South Africa over these years? \n")
print("The min and max values for South Africa over years 1800-2019 are " + str(southAfricaMin()) + " and " + str(southAfricaMax()) + "\n")

print("5. What years were these min and max values in (For South Africa)? \n")
print("The years contain min and max values are " + str(southAfricaMinYear()) + " and " + str(southAfricaMaxYear()) + "\n")

print("6. As of 2018 which country has the highest and lowest life expectancy? \n")
print("The country has the lowest life expectancy in 2018 is " + str(minCountry2018()) + "\nThe country has the highest life expectancy in 2018 is " + str(maxCountry2018()) + "\n")

print("7. In the oldest year we have, how many countries had a life expectancy over 50 years old? \n")
print(str(over50YearsOldCountriesOld()) + " countries \n")

print("8. In the newest year, how many countries had a life expectancy over 50 years old? \n")
print(str(over50YearsOldCountriesNew()) + " country \n")

df.loc[['United States','Germany']].T.plot()
plt.xlabel('Year')
plt.ylabel('Years (How many years)')
plt.title("Life Expectancy of United States vs Germany")
plt.show()


from typing import Any, List, Optional, Dict
import pandas as pd
import re, json

def correct_spellings(txt: str) -> str:
    for cor in REPLACEMENTS:
        for mis in REPLACEMENTS[cor]:
            txt = txt.replace(mis, cor)
    return txt

# drops formatting
def npf_to_quote(npf: List[Dict[str, Any]]) -> str:
    return "\n".join(r["text"] for r in npf)

def is_quote(q: str) -> bool:
    return (len(q) - q.count("\n")) / (q.count("\n") + 1) < 500 and (bool)(
        re.search("^((\*[^\n]+\*|\[[^\n]+\]|[A-Za-z0-9][^\n:]*:[^\n]*)(\n|))+$", q)
    )
    # check for each line, the only colon should NOT be inside parenthesis

def clean(df: Any) -> pd.DataFrame:
    if type(df) is not pd.DataFrame:
        df = pd.DataFrame(df)
    df = df[
        [(not any((bool)(re.search("^not.*quote$", t)) for t in ts)) for ts in df.tags]
    ]
    df["quote"] = df["content"].apply(npf_to_quote)
    df = df[df["quote"].apply(is_quote)]
    return df


#调用该模块返回一个或多个可用的代理

#1.爬取所有代理并保存到本地 upgrade_ip
#2.从本地文件中测试选出可用代理，保存在数组中

import requests
import telnetlib
import threading
import  queue
from multiprocessing import Process
from lxml import etree

q = queue.Queue()

def sava_proxy(url):
   headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"}
   response = requests.get(url,headers = headers)
   html = response.text
   x_html = etree.HTML(html)
   ip_info = x_html.xpath("//tr[@class]")

   with open("ip.txt",'a') as f:
       for i in ip_info:
           ip = i.xpath("./td[2]")[0].text
           port = i.xpath("./td[3]")[0].text
           ip_port = ip+":"+port
           f.write(ip_port+"\n")

#将文件中的Ip存放在queue中
def get_proxy():
    with open("ip.txt")as f:
        while True:
            str = f.readline()
            if not str:
                break
            q.put(str)

#验证代理是否有效
def get_test_proxy():
    while not q.empty():
        ip = q.get().split(":")[0].strip()
        port = q.get().split(":")[1].strip()
        if test_proxy(ip,port):
            return ip,port
        else:
            pass

def threas(fun):
    for i in range(30):
        t = threading.Thread(target = fun )
        t.start()
        t.join()

def test_proxy(ip,port):
    try:
         telnetlib.Telnet(ip,port=port,timeout=3)
    except:
        print("field   "+ip+":"+port)
        return False
    else:
        print("success   "+ip+":"+port)
        return True

if __name__ == '__main__':
    url = "http://www.xicidaili.com/nt/"
    sava_proxy(url)
    get_proxy()
    threas(get_test_proxy)


from operator import itemgetter
import board
import random
import math
import time

class Climber:
    def __init__(self, size):
        self.state = board.Board(size)
        self.h = self.state.get_h()
        self.time = 1

    def solution(self):
        start_time = time.time()
        self.state.get_h_board()
        cont = 0
        h_to_g = [self.h]

        while self.time < 1000:
            cont += 1
            res = self.new_state()
            self.state.get_h_board()
            h_to_g.append(res)
            if res == 0:
                break

        final_time = time.time() - start_time
        return (self.h, cont, final_time, h_to_g)

    def solution_finder(self):
        self.state.print_board()
        self.state.get_h_board()
        print()
        print("H actual: " + str(self.h))
        print("COSTO INICIAL")
        self.state.print_cost()

        print()

        cont = 0

        while self.time < 1000:
            cont += 1
            self.new_state()
            self.state.get_h_board()
        print()

        self.state.print_board()

        print("H actual: " + str(self.h))
        print("Numero de iteraciones llevadas a cabo: " + str(cont))
        print("COSTO ACTUAL")
        self.state.print_cost()

    def new_state(self):
        board = self.state.board
        nodes = []

        for i in range(self.state.size):
            nodes.extend(board[i])

        flag = True
        while flag:
            if len(nodes) == 0:
                break
            rnd = random.randint(0, len(nodes)-1)
            element = nodes.pop(rnd)
            if element.value !=  u"\u2B1B":
                dif = self.h - element.cost
                if dif > 0:
                    self.h = element.cost
                    element.value = u"\u2B1B"
                    self.state.queensNodes[element.x] = u"\u2B1C"
                    self.state.queensNodes[element.x] = element
                    flag = False
                else:
                    prob = 1/self.time
                    num = random.uniform(0, 1)
                    if num < prob:
                        self.h = element.cost
                        element.value = u"\u2B1B"
                        self.state.queensNodes[element.x] = u"\u2B1C"
                        self.state.queensNodes[element.x] = element
                        flag = False

        self.time +=2
        return self.h


"""
Viterbi Algorithm
CSE 415 project, 11/29/2019

Usage:
python viterbi.py hmm_filename inputfilename outputfilename

  * the HMM file must be in format created by the other script.
  * input file is a text file with one sentence per line.
    If omitted, gets input at command line by prompting user
  * output file is where output indicating the best parse found for
    the input sentence(s) is saved.

Example command line arguments:
3g_hmm the_store.txt output.txt
"""

import sys
import math
import numpy as np
import svgwrite

SPACING = 150
RADIUS = 44

def init_drawing(sentence, len=10):
    '''

    :param sentence: name based on the sentence or line being diagrammed
    :param sentence: length of sentence or line, to determine width
    :return: the drawing object named for the line being diagrammed
    '''
    name = sentence + '.svg'
    dwg = svgwrite.Drawing(name, profile='tiny', size=(len*SPACING,len*SPACING))
    return dwg

def draw_word(dwg, word, coords):
    dwg.add(dwg.text(word,
                     insert=coords, font_size="15px", fill='blue'))

def draw_state(dwg, log_prob=-5.12, state_name = "BOS_NNP", center=(100,100)):
    '''

    :param dwg:
    :param log_prob:
    :param state_name:
    :param center:
    :return:
    '''
    radius = RADIUS
    center_offset = 30
    right_side = (center[0]+ radius, center[1])
    dwg.add(dwg.circle(center, radius, stroke='blue', stroke_width=3, fill='none'))
    dwg.add(dwg.text(state_name,
                     insert=(center[0]-center_offset, center[1]+center_offset/2), font_size="15px", fill='red'))
    dwg.add(dwg.text("p={:.2f}".format(log_prob),
                     insert=(center[0]-center_offset, center[1]-center_offset/2), font_size="15px", fill='black'))

    dwg.save()
    return (state_name, right_side)

input_text_file = ''
output_text_file = 'output.txt'
if len(sys.argv) >= 4:
    output_text_file = sys.argv[3] # assume third argument is output file name

if len(sys.argv) > 3:
    input_text_file = sys.argv[2]
def read_hmm():

    states_key = {}
    states_index = {}
    emissions_key = {}
    init_key = {}
    init_lines = []

    def open_hmm():
        init = False
        transition = False
        emission = False
        states_key_counter = 0
        emissions_key_counter = 0

        with open(sys.argv[1], "r") as file:
            for line in file:
                line = line[:-1]
                if line == "":
                    continue
                elif line.startswith("state_num="):
                    state_num = int(line.split("=")[1])
                elif line.startswith("sym_num="):
                    sym_num = int(line.split("=")[1])
                elif line.startswith("init_line_num="):
                    init_line_num = int(line.split("=")[1])
                elif line.startswith("\\init"):
                    init = True
                elif line.startswith("\\transition"):
                    init = False
                    transition = True
                    transitions_array = np.full((state_num, state_num), -np.inf)
                elif line.startswith("\\emission"):
                    transition = False
                    emission = True
                    emissions_array = np.full((sym_num, state_num), -np.inf)
                elif init == True and line[-1].isdigit():
                    line = line.split()
                    start_prob = line[1]
                    start_state = line[0]
                    init_key[start_state] = float(start_prob)
                    init_lines.append(line)
                elif transition == True and line[-1].isdigit():
                    line_full = line
                    line = line.split()
                    if float(line[2]) > 1 or float(line[2]) < 0:
                        sys.stderr.write("warning: the prob is not in [0,1] range:{}".format(line_full))
                    state1 = line[0]
                    state2 = line[1]
                    if len(line) > 3:
                        prob = float(line[3])
                    else:
                        prob = math.log10(float(line[2]))
                        # prob = float(line[2]) # NOTE: in this case, not using log probabilities
                    if state1 not in states_key.keys():
                        states_key[state1] = states_key_counter
                        states_index[states_key_counter] = state1
                        states_key_counter +=1
                    if state2 not in states_key.keys():
                        states_key[state2] = states_key_counter
                        states_index[states_key_counter] = state2
                        states_key_counter += 1
                    i = states_key[state1]
                    j = states_key[state2]
                    transitions_array[i, j] = prob
                elif emission == True and line[-1].isdigit():
                    line_full = line
                    line = line.split()
                    if float(line[2]) > 1 or float(line[2]) < 0:
                        sys.stderr.write("warning: the prob is not in [0,1] range:{}".format(line_full))
                    word = line[1]
                    if word not in emissions_key.keys():
                        emissions_key[word] = emissions_key_counter
                        emissions_key_counter +=1
                    # emission_lines.append(line)
                    if len(line) > 3:
                        word = line[1]
                        state = line[0]
                        prob = float(line[3])
                    else:
                        word = line[1]
                        state = line[0]
                        prob = math.log10(float(line[2]))
                    i = emissions_key[word]
                    j = states_key[state]
                    emissions_array[i, j] = prob

                else:
                    continue
            try:
                k = emissions_key["<unk>"]
                # print(np.shape(np.argwhere(emissions_array[k, :] > -np.inf)))
            except Exception as e:
                print("Warning: No unknown found when loading HMM: {}".format(e))
        return transitions_array, emissions_array

    # open_hmm()

    def store_initials():
        init_probs = {}
        for init in init_lines:
            init_state = states_key[init[0]]
            init_prob = math.log10(float(init[1]))
            init_probs[init_state] = init_prob
        return init_probs

    transitions, emissions = open_hmm()
    init_probs = store_initials()

    return init_probs, states_key, states_index, emissions_key, transitions, emissions

def print_trellis(trellis):
    return

def viterbi(sentence, pi, states_key, states_index, emissions_key, transitions, emissions, line_count=0):

    def run_viterbi(sentence, line_num=0):
        # create diagram for this sentence
        dwg = init_drawing("line"+str(line_num))

        # Create trellis and backpointer matrices
        sentence = sentence.split()

        word_index = {}
        index_word = {}
        index = 0
        for word in sentence:
            index_word[index] = word
            word_index[word] = index
            index += 1
        s = len(sentence) + 1
        trans = len(transitions)
        trellis = np.full((trans,s), -np.inf)
        backpointers = np.full((trans,s), -1) #(fill backpointer array with dummy pointer -1)

        # Initialize array
        trellis_diagram_layers = []
        for n in range(trans):
            if n in pi.keys():
                trellis[n,0] = pi[n]
                trellis_layer_line0 = {}
                draw_word(dwg, 'START', (SPACING-(RADIUS), SPACING-100))
                (st_name, rt_side) = draw_state(dwg, 1, states_index[n],
                                                (SPACING * (0 + 1), SPACING * 1))
                trellis_layer_line0[states_index[n]] = rt_side # save right side coords
        trellis_diagram_layers.append(trellis_layer_line0)

        # Recursive procedure to fill array
        for t in range(s-1):
            # build string to print for this word's trellis layer
            trellis_layer_string = ''
            # hash for drawing lines in diagram
            trellis_layer_lines = {}
            j_found_count = 0  # for use in spacing out trellis diagram

            # Find all cells with values for i-th element - previous cells' probabilities
            prev_probs = trellis[:,t]
            prev_probs = np.where(prev_probs != -np.inf)[0]

            # Get the index of the current word, or <unk> if not in emissions table
            current_word = index_word[t]
            draw_word(dwg, current_word, (SPACING*(t+2)-(.8*RADIUS), SPACING - 100))
            if current_word in emissions_key.keys():
                k = emissions_key[current_word]
            else:
                try:
                    k = emissions_key["<unk>"] # TODO: BUG - WHAT IF NO UNK IN FILE?
                except Exception as e:
                    print("Warning: Word = {}: No unknown probability found with key = {}".format(current_word, e))
            for j in range(trans):
                if emissions[k,j] == -np.inf:
                    continue
                max_prob = -np.inf
                max_trans_emit_p = -np.inf
                max_pointer = -1
                for i in prev_probs:
                    if transitions[i,j] != -np.inf:
                        trans_emit_p = transitions[i,j] + emissions[k,j]
                        temp = trellis[i,t] + trans_emit_p #+ transitions[i,j] + emissions[k,j]
                        if temp > max_prob:
                            max_prob = temp
                            max_trans_emit_p = trans_emit_p
                            max_pointer = i  # comes from i

                trellis[j,t+1] = max_prob

                # Printing and drawing
                # we can print at time t+1, word current_word, state j coming from max_pointer if max_prob!=-inf
                if not max_prob == -np.inf:
                    j_found_count +=1
                    source = states_index[max_pointer]
                    state = states_index[j]  # we've just added this state
                    trellis_layer_string += "[{} (p={:.2f}, from {})]".format(
                        state, max_trans_emit_p, source)

                    (st_name, rt_side) = draw_state(dwg, max_trans_emit_p, state,
                               (SPACING*(t+2), SPACING*j_found_count))
                    # draw lines connecting to previous layer
                    dest_pt = trellis_diagram_layers[t][source]
                    left_side = (rt_side[0]-(2*RADIUS), rt_side[1])
                    dwg.add(dwg.line(left_side, dest_pt, stroke=svgwrite.rgb(10, 10, 16, '%')))
                    dwg.save()
                    trellis_layer_lines[st_name] = rt_side

                # update backpointers
                backpointers[j,t+1] = max_pointer

            # done with for j loop,
            print(current_word + ": " + trellis_layer_string)  #print the trellis layer
            # add new states to row t of trellis diagram layers
            trellis_diagram_layers.append(trellis_layer_lines)

        # Backtrace best path
        out = []

        # Get best final state
        j = np.argmax(trellis[:,s-1],axis=0)
        best_final_state_prob = trellis[j,s-1]
        out.append(states_index[j])

        for t in range(s-1, 0, -1):
            i = backpointers[j,t]
            if (i > -1):
                out.append(states_index[i])
            j = i
        out.reverse()
        return " ".join(out), best_final_state_prob

    output = run_viterbi(sentence, line_num=line_count)
    return output

def get_output_string(line, v_out):
    '''
    Creates a string for output of a line of input followed by its parse
    and its log probabability
    :param line: The line of input. Generally should be a sentence.
    :param v_out: A tuple (parse, lg_prob)
      The parse is a string like: BOS_BOS BOS_DT DT_NN NN_VBD VBD_JJ JJ_NN
      The lg_prob is a negative number like: -17.547289547289.
    :return:
      Example: the store sold expensive goods => BOS_BOS BOS_DT DT_NN NN_VBD VBD_JJ JJ_NNS -17.142151925332413
    '''
    # return line[:-1] + " => " + v_out[0] + " " + str(v_out[1]) + "\n"
    return line.strip() + " => " + v_out[0] + " " + str(v_out[1]) + "\n"

'''
Load the HMM
'''
pi, states_key, states_index, emissions_key, transitions, emissions = read_hmm()

with open(output_text_file, "w") as out: # always logging our output
    if not input_text_file == '':
        with open(input_text_file, "r") as file:
            line_count = 0
            for line in file:
                line_count += 1
                v_out = viterbi(line, pi, states_key, states_index, emissions_key, transitions, emissions, line_count=line_count)
                out.write(get_output_string(line, v_out))
                print(get_output_string(line, v_out))   # also print to screen

do_exit = False
while not do_exit:
    response = input("Enter a sentence to parse. (to quit, enter 'exit' or 'q')")
    if response == "exit" or response == 'q':
        do_exit = True
    else:
        v_out = viterbi(response, pi, states_key, states_index, emissions_key, transitions, emissions)
        print(get_output_string(response, v_out))


import matplotlib.pyplot as plt

with open('data.csv') as f:
    data = f.read()

data = data.split('\n')
del data[-1]
data = list(map(float, data))
plt.plot(data)
plt.savefig('graph.jpg')
plt.close()
print('Graph Created')


import logging
import os
import time

import allure
import tools
from conftest import PLATFORM_NAME, ENV, DEVICE_NAME
from constants import PROJECT_ROOT

class BasePage:
    """Base class to initialize the base page that will be called from all
    pages"""

    def __init__(self, driver):
        self.driver = driver
        self.platform_name = PLATFORM_NAME
        self.device_name = DEVICE_NAME
        self.env = ENV

    current_time = time.strftime("%Y_%m_%d_%H%M%S")

    def take_screenshot(self, screenshot_name):
        directory_new = f'{PROJECT_ROOT}/screenshots/{self.platform_name}/new/{self.device_name}'
        self.check_exist_dir(directory_new)
        path = f'{directory_new}/{screenshot_name}_{self.current_time}.png'
        self.driver.save_screenshot(path)

        tools.crop_status_bar(path, self.platform_name)

    def check_exist_dir(self, dir):
        if not os.path.exists(dir):
            os.makedirs(dir)

    def compare_image(self, org, new):
        directory_org = f'{PROJECT_ROOT}/screenshots/{self.platform_name}/org/{self.device_name}'
        directory_new = f'{PROJECT_ROOT}/screenshots/{self.platform_name}/new/{self.device_name}'
        directory_changes = f'{PROJECT_ROOT}/screenshots/{self.platform_name}/changes/{self.device_name}'
        directory_result = f'{PROJECT_ROOT}/screenshots/{self.platform_name}/result/{self.device_name}'
        self.check_exist_dir(directory_org)
        self.check_exist_dir(directory_new)
        self.check_exist_dir(directory_changes)
        self.check_exist_dir(directory_result)

        if os.path.exists(f'{directory_org}/{org}.png'):
            original_path = f'{directory_org}/{org}.png'
            copy_original_path = f'{directory_org}/{org}_copy.png'
            new_path = f'{directory_new}/{new}_{self.current_time}.png'
            changes_path = f'{directory_changes}/{org}_changes_{self.current_time}.png'
            result_path = f'{directory_result}/{org}_diff_comb_{self.current_time}.png'
            is_same = tools.compare(driver=self.driver, platform=self.platform_name, device_name=self.device_name, img1=original_path, img2=new_path,
                                    changes_path=changes_path)
            if not is_same:
                tools.draw_text('new', new_path)
                tools.draw_text('original', original_path, copy_original_path)
                tools.draw_text('changes', changes_path)
                tools.combine_image(img1=new_path, img2=copy_original_path, img3=changes_path, result_path=result_path)
                allure.attach.file(result_path, name="result_changes_screenshot",
                                   attachment_type=allure.attachment_type.PNG)
                os.remove(copy_original_path)
            with allure.step('Проверка стартовой страницы визуально'):
                assert is_same, f'Скриншоты различаются - разница будет показана на картинке {result_path}'
        else:
            path = f'{directory_org}/{org}.png'
            self.driver.save_screenshot(path)
            tools.crop_status_bar(path, self.platform_name)


from typing import Dict, List, Tuple

import requests
from os import getenv
from json import loads as parse_json
from pathlib import Path
from time import time, sleep
import numpy as np
from math import log

def get_data(cryptos):
	to_time = int(time() // (1440 * 60)) * 1440 * 60

	data = {}

	for crypto in cryptos:
		array = []
		i = -1
		while True:
			new_data = open_or_download(crypto, to_time - i * 1440 * 60, 1440)
			if "Data" not in new_data or len(new_data["Data"]) == 0:
				break

			for (i, v) in enumerate(new_data["Data"][:-1]):
				# new_data["Data"][i] = (log(v["close"]) + 4) / 13
				new_data["Data"][i] = (new_data["Data"][i + 1]["close"] - v["close"]) / v["close"] * 1000

			array = new_data["Data"][:-1] + array

			i += 1

		# print(crypto, min(array), max(array))
		data[crypto] = array

	return collect(data, cryptos)

def open_or_download(crypto: str, to_time: int, limit: int) -> Dict[str, any]:
	filename = Path("data") / "{0}-{1}-{2}.json".format(crypto, to_time, limit)

	try:
		with open(filename) as f:
			return parse_json(f.read())
	except:
		sleep(0.5)
		r = requests.get("https://min-api.cryptocompare.com/data/histominute", params={
			"fsym": crypto,
			"tsym": "GBP",
			"limit": limit,
			"toTs": to_time
		})

		data = r.json()
		with open(filename, "w") as f:
			f.write(r.text)

		return data

def collect(data: Dict[str, List[Dict[str, any]]], cryptos: List[str]) -> np.ndarray:
	values = np.ndarray([0, len(cryptos)])
	for (i, v) in enumerate(data[cryptos[0]]):
		value = np.ndarray([len(cryptos)])
		value[0] = v

		for (k, w) in enumerate(cryptos[1:]):
			value[k + 1] = data[w][i]

		# if i == 2 and j == 4:
		# 	print(value)

		values = np.concatenate((values, value.reshape(1, len(cryptos))))
	return values


# -*- coding: utf-8 -*-
"""
Created on Sat May  2 17:57:08 2020

@author: pselt
"""
import numpy as np
import cpmg_utils as cpmg
import matplotlib.pyplot as plt

font1 = {'family': 'serif',
        'color':  'black',
        'weight': 'normal',
        'size': 12,
        }

###############################################################################
#
# Path to example data
#
path = 'C:/Users/pselt/OneDrive/old_sciebo_share/NMR-Rohdaten/NMR300/p_selt01/nmr/LOH93'

##############################################################################
# Definiton of the window function
#
# The total window function is created by generating an arbitrary window covering
# a single echo. This is then concetaneted to form the window function over the whole
# echo train. additional points can be added at the front or back.

##########################
# Example 1:
# define the gaussian bell
#
# gauss = cpmg.create_gauss(npoints=402,width=20,center=170)
#
# parameter 1 - npoints: number of complex points in echo. Note: top spin stores real and
# imaginary part separately, while python treats them as a single point
# i.e. TD=800 means np=400

# parameter 2 - width: depends on the window function in question, refer to cpmg-utils

# parameter 3 - center: at which point is the center of the window function.
# This is used to for example shift the top of a gaussian bell through the echo

# gauss = cpmg.create_lorentzian(npoints=402,width=5,center=170)
# gauss = cpmg.create_rectangle(npoints=402,width=100,center=170)
# gauss = cpmg.create_cheby(npoints=402,width=50,center=170)
# gauss = cpmg.create_flattop(npoints=352,width=50,center=170)
# gauss = cpmg.create_rectangle(npoints=452,width=452,center=226)

# gauss = cpmg.create_sinc(npoints=402,width=100,center=170)
# concatenated the gaussian bells
multigauss = cpmg.create_rp_wdw(0,gauss,10,0)

test1 = cpmg.cpmg_data(path,expno=10)
# test1 = cpmg.cpmg_data(path,expno=301)

time, data = test1.return_fid()
test1.apply_wdw(multigauss)

time, data2 = test1.return_fid()
freq, fftdata5 = test1.return_fft(256*1024,128*1024)

test1.reload_fid()
time, data3 = test1.return_fid()
freq, fftdata2 = test1.return_fft(256*1024,128*1024)

###############################################################################
#
# Original Spectrum
#
###################
fig = plt.figure(figsize=(5,3),dpi=200)
ax=plt.gca()

plt.plot(freq, np.abs(fftdata5)/10000,linewidth=0.1,color='k')
plt.xlim(freq[-1],freq[0])

plt.tick_params(axis='x', which='both', labelleft=False, left=False, labelsize=12)
plt.tick_params(axis='y', which='both', labelleft=False, left=False, labelsize=12)

ax.set_xlabel(r'$\nu$ '+'($^{195}$Pt) / Hz', fontdict=font1)
# ax.set_ylabel(r'Intensity / ppm', fontdict=font1)

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)

plt.show()
# fig.savefig("CPMG_spec_org_TDEFF_100echoes.png",dpi=300, format='png', bbox_inches='tight',  pad_inches=0.2,transparent=True)
###################
###############################################################################

###############################################################################
#
# New processing
#
###################
fig = plt.figure(figsize=(5,3),dpi=200)
ax=plt.gca()
sumtest = np.zeros(256*1024)

for k in range(0,200,1):
    gauss = cpmg.create_sinc(npoints=452,width=15,center=126+k)
    # gauss = cpmg.create_flattop(npoints=452,width=100,center=126+k)
    # gauss = cpmg.create_rectangle(npoints=452,width=100,center=126+k)
    # gauss = cpmg.create_tukey(npoints=352,width=100,center=126+k,alpha=0.5)
    # gauss = cpmg.create_cheby(npoints=452,width=75,center=126+k)
    # gauss = cpmg.create_lorentzian(npoints=452,width=50,center=126+k)
    # gauss = cpmg.create_gauss(npoints=352,width=50,center=76+k)
    # concatenated the gaussian bells
    multigauss = cpmg.create_rp_wdw(0,gauss,10,0)
    test1.apply_wdw(multigauss)
    freq, fftdata = test1.return_fft(256*1024)
    # sumtest = sumtest+np.abs(fftdata)
    sumtest = np.fmax(np.abs(sumtest),np.abs(fftdata))
    # plt.plot(freq,np.abs(fftdata))
    test1.reload_fid()
plt.plot(freq, np.abs(fftdata5)/1000000,linewidth=0.2,color='r')
plt.plot(freq,sumtest/1000000,linewidth=0.2,color='k')

plt.xlim(freq[-1],freq[0])

plt.tick_params(axis='x', which='both', labelleft=False, left=False, labelsize=12)
plt.tick_params(axis='y', which='both', labelleft=False, left=False, labelsize=12)

ax.set_xlabel(r'$\nu$ '+'($^{195}$Pt) / Hz', fontdict=font1)
# ax.set_ylabel(r'Intensity / ppm', fontdict=font1)

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
plt.show()
# fig.savefig("CPMG_spec_sinc15_td100.png",dpi=300, format='png', bbox_inches='tight',  pad_inches=0.2,transparent=True)
###############################################################################


import sys
import ast
from obiba_mica.core import MicaClient
from obiba_mica.core import MicaRequest

class RestService:
  """
  Perform raw web services requests.
  """

  def __init__(self, client: MicaClient, verbose: bool = False):
     self.client = client
     self.verbose = verbose

  def make_request(self, method: str):
    """
    Creates a MicaRequest instance

    Note: all responses are return in JSON form

    :param method - HTTP method
    """
    request = self.client.new_request()
    request.method(method)
    request.fail_on_error()
    request.accept_json()
    if self.verbose:
        request.verbose()
    return request

  def make_request_with_content_type(self, method: str, contentType: str, content: str = None):
    """
    Creates a MicaRequest instance with a request body

    :param method - HTTP method
    :param contentType - request content type
    :param content - data to be posted (if ignored a prompt will read-in data from commandline ending with a CTRL-D)
    """
    request = self.make_request(method)
    if contentType:
      request.content_type(contentType)

      if content is not None:
          request.content(content.encode('utf-8'))
      else:
        print('Enter content:')
        request.content(str(sys.stdin.read()).encode('utf-8'))

    return request

  def send_request(self, url: str, request: MicaRequest):
    """
    Sends the request to Mica server
    """
    return request.resource(url).send()

  @classmethod
  def add_arguments(cls, parser):
    """
    Add REST command specific options

    :param parser - commandline args parser
    """
    parser.add_argument('ws', help='Web service path, for instance: /study/xxx')
    parser.add_argument('--method', '-m', required=False,
                        help='HTTP method (default is GET, others are POST, PUT, DELETE, OPTIONS)')
    parser.add_argument('--accept', '-a', required=False, help='Accept header (default is application/json)')
    parser.add_argument('--content-type', '-ct', required=False,
                        help='Content-Type header (default is application/json)')
    parser.add_argument('--json', '-j', action='store_true', help='Pretty JSON formatting of the response')

  @classmethod
  def do_command(cls, args):
    """
    Execute REST command

    :param args - commandline args
    """
    # Build and send request
    client = MicaClient.build(MicaClient.LoginInfo.parse(args))

    try:
        request = client.new_request()
        request.fail_on_error()

        if args.accept:
            request.accept(args.accept)
        else:
            request.accept_json()

        if args.content_type:
            request.content_type(args.content_type)
            print('Enter content:')
            request.content(str(sys.stdin.read()).encode('utf-8'))

        if args.verbose:
            request.verbose()

        # send request
        request.method(args.method).resource(args.ws)
        response = request.send()

        # format response
        res = response.as_json()
        if args.json:
            res = response.pretty_json()
        elif args.method in ['OPTIONS']:
            res = response.headers['Allow']

        # output to stdout
        print(res)
    finally:
        client.close()


from imblearn.pipeline import Pipeline
from imblearn.under_sampling import RandomUnderSampler
from scikeras.wrappers import KerasClassifier
from sklearn.compose import ColumnTransformer
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier, StackingClassifier
from sklearn.linear_model import LogisticRegression, RidgeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler, OneHotEncoder, FunctionTransformer
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from tensorflow import keras
import tensorflow as tf
from cursos_df import seed_value, X

def to_dense_f(x):
    return x.toarray()

to_dense = FunctionTransformer(to_dense_f, accept_sparse=True)

def logistic_regression(additional_steps, additional_params={}):
    return {
        "pipeline": Pipeline(steps=[
            *additional_steps,
            ("logistic_regression", LogisticRegression(random_state=seed_value)),
        ]),
        "params": {
            'logistic_regression__C': [0.1, 1.0, 10.0],
            'logistic_regression__solver': ['lbfgs', 'saga'],
            'logistic_regression__max_iter': [100, 200],
            'logistic_regression__penalty': ['l1', 'l2'],
            **additional_params
        }
    }

def ridge_classifier(additional_steps, additional_params={}):
    return {
        "pipeline": Pipeline(steps=[
            *additional_steps,
            ("ridge_classifier", RidgeClassifier(random_state=seed_value)),
        ]),
        "params": {
            'ridge_classifier__alpha': [0.5],
            'ridge_classifier__solver': ['sag', 'lsqr', 'sparse_cg', 'lbfgs'],
            'ridge_classifier__max_iter': [100, 200],
            **additional_params
        }
    }

def decision_tree(additional_steps, additional_params={}):
    return {
        "pipeline": Pipeline(steps=[
            *additional_steps,
            ("decision_tree", DecisionTreeClassifier(random_state=seed_value)),
        ]),
        "params": {
            'decision_tree__max_depth': [10, 30, 50],
            'decision_tree__min_samples_split': [5, 10, 30],
            'decision_tree__min_samples_leaf': [1, 5, 10],
            **additional_params
        }
    }

def random_forest(additional_steps, additional_params={}):
    return {
        "pipeline": Pipeline(steps=[
            *additional_steps,
            ("random_forest", RandomForestClassifier(random_state=seed_value)),
        ]),
        "params": {
            'random_forest__n_estimators': [150, 300],
            'random_forest__max_features': [5, 20, 50],
            'random_forest__max_depth': [20, 50],
            'random_forest__min_samples_leaf': [1, 2, 4],
            **additional_params
        }
    }

def naive_bayes(additional_steps, additional_params={}):
    return {
        "pipeline": Pipeline(steps=[
            *additional_steps,
            ("naive_bayes", GaussianNB()),
        ]),
        "params": {
            'naive_bayes__var_smoothing': [1e-9, 1e-7],
            **additional_params
        }
    }

def mlp(additional_steps, additional_params={}):
    return {
        "pipeline": Pipeline(steps=[
            *additional_steps,
            ("mlp", MLPClassifier(random_state=seed_value)),
        ]),
        "params": {
            'mlp__hidden_layer_sizes': [(50, 50)],
            'mlp__activation': ['logistic', 'relu'],
            'mlp__solver': ['adam'],
            'mlp__alpha': [0.1],
            'mlp__learning_rate': ['adaptive'],
            **additional_params
        }
    }

def svm(additional_steps, additional_params={}):
    return {
        "pipeline": Pipeline(steps=[
            *additional_steps,
            ("svm", SVC(random_state=seed_value)),
        ]),
        "params": {
            'svm__C': [0.1, 1, 10],
            'svm__gamma': ['auto'],
            'svm__kernel': ['linear'],
            **additional_params
        }
    }

def get_model(hidden_layer_dim, meta):
    n_features_in_ = meta["n_features_in_"]

    model = keras.models.Sequential()
    model.add(keras.layers.Dense(hidden_layer_dim, input_shape=(n_features_in_,), activation='relu'))
    model.add(keras.layers.Dense(hidden_layer_dim, activation='relu'))
    model.add(keras.layers.Dense(1, activation='sigmoid'))

    return model

def keras_model(additional_steps, additional_params={}):
    return {
        "pipeline": Pipeline(steps=[
            *additional_steps,
            ("keras", KerasClassifier(get_model, verbose=0)),
        ]),
        "params": {
            "keras__model__hidden_layer_dim": [50, 100, 200],
            "keras__optimizer": ["adam"],
            "keras__loss": ["binary_crossentropy"],
            "keras__epochs": [1, 5, 10, 20],
            **additional_params
        }
    }

def stacking(additional_steps, additional_params={}):
    stacking_prefix = 'stacking (naive bayes, decision tree, keras) + logistic regression'

    return {
        "pipeline": Pipeline(steps=[
            *additional_steps,
            (stacking_prefix, StackingClassifier(estimators=[
                ("naive_bayes", Pipeline(steps=[("to_dense", to_dense), ("naive_bayes", GaussianNB())])),
                ("decision_tree", DecisionTreeClassifier(random_state=seed_value)),
                ("keras", KerasClassifier(get_model, verbose=0))
            ], final_estimator=LogisticRegression(random_state=seed_value)))
        ]),
        "params": {
            ('%s__naive_bayes__naive_bayes__var_smoothing' % stacking_prefix): [1e-9, 1e-7],
            ('%s__decision_tree__max_depth' % stacking_prefix): [30],
            ('%s__decision_tree__min_samples_split' % stacking_prefix): [5, 10],
            ('%s__decision_tree__min_samples_leaf' % stacking_prefix): [3, 5],
            ('%s__keras__model__hidden_layer_dim' % stacking_prefix): [100],
            ('%s__keras__optimizer' % stacking_prefix): ["adam"],
            ('%s__keras__loss' % stacking_prefix): ["binary_crossentropy"],
            ('%s__keras__epochs' % stacking_prefix): [20],
            ('%s__final_estimator__C' % stacking_prefix): [0.1],
            ('%s__final_estimator__solver' % stacking_prefix): ['saga'],
            ('%s__final_estimator__max_iter' % stacking_prefix): [200],
            ('%s__final_estimator__penalty' % stacking_prefix): ['l1'],
            **additional_params
        }
    }

preprocessor = ('preprocessor (onehot + scaler)', ColumnTransformer(
    transformers=[
        ('scaler', StandardScaler(), X.select_dtypes(include=['float64', 'int']).columns),
        ('onehot', OneHotEncoder(handle_unknown='ignore'), X.select_dtypes(include=['object', 'category']).columns),
    ],
    remainder='passthrough'
))

sampler = ("undersampler", RandomUnderSampler(random_state=seed_value))
pca = [("to_dense", to_dense), ("pca", PCA())]
pca_params = {'pca__n_components': [15, 22]}

tf.config.set_visible_devices([], 'GPU')

pipelines = [
    # logistic_regression([preprocessor, sampler]),
    decision_tree([preprocessor, sampler]),
    # random_forest([preprocessor, sampler]),
    naive_bayes([preprocessor, sampler, ("to_dense", to_dense)]),
    svm([preprocessor, sampler, *pca], additional_params={**pca_params}),
    # mlp([preprocessor, sampler]),
    keras_model([preprocessor, sampler]),
    stacking([preprocessor, sampler])
]


from spacy_types import PreFormatDataset
import os

def process_wiki_ner(
    path: str, categoriesMapping: dict[str, str], categories_prefix=False
) -> PreFormatDataset:
    current_directory = os.path.dirname(os.path.realpath(__file__))
    root_directory = os.path.dirname(os.path.dirname(current_directory))
    path = os.path.join(root_directory, path)

    training_data = []

    annotations = []
    accumulator = []

    for line in open(path, "r", encoding="utf-8"):
        if line == "\n":
            continue

        # split line by \t
        lineContent = line.strip().split(" ")
        # discard the first element second element is the word and the last element is the NER tag

        full_sentence = ""

        for entry in lineContent:
            is_previous_ner_tag = False
            word, _, nerTag = entry.split("|")

            ner_categories = nerTag.split("-")

            if len(ner_categories) == 1:
                nerTag = categoriesMapping[ner_categories[0]]

                if nerTag != "O" and categories_prefix:
                    if is_previous_ner_tag:
                        nerTag = "I-" + nerTag
                    else:
                        nerTag = "B-" + nerTag

                if nerTag.startswith("B-"):
                    is_previous_ner_tag = True

                if nerTag.startswith("O"):
                    is_previous_ner_tag = False

            elif len(ner_categories) == 2:
                if categories_prefix and categoriesMapping[ner_categories[1]] != "O":
                    ner_categories[1] = categoriesMapping[ner_categories[1]]
                    nerTag = "-".join(ner_categories)
                else:
                    nerTag = categoriesMapping[ner_categories[1]]

            startPointer = len(full_sentence)

            accumulator.append((word, nerTag, startPointer))

            full_sentence += word + " "

        # annotations.append(accumulator)
        # based on the accumulator and the full sentence create a object similar to   ("Tokyo Tower is 333m tall.", [(0, 11, "BUILDING")]),
        # and append it to the training data
        for annotationEntry in accumulator:
            word, nerTag, start = (
                annotationEntry[0],
                annotationEntry[1],
                annotationEntry[2],
            )

            wordStartIndex = full_sentence.find(word, start)
            wordEndIndex = wordStartIndex + len(word)

            annotations.append((wordStartIndex, wordEndIndex, nerTag))

        training_data.append((full_sentence, annotations, False))

        accumulator = []
        annotations = []
        full_sentence = ""

    print("amount of sentences in wiki-ner training data: ", len(training_data))
    return training_data

def main():
    process_wiki_ner("../../data/wiki-ner/aij-wikiner-pl-wp3")

if __name__ == "__main__":
    main()


def split(number_list, parts):
    newarr = []
    temparr = []
    x = 0

    for val in number_list:
        if x < parts:
            temparr.append(val)
            x += 1
        if x >= parts:
            newarr.append(temparr)
            temparr = []
            x = 0

    if len(temparr) > 0:
        newarr.append(temparr)

    return newarr


"""
Builder

Classes for programmatically constructing and writing out a MADX
lattice. You can create a lattice using one of the predefined simple
lattices or by instantiating the Machine class and adding many
elements to it using its various Add methods. This instance may be
written out to a MADX input text file using the WriteMachine method.

Classes:

Element - beam line element that always has name and type
Line    - a list of elements
Machine - a sequence of elements and associated options and beam etc.

"""

from . import _General
from ._General import IsFloat as _IsFloat
from   decimal import Decimal as _Decimal
import time

from .Beam import Beam as _Beam

madxcategories = [
    'drift',
    'solenoid',
    'sbend',
    'rbend',
    'hkicker',
    'vkicker',
    'tkicker',
    'quadrupole',
    'sextupole',
    'octupole',
    'decapole',
    'multipole',
    'marker'
    ]

class Element(dict) :
    """
    Element - a beam element class - inherits dict

    Element(name,type,**kwargs)

    A beam line element must ALWAYs have a name, and type.
    The keyword arguments are specific to the type and are up to
    the user to specify.

    Numbers are converted to a python Decimal type to provide
    higher accuracy in the representation of numbers - 15
    decimal places are used.
    """
    def __init__(self, name, category, **kwargs):
        if category not in madxcategories:
            raise ValueError("Not a valid MADX element type")
        self.name     = str(name)
        self.category = str(category)
        self.length      = 0.0 #for bookeeping only
        self['name']     = self.name
        self['category'] = self.category
        self._keysextra = []
        for key,value in kwargs.iteritems():
            if type(value) == tuple and category != 'multipole':
                #use a tuple for (value,units)
                self[key] = (_Decimal(str(value[0])),value[1])
            elif type(value) == tuple and category == 'multipole' :
                self[key] = value
            elif _IsFloat(value):
                #just a number
                self[key] = _Decimal(str(value))
            else:
                #must be a string
                self[key] = '"'+value+'"'
            self._keysextra.append(str(key)) #order preserving
        if 'l' in self:
            if type(self['l']) == tuple:
                ll = self['l'][0]
            else:
                ll = self['l']
            self.length += float(ll)

    def keysextra(self):
        #so behaviour is similar to dict.keys()
        return self._keysextra

    def __repr__(self):
        s = ''
        s += self.name + ': '
        s += self.category
        if len(self._keysextra) > 0:
            for key in self._keysextra:
                if type(self[key]) == tuple and self.category != 'multipole':
                    s += ', ' + key + '=' + str(self[key][0]) + '*' + str(self[key][1])
                elif type(self[key]) == tuple and self.category == 'multipole' :
                    s += ', ' + key + '=' + '{'+(','.join([str(s) for s in self[key]]))+'}'
                else:
                    s += ', ' + key + '=' + str(self[key])
        s += ';\n'
        return s

class Line(list):
    def __init__(self,name,*args):
        for item in args[0]:
            if type(item) != Element:
                raise TypeError("Line is a list of Elements")
        list.__init__(self,*args)
        self.name   = name
        self.length = 0.0
        for item in args[0]:
            self.length += item.length

    def __repr__(self):
        s = ''
        for item in self:
            s += str(item)+'\n' #uses elements __repr__ function
        s += self.name+ ': line=('
        s += ', '.join([item.name for item in self]) + ');\n'
        return s

    def DefineConstituentElements(self):
        s = ''
        for item in self:
            s += str(item) #uses elements __repr__ function
        return s

class Sampler(object):
    """
    Class that can return the appropriate sampler syntax if required.
    """
    def __init__(self,name):
        self.name = name

    def __repr__(self):
        return 'PTC_OBSERVE, place='+self.name+';\n'

class Machine(object):
    def __init__(self,verbose=False):
        self.verbose   = verbose
        self.sequence  = []
        self.elements  = []
        self.elementsd = {}
        self.samplers  = []
        self.length    = 0.0
        self.angint    = 0.0
        self.beam      = _Beam() # always construct at least default beam
        self.ptcaper   = []

    def __repr__(self):
        s = ''
        s += 'pymadx.Builder.Machine instance\n'
        s += str(len(self.sequence)) + ' items in sequence\n'
        s += str(len(self.elements)) + ' unique elements defined\n'
        return s

    def __iter__(self):
        self._iterindex = -1
        return self

    def next(self):
        if self._iterindex == len(self.sequence)-1:
            raise StopIteration
        self._iterindex += 1
        return self.elementsd[self.sequence[self._iterindex]]

    def __getitem__(self,name):
        if _IsFloat(name):
            return self.elementsd[self.sequence[name]]
        else:
            return self.elementsd[name]

    def __len__(self):
        return len(self.elementsd.keys())

    def Append(self,object):
        if type(object) not in (Element,Line):
            raise TypeError("Only Elements or Lines can be added to the machine")
        elif object.name not in self.sequence:
            #hasn't been used before - define it
            if type(object) is Line:
                for element in object:
                    self.elements.append(element)
                    self.elementsd[element.name] = element
                self.elements.append(object)
                self.elementsd[object.name] = object
            else:
                self.elements.append(object)
                self.elementsd[object.name] = object
        #finally add it to the sequence
        self.sequence.append(object.name)
        self.length += object.length

    def Write(self,filename,verbose=False):
        """
        Write the machine to a series of gmad files.
        """
        verboseresult = verbose or self.verbose
        WriteMachine(self,filename,verboseresult)

    def AddDrift(self, name='dr', length=0.1, **kwargs):
        if self.verbose:
            print('AddDrift>  ',name,' ',length,' ',kwargs)
        if length < 1e-12:
            self.AddMarker(name)
        else:
            self.Append(Element(name,'drift',l=length,**kwargs))

    def AddDipole(self, name='dp', category='sbend', length=0.1, angle=0.001, **kwargs):
        """
        AddDipole(category='sbend')

        category - 'sbend' or 'rbend' - sector or rectangular bend
        """
        if self.verbose:
            print('AddDipole> ',name,' ',length,' ',kwargs)
        if length < 1e-12:
            self.AddMarker(name)
        self.Append(Element(name,category,l=length,angle=angle,**kwargs))

    def AddHKicker(self, name='hk', hkick=0, length=0, **kwargs):
        self.Append(Element(name,'hkicker',hkick=hkick,l=length,**kwargs))

    def AddVKicker(self, name='vk', vkick=0, length=0, **kwargs):
        self.Append(Element(name,'vkicker',vkick=vkick,l=length,**kwargs))

    def AddTKicker(self, name='tk', vkick=0, hkick=0, length=0, **kwargs):
        self.Append(Element(name,'tkicker',vkick=vkick, hkick=hkick,
                            l=length,**kwargs))

    def AddQuadrupole(self, name='qd', length=0.1, k1=0.0, **kwargs):
        self.Append(Element(name,'quadrupole',l=length,k1=k1,**kwargs))

    def AddSextupole(self, name='sd', length=0.1, k2=0.0, **kwargs):
        self.Append(Element(name,'sextupole',l=length,k2=k2,**kwargs))

    def AddOctupole(self, name='oc', length=0.1, k3=0.0, **kwargs):
        self.Append(Element(name,'octupole',l=length,k3=k3,**kwargs))

    def AddDecapole(self, name='dd', length=0.1, k4=0.0, **kwargs):
        self.Append(Element(name,'decapole',l=length,k4=k4,**kwargs))

    def AddMultipole(self, name='mp', knl=(0), ksl=(0), **kwargs):
        self.Append(Element(name,'multipole', knl=knl, ksl=ksl, **kwargs))

    def AddSampler(self,*elementnames):
        if elementnames[0] == 'all':
            for element in self.elements:
                #remember we can only have samplers on uniquely
                #named elements (for now)
                self.samplers.append(Sampler(element.name))
        elif elementnames[0] == 'first':
            self.samplers.append(Sampler(self.elements[0].name))
        elif elementnames[0] == 'last':
            self.samplers.append(Sampler(self.elements[-1].name))
        else:
            for element in elementnames:
                if element not in self.sequence:
                    raise ValueError(element+" is not a valid element in this machine")
                else:
                    self.samplers.append(Sampler(element))

    def AddBeam(self, beam=None) :
        self.beam = beam

    def AddMarker(self, name="mk", **kwargs):
        self.Append(Element(name,'marker', **kwargs))

    def AddSolenoid(self, name='sl', length=0.1, ks=0.0, **kwargs):
        self.Append(Element(name,'solenoid',l=length,ks=ks,**kwargs))

    def AddOptions(self,*args,**kwargs):
        pass

    def AddPTCTrackAperture(self, aperture=[]):
        """
        Add a PTC 6D max aperture for ptc_track command.
        """
        if len(aperture) > 0 and len(aperture) != 6:
            raise IndexError("Aperture list must contain exactly 6 values")
        # convert all to float to ensure it can be written
        aper = [float(i) for i in aperture]
        self.ptcaper = aper

# General scripts below this point

def WriteMachine(machine, filename, verbose=False):
    """
    WriteMachine(machine(machine),filename(string),verbose(bool))

    Write a lattice to disk. This writes several files to make the
    machine, namely:

     * filename_components.madx - component files (max 10k per file)
     * filename_sequence.madx   - lattice definition
     * filename_samplers.madx   - sampler definitions (max 10k per file)
     * filename.gmad            - suitable main file with all sub
                                  files in correct order

    These are prefixed with the specified filename / path.
    """

    if not isinstance(machine,Machine):
        raise TypeError("Not machine instance")

    elementsperline = 100 #number of machine elements per madx line (not text line)

    #check filename
    if filename[-5:] != '.madx':
        filename += '.madx'
    #check if file already exists
    ofilename = filename
    filename = _General.CheckFileExists(filename)
    if filename != ofilename:
        print('Warning, chosen filename already exists - using filename: ',filename.split('.')[0])
    basefilename = filename[:-5]#.split('/')[-1]

    #prepare names
    files         = []
    fn_main       = basefilename + '.madx'
    fn_components = basefilename + '_components.madx'
    fn_sequence   = basefilename + '_sequence.madx'
    fn_beam       = basefilename + '_beam.madx'
    fn_options    = basefilename + '_options.madx'
    fn_ptc        = basefilename + '_ptcjob.madx'
    timestring = '! ' + time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()) + '\n'

    # write beam
    f = open(fn_beam,'w')
    files.append(fn_beam)
    f.write(timestring)
    f.write('! pymadx.Builder \n')
    f.write('! BEAM DEFINITION \n\n')
    f.write(machine.beam.ReturnBeamString())
    f.close()

    #write component files
    f = open(fn_components,'w')
    files.append(fn_components)
    f.write(timestring)
    f.write('! pymadx.Builder Machine \n')
    f.write('! COMPONENT DEFINITION\n\n')
    for element in machine.elements:
        f.write(str(element))
    f.close()

    #write lattice sequence
    f = open(fn_sequence,'w')
    files.append(fn_sequence)
    f.write(timestring)
    f.write('! pymadx.Builder Machine \n')
    f.write('! LATTICE SEQUENCE DEFINITION\n\n')
    sequencechunks = _General.Chunks(machine.sequence,elementsperline)
    linelist = []
    ti = 0
    for line in _General.Chunks(machine.sequence,elementsperline):
        f.write('l'+str(ti)+': line = ('+', '.join(line)+');\n')
        linelist.append('l'+str(ti))
        ti += 1
    # need to define the period before making sampler planes
    f.write('lattice: line = ('+', '.join(linelist)+');\n')
    f.write('use, period=lattice;\n')
    f.close()

    # optionally write start of ptc job / inialise the universe
    if machine.beam['distrType'] == 'ptc':
        f = open(fn_ptc,'w')
        files.append(fn_ptc)
        f.write(timestring)
        f.write('! pymadx.Builder Machine \n')
        f.write('! PTC JOB SPECIFICATION\n\n')
        f.write(machine.beam.ReturnPtcString())

        ptcTrackstr = ''
        # check attribute existance in case an old machine instance is supplied
        if hasattr(machine, 'ptcaper'):
            # check for correct no. of aperture dimensions
            if len(machine.ptcaper) > 0 and len(machine.ptcaper) != 6:
                raise IndexError("Aperture list must contain exactly 6 values")
            # string with ptc track apertures if defined.
            if len(machine.ptcaper) > 0:
                ptcTrackstr = ', maxaper={'
                for index,aper in enumerate(machine.ptcaper):
                    ptcTrackstr += str(aper)
                    if index != (len(machine.ptcaper)-1):
                        ptcTrackstr += ', '
                ptcTrackstr += '}'

        #write samplers - only for PTC jobs
        if len(machine.samplers) > 0:
            f.write('\n! SAMPLER DEFINITION\n\n')
            for sampler in machine.samplers:
                f.write(str(sampler))
            f.write('ptc_track, element_by_element, dump, turns=1, icase=5, onetable' + ptcTrackstr + ';\n')
            f.write('PTC_TRACK_END;\n')
            f.write('ptc_end;\n')
        f.close()

    # write main file
    f = open(fn_main,'w')
    f.write(timestring)
    f.write('! pymadx.Builder Machine \n')
    f.write('! number of elements = ' + str(len(machine.elements)) + '\n')
    f.write('! total length       = ' + str(machine.length) + ' m\n\n')
    f.write('set, format="22.16e";\n')

    for fn in files:
        fn = fn.split('/')[-1]
        f.write("call, file='"+fn+"';\n")

    # line in main file for outputting twiss params to .tfs file
    if machine.beam['distrType'] == 'ptctwiss':
        f.write('\n')
        f.write(machine.beam.ReturnPtcTwissString(basefilename))
        f.write('ptc_end;\n')
    elif not machine.beam['distrType'] == 'ptc':
        f.write('\n')
        f.write(machine.beam.ReturnTwissString(basefilename))

    f.close()

    #user feedback
    print('Machine written to:')
    for fn in files:
        print(fn)
    print('All included in main file: \n',fn_main)


# -*- coding: utf-8 -*-
"""
Created on Wed Jul 14 06:25:01 2021

@author: Miles Miller

--> This script helps to search for a limited set of points that reflect the different
phytoplankton concentration profiles within the ROMS output domain.

--> It functions basically by numerically integrating vertically over all profiles
within the domainand then placing the resulting integral solutions into bins
and finding the index of one random point from within each bin.

--> This helps limit the field of calculation in the case of computationally
costly sensitivity studies and lessen time for computation.

"""

## Importing Ocean_Irradiance modules.
import os
cwd = os.getcwd()
os.chdir('../ocean_irradiance_module')
import Ocean_Irradiance
import Ocean_Irradiance_ROMS
from absorbtion_and_scattering_coefficients import absorbtion_scattering as abscat
os.chdir(cwd)
import wavelength_to_rgb
import PARAMS

## Importing other modules.
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import random

def Rep_ROMS_Phy_Prof_Loc(nxi, nyi, chl_diatom, chl_nanophyt,
                          z_r, n_bins, db =20, plot_flag=True) :
    """
    This function calculates the index locations of a set of points representative
    of different phytoplankton profiles.

    Parameters
    ----------
    nxi : Float
        The number of points in the x direction, number of columns.
    nyi : Float
        The number of points in the y direction, number of rows.
    chl_diatom : 3-D Array
        The diatom chl concentration array.
    chl_nanophyt : 3-D Array
        The diatom chl concentration array.
    z_r : 3-D Array
        The rho grid. The cell centers.
    n_bins : Float
        The number of bins to seperate into. Also the number of representative
        indexes to be returned.
    db : Float, optional
        The boundary distance in indices. The default is 20.
    plot_flag : Boolean, optional
        To plot or not. Plots the position of representative points on a contour of
        the integrals. The default is True.

    Returns
    -------
    bin_point_index: 2-D Array
        The index positions of the representative points on the unbounded ROMS
        domain.

    """

    def Integrate_Phy_Prof(nyi_db, nxi_db, phyt_profiles, zarr_phy) :
        """
        Integrates over the vertical phytoplankton profiles within the horizontal domain.
        Each point in the horizontal ROMS domain is then represented by a
        float of the integral.

        Parameters
        ----------
        phyt_profiles : 3-D Array
            The phytoplankton concentration profiles. [z,y,x]
        zarr_phy : 3-D Array
            The corresponding coordinates of the phytoplankton concentrations.

        Returns
        -------
        integral_phy : 2-D Array
            The vertical integral of the phytoplankton profiles for each point
            in the horizontal domain.

        """
        ## Empty integral array of same shape as the phyt_profile array.
        integral_phy = np.zeros_like(phyt_profiles[0,:,:])

        ## Looping over the horizontal domain.
        for k in range(nyi_db) :
            for j in range(nxi_db) :
                ## Integrating over the vertical direction of array.
                integral_phy[k,j] = np.trapz(phyt_profiles[:,k,j], zarr_phy[:,k,j])

        return integral_phy

    def Find_Random_Point_In_Bin(integral_map, bin_edges, points_in_bins) :
        """
        This finds the index of a random point that lies within each integral bin.

        Parameters
        ----------
        integral_map : 2-D Array
            The horizontal map of integral values within bounded domain.
        bin_edges : 1-D Array
            The value of the bin edges. Should be of length one greater than the
            number of bins.
        points_in_bins : 1-D Array
            The number of points in each bin. The values of each bar in the histogram.

        Returns
        -------
        bin_point_index : 2-D Array
            The index of the representative points on the bounded domain.

        """
        ## The index location of the chosen points within the bounded ROMS domain.
        ## The 2 in the second dimension is for (y,x)
        bin_point_index = np.zeros((len(points_in_bins), 2))
        ## Randomizing the indexes so that the points are taken in different locations in domain.
        rand_nyi_arr = np.arange(0, nyi_db)
        rand_nxi_arr = np.arange(0, nxi_db)
        random.shuffle(rand_nyi_arr)
        random.shuffle(rand_nxi_arr)

        ## Looping over the bins.
        for k in range(len(points_in_bins)) :
            ## If there are no points in the bin then return the location as NaN.
            if points_in_bins[k] == 0 :
                bin_point_index[k,:] = np.NaN
            ## If there are point sin the bin then loop over the domain
            ## to find the index of a point that is whithin that bin.
            if points_in_bins[k] > 0 :
                ## Loop over the horizontal domain.
                for yi in rand_nyi_arr :
                    for xi in rand_nxi_arr :
                        ## If the value of the integral lies within the current bin
                        ## set the bin_point_index for that integral point to be
                        ## the current index and then break out of both loops.
                        if bin_edges[k] < integral_map[yi,xi] < bin_edges[k+1]:
                            bin_point_index[k,:] = [yi,xi]
                            break
                    else:
                        continue
                    break

        return bin_point_index

    ## Taking only points in arays within the boundary of db.
    chl_diatom_db = chl_diatom[:,db:nyi-db, db:nxi-db]
    chl_nanophyt_db = chl_nanophyt[:, db:nyi-db, db:nxi-db]

    ## The number of points in y,x directions in boundary domain
    nyi_db = len(chl_diatom_db[0,:,0])
    nxi_db = len(chl_diatom_db[0,0,:])

    ## The z grid at which the phytoplankton concentrations are located.
    ## Spliced to the correct domain within the boundary db.
    zarr_phy = np.copy(z_r[:,db:nyi-db,db:nxi-db])

    ## Integrating over vertical profiles in bounded domain as a metric of the
    ## concentration profile structure.
    diatom_integrate = Integrate_Phy_Prof(nyi_db, nxi_db, chl_diatom_db, zarr_phy)
    nanophyt_integrate = Integrate_Phy_Prof(nyi_db, nxi_db, chl_nanophyt_db, zarr_phy)
    ##Total integral of points
    integral_map = diatom_integrate + nanophyt_integrate
    ## Log base 10 of integral field
    log10_integral_map = np.log10(integral_map)
    ## Binning distribution
    points_in_bins, bin_edges = np.histogram(log10_integral_map, n_bins)

    ## Getting the y,x index of random points that reside within each bin.
    bin_point_index = Find_Random_Point_In_Bin(log10_integral_map, bin_edges, points_in_bins)
    ## Adding the boundary value back so that the indexes represent the indexes on
    ## the unbounded ROMS grid such that and index of (0,0) on the bounded domain
    ## would become (db,db) on the unbounded.
    bin_point_index = bin_point_index + db

    if plot_flag == True :
        ## Integrating over vertical profiles in FULL non-bounded domain as a metric of the
        ## concentration profile structure.
        diatom_integrate_full = Integrate_Phy_Prof(nyi, nxi, chl_diatom, z_r)
        nanophyt_integrate_full = Integrate_Phy_Prof(nyi, nxi, chl_nanophyt, z_r)
        ##Total integral of points in full domain
        integral_map_full = diatom_integrate_full + nanophyt_integrate_full
        ## Log base 10 of integral field
        log10_integral_map_full = np.log10(integral_map_full)
        ##plotting diatom
        fig, ax = plt.subplots()
        ax.pcolormesh(log10_integral_map_full)
        # for k in range(len(bin_point_index)) :
        ax.plot(bin_point_index[:,1], bin_point_index[:,0], 'ro', markersize = 4, label='Location of Chosen Profiles')
        ax.set_ylabel('nyi')
        ax.set_xlabel('nxi')
        ax.set_title(r'$\log _{10} (\int \mathrm{diatom} + \int \mathrm{nano} )$')
        ax.legend(title=f'N Profiles = {n_bins}')

    return bin_point_index

if __name__ == '__main__':

    ## Creating a parameter object.
    file = '/Users/Miles Miller/da_fwd_002.nc'
    p = PARAMS.Param_Init(file)
    ## The number of representative points.
    n_bins = 20
    Rep_ROMS_Phy_Prof_Loc(p.nxi, p.nyi, p.chl_diatom, p.chl_nanophyt,
                          p.z_r, n_bins, db =20, plot_flag=True)


import graf
import  config

import copy

def create_temlate(dex_factoty: str, tokens: list, amount=None, minimum_receive=None, max_spread=None):
    tp = copy.deepcopy(config.template)
    operations_to_add = []
    swap = config.dex_names[dex_factoty]
    op = {swap: config.operation.copy()}

    for i in range(len(tokens) - 1):

        if tokens[i] in config.native_tokens:
            offer = config.asset_info[1]
            offer["native_token"]["denom"] = tokens[i]
        else:
            offer = config.asset_info[0]
            offer["token"]["contract_addr"] = tokens[i]
        op[swap]["offer_asset_info"] = copy.deepcopy(offer)

        if tokens[i + 1] in config.native_tokens:
            ask = config.asset_info[1]
            ask["native_token"]["denom"] = tokens[i + 1]
        else:
            ask = config.asset_info[0]
            ask["token"]["contract_addr"] = tokens[i + 1]

        op[swap]["ask_asset_info"] = copy.deepcopy(ask)
        operations_to_add.append(copy.deepcopy(op))

    tp["execute_swap_operations"]["operations"] = operations_to_add

    if amount:
        tp["execute_swap_operations"]["offer_amount"] = str(int(amount * config.to_million))
    if minimum_receive:
        tp["execute_swap_operations"]["minimum_receive"] = str(int(minimum_receive * config.to_million))
    if max_spread:
        tp["execute_swap_operations"]["max_spread"] = str(max_spread)
    return tp

print(create_temlate("terra16t7dpwwgx9n3lq6l6te3753lsjqwhxwpday9zx",('terra15gwkyepfc6xgca5t5zefzwy42uts8l2m4g40k6', 'uusd', 'uluna')))

def simulation(wasm, dex, amount, *tokens):
    tp = create_temlate(dex, tokens, amount=amount)
    tp_query = {"simulate_swap_operations": tp["execute_swap_operations"]}
    res = wasm.contract_query(dex, tp_query)
    return res


import sys
import math
input = sys.stdin.readline

N = int(input())
arrow = {}
for _ in range(N):
    x, y = map(int, input().split())
    g = math.gcd(x, y)
    arrow.setdefault((x//g, y//g), 0)
    arrow[(x//g, y//g)] += 1

print(max(arrow.values()))