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

from setuptools import find_packages
from setuptools import setup

def read(fname):
    file_path = os.path.join(os.path.dirname(__file__), fname)
    with open(file_path, encoding="utf-8") as file_handle:
        return file_handle.read()

requirements = ["pytest>=4.0.0"]

setup(
    name="pytest-subprocess",
    version="1.5.0",
    author="Andrzej Klajnert",
    author_email="python@aklajnert.pl",
    maintainer="Andrzej Klajnert",
    maintainer_email="python@aklajnert.pl",
    license="MIT",
    project_urls={
        "Documentation": "https://pytest-subprocess.readthedocs.io",
        "Source": "https://github.com/aklajnert/pytest-subprocess",
        "Tracker": "https://github.com/aklajnert/pytest-subprocess/issues",
    },
    description="A plugin to fake subprocess for pytest",
    long_description=read("README.rst") + "\n" + read("HISTORY.rst"),
    py_modules=["pytest_subprocess"],
    python_requires=">=3.6",
    install_requires=requirements,
    extras_require={
        "test": [
            "pytest>=4.0",
            "coverage",
            "docutils>=0.12",
            "Pygments>=2.0",
            "pytest-rerunfailures",
            "pytest-asyncio>=0.15.1",
            "pytest-timeout",
            "anyio",
        ],
        "dev": ["nox", "changelogd"],
        "docs": [
            "sphinx",
            "furo",
            "sphinxcontrib-napoleon",
            "sphinx-autodoc-typehints",
            "changelogd",
        ],
    },
    packages=find_packages(exclude=["docs"]),
    package_data={"pytest_subprocess": ["py.typed"]},
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Framework :: Pytest",
        "Intended Audience :: Developers",
        "Topic :: Software Development :: Testing",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
        "Programming Language :: Python :: Implementation :: CPython",
        "Programming Language :: Python :: Implementation :: PyPy",
        "Operating System :: OS Independent",
        "License :: OSI Approved :: MIT License",
    ],
    entry_points={
        "pytest11": [
            "subprocess = pytest_subprocess.fixtures",
        ],
    },
)


import os,sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)

import xmind
from xmind.core.markerref import MarkerId
xmind_name="netty"
w = xmind.load(os.path.dirname(os.path.abspath(__file__))+"\\"+xmind_name+".xmind")
s2=w.createSheet()
s2.setTitle("FileChannel文件通道")
r2=s2.getRootTopic()
r2.setTitle("FileChannel文件通道")

content={
'定义':[
    '表示一个网络连接,类似OIO中的两个流的结合体，既可以从通道读取，也可以向通道写入',
    '表示一个底层的文件描述符，例如硬件设备、文件、网络连接',
    '不同的网络传输协议类型，在Java中都有不同的NIO Channel（通道）实现,涵盖文件IO、TCP网络IO、UDP网络IO'
],
'分类':[
    'FileChannel文件通道',
    'SocketChannel套接字通道',
    'ServerSocketChannel服务器监听通道',
    'DatagramChannel数据报通道'
],
'FileChannel文件通道':[
    '阻塞模式,用于文件的数据读写',
    {'4个核心操作':[
        {'获取FileChannel通道':[
            'getChannel()',
            {'例':[
                'FileInputStream fis=new FileInputStream("xxx")',
                'FileChannel inChannel=fis.getChannel()',
                'FileOutStream fos=new FileOutStream("xxx")',
                'FileChannel outChannel=fos.getChannel()'
            ]}
        ]},
        {'读取FileChannel通道':[
            'int read（ByteBuffer buf）',
            '从通道读取到数据，写入到ByteBuffer缓冲区,返回读取到的字节数',
            {'例':[
                'ByteBuffer buf=ByteBuffer.allocate(20)',
                'inChannel.read(buf)',
                'System.out.print(new String(buf.array()))',
            ]}
        ]},
        {'写入FileChannel通道':[
            'int write（ByteBuffer buf）',
            '从ByteBuffer缓冲区中读取数据，然后写入到通道,返回写入成功的字节数',
            {'例':[
                'buf.flip()',
                'int outlength=0',
                'while((length=outChannel.write(buf)!=0){',
                '   //写入字节数据',
                '}'
            ]}
        ]},
        {'关闭通道':[
            'close()',
            {'例':[
                'inChannel.close()'
            ]}
        ]},
        {'强制刷新到磁盘(保证写入通道的缓冲数据，都真写入磁盘)':[
            'force()',
            {'例':[
                'inChannel.force()'
            ]}
        ]},
        {'更高效的文件复制':[
            'transferFrom(ReadableByteChannel target,long position,long count)',
            '数据从目标通道复制给当前通道',
            'transferTo(long position,long count,WritableByteChannel target)',
            '数据从当前通道复制给目标通道'
        ]}

    ]}
],

}

#构建xmind
xmind.build(content,r2)
#保存xmind
xmind.save(w,os.path.dirname(os.path.abspath(__file__))+"\\"+xmind_name+".xmind")


#!/bin/env python
"""
A quick script to download the lua manuals, and convert them to json

Using some oneliner like
```bash
manualparser.py | \
lua -e 'pretty = require"pl.pretty" json = require"json" io.stdout:write(pretty.write(json.decode(io.stdin:read"*a")))'
```
will convert it the json to a lua table, used to write builtins.lua
note: oneliner requires penlight and some json library
"""
from __future__ import print_function
import sys
import re
import json
import requests
import html2text

def get_docs(manual_url, starting_line, ending_line):
    manual_text = html2text.html2text(requests.get(manual_url).text)
    lib_text = "\n".join(manual_text.split("\n")[starting_line:ending_line])
    return {
        func: {
            'signature': func + proto,
            'documentation': doc
        }
        for func, proto, doc in re.findall(r"\* \* \*\n\n### `([\w:.]+) "
                                           r"(\(.*?\))`\n\n(.*?)"
                                           r"(?=\n\n\* \* \*|\n\n#{1,3}(?!#))",
                                           lib_text, re.DOTALL)
    }

def main():
    docs_dict = {}
    docs_dict.update(get_docs("https://www.lua.org/manual/5.1/manual.html",
                              4386, 6018))
    docs_dict.update(get_docs("https://www.lua.org/manual/5.2/manual.html",
                              5215, 7071))
    docs_dict.update(get_docs("https://www.lua.org/manual/5.3/manual.html",
                              5306, 7227))
    json.dump(docs_dict, sys.stdout, indent=4)

if __name__ == '__main__':
    main()


from __future__ import annotations

import itertools
import warnings
from copy import deepcopy

import numpy as np

from causaldmir.graph import dag2cpdag, Edge, Mark
from causaldmir.graph.pdag2dag import pdag2dag
from causaldmir.utils.local_score import *
from causaldmir.graph.pdag import PDAG

def kernel(x, xKern, theta):
    # KERNEL Compute the rbf kernel
    n2 = dist2(x, xKern)
    if (theta[0] == 0):
        theta[0] = 2 / np.median(n2[np.where(np.tril(n2) > 0)])
        theta_new = theta[0]
    wi2 = theta[0] / 2
    kx = theta[1] * np.exp(-n2 * wi2)
    bw_new = 1 / theta[0]
    return kx, bw_new

def Combinatorial(T0):
    # sub = Combinatorial (T0); % find all the sbusets of T0
    sub = []
    count = 0
    if (len(T0) == 0):
        sub.append(())  # a 1x0 empty matrix
    else:
        if (len(T0) == 1):
            sub.append(())
            sub.append(T0)  # when T0 is a scale, it is a special case!!
        else:
            for n in range(len(T0) + 1):
                for S in list(itertools.combinations(T0, n)):
                    sub.append(S)
    return sub

def Score_G(G, score_func):  # calculate the score for the current G
    # here G is a DAG
    score = 0
    for i, node in enumerate(G.node_list):
        PA = []
        for node_v in G.get_neighbours(node):
            if G.is_arrow(node_v, node):
                PA.append(node_v)

        delta_score = score_func(i, PA)
        score = score + delta_score
    return score

def Insert_validity_test1(G, i, j, T):
    # V=Insert_validity_test1(G, X, Y, T,1); % do validity test for the operator Insert; V=1 means valid, V=0 mean invalid;
    # here G is CPDAG
    V = 0

    # condition 1
    Tj = np.intersect1d(np.where([G.is_tail(G.node_list[j], G.node_list[j_tail]) for j_tail in range(G.number_of_nodes())])[0], np.where([G.is_tail(G.node_list[j_tail], G.node_list[j]) for j_tail in range(G.number_of_nodes())])[0])  # neighbors of Xj
    Ti = np.where([G.is_connected(G.node_list[i], G.node_list[i_nei]) for i_nei in range(G.number_of_nodes())])[0]  # adjacent to Xi;
    NA = np.intersect1d(Tj, Ti)  # find the neighbours of Xj and are adjacent to Xi
    V = check_clique(G, list(np.union1d(NA, T).astype(int)))  # check whether it is a clique
    return V

def check_clique(G, subnode):  # check whether node subnode is a clique in G
    # here G is a CPDAG
    # the definition of clique here: a clique is defined in an undirected graph
    # when you ignore the directionality of any directed edges

    Gs = np.zeros((G.number_of_nodes(), G.number_of_nodes()), dtype=int)
    for edge in G.edges:
        Gs[G.node_list.index(edge.node_u), G.node_list.index(edge.node_v)] = edge.mark_u.value
        Gs[G.node_list.index(edge.node_v), G.node_list.index(edge.node_u)] = edge.mark_v.value
    Gs = deepcopy(Gs[np.ix_(subnode, subnode)])  # extract the subgraph
    ns = len(subnode)

    if ns == 0:
        s = 1
    else:
        row, col = np.where(Gs == 1)
        Gs[row, col] = -1
        Gs[col, row] = -1
        if np.all((np.eye(ns) - np.ones((ns, ns))) == Gs):  # check whether it is a clique
            s = 1
        else:
            s = 0
    return s

def Insert_validity_test2(G, i, j, T):
    # V=Insert_validity_test(G, X, Y, T,1); % do validity test for the operator Insert; V=1 means valid, V=0 mean invalid;
    # here G is CPDAG
    V = 0
    Tj = np.intersect1d(np.where([G.is_tail(G.node_list[j], G.node_list[j_tail]) for j_tail in range(G.number_of_nodes())])[0], np.where([G.is_tail(G.node_list[j_tail], G.node_list[j]) for j_tail in range(G.number_of_nodes())])[0])  # neighbors of Xj
    Ti = np.where([G.is_connected(G.node_list[i], G.node_list[i_nei]) for i_nei in range(G.number_of_nodes())])[0]  # adjacent to Xi;
    NA = np.intersect1d(Tj, Ti)  # find the neighbours of Xj and are adjacent to Xi

    # condition 2: every semi-directed path from Xj to Xi contains a node in union(NA,T)
    # Note: EVERY!!
    s2 = Insert_vC2_new(G, j, i, np.union1d(NA, T))
    if s2:
        V = 1

    return V

def Insert_vC2_new(G, j, i, NAT):  # validity test for condition 2 of Insert operator
    # here G is CPDAG
    # Use Depth-first-Search
    start = j
    target = i
    # stack(1)=start; % initialize the stack
    stack = [{'value': start, 'pa': {}}]
    sign = 1  # If every semi-pathway contains a node in NAT, than sign=1;

    while len(stack):
        top = stack[0]
        stack = stack[1:]  # pop
        if top['value'] == target:  # if find the target, search that pathway to see whether NAT is in that pathway
            curr = top
            ss = 0
            while True:
                if len(curr['pa']):
                    if curr['pa']['value'] in NAT:  # contains a node in NAT
                        ss = 1
                        break
                else:
                    break
                curr = curr['pa']
            if not ss:  # do not include NAT
                sign = 0
                break
        else:
            child = np.concatenate((np.where([G.is_arrow(G.node_list[top['value']], G.node_list[other]) for other in range(G.number_of_nodes())])[0],
                                    np.intersect1d(np.where([G.is_tail(G.node_list[top['value']], G.node_list[other]) for other in range(G.number_of_nodes())])[0], np.where([G.is_tail(G.node_list[other], G.node_list[top['value']]) for other in range(G.number_of_nodes())])[0])))
            sign_child = np.ones(len(child))
            # check each child, whether it has appeared before in the same pathway
            for k in range(len(child)):
                curr = top
                while True:
                    if len(curr['pa']):
                        if curr['pa']['value'] == child[k]:
                            sign_child[k] = 0  # has appeared in that path before
                            break
                    else:
                        break
                    curr = curr['pa']

            for k in range(len(sign_child)):
                if sign_child[k]:
                    stack.insert(0, {'value': child[k], 'pa': top})  # push
    return sign

def find_subset_include(s0, sub):
    # S = find_subset_include(sub(k),sub); %  find those subsets that include sub(k)
    if len(s0) == 0 or len(sub) == 0:
        Idx = np.ones(len(sub))
    else:
        Idx = np.zeros(len(sub))
        for i in range(len(sub)):
            tmp = set(s0).intersection(set(sub[i]))
            if len(tmp):
                if tmp == set(s0):
                    Idx[i] = 1
    return Idx

def Insert_changed_score(G, i, j, T, record_local_score, score_func):
    # calculate the changed score after the insert operator: i->j
    Tj = np.intersect1d(np.where([G.is_tail(G.node_list[j], G.node_list[j_tail]) for j_tail in range(G.number_of_nodes())])[0], np.where([G.is_tail(G.node_list[j_tail], G.node_list[j]) for j_tail in range(G.number_of_nodes())])[0])  # neighbors of Xj
    Ti = np.where([G.is_connected(G.node_list[i], G.node_list[i_nei]) for i_nei in range(G.number_of_nodes())])[0]  # adjacent to Xi;
    NA = np.intersect1d(Tj, Ti)  # find the neighbours of Xj and are adjacent to Xi
    Paj = np.where([G.is_arrow(G.node_list[j_parent], G.node_list[j]) for j_parent in range(G.number_of_nodes())])[0]  # find the parents of Xj
    # the function local_score() calculates the local score
    tmp1 = np.union1d(NA, T).astype(int)
    tmp2 = np.union1d(tmp1, Paj)
    tmp3 = np.union1d(tmp2, [i]).astype(int)

    # before you calculate the local score, firstly you search in the
    # "record_local_score", to see whether you have calculated it before
    r = len(record_local_score[j])
    s1 = 0
    s2 = 0

    for r0 in range(r):
        if not np.setxor1d(record_local_score[j][r0][0:-1], tmp3).size:
            score1 = record_local_score[j][r0][-1]
            s1 = 1

        if (not np.setxor1d(record_local_score[j][r0][0:-1],
                            tmp2).size):  # notice the differnece between 0*0 empty matrix and 1*0 empty matrix
            score2 = record_local_score[j][r0][-1]
            s2 = 1
        else:
            if (not np.setxor1d(record_local_score[j][r0][0:-1], [-1]).size) and (not tmp2.size):
                score2 = record_local_score[j][r0][-1]
                s2 = 1

        if s1 and s2:
            break

    if not s1:
        score1 = score_func(j, tmp3)
        temp = list(tmp3)
        temp.append(score1)
        record_local_score[j].append(temp)

    if not s2:
        score2 = score_func(j, tmp2)
        # r = len(record_local_score[j])
        if len(tmp2) != 0:
            temp = list(tmp2)
            temp.append(score2)
            record_local_score[j].append(temp)
        else:
            record_local_score[j].append([-1, score2])

    chscore = score1 - score2
    desc = [i, j, T]
    return chscore, desc, record_local_score

def Insert(G, i, j, T):
    # Insert operator
    # insert the directed edge Xi->Xj
    nodes = G.node_list
    G.add_edge(Edge(nodes[i], nodes[j], Mark.Tail, Mark.ARROW), overwrite=True)

    for k in range(len(T)):  # directing the previous undirected edge between T and Xj as T->Xj
        if G.get_edge(nodes[T[k]], nodes[j]) is not None:
            G.remove_edge(nodes[T[k]], nodes[j])
        G.add_edge(Edge(nodes[T[k]], nodes[j], Mark.Tail, Mark.ARROW), overwrite=True)

    return G

def Delete_validity_test(G, i, j, H):
    # V=Delete_validity_test(G, X, Y, H); % do validity test for the operator Delete; V=1 means valid, V=0 mean invalid;
    # here G is CPDAG
    V = 0

    # condition 1
    Hj = np.intersect1d(np.where([G.is_tail(G.node_list[j], G.node_list[j_tail]) for j_tail in range(G.number_of_nodes())])[0], np.where([G.is_tail(G.node_list[j_tail], G.node_list[j]) for j_tail in range(G.number_of_nodes())])[0])  # neighbors of Xj
    Hi = np.where([G.is_connected(G.node_list[i], G.node_list[i_nei]) for i_nei in range(G.number_of_nodes())])[0]  # adjacent to Xi;
    NA = np.intersect1d(Hj, Hi)  # find the neighbours of Xj and are adjacent to Xi
    s1 = check_clique(G, list(set(NA) - set(H)))  # check whether it is a clique

    if s1:
        V = 1

    return V

def Delete_changed_score(G, i, j, H, record_local_score, score_func):
    # calculate the changed score after the Delete operator
    Hj = np.intersect1d(np.where([G.is_tail(G.node_list[j], G.node_list[j_tail]) for j_tail in range(G.number_of_nodes())])[0], np.where([G.is_tail(G.node_list[j_tail], G.node_list[j]) for j_tail in range(G.number_of_nodes())])[0])  # neighbors of Xj
    Hi = np.where([G.is_connected(G.node_list[i], G.node_list[i_nei]) for i_nei in range(G.number_of_nodes())])[0]  # adjacent to Xi;
    NA = np.intersect1d(Hj, Hi)  # find the neighbours of Xj and are adjacent to Xi
    Paj = np.union1d(np.where([G.is_arrow(G.node_list[j_parent], G.node_list[j]) for j_parent in range(G.number_of_nodes())])[0], [i])  # find the parents of Xj
    # the function local_score() calculates the local score
    tmp1 = set(NA) - set(H)
    tmp2 = set.union(tmp1, set(Paj))
    tmp3 = tmp2 - {i}

    # before you calculate the local score, firstly you search in the
    # "record_local_score", to see whether you have calculated it before
    r = len(record_local_score[j])
    s1 = 0
    s2 = 0

    for r0 in range(r):
        if set(record_local_score[j][r0][0:-1]) == tmp3:
            score1 = record_local_score[j][r0][-1]
            s1 = 1

        if set(record_local_score[j][r0][0:-1]) == tmp2:  # notice the differnece between 0*0 empty matrix and 1*0 empty matrix
            score2 = record_local_score[j][r0][-1]
            s2 = 1
        else:
            if (set(record_local_score[j][r0][0:-1]) == {-1}) and len(tmp2) == 0:
                score2 = record_local_score[j][r0][-1]
                s2 = 1

        if s1 and s2:
            break

    if not s1:
        score1 = score_func(j, list(tmp3))
        temp = list(tmp3)
        temp.append(score1)
        record_local_score[j].append(temp)

    if not s2:
        score2 = score_func(j, list(tmp2))
        if len(tmp2) != 0:
            temp = list(tmp2)
            temp.append(score2)
            record_local_score[j].append(temp)
        else:
            record_local_score[j].append([-1, score2])

    chscore = score1 - score2
    desc = [i, j, H]
    return chscore, desc, record_local_score

def Delete(G, i, j, H):
    # Delete operator
    nodes = G.node_list
    if G.get_edge(nodes[i], nodes[j]) is not None:
        # delete the edge between Xi and Xj
        G.remove_edge(nodes[i], nodes[j])
    for k in range(len(H)):  # directing the previous undirected edge
        if G.get_edge(nodes[j], nodes[H[k]]) is not None:
            G.remove_edge(nodes[j], nodes[H[k]])
        if G.get_edge(nodes[i], nodes[H[k]]) is not None:
            G.remove_edge(nodes[i], nodes[H[k]])
        G.add_edge(Edge(nodes[j], nodes[H[k]], Mark.Tail, Mark.ARROW), overwrite=True)
        G.add_edge(Edge(nodes[i], nodes[H[k]], Mark.Tail, Mark.ARROW), overwrite=True)
    return G

def dist2(x, c):
    # DIST2	Calculates squared distance between two sets of points.
    #
    # Description
    # D = DIST2(X, C) takes two matrices of vectors and calculates the
    # squared Euclidean distance between them.  Both matrices must be of
    # the same column dimension.  If X has M rows and N columns, and C has
    # L rows and N columns, then the result has M rows and L columns.  The
    # I, Jth entry is the  squared distance from the Ith row of X to the
    # Jth row of C.
    #
    # See also
    # GMMACTIV, KMEANS, RBFFWD
    #

    ndata, dimx = x.shape
    ncentres, dimc = c.shape
    if (dimx != dimc):
        raise Exception('Data dimension does not match dimension of centres')

    n2 = (np.matlib.ones((ncentres, 1)) * np.sum(np.multiply(x, x).T, axis=0)).T + \
         np.matlib.ones((ndata, 1)) * np.sum(np.multiply(c, c).T, axis=0) - \
         2 * (x * c.T)

    # Rounding errors occasionally cause negative entries in n2
    n2[np.where(n2 < 0)] = 0
    return n2

def pdinv(A):
    # PDINV Computes the inverse of a positive definite matrix
    numData = A.shape[0]
    try:
        U = np.linalg.cholesky(A).T
        invU = np.eye(numData).dot(np.linalg.inv(U))
        Ainv = invU.dot(invU.T)
    except np.linalg.LinAlgError as e:
        warnings.warn('Matrix is not positive definite in pdinv, inverting using svd')
        u, s, vh = np.linalg.svd(A, full_matrices=True)
        Ainv = vh.T.dot(np.diag(1 / s)).dot(u.T)
    except Exception as e:
        raise e
    return np.matlib.asmatrix(Ainv)

class GES(object):

    def __init__(self, score_function, max_p: int | None = None):
        if not issubclass(type(score_function), BaseLocalScoreFunction):
            raise Exception("'score_function' must be subclass of 'BaseLocalScoreFunction'!")
        self.score_function = score_function

        if type(score_function) == MultiCVScore or type(score_function) == MultiMarginalScore:
            self.var_count = len(score_function.d_label)
        else:
            self.var_count = score_function.data.shape[1]
        if max_p is None:
            max_p = self.var_count / 2
        self.max_p = max_p
        self.__causal_graph = None
        self.__score = None

    def get_causal_graph(self):
        if self.__causal_graph is None:
            raise Exception("please fit some data with this algorithm before get causal graph!")
        return self.__causal_graph

    def get_score(self):
        if self.__score is None:
            raise Exception("please fit some data with this algorithm before get score!")
        return self.__score

    def fit(self):
        # Greedy equivalence search
        # INPUT:
        # X: Data with T*D dimensions
        # score_func: the score function you want to use
        # maxP: allowed maximum number of parents when searching the graph
        # parameters: when using CV likelihood,
        #               parameters['kfold']: k-fold cross validation
        #               parameters['lambda']: regularization parameter
        #               parameters['dlabel']: for variables with multi-dimensions,
        #                            indicate which dimensions belong to the i-th variable.

        node_names = [("x%d" % i) for i in range(self.var_count)]

        G = PDAG(node_names)
        # G = np.matlib.zeros((N, N)) # initialize the graph structure
        score = Score_G(G, score_func=self.score_function)  # initialize the score

        G = pdag2dag(G)
        G = dag2cpdag(G)

        ## --------------------------------------------------------------------
        ## forward greedy search
        record_local_score = [[] for _ in range(self.var_count)]  # record the local score calculated each time. Thus when we transition to the second phase, many of the operators can be scored without an explicit call the the scoring function
        # record_local_score{trial}{j} record the local scores when Xj as a parent
        score_new = score
        count = 0

        while True:
            count += 1
            score = score_new
            max_chscore = -1e7
            max_ac = []
            for i in range(self.var_count):
                for j in range(self.var_count):
                    if not G.is_connected(G.node_list[i], G.node_list[j]) and i != j and len(np.where([G.is_arrow(G.node_list[j_parent], G.node_list[j]) for j_parent in range(G.number_of_nodes())])[0]) <= self.max_p:  # find a pair (Xi, Xj) that is not adjacent in the current graph , and restrict the number of parents
                        Tj = np.intersect1d(np.where([G.is_tail(G.node_list[j], G.node_list[j_tail]) for j_tail in range(G.number_of_nodes())])[0], np.where([G.is_tail(G.node_list[j_tail], G.node_list[j]) for j_tail in range(G.number_of_nodes())])[0])  # neighbors of Xj
                        Ti = np.where([G.is_connected(G.node_list[i], G.node_list[i_nei]) for i_nei in range(G.number_of_nodes())])[0]  # adjacent to Xi
                        NTi = np.setdiff1d(np.arange(self.var_count), Ti)
                        T0 = np.intersect1d(Tj, NTi)  # find the neighbours of Xj that are not adjacent to Xi
                        # for any subset of T0
                        sub = Combinatorial(T0.tolist())  # find all the subsets for T0
                        S = np.zeros(len(sub))
                        # S indicate whether we need to check sub{k}.
                        # 0: check both conditions.
                        # 1: only check the first condition
                        # 2: check nothing and is not valid.
                        for k in range(len(sub)):
                            if S[k] < 2:  # S indicate whether we need to check subset(k)
                                V1 = Insert_validity_test1(G, i, j, sub[k])  # Insert operator validation test:condition 1
                                if V1:
                                    if not S[k]:
                                        V2 = Insert_validity_test2(G, i, j, sub[k])  # Insert operator validation test:condition 2
                                    else:
                                        V2 = 1
                                    if V2:
                                        Idx = find_subset_include(sub[k], sub)  # find those subsets that include sub(k)
                                        S[np.where(Idx == 1)] = 1
                                        chscore, ac, record_local_score = Insert_changed_score(G, i, j, sub[k], record_local_score, self.score_function)  # calculate the changed score after Insert operator
                                        # desc{count} saves the corresponding (i,j,sub{k})
                                        if chscore > max_chscore:
                                            max_chscore = chscore
                                            max_ac = ac
                                else:
                                    Idx = find_subset_include(sub[k], sub)  # find those subsets that include sub(k)
                                    S[np.where(Idx == 1)] = 2

            if len(max_ac) != 0:
                score_new = score + max_chscore
                if score_new - score <= 0:
                    break
                G = Insert(G, max_ac[0], max_ac[1], max_ac[2])
                G = pdag2dag(G)
                G = dag2cpdag(G)
            else:
                score_new = score
                break

        ## --------------------------------------------------------------------
        # backward greedy search
        score_new = score
        while True:
            score = score_new
            max_chscore = -1e7
            max_ac = []
            for i in range(self.var_count):
                for j in range(self.var_count):
                    if (G.is_tail(G.node_list[j], G.node_list[i]) and G.is_tail(G.node_list[i], G.node_list[j])) or G.is_arrow(G.node_list[i], G.node_list[j]):  # if Xi - Xj or Xi -> Xj
                        Hj = np.intersect1d(np.where([G.is_tail(G.node_list[j], G.node_list[j_tail]) for j_tail in range(G.number_of_nodes())])[0], np.where([G.is_tail(G.node_list[j_tail], G.node_list[j]) for j_tail in range(G.number_of_nodes())])[0])  # neighbors of Xj
                        Hi = np.where([G.is_connected(G.node_list[i], G.node_list[i_nei]) for i_nei in range(G.number_of_nodes())])[0]  # adjacent to Xi
                        H0 = np.intersect1d(Hj, Hi)  # find the neighbours of Xj that are adjacent to Xi
                        # for any subset of H0
                        sub = Combinatorial(H0.tolist())  # find all the subsets for H0
                        S = np.ones(len(sub))  # S indicate whether we need to check sub{k}.
                        # 1: check the condition,
                        # 2: check nothing and is valid;
                        for k in range(len(sub)):
                            if S[k] == 1:
                                V = Delete_validity_test(G, i, j, sub[k])  # Delete operator validation test
                                if V:
                                    # find those subsets that include sub(k)
                                    Idx = find_subset_include(sub[k], sub)
                                    S[np.where(Idx == 1)] = 2  # and set their S to 2
                            else:
                                V = 1

                            if V:
                                chscore, ac, record_local_score = Delete_changed_score(G, i, j, sub[k], record_local_score, self.score_function)  # calculate the changed score after Insert operator
                                # desc{count} saves the corresponding (i,j,sub{k})
                                if chscore > max_chscore:
                                    max_chscore = chscore
                                    max_ac = ac

            if len(max_ac) != 0:
                score_new = score + max_chscore
                if score_new - score <= 0:
                    break
                G = Delete(G, max_ac[0], max_ac[1], max_ac[2])
                G = pdag2dag(G)
                G = dag2cpdag(G)

            else:
                score_new = score
                break

        self.__causal_graph = G
        self.__score = score


import time
import psutil
import uvicorn
from fastapi import FastAPI,Request,Body
from fastapi.templating import Jinja2Templates
import datetime
from multiprocessing import Process
from fastapi.responses import RedirectResponse
proc_api = FastAPI()
templates = Jinja2Templates(directory="templates")
proc_list = []

def new_proc(seconds):
    print(f"started sleeping for {seconds} seconds")
    time.sleep(seconds)
    print('Done Sleeping')
    return ""

@proc_api.post("/processolustur")
async def proc(body:dict=Body(...)):
    global proc_list
    seconds = body.get("seconds")
    p = Process(target=new_proc, args=[seconds])
    p.start()
    pd = p.pid
    proc_dict = {"pid":pd,"seconds":seconds}
    proc_list.append(proc_dict.copy())
    return {"proc_list":proc_list}

@proc_api.get("/processcheck")
def processcheck():
    global proc_list
    existing_list = []
    p = Process(target=new_proc, args=[0])
    p.start()
    p.join()
    for proc in proc_list:
        if psutil.pid_exists(proc["pid"]):
            existing_list.append(proc)
    proc_list = existing_list
    return {"existing_list":existing_list}


"""Containers CDK construct module."""

import aws_cdk as cdk
from aws_cdk import aws_ec2 as ec2
from aws_cdk import aws_ecr as ecr
from aws_cdk import aws_ecr_assets as ecr_assets
from aws_cdk import aws_ecs as ecs
from aws_cdk import aws_iam as iam
from aws_cdk import aws_logs as logs
from cdk_ecr_deployment import DockerImageName, ECRDeployment
from constructs import Construct

class ContainersConstruct(Construct):
    """Containers CDK construct class."""

    def __init__(
        self,
        scope: Construct,
        id: str,
        vpc: ec2.IVpc,
        container_security_group: ec2.ISecurityGroup,
        *,
        prefix=None,
    ):
        """Construct initialization."""
        super().__init__(scope, id)

        ecr_repository = ecr.Repository(
            self,
            "ECRRepository",
            encryption=ecr.RepositoryEncryption.AES_256,
            removal_policy=cdk.RemovalPolicy.DESTROY,
        )

        ecr_image = ecr_assets.DockerImageAsset(
            self, "DockerImage", directory="cdk/containers"
        )

        ecr_deployment = ECRDeployment(  # noqa: F841
            self,
            "ECRDeployment",
            src=DockerImageName(name=ecr_image.image_uri),
            dest=DockerImageName(name=ecr_repository.repository_uri),
        )
        ecs_cluster = ecs.Cluster(self, "Cluster", vpc=vpc)

        ecs_task_role = iam.Role(
            self,
            "TaskRole",
            assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
            inline_policies={
                "GenericECSTask": iam.PolicyDocument(
                    assign_sids=True,
                    minimize=True,
                    statements=[
                        iam.PolicyStatement(
                            resources=["*"],
                            actions=[
                                "logs:CreateLogStream",
                                "logs:DescribeLogGroups",
                                "logs:DescribeLogStreams",
                                "logs:CreateLogGroup",
                                "logs:PutLogEvents",
                                "logs:PutRetentionPolicy",
                            ],
                        ),
                        iam.PolicyStatement(
                            resources=["*"], actions=["ec2:DescribeRegions"]
                        ),
                        iam.PolicyStatement(
                            resources=["*"],
                            actions=[
                                "ssmmessages:CreateControlChannel",
                                "ssmmessages:CreateDataChannel",
                                "ssmmessages:OpenControlChannel",
                                "ssmmessages:OpenDataChannel",
                            ],
                        ),
                        iam.PolicyStatement(
                            resources=["*"],
                            actions=[
                                "cloudwatch:PutMetricData",
                                "cloudwatch:ListMetrics",
                            ],
                        ),
                    ],
                )
            },
        )

        ecs_task_execution_role = iam.Role(
            self,
            "TaskExecutionRole",
            assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
            managed_policies=[
                iam.ManagedPolicy.from_managed_policy_arn(
                    self,
                    "ServiceRole",
                    managed_policy_arn="arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",
                )
            ],
        )

        ecs_task_definition = ecs.FargateTaskDefinition(
            self,
            "TaskDefinition",
            cpu=512,
            memory_limit_mib=2048,
            execution_role=ecs_task_execution_role,
            task_role=ecs_task_role,
            runtime_platform=ecs.RuntimePlatform(
                operating_system_family=ecs.OperatingSystemFamily.LINUX,
                cpu_architecture=ecs.CpuArchitecture.X86_64,
            ),
        )

        ecs_ssm_agent_container = ecs_task_definition.add_container(  # noqa: F841
            "ssm-agent",
            image=ecs.ContainerImage.from_ecr_repository(
                repository=ecr_repository, tag="latest"
            ),
            privileged=False,
            logging=ecs.LogDriver.aws_logs(
                stream_prefix="ContainerLogs-",
                log_retention=logs.RetentionDays.ONE_WEEK,
            ),
        )

        ecs_service = ecs.FargateService(  # noqa: F841
            self,
            "EcsService",
            cluster=ecs_cluster,
            task_definition=ecs_task_definition,
            security_groups=[container_security_group],
            vpc_subnets=ec2.SubnetSelection(
                subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
            ),
            enable_execute_command=True,
        )

        cdk.CfnOutput(self, "ECSClusterArn", value=ecs_cluster.cluster_arn)

        self.ecs_task_role = ecs_task_role


from constants.global_contexts import kite_context
import pandas as pd
import numpy as np

from logging import Logger

from utils.logger import get_logger
from time import sleep

logger:Logger = get_logger(__name__)

class Stock:
    """
        Given a symbol and exchange it holds all the information related to the stock such as price
    """
    def __init__(
            self,
            symbol:str,
            exchange:str
        ) -> None:
        self.stock_name = symbol
        self.exchange = exchange
        # self.lowest_price = None
        self.latest_price = None

        self.__result_stock_df:pd.DataFrame = None

    @property
    def current_price(self):
        """
            returns the current price in the market or else None if the connection interrupts
        """

        try:
            return kite_context.ltp([f"NSE:{self.stock_name}"])[f"NSE:{self.stock_name}"]["last_price"]
        except:
            return None

    def update_price(self):
        """
            for every new price it sets the last price after trying 4 times
        """
        retries = 0
        current_price = None
        while retries < 4:
            current_price = self.current_price
            if current_price:
                break
            retries += 1
            sleep(1)
        # if current_price:
        #     if self.lowest_price:
        #         if current_price < self.lowest_price:
        #             self.lowest_price = current_price
        #     else:
        #         self.lowest_price = current_price
        self.latest_price = current_price
        self.update_stock_df(self.latest_price)

    def whether_buy(self):
        # retries = 0
        # current_price = None
        # while retries < 4:
        #     current_price = self.current_price
        #     if current_price:
        #         break
        #     retries += 1
        #     sleep(1)

        # logger.info(f"prices {self.lowest_price} {self.latest_price}")
        df = self.__result_stock_df.copy()
        if df.shape[0] > 22:

            df['line'] = self.KAMA(df["price"])
            df['signal'] = df['line'].ewm(span=12).mean()
            df = df.fillna(999)
            returns = df['signal'].pct_change()+1
            if returns.iloc[-1] != 999:
                if returns.iloc[-1] >1 and returns.iloc[-2] <=1 and returns.iloc[-3] <=1:
                    return True
        return False

        # if self.lowest_price and self.latest_price:
        #     if current_price > self.latest_price and self.latest_price > self.lowest_price:
        #         return True
        # else:
        #     return False

    def update_stock_df(self, current_price:float):
        try:
            self.__result_stock_df = pd.read_csv(f"temp/{self.stock_name}.csv")
            self.__result_stock_df.drop(self.__result_stock_df.columns[0], axis=1, inplace=True)
        except:
            self.__result_stock_df = None
        stock_df = pd.DataFrame({"price":[current_price]})
        if self.__result_stock_df is not None:
            self.__result_stock_df = pd.concat([self.__result_stock_df, stock_df],ignore_index=True)
        else:
            self.__result_stock_df = stock_df
        self.__result_stock_df.to_csv(f"temp/{self.stock_name}.csv")
        self.__result_stock_df = self.__result_stock_df.fillna(method='bfill').fillna(method='ffill')
        self.__result_stock_df.dropna(axis=1,inplace=True)

    @staticmethod
    def KAMA(price, n=10, pow1=2, pow2=30):
        ''' kama indicator '''
        ''' accepts pandas dataframe of prices '''

        absDiffx = abs(price - price.shift(1) )
        abs_price_change = np.abs(price - price.shift(n))
        vol = absDiffx.rolling(n).sum()
        ER = abs_price_change/vol
        fastest_SC, slowest_SC = 2/(pow1+1), 2/(pow2+1)

        sc = (ER*(fastest_SC-slowest_SC)+slowest_SC) ** 2.0

        answer = np.zeros(sc.size)
        N = len(answer)
        first_value = True

        for i in range(N):
            if sc[i] != sc[i]:
                answer[i] = np.nan
            else:
                if first_value:
                    answer[i] = price[i]
                    first_value = False
                else:
                    answer[i] = answer[i-1] + sc[i] * (price[i] - answer[i-1])
        return answer


import numpy as np
from typing import Dict, Tuple
from copy import deepcopy

from numpy.random import exponential, uniform, choice
from utils.objects import Sprite, Move, Fade, VectorScale, Scale, Color, Rotate, MoveX, MoveY, Loop
from utils.constants import SB_WIDTH, SB_HEIGHT, SB_LEFT, SB_RIGHT, SB_LOWER, SB_UPPER
from utils.midiparser.parser import get_timestamps_and_pitches, get_time_signatures
from essence.config import constellation_vertices_timestamps, essence_constellation_edges_pred
from .uncertainty import Uncertainty
from .stars import Plexus3D
from .orb_rotation import OrbRotation
from .bubble import Bubble

from .constellation import ConstellationAnimation

def background():
    gradient = Sprite('sb/backgrounds/gradient.png')
    gradient.add_actions([
        Scale(0, 335785, 374399, 1.5, 1.5),
        Color(0, 335785, 336781, (0,0,0), (69,0,0)),
        Color(0, 344340, 365257, (0,0,60), (0,0,255)),
        Color(0, 365257, 371371, (0,0,255), (255,0,0)),
        Color(0, 374399, 374400, (0,0,0), (0,0,0))
    ])
    return [gradient]

def true_essence_1(start, fade_out_start, end):
    ts = constellation_vertices_timestamps.copy()
    for k in ts.keys():
        ts[k] = start
    constellation = ConstellationAnimation(ts, essence_constellation_edges_pred)
    constellation_render = constellation.render(fade_out_start)
    for i in range(len(constellation_render)):
        for action in constellation_render[i].action.copy():
            if action.event_type == "M":
                mx, my = action.params[:2]
                constellation_render[i].add_actions([
                    Move(0, fade_out_start, end, (mx, my), (320, 240))
                ])
                break
        if constellation_render[i].filename == constellation._star:
            constellation_render[i].add_actions([
                Scale(0, fade_out_start, end, 2, 0)
            ])
        else:
            for action in constellation_render[i].action.copy():
                if action.event_type == "V":
                    vector_x, vector_y = action.params[:2]
                    constellation_render[i].add_actions([
                        VectorScale(0, fade_out_start, end, (vector_x, vector_y), (0,0))
                    ])
    bubbles = Bubble(50).render(start, end, 4500)
    black = Sprite("sb/backgrounds/black.png")
    black.add_action(Fade(0, start, end, 0.4, 0.4))
    return bubbles + [black] + constellation_render

def true_essence_2(start, midi_file):
    hexagon = 'sb/elements/hexagon.png'
    timestamps = get_timestamps_and_pitches(midi_file)
    timestamps = timestamps[0][1]
    max_ts = max(timestamps)
    all_sprites = []
    for timestamp in timestamps:
        hex_ = Sprite(hexagon)
        pos = (uniform(SB_LEFT, SB_RIGHT), uniform(SB_UPPER, SB_LOWER))
        timestamp += start
        hex_.add_actions([
            Move(0, start, start + max_ts, pos, pos),
            Scale(0, timestamp, timestamp + 1000, 0, 0.2),
            Fade(0, timestamp, timestamp + 500, 0, 1),
            Fade(0, timestamp+500, timestamp+1000, 1, 0)
        ])
        all_sprites.append(hex_)
    return all_sprites

def true_essence_3(start, midi_file):
    uncertainty = Uncertainty(midi_file)
    return uncertainty.render(start)

def true_essence_4(start, midi_file):
    uncertainty = Uncertainty(midi_file)
    return uncertainty.render(start)

def true_essence_5(start, plexus_appear, end):
    plexus = Plexus3D(800).render(start, end)
    filtered_plexus = []
    for i in range(len(plexus)):
        vectorscale_actions = list(filter(lambda x: x.event_type == 'V' and x.end_time < end, plexus[i].action))
        if 'line' not in plexus[i].filename:
            filtered_plexus.append(plexus[i])
            continue
        if len(plexus[i].action) == 0:
            continue
        if max(vectorscale_actions, key=lambda x: x.end_time).end_time < plexus_appear + 2000:
            continue
        filtered_plexus.append(plexus[i])
        filtered_plexus[-1].add_action(Fade(0, plexus_appear, plexus_appear + 2000, 0, 1))
    return filtered_plexus

def true_essence_6(start, end):
    essence_orbit = OrbRotation(40).render(start, end, 0.0008, 0.002, 0.003)
    essence_red = Sprite('sb/elements/essence_red.png')
    essence_red.add_actions(essence_orbit[-1].action.copy())
    essence_orbit[-1].add_action(Fade(0, start // 4 + end // 4 * 3, end, 1, 0))
    essence_red.add_action(Fade(0, (start + end) // 2, start // 4 + end // 4 * 3, 0, 1))
    return essence_orbit + [essence_red]

def divide_screen(sprites: list[Sprite], divisors: int, offset: int, time_scale=1):
    # normalizing the sb
    new_sprites = []
    scale_down = 1 / (divisors ** 2)
    relative_left = SB_LEFT - 320
    relative_right = SB_RIGHT - 320
    relative_top = SB_UPPER - 240
    relative_bottom = SB_LOWER - 240
    xdiv = (relative_right - relative_left) / divisors
    ydiv = (relative_bottom - relative_top) / divisors
    for row in range(divisors):
        for column in range(divisors):
            x_left = relative_left + column * xdiv
            y_top = relative_top + row * ydiv
            x_right = relative_left + (column + 1) * xdiv
            y_bottom = relative_top + (row + 1) * ydiv
            for sprite in sprites.copy():
                new_sprite = deepcopy(sprite)
                new_action = []
                for action in new_sprite.action:
                    if action.event_type in ["S", "V"]:
                        for i in range(len(action.params)):
                            action.params[i] *= np.sqrt(scale_down)
                    elif action.event_type == "M":
                        old_rel_x_start, old_rel_y_start = action.x_start - 320, action.y_start - 240
                        old_rel_x_end, old_rel_y_end = action.x_end - 320, action.y_end - 240
                        normalized_old_rel_x_start = (old_rel_x_start - relative_left) / (relative_right - relative_left)
                        normalized_old_rel_y_start = (old_rel_y_start - relative_top) / (relative_bottom - relative_top)
                        normalized_old_rel_x_end = (old_rel_x_end - relative_left) / (relative_right - relative_left)
                        normalized_old_rel_y_end = (old_rel_y_end - relative_top) / (relative_bottom - relative_top)
                        x_start = x_left + (x_right - x_left) * normalized_old_rel_x_start + 320
                        y_start = y_top + (y_bottom - y_top) * normalized_old_rel_y_start + 240
                        x_end = x_left + (x_right - x_left) * normalized_old_rel_x_end + 320
                        y_end = y_top + (y_bottom - y_top) * normalized_old_rel_y_end + 240
                        action.params = [x_start, y_start, x_end, y_end]
                    old_start_time = action.start_time
                    action.start_time = int(offset)
                    action.end_time = int(offset + (action.end_time - old_start_time) * time_scale)
                    new_action.append(action)
                new_sprite.action = new_action
                new_sprites.append(new_sprite)
    return new_sprites

def supernova(p1, p2, p3, pend):
    essence1 = Sprite('sb/elements/essence_red.png')
    essenceboom = Sprite('sb/elements/essence_red.png')
    essence1.add_action(Move(0, p1, p2, (320, 240), (320, 240)))
    essence1.add_action(Scale(0, p1, p2, 0.2, 0.2))
    essenceboom.add_action(Move(0, p1, p2, (320, 240), (320, 240)))
    essenceboom.add_action(Fade(0, p1, p2, 0.3, 0.3))
    essenceboom.add_action(Scale(0, p1, p2, 0.2, 2.8))
    initial_sprite = [essence1, essenceboom]
    for _ in range(20):
        star = Sprite('sb/elements/star.png')
        x = uniform(SB_LEFT, SB_RIGHT)
        y = uniform(SB_UPPER, SB_LOWER)
        star.add_action(Move(0, p1, p2, (x, y), (x, y)))
        star.add_action(Scale(0, p1, p2, 1.8, 1.8))
        initial_sprite.append(star)
    all_sprites = initial_sprite.copy()
    all_sprites.extend(divide_screen(initial_sprite, 2, p2, (p3 - p2) / (p2 - p1)))
    all_sprites.extend(divide_screen(initial_sprite, 4, p3, (pend - p3) / (p2 - p1)))
    return all_sprites

def essence_orb():
    orb = Sprite('sb/elements/orb.png')
    orb.add_actions([
        Scale(0, 320470, 321470, 0, 0.1),
        Scale(0, 344340, 344341, 0.1, 0)
    ])
    return orb

def true_essence():
    true_essence_elements = [essence_orb()] + true_essence_1(311936, 320205, 320470) + \
        true_essence_2(320470, 'assets/chiptune.mid') + \
        true_essence_3(328782, 'assets/xi.mid') + \
        true_essence_4(336781, 'assets/artcore.mid') + \
        true_essence_5(344340, 351558, 358565) + \
        true_essence_6(358565, 371371) + \
        supernova(371371, 372128, 372885, 374399) # + \
        # true_essence_7(365257, 371371)
    return true_essence_elements + background()


from setuptools import setup

__author__ = 'gm'

setup(name='fiduccia_mattheyses',
      version='1.0.0a',
      description='An implementation of the Fiduccia Mattheyses algorithm',
      url='https://github.com/GeoMSK/FiducciaMattheyses',
      author='George Mantakos',
      packages=['FiducciaMattheyses'],
      install_requires=[
          'numpy',
      ],
      zip_safe=False)


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

"""Module containing an helper widgets.
"""

from __future__ import division
from math import pi

import cairo
import gobject
import gtk
from gtk import gdk

class Pad(gtk.DrawingArea):
    """Widget used to generate pairs of coordinate values.

    Create a drawing area connected to mouse events. Generate a couple of
    values between -1 and +1 depending on the position of the mouse during a
    drag and drop operation.
    """

    __gsignals__ = {
            'start-dnd': (gobject.SIGNAL_RUN_FIRST, None, ()),
            'dnd-value': (gobject.SIGNAL_RUN_FIRST, None,
                (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
            'end-dnd': (gobject.SIGNAL_RUN_FIRST, None, ()),
    }

    def __init__(self):
        """Constructor.

        Create a drawing area and connect to mouse events.
        """
        super(Pad, self).__init__()

        self.oldx, self.oldy = -1, -1
        self.width, self.height = -1, -1
        self.surface, self.cr = None, None

        self.add_events(gdk.BUTTON_PRESS_MASK
                        | gdk.BUTTON_RELEASE_MASK
                        | gdk.POINTER_MOTION_MASK
                        | gdk.POINTER_MOTION_HINT_MASK)
        self.connect('button-press-event', self.button_press_cb)
        self.connect('button-release-event', self.button_release_cb)
        self.connect('configure-event', self.configure_cb)
        self.connect('expose-event', self.expose_cb)
        self.connect('motion_notify_event', self.motion_notify_cb)

    def button_press_cb(self, darea, event):
        """Notify the beginning of a drag and drop event.
        """
        x, y = event.x, event.y
        self.draw_pointer(self.cr, x, y)
        self.queue_draw()
        self.oldx, self.oldy = x, y
        rel_x, rel_y = self.absolute_to_relative(x, y)
        self.emit('dnd-value', rel_x, rel_y)
        self.emit('start-dnd')
        return True

    def button_release_cb(self, darea, event):
        """Notify the end of a drag and trop event.
        """
        self.oldx, self.oldy = event.x, event.y
        self.draw_pointer(self.cr, None, None)
        self.queue_draw()
        self.oldx, self.oldy = None, None
        self.emit('end-dnd')
        return True

    def configure_cb(self, darea, event):
        """Update the cairo context used for the drawing actions.
        """
        self.width, self.height = darea.window.get_size()
        self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width,
                                          self.height)
        self.cr = cairo.Context(self.surface)
        self.draw(self.cr, self.width, self.height)

        return True

    def expose_cb(self, darea, event):
        """Redraw either the whole window or a part of it.
        """
        cr = darea.window.cairo_create()
        cr.rectangle(event.area.x, event.area.y,
                     event.area.width, event.area.height)
        cr.clip()
        cr.set_source_surface(self.surface, 0, 0)
        cr.paint()

        return False

    def motion_notify_cb(self, darea, event):
        """Emit a new drag and drop value.
        """
        if event.is_hint:
            x, y, state = event.window.get_pointer()
        else:
            x = event.x
            y = event.y
            state = event.state
        if state & gdk.BUTTON1_MASK or state & gdk.BUTTON3_MASK:
            self.draw_pointer(self.cr, x, y)
            self.queue_draw()
            self.oldx, self.oldy = x, y
            rel_x, rel_y = self.absolute_to_relative(x, y)
            self.emit('dnd-value', rel_x, rel_y)
        return True

    def draw(self, cr, width, height):
        """Draw the white background of the pad widget.

        Keywords:
            cr cairo context used for drawing operations.
            width width of the cairo context.
            height height of the cairo context.
        """
        cr.set_source_rgb(0, 0, 0)
        cr.rectangle(0, 0, width, height)
        cr.fill()

    def draw_pointer(self, cr, newx, newy):
        """Draw a circle surrounding the the pointer.

        Keywords:
            cr cairo context.
            newx new x coordinate of the pointer.
            newy new y coordinate of the pointer.
        """
        data = [(self.oldx, self.oldy, 15, (0, 0, 0)),
                (newx, newy, 10, (.8, .8, .8))]
        for (x, y, radius, (r, g, b)) in data:
            if x and y:
                cr.set_source_rgb(r, g, b)
                cr.arc(x, y, radius, 0, 2 * pi)
                cr.fill()

    def absolute_to_relative(self, x, y):
        """Convert given coordinate from absolute to relative.

        The returned coordinates are relative to the center of the widget.

        Keywords:
            x x coordinate of the mouse.
            y y coordinate of the mouse.
            width width of the window.
            height height of the window.

        Return:
            Pair of relative coordinates bounded between -1 and +1.
        """
        rel_x = (x - self.width / 2) / (self.width / 2)
        if rel_x > 1:
            rel_x = 1
        elif rel_x < -1:
            rel_x = -1

        rel_y = (self.height / 2 - y) / (self.height / 2)
        if rel_y > 1:
            rel_y = 1
        elif rel_y < -1:
            rel_y = -1

        return rel_x, rel_y


from tkinter import *
from gameplay import *
import random

class gameBoard:
  # Class variables --------------------------------------------------------
  ENTRY_BOX_WIDTH = 14
  GAME_DIMENSIONS = 0
  CUSTOM_FONT = ('Comic Sans MS', 11)
  COLORS = ['black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow']

  NUM_COLUMNS = 7
  NUM_ROWS = 6
  CIRCLE_SIZE = 60
  GAP = 10

  COLUMN_ONE = 65
  COLUMN_TWO = 125
  COLUMN_THREE = 185
  COLUMN_FOUR = 245
  COLUMN_FIVE = 305
  COLUMN_SIX = 365

  # Constructor ------------------------------------------------------------
  def __init__(self):
    # Window
    self.__win = Tk()
    self.__win.wm_title('Connect Four Game')

    # Initialize game
    self.__game = game()

    # New Game Button
    Button(self.__win, text = 'New Game', command = self.newGame, \
           font = gameBoard.CUSTOM_FONT).grid \
           (row = 0, column = 0, columnspan = 5)

    # Tells which player to go
    self.__playerTurn = StringVar()
    self.__playerTurn.set('Welcome to Connect Four! Click board to begin.')
    self.__whoseTurn = Label(self.__win, textvariable = self.__playerTurn, \
                             font = gameBoard.CUSTOM_FONT). \
                             grid(row = 0, column = 5)

    # Player One Name
    Label(self.__win, text = 'Player One: '). \
                      grid(row = 1, column = 0, \
                           sticky = S + W, columnspan = 2)
    self.__nameOne = StringVar()
    self.__nameOne.set(self.__game.getPlayerOneName())
    self.__playerOneName = Entry(self.__win, \
                                 textvariable = self.__nameOne, \
                                 width = gameBoard.ENTRY_BOX_WIDTH)
    self.__playerOneName.grid(row = 1, column = 1, \
                                sticky = S + E, columnspan = 3)

    # Player One Color; default 'red'
    Label(self.__win, text = 'Color: ').grid(row = 2, column = 0)
    self.__playerOneColor = StringVar()
    self.__playerOneColor.set(self.__game.getPlayerOneColor())
    self.__colorOne = OptionMenu(self.__win, self.__playerOneColor, \
                                 *gameBoard.COLORS)
    self.__colorOne.grid(row = 2, column = 1)

    # Player One Score
    Label(self.__win, text = 'Score: ').grid(row = 2, column = 2)
    self.__playerOneScore = IntVar()
    self.__playerOneScore.set(self.__game.getPlayerOneScore())
    self.__scoreOne = Label(self.__win, \
                      textvariable = self.__playerOneScore). \
                      grid(row = 2, column = 3)

    # Player One is computer?
    self.__playerOneCpu = IntVar()
    self.__playerOneCpu.set(0)
    self.__computerOne = Checkbutton(self.__win, text = ' is a computer', \
                           variable = self.__playerOneCpu). \
                           grid(row = 3, column = 0, \
                           sticky = N, columnspan = 5)

    # Player Two Name
    Label(self.__win, text = 'Player Two: '). \
                      grid(row = 4, column = 0, \
                           sticky = S + W, columnspan = 2)
    self.__nameTwo = StringVar()
    self.__nameTwo.set(self.__game.getPlayerTwoName())
    self.__playerTwoName = Entry(self.__win, \
                                 textvariable = self.__nameTwo, \
                                 width = gameBoard.ENTRY_BOX_WIDTH)
    self.__playerTwoName.grid(row = 4, column = 1, \
                                sticky = S + E, columnspan = 3)

    # Player Two Color; default 'red'
    Label(self.__win, text = 'Color: ').grid(row = 5, column = 0)
    self.__playerTwoColor = StringVar()
    self.__playerTwoColor.set(self.__game.getPlayerTwoColor())
    self.__colorTwo = OptionMenu(self.__win, self.__playerTwoColor, \
                                 *gameBoard.COLORS).grid(row = 5, column = 1)

    # Player Two Score
    Label(self.__win, text = 'Score: ').grid(row = 5, column = 2)
    self.__playerTwoScore = IntVar()
    self.__playerTwoScore.set(self.__game.getPlayerTwoScore())
    self.__scoreTwo = Label(self.__win, textvariable = \
                            self.__playerTwoScore).grid(row = 5, column = 3)

    # Player One is computer?
    self.__playerTwoCpu = IntVar()
    self.__playerTwoCpu.set(0)
    self.__computerTwo = Checkbutton(self.__win, text = ' is a computer', \
                           variable = self.__playerTwoCpu). \
                           grid(row = 6, column = 0, \
                           sticky = N, columnspan = 5)

    # Who goes first?
    Label(self.__win, text = 'Who is going first?', \
          font = gameBoard.CUSTOM_FONT). \
          grid(row = 7, column = 0, sticky = S, columnspan = 5)
    self.__playerOneFirst = Button(self.__win, text = 'Player One', \
                                   bg = 'light gray', \
                                   command = self.playerOneGoesFirst)
    self.__playerOneFirst.grid(row = 8, column = 0, columnspan = 2)

    self.__playerTwoFirst = Button(self.__win, text = 'Player Two', \
                                   command = self.playerTwoGoesFirst)
    self.__playerTwoFirst.grid(row = 8, column = 1, \
                               sticky = E, columnspan = 2)

    # Create the playing board
    self.__frame = Frame(self.__win)
    self.__frame.grid(row = 1, column = 5, rowspan = 10)

    self.__circles = Canvas(self.__frame, bg = 'powder blue', \
                            height= 370, width = 430)
    self.__grid = []

    # Iterate circles in canvas
    for col in range(gameBoard.NUM_COLUMNS):
      singleCol = []
      for row in range(gameBoard.NUM_ROWS):
        singleCol.append(self.__circles.create_oval(col * \
                           gameBoard.CIRCLE_SIZE + gameBoard.GAP, \
                           row * gameBoard.CIRCLE_SIZE + gameBoard.GAP, \
                           (col+1) * gameBoard.CIRCLE_SIZE, \
                           (row+1) * gameBoard.CIRCLE_SIZE, fill='white'))
      self.__grid.append(singleCol)
    self.__circles.grid()

    self.__circles.bind('<Button-1>', self.move)

    self.__turn = 0

  # Mutators --------------------------------------------------------------

  # Starts game
  # Applies new information and wipes boards
  def newGame(self):
    # sets names
    self.__game.changeName(self.__game.PLAYER_ONE, self.__playerOneName.get())
    self.__game.changeName(self.__game.PLAYER_TWO, self.__playerTwoName.get())

    # sets colors
    self.__game.changePlayerColor(self.__game.PLAYER_ONE, \
                                  self.__playerOneColor.get())
    self.__game.changePlayerColor(self.__game.PLAYER_TWO, \
                                  self.__playerTwoColor.get())

    # sets who goes first
    self.__game.setFirstTurn()

    # sets computers
    self.__game.setComputers(self.__playerOneCpu.get(), \
                             self.__playerTwoCpu.get())

##    print(self.__game.getPlayerOneName())
##    print(self.__game.getPlayerTwoName())

    self.__playerTurn.set(self.__game.getPlayerTurn() + "'s Turn")
    self.__game.newGame()
    for col in range(7):
      for row in range(6):
        self.__circles.itemconfig(self.__grid[col][row], fill='white')

  # change bottom button color
  def playerOneGoesFirst(self):
    self.__playerOneFirst.configure(bg = 'light gray')
    self.__playerTwoFirst.config(bg = 'SystemButtonFace')
    self.__game.setGoFirst(self.__game.PLAYER_ONE)

  # change bottom button color
  def playerTwoGoesFirst(self):
    self.__playerTwoFirst.configure(bg = 'light gray')
    self.__playerOneFirst.config(bg = 'SystemButtonFace')
    self.__game.setGoFirst(self.__game.PLAYER_TWO)

  def updateScore(self):
    self.__playerOneScore.set(self.__game.getPlayerOneScore())
    self.__playerTwoScore.set(self.__game.getPlayerTwoScore())

  # displays winner
  def updateWinner(self):
    if self.__game.getTurn() == self.__game.PLAYER_ONE:
      self.__playerTurn.set('Winner is %s!  Click New Game to play again.' \
                            %(self.__game.getPlayerTurn()))
    elif self.__game.getTurn() == self.__game.PLAYER_TWO:
      self.__playerTurn.set('Winner is %s!  Click New Game to play again.' \
                            %(self.__game.getPlayerTurn()))
    else:
      self.__playerTurn.set('No Winner!  Click New Game to play again.')

  # Plots circle on grid
  def move(self,event):
##    print(self.__game.getGameArray())
##    print(self.__game.getGameStatus())
    # Prevents moves if game is over
    if self.__game.getGameStatus():
      # Gets x-coordinate
      if event.x >= gameBoard.COLUMN_SIX:
        xCoord = 6
      elif event.x >= gameBoard.COLUMN_FIVE:
        xCoord = 5
      elif event.x >= gameBoard.COLUMN_FOUR:
        xCoord = 4
      elif event.x >= gameBoard.COLUMN_THREE:
        xCoord = 3
      elif event.x >= gameBoard.COLUMN_TWO:
        xCoord = 2
      elif event.x >= gameBoard.COLUMN_ONE:
        xCoord = 1
      else:
        xCoord = 0

      # Get lowest blank space in column
      # In other words, gets y-coordinate
      yCoord = self.__game.possibleMove(xCoord)

      # Checks if y-coordinate is on gameboard
      if yCoord < gameBoard.NUM_ROWS:
        # Gets color
        color = self.__game.getPlayerOneColor()
        if self.__game.getTurn() == self.__game.PLAYER_TWO:
          color = self.__game.getPlayerTwoColor()

        # Shades in circle on grid
        self.__circles.itemconfig(self.__grid[xCoord][5 - yCoord], \
                                  fill = color)
        self.__game.changeColor(xCoord, yCoord)

        # Checks for win; stops game if won
        self.__game.checkWin()

        # Increments score and displays winner
        if not self.__game.getGameStatus():
          self.__game.incrementScore()
          self.updateScore()

          self.updateWinner()
        else:
          self.__game.switchTurn()
          self.__playerTurn.set(self.__game.getPlayerTurn() + "'s Turn")

    mainloop()

gameBoard()


from flask import url_for

from tests.utils import login

def test_setup_done(flask_client):
    login(flask_client)

    r = flask_client.get(
        url_for("dashboard.setup_done"),
    )

    assert r.status_code == 302
    # user is redirected to the dashboard page
    assert r.headers["Location"].endswith("/dashboard/")
    assert "setup_done=true" in r.headers["Set-Cookie"]


import gradio as gr
import time
import os.path
from datetime import datetime
from io import StringIO
import sys
import requests
import json

def jprint(obj):
    text = ""
    for x in obj['data']:
            text += x
    return text

title = "GPT Interface"
description = "This interface uses APIs to connect to different VMs"
article="The following shows the carbon emission of GPT models when answering questions."

VirginiaURL = 'https://8b2ceb48d74ce910.gradio.app/api/predict'

examples = [
    ["gpt2", 'What is a computer?', "Virginia"],
    ["gptj13B", 'What is a computer?', "Virginia"],
    ["gpt125M", 'What is a computer?', "Virginia"]
]

def fn(model_choice, input, location):
    start_time = time.time()

    if location == "Virginia":
        url = VirginiaURL

    data = {'data': [model_choice, input]}
    response = requests.post(url, json=data)
    genOutput = jprint(response.json())
    strRuntime = str(time.time()-start_time)
    formattedOutput = location + " " +  strRuntime + "\n" + genOutput

    return formattedOutput

gr.Interface(fn, [gr.inputs.Dropdown(["gpt2", "gpt-j-1.3B", "gpt-neo-125M"]), "text", gr.inputs.Dropdown(["Virginia"])], "text", examples=examples, title=title, description=description, article=article).launch(debug=True, share=True)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@File    :   flower_config.py
@Time    :   2022/08/04 19:56:18
@Author  :   Alex Wong
@Version :   1.0
@Desc    :   花朵分类参数配置
'''

import torch
import torchvision.transforms as transforms
from easydict import EasyDict

cfg = EasyDict()  # 访问属性的方式去使用key-value 即通过key获得value
cfg.train_bs = 32
cfg.valid_bs = 64
cfg.workers = 0

cfg.lr_init = 0.01
cfg.momentum = 0.9
cfg.weight_decay = 1e-4
cfg.factor = 0.1
cfg.milestones = [30, 45]
cfg.max_epoch = 50

cfg.log_interval = 10

norm_mean = [0.485, 0.456, 0.406]  # imagenet 120万图像统计得来
norm_std = [0.229, 0.224, 0.225]
normTransform = transforms.Normalize(norm_mean, norm_std)

cfg.transforms_train = transforms.Compose([
        transforms.Resize((256)),  # (256, 256) 区别； （256） 最短边256
        transforms.CenterCrop(256),
        transforms.RandomCrop(224),
        transforms.RandomHorizontalFlip(p=0.5),
        transforms.ToTensor(),
        normTransform,
])
cfg.transforms_valid = transforms.Compose([
        transforms.Resize((224, 224)),
        transforms.ToTensor(),
        normTransform,
])


from typing import Type

from asn1crypto import cms, core

__all__ = ['as_set_of', 'register_cms_attribute']

def as_set_of(asn1_type: Type):
    return type(
        'SetOf' + asn1_type.__name__, (core.SetOf,), {'_child_spec': asn1_type}
    )

def register_cms_attribute(
    dotted_oid: str, readable_name: str, asn1_type: Type
):
    cms.CMSAttributeType._map[dotted_oid] = readable_name
    cms.CMSAttribute._oid_specs[readable_name] = as_set_of(asn1_type)


#!/usr/bin/env python

from siconos.mechanics.collision.tools import Contactor
from siconos.mechanics.collision.convexhull import ConvexHull
from siconos.io.mechanics_run import MechanicsHdf5Runner
import siconos.numerics as sn
import siconos.kernel as sk
import math, random, numpy
# A collection of box stacks for stress-testing Siconos solver with
# chains of contacts.

#configuration = 'pyramid_wall'
configuration = 'wide_wall'
configuration = 'wide_wall_with_buttress'
configuration = 'tall_wall_with_buttress'
#configuration = 'tall_wall'

rock_velocity = [-10,0,-35.,0.5,0.1,0.1]
rock_tob = 0.01
rock_size = 5.0

def one_rock(io, name, cname, rock_size=0.05, density=1, trans=None, velo=None, tob=None):
    # Definition of an irregular polyhedron as a convex shape

    rd = [math.pi/2 * random.gauss(0.5,0.2) for _ in range(16)]
    rd = [1.143194140731269, 0.6247636994959747, 0.4198206059540749, 1.1116480956118107, 0.8965451614785596, 0.8819019228647785, 0.2592675582459427, 0.22899315888913663, 0.23837569282753324, 0.6585606791241505, 1.0084563758002816, 0.9096785924063177, 0.8633716705085941, 1.1215975890657788, 1.1983269522076825, 0.5443688021200721]

    # print('rd', rd)
    # input()
    def vert(id1, id2, a, b, c):
        return (a*math.cos(rd[id1])*math.cos(rd[id2]),
                b*math.sin(rd[id1])*math.cos(rd[id2]),
                c*math.sin(rd[id2]))

    vertices = [ vert( 0,  1,   1,  1,  1),
                 vert( 2,  3,   1, -1,  1),
                 vert( 4,  5,  -1,  1,  1),
                 vert( 6,  7,  -1, -1,  1),
                 vert( 8,  9,   1,  1, -1),
                 vert(10, 11,   1, -1, -1),
                 vert(12, 13,  -1,  1, -1),
                 vert(14, 15,  -1, -1, -1) ]

    scale = rock_size / max(numpy.array(vertices).max(axis=0)
                            - numpy.array(vertices).min(axis=0))

    ch = ConvexHull(vertices)
    cm = ch.centroid()

    # correction of vertices such that 0 is the centroid
    vertices = (numpy.array(vertices)[:] - cm[:]) * scale

    ch = ConvexHull(vertices)
    cm = ch.centroid()

    # Definition of a polyhedron as a convex shape
    io.add_convex_shape(cname, vertices, insideMargin=0.1*rock_size)

    # computation of inertia and volume
    inertia,volume=ch.inertia(ch.centroid())

    # print('geometric inertia:', inertia)
    # print('volume:', volume)
    # print('mass:', volume*density)
    # print('inertia:', inertia*density)

    io.add_object(name,
                 [Contactor(cname)],
                 translation=trans,
                 velocity=velo,
                 mass=volume*density,
                 time_of_birth=tob,
                 inertia=inertia*density)

# Creation of the hdf5 file for input/output
with MechanicsHdf5Runner() as io:

    width, depth, height = 1, 2, 1
    io.add_primitive_shape('Box', 'Box', [width, depth, height])
    io.add_primitive_shape('Half_Box', 'Box', [width, depth/2.0, height])

    k = 0
    sep = 0.01

    def make_stack(X, Y, N, M, W):
        global k
        z = height/2.0
        while W > 0:
            for i in range(N):
                for j in range(M):
                    x = (i-N/2.0)*(width+sep) + X
                    y = (j-M/2.0)*(depth+sep) + Y
                    io.add_object('box%03d' % k, [Contactor('Box')],
                                  translation=[x, y, z],
                                  mass=1.0)
                    k += 1
            N = N - 1 if N > 1 else N
            M = M - 1 if M > 1 else M
            W = W - 1
            z += height + sep

    def make_large_stack(X, Y, N, M, W, orientation=[1.0,0.0,0.0], density=1.0):
        """
        N is the depth of the wall
        W is th height
        """
        global k
        z = height/2.0
        volume= height*width*depth
        angle = math.acos(orientation[0]/numpy.linalg.norm(orientation))
        while W > 0:
            for i in range(N):
                for j in range(M):
                    x = (i-N/2.0)*(width+sep) + X
                    y = (j-M/2.0)*(depth+sep) + Y

                    # apply rotation around z axis
                    X_r =  x*math.cos(angle) + y* math.sin(angle)
                    Y_r = -x*math.sin(angle) + y* math.cos(angle)

                    io.add_object('box%03d' % k, [Contactor('Box')],
                                  translation=[X_r, Y_r, z],
                                  orientation =[math.cos(-angle/2.0),
                                                0.0,0.0,
                                                math.sin(-angle/2.0)],
                                  mass=volume*density)
                    k += 1
            N = N - 1 if N > 1 else N
            M = M - 1 if M > 1 else M
            W = W - 1
            z += height + sep

    def make_large_stack_with_straight_side(X, Y, N, M, W, orientation=[1.0,0.0,0.0], density=1.0):
        """
        N is the depth of the wall
        M is the width
        W is the height
        """
        global k
        z = height/2.0

        angle = math.acos(orientation[0]/numpy.linalg.norm(orientation))
        while W > 0:
            for i in range(N):
                for j in range(M):
                    if (j == M-1 and W%2 ==0):
                        shape = 'Half_Box'
                        volume= height*width*depth/2.0
                        offset = -depth/4.0
                    elif (j == 0 and W%2 ==1):
                        shape = 'Half_Box'
                        volume= height*width*depth/2.0
                        offset = depth/4.0
                    else:
                        volume= height*width*depth
                        shape = 'Box'
                        offset=0.0

                    x = (i-N/2.0)*(width+sep) + X
                    y = (j-(M +  W%2 )/2.0)*(depth+sep) + Y +offset

                    # apply rotation around z axis
                    X_r =  x*math.cos(angle) + y* math.sin(angle)
                    Y_r = -x*math.sin(angle) + y* math.cos(angle)

                    io.add_object('box%03d' % k, [Contactor(shape)],
                                  translation=[X_r, Y_r, z],
                                  orientation =[math.cos(-angle/2.0),
                                                0.0,0.0,
                                                math.sin(-angle/2.0)],
                                  mass=volume*density)
                    k += 1
            N = N - 1 if N > 1 else N
            M = M  if M > 1 else M
            W = W - 1
            z += height + sep
    # A wall

    if configuration == 'wide_wall':
        make_large_stack(0, 0, 1, 20, 5, density=2300)
    if configuration == 'tall_wall':
        make_large_stack(0, 0, 1, 20, 10, density=2300)
    elif  configuration == 'pyramid_wall':
        make_large_stack(0, 0, 1, 10, 10, density=2300)
    elif configuration == 'wide_wall_with_buttress':
        make_large_stack(0, 0, 1, 20, 5, density=2300)
        make_large_stack_with_straight_side(10,-1.5*depth, 1, 4, 5, orientation= [0.0,1.0, 0.0], density=2300)
        make_large_stack_with_straight_side(5,-1.5*depth, 1, 4, 5, orientation= [0.0,1.0, 0.0], density=2300)
        make_large_stack_with_straight_side(0,-1.5*depth, 1, 4, 5, orientation= [0.0,1.0, 0.0], density=2300)
        make_large_stack_with_straight_side(-5,-1.5*depth, 1, 4, 5, orientation= [0.0,1.0, 0.0], density=2300)
        make_large_stack_with_straight_side(-10,-1.5*depth, 1, 4, 5, orientation= [0.0,1.0, 0.0], density=2300)
    elif configuration == 'tall_wall_with_buttress':
        buttress_offset = -depth/2.0
        make_large_stack(0, 0, 1, 20, 10, density=2300)
        make_large_stack_with_straight_side(15+buttress_offset,-1.5*depth, 1, 4, 5, orientation= [0.0,1.0, 0.0], density=2300)
        make_large_stack_with_straight_side(10+buttress_offset,-1.5*depth, 1, 4, 5, orientation= [0.0,1.0, 0.0], density=2300)
        make_large_stack_with_straight_side(5+buttress_offset,-1.5*depth, 1, 4, 5, orientation= [0.0,1.0, 0.0], density=2300)
        make_large_stack_with_straight_side(0+buttress_offset,-1.5*depth, 1, 4, 5, orientation= [0.0,1.0, 0.0], density=2300)
        make_large_stack_with_straight_side(-5+buttress_offset,-1.5*depth, 1, 4, 5, orientation= [0.0,1.0, 0.0], density=2300)
        make_large_stack_with_straight_side(-10+buttress_offset,-1.5*depth, 1, 4, 5, orientation= [0.0,1.0, 0.0], density=2300)

    # # a big ball
    # io.add_primitive_shape('Ball', 'Sphere', [width])
    # io.add_object('Ball' % k, [Contactor('Ball')],
    #               translation=[0., 0., 0.],
    #               mass=1.0)

    # a big rock
    one_rock(io, 'rock', 'rock_shape', rock_size = rock_size,
             density=2300,
             trans = [30.,0. ,35.],
             velo=rock_velocity, tob=rock_tob)

    # Definition of the ground
    io.add_primitive_shape('Ground', 'Box', (50, 50, 0.1))
    io.add_object('ground', [Contactor('Ground')], [0, 0, -0.05])
    # Definition of the slope
    angle_slope= -math.pi/4.0
    io.add_object('slope', [Contactor('Ground',
                                      relative_translation=[30.0, 0.0, -25.0* math.sin(angle_slope)],
                                      relative_orientation=[math.cos(angle_slope/2.0),
                                                            0.0,
                                                            math.sin(angle_slope/2.0),
                                                            0.0]) ],
                  [0, 0, -0.05])

    # # Enable to smash the wall
    # io.add_primitive_shape('Ball', 'Sphere', [1,])
    # io.add_object('WreckingBall', [Contactor('Ball')],
    #              translation=[25,0,3], velocity=[-30,0,2,0,0,0],
    #              mass=10)

    # Definition of a non smooth law. As no group ids are specified it
    # is between contactors of group id 0.
    io.add_Newton_impact_friction_nsl('contact', mu=0.6, e=0.0)

T = 6.0
#T = 3e-2
h_step = 5e-3

options = sk.solver_options_create(sn.SICONOS_FRICTION_3D_NSGS)
options.iparam[sn.SICONOS_IPARAM_MAX_ITER] = 1000
options.dparam[sn.SICONOS_DPARAM_TOL] = 1e-4
options.iparam[sn.SICONOS_FRICTION_3D_NSGS_FREEZING_CONTACT] = 100

# Load and run the simulation
with MechanicsHdf5Runner(mode='r+') as io:
    io.run(t0=0,
           T=T,
           h=h_step,
           theta=0.5,
           Newton_max_iter=1,
           solver_options=options,
           output_frequency=1,
           with_timer=True)


# Project on TIC TAC TOE Game

def printBoard(xst, zst):
    zero='X' if xst[0] else ('O' if zst[0] else 0)
    one='X' if xst[1] else ('O' if zst[1] else 1)
    two='X' if xst[2] else ('O' if zst[2] else 2)
    three='X' if xst[3] else ('O' if zst[3] else 3)
    four='X' if xst[4] else ('O' if zst[4] else 4)
    five='X' if xst[5] else ('O' if zst[5] else 5)
    six='X' if xst[6] else ('O' if zst[6] else 6)
    seven='X' if xst[7] else ('O' if zst[7] else 7)
    eight='X' if xst[8] else ('O' if zst[8] else 8)

    print(f" {zero} | {one} | {two} ")
    print(f"---|---|---")
    print(f" {three} | {four} | {five} ")
    print(f"---|---|---")
    print(f" {six} | {seven} | {eight} ")

def sum(a,b,c):
    return a+b+c

def checkWinner(xst, zst):
    win=[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
    for w in win:

        #If Player 1 wins
        if (sum(xst[w[0]], xst[w[1]], xst[w[2]])==3):
            printBoard(xst, zst)
            print(a," won !!")
            return 1

        #If Player 2 wins
        if (sum(zst[w[0]], zst[w[1]], zst[w[2]])==3):
            printBoard(xst, zst)
            print(b," won !!")
            return 0

        # If there is a draw in the game
        if all(xst[i] == 1 or zst[i] == 1 for i in range(9)):
            printBoard(xst, zst)
            print("It's a draw !!")
            return -1

    # If no winner or draw, the game is still ongoing
    return None

if __name__=="__main__":
    xst=[0,0,0,0,0,0,0,0,0]
    zst=[0,0,0,0,0,0,0,0,0]
    turn=1            # 1 for X and 0 for O

    a=input("Enter name of player 1 :  ")
    b=input("Enter name of player 2 :  ")

    print("-----Welcome to TIC TAC TOE Game----- ")

    while (True):
        printBoard(xst,zst)
        if (turn==1):
            print(a,"'s turn...")
            val=int(input("Enter value from the available values.. : "))
            xst[val]=1
        else:
            print(b,"'s turn...")
            val=int(input("Enter value from the available values.. : "))
            zst[val]=1

        c=checkWinner(xst, zst)
        if (c!= None):
            break

        turn=1-turn


import argparse
import json
import logging
import os
import random
import signal
import sys

import tornado.httpclient

__author__ = 'Antonio Serrano Hernandez'
__copyright__ = 'Copyright (C) 2018 Antonio Serrano Hernandez'
__version__ = '0.1'
__license__ = 'GPL'
__maintainer__ = 'Antonio Serrano Hernandez'
__email__ = 'toni.serranoh@gmail.com'
__status__ = 'Development'

DEFAULT_CONFIG_FILE = os.path.join('/etc', os.path.basename(sys.argv[0]))
SECRET_BITS = 128

# Select libcurl implementation for HTTP requests
tornado.httpclient.AsyncHTTPClient.configure(
    "tornado.curl_httpclient.CurlAsyncHTTPClient")

class HTTPServerError(Exception): pass

class HTTPServer(object):
    '''A generic HTTPServer.'''

    def __init__(self, name, description, version=None, epilog=None,
            settings={}):
        '''kwargs may contain description, epilog and version.'''
        # Parse the command line options
        kwargs = {'prog': name, 'description': description}
        if epilog is not None:
            kwargs['epilog'] = epilog
        self._command_line_options(version, **kwargs)
        # Load the configuration file
        try:
            with open(self.config_file, 'r') as f:
                self.options = json.loads(f.read())
        except OSError:
            msg = 'cannot load options file'
            print('error:', msg, file=sys.stderr)
            raise HTTPServerError(msg)
        # Instantiate the application
        settings['cookie_secret'] = '{:x}'.format(
            random.getrandbits(SECRET_BITS))
        self._app = tornado.web.Application(**settings)
        # Handle signals
        def signal_handler(signum, frame):
            logging.info('sinal received, terminating...')
            tornado.ioloop.IOLoop.current().stop()
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)

    def _command_line_options(self, version=None, **kwargs):
        '''Process the command line options. kwargs may contain prog, epilog
        and description arguments for the argparse constructor.
        '''
        parser = argparse.ArgumentParser(**kwargs,
            formatter_class=argparse.RawTextHelpFormatter)
        if version is not None:
            parser.add_argument('--version', action='version', version=version)
        parser.add_argument('-c', '--config', default=DEFAULT_CONFIG_FILE,
            help='configuration file')
        parser.add_argument('-d', '--daemonize', action='store_true',
            help='daemonize this server')
        args = parser.parse_args()
        self.config_file = args.config
        self.daemonize = args.daemonize

    def add_handlers(self, handlers):
        '''Add the handlers for the sites.'''
        self._app.add_handlers(r'.*', handlers)

    def run(self):
        '''Run the HTTP server and start processing requests.'''
        self._app.listen(self.options['server']['port'])
        tornado.ioloop.IOLoop.current().start()


import unittest
import sys

from  util.ip import *
from ipaddress import ip_network, ip_address

class TestIP(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(TestIP, self).__init__(*args, **kwargs)
        self.ipList = ["any", "192.168.0.0 - 192.168.255.255", \
                       "10.10.10.10/32", "10.10.10.0/24", "0.0.0.0/32", "255.255.255.255/32"]

    def test_IP(self):
        ipany = "*"
        iprange = "192.168.0.0 - 192.168.255.255"
        iplist = "192.168.100.101, 192.168.100.102, 192.168.100.103"
        ipsubnet = "10.10.10.10/32"
        ipinvalid = "asd"

        self.assertEqual(IP(ipany), IPAny(ipany),
                            "Should be True")
        self.assertEqual(IP(iprange), IPRange(iprange),
                         "Should be True")
        self.assertEqual(IP(iplist), IPList(iplist),
                         "Should be True")
        self.assertEqual(IP(ipsubnet), IPSubnet(ipsubnet),
                         "Should be True")
        self.assertNotEqual(IP(ipsubnet), None,
                         "Should not be same")
        self.assertRaisesRegex(ValueError, "Can not parse IP from '%s'"%ipinvalid, IP, ipinvalid)

    def test_IPAny(self):
        self.assertEqual(str(IPAny("any")), "any", "should be any")
        self.assertEqual(IPAny("any"), IPAny("any"),
                         "should be True")
        self.assertNotEqual(IPAny("any"), IPSubnet("10.10.10.0/24"),
                         "asda")

    def test_IPRange(self):
        iprange = "192.168.0.0 - 192.168.255.255"
        self.assertEqual(str(IPRange(iprange)), iprange, "should be %s"%iprange)
        self.assertEqual(IPRange(iprange).ipType, IPType.IP_RANGE, "should be %s"%IPType.IP_RANGE.name)
        self.assertEqual(IPRange(iprange).version, 4, "should be 4")

        self.assertRaisesRegex(ValueError, "Invalid IP range 192.168.255.255 - 192.168.25500.0",
                               IPRange, "192.168.255.255 - 192.168.25500.0")
        self.assertRaisesRegex(ValueError, "Invalid IP range 192.168.255.255 - 2001::11",
                               IPRange, "192.168.255.255 - 2001::11")
        self.assertRaisesRegex(ValueError, "Invalid IP range, start 192.168.255.255 can not be greater than end 192.168.255.0",
                               IPRange, "192.168.255.255 - 192.168.255.0")

        iprange = "192.168.100.1 - 192.168.100.101"
        iprange2 = "192.168.100.1 - 192.168.100.102"
        in_host = ip_address("192.168.100.101")
        out_host = ip_address("192.168.100.105")

        self.assertEqual(IPRange(iprange), IPRange(iprange),
                         "should be same")
        self.assertNotEqual(IPRange(iprange), IPRange(iprange2),
                         "should not be same")
        self.assertNotEqual(IPRange(iprange), IPAny("any"),
                          "should not be same")
        self.assertIn(in_host, IPRange(iprange),
                      "%s should match in %s"%(in_host, IPRange(iprange)))
        self.assertNotIn(out_host, IPRange(iprange),
                          "%s should not match in %s"%(out_host, IPRange(iprange)))

    def test_IPList(self):
        iplist = "192.168.100.101, 192.168.100.102, 192.168.100.103"
        op = ', '.join(sorted(str(IPList(iplist)).split(', ')))
        self.assertEqual(IPList(iplist).ipType, IPType.IP_LIST, "should be same %s"%IPType.IP_LIST.name)
        self.assertEqual(IPList(iplist).version, 4, "should be same 4")

        iplist = "192.168.100.101, 192.168.100.102.123, 192.168.100.103"
        self.assertRaisesRegex(ValueError, "\'192.168.100.102.123\' does not appear to be an IPv4 or IPv6 address", IPList, iplist)

        iplist = "192.168.100.101, 192.168.100.102, 192.168.100.103, "
        self.assertRaisesRegex(ValueError, "\'\' does not appear to be an IPv4 or IPv6 address", IPList, iplist)

        iplist = "192.168.100.101, 192.168.100.102, 192.168.100.103, 2001::1"
        self.assertRaisesRegex(ValueError, "All addresses in iplist are not of same version 192.168.100.101, 192.168.100.102, 192.168.100.103, 2001::1", IPList, iplist)

        iplist = "192.168.100.101, 192.168.100.102, 192.168.100.103"
        iplist2 = "192.168.100.101, 192.168.100.102, 192.168.100.103, 192.168.100.104"
        in_host = ip_address("192.168.100.101")
        out_host = ip_address("192.168.100.105")

        self.assertEqual(IPList(iplist), IPList(iplist),
                         "should be same")
        self.assertNotEqual(IPList(iplist), IPList(iplist2),
                         "should not be same")
        self.assertNotEqual(IPList(iplist), IPAny("any"),
                         "should not be same")
        self.assertIn(in_host, IPList(iplist),
                      "%s should match in %s"%(in_host, IPList(iplist)))
        self.assertNotIn(out_host, IPList(iplist),
                         "%s should not match in %s"%(out_host, IPList(iplist)))

    def test_IPSubnet(self):
        ip = "10.10.10.10/32"
        net = IPSubnet(ip)
        self.assertEqual(net.subnet, ip_network(ip), "should be %s"%ip)
        self.assertRaisesRegex(ValueError, "\'10.10.10.10.asd\' does not appear to be an IPv4 or IPv6 network", IPSubnet, "10.10.10.10.asd")
        self.assertEqual(net.version, 4, "should be 4")
        self.assertEqual(net.ipType, IPType.IP_SUBNET, "should be %s"%IPType.IP_SUBNET.name)

        net = IPSubnet(ip)
        self.assertEqual(str(net), ip, "should match %s"%( ip))

        net = IPSubnet("10.10.10.10")
        self.assertEqual(net.subnet, ip_network(ip), "should be %s"%(ip_network(ip)))

        net1 = IPSubnet(ip)
        same_net = IPSubnet(ip)
        not_same_net = IPSubnet("20.20.20.20")
        self.assertEqual(net1, same_net, "%s and %s should be same"%(net1, same_net))
        self.assertNotEqual(net1, not_same_net,"%s and %s not should be same"%(net1, not_same_net))
        self.assertNotEqual(net1, IPAny("any"), "%s and %s not should be same"%(net1, not_same_net))

        net = IPSubnet("10.10.10.0/24")
        in_host = ip_address("10.10.10.10")
        out_host = ip_address("192.168.100.101")
        self.assertIn(in_host, net,"%s and %s should match"%(net, in_host))
        self.assertNotIn(out_host, net, "%s and %s should not match"%(net, out_host))

    def test_ip_getRandom(self):
        for ip in self.ipList:
            ip = IP(ip)
            ran = ip.getRandom()
            self.assertIn(ran, ip, "%s should match in %s"%(ran, ip))

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