from __future__ import annotations

from typing import Dict, Set, List, Tuple, Optional, Any, Union, NamedTuple, Deque
import datetime
import enum
import gc
import math
import os
import pickle
import struct
import sys

import pytest

import msgspec

class FruitInt(enum.IntEnum):
    APPLE = 1
    BANANA = 2

class FruitStr(enum.Enum):
    APPLE = "apple"
    BANANA = "banana"

class Person(msgspec.Struct):
    first: str
    last: str
    age: int
    prefect: bool = False

class PersonAA(msgspec.Struct, asarray=True):
    first: str
    last: str
    age: int
    prefect: bool = False

class Node(msgspec.Struct):
    left: Optional[Node] = None
    right: Optional[Node] = None

class Point(NamedTuple):
    x: float
    y: float

INTS = [
    -(2 ** 63),
    -(2 ** 31 + 1),
    -(2 ** 31),
    -(2 ** 15 + 1),
    -(2 ** 15),
    -(2 ** 7 + 1),
    -(2 ** 7),
    -(2 ** 5 + 1),
    -(2 ** 5),
    -1,
    0,
    1,
    2 ** 7 - 1,
    2 ** 7,
    2 ** 8 - 1,
    2 ** 8,
    2 ** 16 - 1,
    2 ** 16,
    2 ** 32 - 1,
    2 ** 32,
    2 ** 64 - 1,
]

FLOATS = [
    -1.5,
    0.0,
    1.5,
    -float("inf"),
    float("inf"),
    float("nan"),
    sys.float_info.max,
    sys.float_info.min,
    -sys.float_info.max,
    -sys.float_info.min,
]

SIZES = [0, 1, 31, 32, 2 ** 8 - 1, 2 ** 8, 2 ** 16 - 1, 2 ** 16]

def assert_eq(x, y):
    if isinstance(x, float) and math.isnan(x):
        assert math.isnan(y)
    else:
        assert x == y

class TestEncodeFunction:
    def test_encode(self):
        dec = msgspec.Decoder()
        assert dec.decode(msgspec.encode(1)) == 1

    def test_encode_error(self):
        with pytest.raises(TypeError):
            msgspec.encode(object())

    def test_encode_large_object(self):
        """Check that buffer resize works"""
        data = b"x" * 4097
        dec = msgspec.Decoder()
        assert dec.decode(msgspec.encode(data)) == data

    def test_encode_no_enc_hook(self):
        class Foo:
            pass

        with pytest.raises(
            TypeError, match="Encoding objects of type Foo is unsupported"
        ):
            msgspec.encode(Foo())

    def test_encode_enc_hook(self):
        unsupported = object()

        def enc_hook(x):
            assert x is unsupported
            return "hello"

        orig_refcount = sys.getrefcount(enc_hook)

        res = msgspec.encode(unsupported, enc_hook=enc_hook)
        assert msgspec.encode("hello") == res
        assert sys.getrefcount(enc_hook) == orig_refcount

    def test_encode_enc_hook_errors(self):
        def enc_hook(x):
            raise TypeError("bad")

        orig_refcount = sys.getrefcount(enc_hook)

        with pytest.raises(TypeError, match="bad"):
            msgspec.encode(object(), enc_hook=enc_hook)

        assert sys.getrefcount(enc_hook) == orig_refcount

    def test_encode_parse_arguments_errors(self):
        with pytest.raises(TypeError, match="Missing 1 required argument"):
            msgspec.encode()

        with pytest.raises(TypeError, match="Extra positional arguments"):
            msgspec.encode(1, lambda x: None)

        with pytest.raises(TypeError, match="Extra positional arguments"):
            msgspec.encode(1, 2, 3)

        with pytest.raises(TypeError, match="Extra keyword arguments"):
            msgspec.encode(1, bad=1)

        with pytest.raises(TypeError, match="Extra keyword arguments"):
            msgspec.encode(1, enc_hook=lambda x: None, extra="extra")

class TestDecodeFunction:
    def setup(self):
        self.buf = msgspec.encode([1, 2, 3])

    def test_decode(self):
        assert msgspec.decode(self.buf) == [1, 2, 3]

    def test_decode_type_keyword(self):
        assert msgspec.decode(self.buf, type=List[int]) == [1, 2, 3]

        with pytest.raises(msgspec.DecodingError):
            assert msgspec.decode(self.buf, type=List[str])

    def test_decode_type_any(self):
        assert msgspec.decode(self.buf, type=Any) == [1, 2, 3]

    def test_decode_invalid_type(self):
        with pytest.raises(TypeError, match="Type '1' is not supported"):
            msgspec.decode(self.buf, type=1)

    def test_decode_invalid_buf(self):
        with pytest.raises(TypeError):
            msgspec.decode(1)

    def test_decode_parse_arguments_errors(self):
        with pytest.raises(TypeError, match="Missing 1 required argument"):
            msgspec.decode()

        with pytest.raises(TypeError, match="Extra positional arguments"):
            msgspec.decode(self.buf, List[int])

        with pytest.raises(TypeError, match="Extra positional arguments"):
            msgspec.decode(self.buf, 2, 3)

        with pytest.raises(TypeError, match="Extra keyword arguments"):
            msgspec.decode(self.buf, bad=1)

        with pytest.raises(TypeError, match="Extra keyword arguments"):
            msgspec.decode(self.buf, type=List[int], extra=1)

    def test_decode_dec_hook(self):
        def dec_hook(typ, obj):
            assert typ is Point
            return typ(*obj)

        buf = msgspec.encode((1, 2))
        res = msgspec.decode(buf, type=Point, dec_hook=dec_hook)
        assert res == Point(1, 2)
        assert isinstance(res, Point)

class TestEncoderMisc:
    @pytest.mark.parametrize("x", [-(2 ** 63) - 1, 2 ** 64])
    def test_encode_integer_limits(self, x):
        enc = msgspec.Encoder()
        with pytest.raises(OverflowError):
            enc.encode(x)

    def rec_obj1(self):
        o = []
        o.append(o)
        return o

    def rec_obj2(self):
        o = ([],)
        o[0].append(o)
        return o

    def rec_obj3(self):
        o = {}
        o["a"] = o
        return o

    def rec_obj4(self):
        class Box(msgspec.Struct):
            a: "Box"

        o = Box(None)
        o.a = o
        return o

    @pytest.mark.parametrize("case", [1, 2, 3, 4])
    def test_encode_infinite_recursive_object_errors(self, case):
        enc = msgspec.Encoder()
        o = getattr(self, "rec_obj%d" % case)()
        with pytest.raises(RecursionError):
            enc.encode(o)

    def test_getsizeof(self):
        enc1 = msgspec.Encoder(write_buffer_size=64)
        enc2 = msgspec.Encoder(write_buffer_size=128)
        assert sys.getsizeof(enc1) == sys.getsizeof(enc2)  # no buffer allocated yet
        enc1.encode(None)
        enc2.encode(None)
        assert sys.getsizeof(enc1) < sys.getsizeof(enc2)

    def test_write_buffer_size_attribute(self):
        enc1 = msgspec.Encoder(write_buffer_size=64)
        enc2 = msgspec.Encoder(write_buffer_size=128)
        enc3 = msgspec.Encoder(write_buffer_size=1)
        assert enc1.write_buffer_size == 64
        assert enc2.write_buffer_size == 128
        assert enc3.write_buffer_size == 32

    def test_encode_no_enc_hook(self):
        class Foo:
            pass

        enc = msgspec.Encoder()
        assert enc.enc_hook is None

        with pytest.raises(
            TypeError, match="Encoding objects of type Foo is unsupported"
        ):
            enc.encode(Foo())

    def test_encode_enc_hook(self):
        unsupported = object()

        def enc_hook(x):
            assert x is unsupported
            return "hello"

        orig_refcount = sys.getrefcount(enc_hook)

        enc = msgspec.Encoder(enc_hook=enc_hook)

        assert enc.enc_hook is enc_hook
        assert sys.getrefcount(enc.enc_hook) == orig_refcount + 2
        assert sys.getrefcount(enc_hook) == orig_refcount + 1

        res = enc.encode(unsupported)
        assert enc.encode("hello") == res

        del enc
        assert sys.getrefcount(enc_hook) == orig_refcount

    def test_encode_enc_hook_errors(self):
        def enc_hook(x):
            raise TypeError("bad")

        enc = msgspec.Encoder(enc_hook=enc_hook)

        with pytest.raises(TypeError, match="bad"):
            enc.encode(object())

    def test_encode_enc_hook_recurses(self):
        class Node:
            def __init__(self, a):
                self.a = a

        def enc_hook(x):
            return {"type": "Node", "a": x.a}

        enc = msgspec.Encoder(enc_hook=enc_hook)

        msg = enc.encode(Node(Node(1)))
        res = msgspec.decode(msg)
        assert res == {"type": "Node", "a": {"type": "Node", "a": 1}}

    def test_encode_enc_hook_recursion_error(self):
        enc = msgspec.Encoder(enc_hook=lambda x: x)

        with pytest.raises(RecursionError):
            enc.encode(object())

    def test_encode_into_bad_arguments(self):
        enc = msgspec.Encoder()

        with pytest.raises(TypeError, match="bytearray"):
            enc.encode_into(1, b"test")

        with pytest.raises(TypeError):
            enc.encode_into(1, bytearray(), "bad")

        with pytest.raises(ValueError, match="offset"):
            enc.encode_into(1, bytearray(), -2)

    @pytest.mark.parametrize("buf_size", [0, 1, 16, 55, 60])
    def test_encode_into(self, buf_size):
        enc = msgspec.Encoder()

        msg = {"key": "x" * 48}
        encoded = msgspec.encode(msg)

        buf = bytearray(buf_size)
        out = enc.encode_into(msg, buf)
        assert out is None
        assert buf == encoded

    def test_encode_into_offset(self):
        enc = msgspec.Encoder()
        msg = {"key": "value"}
        encoded = enc.encode(msg)

        # Offset 0 is default
        buf = bytearray()
        enc.encode_into(msg, buf, 0)
        assert buf == encoded

        # Offset in bounds uses the provided offset
        buf = bytearray(b"01234")
        enc.encode_into(msg, buf, 2)
        assert buf == b"01" + encoded

        # Offset out of bounds appends to end
        buf = bytearray(b"01234")
        enc.encode_into(msg, buf, 1000)
        assert buf == b"01234" + encoded

        # Offset -1 means append at end
        buf = bytearray(b"01234")
        enc.encode_into(msg, buf, -1)
        assert buf == b"01234" + encoded

    def tesT_encode_into_handles_errors_properly(self):
        enc = msgspec.Encoder()
        out1 = enc.encode([1, 2, 3])

        msg = [1, 2, object()]
        buf = bytearray()
        with pytest.raises(TypeError):
            enc.encode_into(msg, buf)

        assert buf  # buffer isn't reset upon error

        # Encoder still works
        out2 = enc.encode([1, 2, 3])
        assert out1 == out2

class TestDecoderMisc:
    def test_decoder_type_attribute(self):
        dec = msgspec.Decoder()
        assert dec.type is Any

        dec = msgspec.Decoder(int)
        assert dec.type is int

    def test_decoder_ext_hook_attribute(self):
        def ext_hook(code, buf):
            pass

        dec = msgspec.Decoder()
        assert dec.ext_hook is None

        dec = msgspec.Decoder(ext_hook=None)
        assert dec.ext_hook is None

        dec = msgspec.Decoder(ext_hook=ext_hook)
        assert dec.ext_hook is ext_hook

    def test_decoder_ext_hook_not_callable(self):
        with pytest.raises(TypeError):
            msgspec.Decoder(ext_hook=1)

    def test_decoder_dec_hook_attribute(self):
        def dec_hook(typ, obj):
            pass

        dec = msgspec.Decoder()
        assert dec.dec_hook is None

        dec = msgspec.Decoder(dec_hook=None)
        assert dec.dec_hook is None

        dec = msgspec.Decoder(dec_hook=dec_hook)
        assert dec.dec_hook is dec_hook

    def test_decoder_dec_hook_not_callable(self):
        with pytest.raises(TypeError):
            msgspec.Decoder(dec_hook=1)

    def test_decoder_dec_hook(self):
        called = False

        def dec_hook(typ, obj):
            nonlocal called
            called = True
            assert typ is Point
            return Point(*obj)

        dec = msgspec.Decoder(type=List[Point], dec_hook=dec_hook)
        buf = msgspec.encode([(1, 2), (3, 4), (5, 6)])
        msg = dec.decode(buf)
        assert called
        assert msg == [Point(1, 2), Point(3, 4), Point(5, 6)]
        assert isinstance(msg[0], Point)

    def test_decode_dec_hook_errors(self):
        def dec_hook(typ, obj):
            assert obj == "some string"
            raise TypeError("Oh no!")

        buf = msgspec.encode("some string")
        dec = msgspec.Decoder(type=Point, dec_hook=dec_hook)

        with pytest.raises(TypeError, match="Oh no!"):
            dec.decode(buf)

    def test_decode_dec_hook_wrong_type(self):
        dec = msgspec.Decoder(type=Point, dec_hook=lambda t, o: o)
        buf = msgspec.encode((1, 2))

        with pytest.raises(
            msgspec.DecodingError,
            match="Error decoding `Point`: expected `Point`, got `list`",
        ):
            dec.decode(buf)

    def test_decode_dec_hook_wrong_type_in_struct(self):
        class Test(msgspec.Struct):
            point: Point
            other: int

        dec = msgspec.Decoder(type=Test, dec_hook=lambda t, o: o)
        buf = msgspec.encode(Test((1, 2), 3))

        with pytest.raises(msgspec.DecodingError) as rec:
            dec.decode(buf)

        assert (
            "Error decoding `Test` field `point` (`Point`): expected `Point`, "
            "got `list`"
        ) == str(rec.value)

    def test_decode_dec_hook_wrong_type_generic(self):
        dec = msgspec.Decoder(type=Deque[int], dec_hook=lambda t, o: o)
        buf = msgspec.encode([1, 2, 3])

        with pytest.raises(msgspec.DecodingError) as rec:
            dec.decode(buf)

        assert (
            "Error decoding `typing.Deque[int]`: expected "
            "`collections.deque`, got `list`"
        ) == str(rec.value)

    def test_decode_dec_hook_isinstance_errors(self):
        class Metaclass(type):
            def __instancecheck__(self, obj):
                raise TypeError("Oh no!")

        class Custom(metaclass=Metaclass):
            pass

        dec = msgspec.Decoder(type=Custom)
        buf = msgspec.encode(1)

        with pytest.raises(TypeError, match="Oh no!"):
            dec.decode(buf)

    @pytest.mark.parametrize("typ, typstr", [(None, "None"), (Any, "Any")])
    def test_decoder_none_any_repr(self, typ, typstr):
        dec = msgspec.Decoder(typ)
        assert repr(dec) == f"Decoder({typstr})"
        # Optionality of None/Any doesn't change things
        dec = msgspec.Decoder(Optional[typ])
        assert repr(dec) == f"Decoder({typstr})"

    @pytest.mark.parametrize(
        "typ, typstr",
        [
            (bool, "bool"),
            (int, "int"),
            (float, "float"),
            (str, "str"),
            (bytes, "bytes"),
            (bytearray, "bytearray"),
            (datetime.datetime, "datetime"),
            (msgspec.Ext, "Ext"),
            (Dict, "Dict[Any, Any]"),
            (Dict[int, str], "Dict[int, str]"),
            (List, "List[Any]"),
            (List[Optional[int]], "List[Optional[int]]"),
            (Set, "Set[Any]"),
            (Set[Optional[int]], "Set[Optional[int]]"),
            (Tuple, "Tuple[Any, ...]"),
            (Tuple[Optional[int], ...], "Tuple[Optional[int], ...]"),
            (Tuple[int, str], "Tuple[int, str]"),
            (Person, "Person"),
            (FruitInt, "FruitInt"),
            (FruitStr, "FruitStr"),
            (Deque, "typing.Deque"),
            (Deque[int], str(Deque[int])),
            (List[Optional[Dict[str, Person]]], "List[Optional[Dict[str, Person]]]"),
        ],
    )
    def test_decoder_repr(self, typ, typstr):
        dec = msgspec.Decoder(typ)
        assert repr(dec) == f"Decoder({typstr})"

        dec = msgspec.Decoder(Optional[typ])
        assert repr(dec) == f"Decoder(Optional[{typstr}])"

    def test_decoder_unsupported_type(self):
        with pytest.raises(TypeError):
            msgspec.Decoder(1)

        with pytest.raises(TypeError):
            msgspec.Decoder(Union[int, float])

    def test_decoder_validates_struct_definition_unsupported_types(self):
        """Struct definitions aren't validated until first use"""

        class Test(msgspec.Struct):
            a: 1

        with pytest.raises(TypeError):
            msgspec.Decoder(Test)

class TestTypedDecoder:
    def check_unexpected_type(self, dec_type, val, msg):
        dec = msgspec.Decoder(dec_type)
        s = msgspec.Encoder().encode(val)
        with pytest.raises(msgspec.DecodingError, match=msg):
            dec.decode(s)

    def test_none(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(None)
        assert dec.decode(enc.encode(None)) is None
        with pytest.raises(msgspec.DecodingError, match="expected `None`"):
            assert dec.decode(enc.encode(1))

    @pytest.mark.parametrize("x", [False, True])
    def test_bool(self, x):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(bool)
        assert dec.decode(enc.encode(x)) is x

    def test_bool_unexpected_type(self):
        self.check_unexpected_type(bool, "a", "expected `bool`")

    @pytest.mark.parametrize("x", INTS)
    def test_int(self, x):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(int)
        assert dec.decode(enc.encode(x)) == x

    def test_int_unexpected_type(self):
        self.check_unexpected_type(int, "a", "expected `int`")

    @pytest.mark.parametrize("x", FLOATS + INTS)
    def test_float(self, x):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(float)
        res = dec.decode(enc.encode(x))
        sol = float(x)
        if math.isnan(sol):
            assert math.isnan(res)
        else:
            assert res == sol

    def test_float_unexpected_type(self):
        self.check_unexpected_type(float, "a", "expected `float`")

    def test_decode_float4(self):
        x = 1.2
        packed = struct.pack(">f", x)
        # Loss of resolution in float32 leads to some rounding error
        x4 = struct.unpack(">f", packed)[0]
        msg = b"\xca" + packed
        assert msgspec.decode(msg) == x4
        assert msgspec.decode(msg, type=float) == x4

    @pytest.mark.parametrize("size", SIZES)
    def test_str(self, size):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(str)
        x = "a" * size
        res = dec.decode(enc.encode(x))
        assert res == x

    def test_str_unexpected_type(self):
        self.check_unexpected_type(str, 1, "expected `str`")

    @pytest.mark.parametrize("size", SIZES)
    def test_bytes(self, size):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(bytes)
        x = b"a" * size
        res = dec.decode(enc.encode(x))
        assert isinstance(res, bytes)
        assert res == x

    def test_bytes_unexpected_type(self):
        self.check_unexpected_type(bytes, 1, "expected `bytes`")

    @pytest.mark.parametrize("size", SIZES)
    def test_bytearray(self, size):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(bytearray)
        x = bytearray(size)
        res = dec.decode(enc.encode(x))
        assert isinstance(res, bytearray)
        assert res == x

    def test_bytearray_unexpected_type(self):
        self.check_unexpected_type(bytearray, 1, "expected `bytearray`")

    def test_datetime(self):
        dec = msgspec.Decoder(datetime.datetime)
        x = datetime.datetime.now()
        res = dec.decode(msgspec.encode(x))
        assert x == res

    def test_datetime_unexpected_type(self):
        self.check_unexpected_type(datetime.datetime, 1, "expected `datetime`")
        self.check_unexpected_type(
            datetime.datetime, msgspec.Ext(1, b"test"), "expected `datetime`"
        )

    @pytest.mark.parametrize("size", SIZES)
    def test_list_lengths(self, size):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(list)
        x = list(range(size))
        res = dec.decode(enc.encode(x))
        assert res == x

    @pytest.mark.parametrize("typ", [list, List, List[Any]])
    def test_list_any(self, typ):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(typ)
        x = [1, "two", b"three"]
        res = dec.decode(enc.encode(x))
        assert res == x
        with pytest.raises(msgspec.DecodingError, match="expected `list`"):
            dec.decode(enc.encode(1))

    def test_list_typed(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(List[int])
        x = [1, 2, 3]
        res = dec.decode(enc.encode(x))
        assert res == x
        with pytest.raises(msgspec.DecodingError, match="expected `int`"):
            dec.decode(enc.encode([1, 2, "three"]))

    @pytest.mark.parametrize("size", SIZES)
    def test_set_lengths(self, size):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(set)
        x = set(range(size))
        res = dec.decode(enc.encode(x))
        assert res == x

    @pytest.mark.parametrize("typ", [set, Set, Set[Any]])
    def test_set_any(self, typ):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(typ)
        x = {1, "two", b"three"}
        res = dec.decode(enc.encode(x))
        assert res == x
        with pytest.raises(msgspec.DecodingError, match="expected `set`"):
            dec.decode(enc.encode(1))

    def test_set_typed(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Set[int])
        x = {1, 2, 3}
        res = dec.decode(enc.encode(x))
        assert res == x
        with pytest.raises(msgspec.DecodingError, match="expected `int`"):
            dec.decode(enc.encode({1, 2, "three"}))

    @pytest.mark.parametrize("size", SIZES)
    def test_vartuple_lengths(self, size):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(tuple)
        x = tuple(range(size))
        res = dec.decode(enc.encode(x))
        assert res == x

    @pytest.mark.parametrize("typ", [tuple, Tuple, Tuple[Any, ...]])
    def test_vartuple_any(self, typ):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(typ)
        x = (1, "two", b"three")
        res = dec.decode(enc.encode(x))
        assert res == x
        with pytest.raises(msgspec.DecodingError, match="expected `tuple`"):
            dec.decode(enc.encode(1))

    def test_vartuple_typed(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Tuple[int, ...])
        x = (1, 2, 3)
        res = dec.decode(enc.encode(x))
        assert res == x
        with pytest.raises(msgspec.DecodingError, match="expected `int`"):
            dec.decode(enc.encode((1, 2, "three")))

    def test_fixtuple_any(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Tuple[Any, Any, Any])
        x = (1, "two", b"three")
        res = dec.decode(enc.encode(x))
        assert res == x
        with pytest.raises(msgspec.DecodingError, match="expected `tuple`"):
            dec.decode(enc.encode(1))
        with pytest.raises(
            msgspec.DecodingError,
            match=r"Error decoding `Tuple\[Any, Any, Any\]`: expected tuple of length 3, got 2",
        ):
            dec.decode(enc.encode((1, 2)))

    def test_fixtuple_typed(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Tuple[int, str, bytes])
        x = (1, "two", b"three")
        res = dec.decode(enc.encode(x))
        assert res == x
        with pytest.raises(msgspec.DecodingError, match="expected `bytes`"):
            dec.decode(enc.encode((1, "two", "three")))
        with pytest.raises(
            msgspec.DecodingError,
            match=r"Error decoding `Tuple\[int, str, bytes\]`: expected tuple of length 3, got 2",
        ):
            dec.decode(enc.encode((1, 2)))

    @pytest.mark.parametrize("size", SIZES)
    def test_dict_lengths(self, size):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(dict)
        x = {i: i for i in range(size)}
        res = dec.decode(enc.encode(x))
        assert res == x

    @pytest.mark.parametrize("typ", [dict, Dict, Dict[Any, Any]])
    def test_dict_any_any(self, typ):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(typ)
        x = {1: "one", "two": 2, b"three": 3.0}
        res = dec.decode(enc.encode(x))
        assert res == x
        with pytest.raises(msgspec.DecodingError, match="expected `dict`"):
            dec.decode(enc.encode(1))

    def test_dict_any_val(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Dict[str, Any])
        x = {"a": 1, "b": "two", "c": b"three"}
        res = dec.decode(enc.encode(x))
        assert res == x
        with pytest.raises(msgspec.DecodingError, match="expected `str`"):
            dec.decode(enc.encode({1: 2}))

    def test_dict_any_key(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Dict[Any, str])
        x = {1: "a", "two": "b", b"three": "c"}
        res = dec.decode(enc.encode(x))
        assert res == x
        with pytest.raises(msgspec.DecodingError, match="expected `str`"):
            dec.decode(enc.encode({1: 2}))

    def test_dict_typed(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Dict[str, int])
        x = {"a": 1, "b": 2}
        res = dec.decode(enc.encode(x))
        assert res == x
        with pytest.raises(msgspec.DecodingError, match="expected `str`"):
            dec.decode(enc.encode({1: 2}))
        with pytest.raises(msgspec.DecodingError, match="expected `int`"):
            dec.decode(enc.encode({"a": "two"}))

    def test_enum(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(FruitStr)

        a = enc.encode(FruitStr.APPLE)
        assert enc.encode("APPLE") == a
        assert dec.decode(a) == FruitStr.APPLE

        with pytest.raises(msgspec.DecodingError, match="truncated"):
            dec.decode(a[:-2])
        with pytest.raises(
            msgspec.DecodingError, match="Error decoding enum `FruitStr`"
        ):
            dec.decode(enc.encode("MISSING"))
        with pytest.raises(msgspec.DecodingError):
            dec.decode(enc.encode(1))

    def test_int_enum(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(FruitInt)

        a = enc.encode(FruitInt.APPLE)
        assert enc.encode(1) == a
        assert dec.decode(a) == FruitInt.APPLE

        with pytest.raises(msgspec.DecodingError, match="truncated"):
            dec.decode(a[:-2])
        with pytest.raises(
            msgspec.DecodingError, match="Error decoding enum `FruitInt`"
        ):
            dec.decode(enc.encode(1000))
        with pytest.raises(msgspec.DecodingError):
            dec.decode(enc.encode("INVALID"))

    def test_struct(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Person)

        x = Person(first="harry", last="potter", age=13)
        a = enc.encode(x)
        assert (
            enc.encode(
                {"first": "harry", "last": "potter", "age": 13, "prefect": False}
            )
            == a
        )
        assert dec.decode(a) == x

        with pytest.raises(msgspec.DecodingError, match="truncated"):
            dec.decode(a[:-2])

        with pytest.raises(
            msgspec.DecodingError,
            match="Error decoding `Person`: expected `struct`, got `int`",
        ):
            dec.decode(enc.encode(1))

        with pytest.raises(
            msgspec.DecodingError,
            match="Error decoding `Person`: expected `str`, got `int`",
        ):
            dec.decode(enc.encode({1: "harry"}))

    def test_struct_field_wrong_type(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Person)

        bad = enc.encode({"first": "harry", "last": "potter", "age": "thirteen"})
        with pytest.raises(msgspec.DecodingError, match="expected `int`"):
            dec.decode(bad)

    def test_struct_missing_fields(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Person)

        bad = enc.encode({"first": "harry", "last": "potter"})
        with pytest.raises(msgspec.DecodingError, match="missing required field `age`"):
            dec.decode(bad)

        bad = enc.encode({})
        with pytest.raises(
            msgspec.DecodingError, match="missing required field `first`"
        ):
            dec.decode(bad)

    @pytest.mark.parametrize(
        "extra",
        [
            None,
            False,
            True,
            1,
            2.0,
            "three",
            b"four",
            [1, 2],
            {3: 4},
            msgspec.Ext(1, b"12345"),
            msgspec.Ext(1, b""),
        ],
    )
    def test_struct_ignore_extra_fields(self, extra):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Person)

        a = enc.encode(
            {
                "extra1": extra,
                "first": "harry",
                "extra2": extra,
                "last": "potter",
                "age": 13,
                "extra3": extra,
            }
        )
        res = dec.decode(a)
        assert res == Person("harry", "potter", 13)

    def test_struct_defaults_missing_fields(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Person)

        a = enc.encode({"first": "harry", "last": "potter", "age": 13})
        res = dec.decode(a)
        assert res == Person("harry", "potter", 13)
        assert res.prefect is False

    def test_struct_asarray(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(PersonAA)

        x = PersonAA(first="harry", last="potter", age=13)
        a = enc.encode(x)
        assert enc.encode(("harry", "potter", 13, False)) == a
        assert dec.decode(a) == x

        with pytest.raises(msgspec.DecodingError, match="truncated"):
            dec.decode(a[:-2])

        with pytest.raises(
            msgspec.DecodingError,
            match="Error decoding `PersonAA`: expected `struct`, got `int`",
        ):
            dec.decode(enc.encode(1))

        # Wrong field type
        bad = enc.encode(("harry", "potter", "thirteen"))
        with pytest.raises(msgspec.DecodingError, match="expected `int`"):
            dec.decode(bad)

        # Missing fields
        bad = enc.encode(("harry", "potter"))
        with pytest.raises(msgspec.DecodingError, match="missing required field `age`"):
            dec.decode(bad)

        bad = enc.encode(())
        with pytest.raises(
            msgspec.DecodingError, match="missing required field `first`"
        ):
            dec.decode(bad)

        # Extra fields ignored
        dec2 = msgspec.Decoder(List[PersonAA])
        msg = enc.encode(
            [
                ("harry", "potter", 13, False, 1, 2, 3, 4),
                ("ron", "weasley", 13, False, 5, 6),
            ]
        )
        res = dec2.decode(msg)
        assert res == [PersonAA("harry", "potter", 13), PersonAA("ron", "weasley", 13)]

        # Defaults applied
        res = dec.decode(enc.encode(("harry", "potter", 13)))
        assert res == PersonAA("harry", "potter", 13)
        assert res.prefect is False

    def test_struct_only_asarray_structs_can_decode_from_array(self):
        array_msg = msgspec.encode(("harry", "potter", 13))
        map_msg = msgspec.encode({"first": "harry", "last": "potter", "age": 13})
        sol = Person("harry", "potter", 13)
        array_sol = PersonAA("harry", "potter", 13)

        dec = msgspec.Decoder(Person)
        array_dec = msgspec.Decoder(PersonAA)

        assert array_dec.decode(map_msg) == array_sol
        assert array_dec.decode(array_msg) == array_sol
        assert dec.decode(map_msg) == sol
        with pytest.raises(
            msgspec.DecodingError,
            match="Error decoding `Person`: expected `struct`, got `list`",
        ):
            dec.decode(array_msg)

    @pytest.mark.parametrize("asarray", [False, True])
    def test_struct_gc_maybe_untracked_on_decode(self, asarray):
        class Test(msgspec.Struct, asarray=asarray):
            x: Any
            y: Any
            z: Tuple = ()

        enc = msgspec.Encoder()
        dec = msgspec.Decoder(List[Test])

        ts = [
            Test(1, 2),
            Test(3, "hello"),
            Test([], []),
            Test({}, {}),
            Test(None, None, ()),
        ]
        a, b, c, d, e = dec.decode(enc.encode(ts))
        assert not gc.is_tracked(a)
        assert not gc.is_tracked(b)
        assert gc.is_tracked(c)
        assert gc.is_tracked(d)
        assert not gc.is_tracked(e)

    def test_struct_recursive_definition(self):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Node)

        x = Node(Node(Node(), Node(Node())))
        s = enc.encode(x)
        res = dec.decode(s)
        assert res == x

    @pytest.mark.parametrize(
        "typ, value",
        [
            (bool, False),
            (bool, True),
            (int, 1),
            (float, 2.5),
            (str, "a"),
            (bytes, b"a"),
            (bytearray, bytearray(b"a")),
            (FruitInt, FruitInt.APPLE),
            (FruitStr, FruitStr.APPLE),
            (Person, Person("harry", "potter", 13)),
            (list, [1]),
            (set, {1}),
            (tuple, (1, 2)),
            (Tuple[int, int], (1, 2)),
            (dict, {1: 2}),
            (datetime.datetime, datetime.datetime.now()),
        ],
    )
    def test_optional(self, typ, value):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(Optional[typ])

        s = enc.encode(value)
        s2 = enc.encode(None)
        assert dec.decode(s) == value
        assert dec.decode(s2) is None

        dec = msgspec.Decoder(typ)
        with pytest.raises(msgspec.DecodingError):
            dec.decode(s2)

    @pytest.mark.parametrize(
        "typ, value",
        [
            (List[Optional[int]], [1, None]),
            (Tuple[Optional[int], int], (None, 1)),
            (Set[Optional[int]], {1, None}),
            (Dict[str, Optional[int]], {"a": 1, "b": None}),
            (Dict[Optional[str], int], {"a": 1, None: 2}),
        ],
    )
    def test_optional_nested(self, typ, value):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder(typ)

        s = enc.encode(value)
        assert dec.decode(s) == value

    def test_decoding_error_no_struct_toplevel(self):
        b = msgspec.Encoder().encode([{"a": 1}])
        dec = msgspec.Decoder(List[Dict[str, str]])
        with pytest.raises(
            msgspec.DecodingError,
            match=r"Error decoding `List\[Dict\[str, str\]\]`: expected `str`, got `int`",
        ):
            dec.decode(b)

class TestExt:
    @pytest.mark.parametrize("data", [b"test", bytearray(b"test"), memoryview(b"test")])
    def test_init(self, data):
        x = msgspec.Ext(1, data)
        assert x.code == 1
        assert x.data == data

    def test_compare(self):
        x = msgspec.Ext(1, b"two")
        x2 = msgspec.Ext(1, b"two")
        x3 = msgspec.Ext(1, b"three")
        x4 = msgspec.Ext(2, b"two")
        assert x == x2
        assert not (x != x2)
        assert x != x3
        assert not (x == x3)
        assert x != x4
        assert not (x == x4)

    @pytest.mark.parametrize("code", [-129, 128, 2 ** 65])
    def test_code_out_of_range(self, code):
        with pytest.raises(ValueError):
            msgspec.Ext(code, b"bad")

    def test_data_wrong_type(self):
        with pytest.raises(TypeError):
            msgspec.Ext(1, 2)

    def test_code_wrong_type(self):
        with pytest.raises(TypeError):
            msgspec.Ext(b"bad", b"bad")

    def test_immutable(self):
        x = msgspec.Ext(1, b"two")
        with pytest.raises(AttributeError):
            x.code = 2

    def test_pickleable(self):
        x = msgspec.Ext(1, b"two")
        x2 = pickle.loads(pickle.dumps(x))
        assert x2.code == 1
        assert x2.data == b"two"

    @pytest.mark.parametrize("size", sorted({0, 1, 2, 4, 8, 16, *SIZES}))
    def test_serialize_compatibility(self, size):
        msgpack = pytest.importorskip("msgpack")
        data = b"x" * size
        code = 5

        msgspec_bytes = msgspec.encode(msgspec.Ext(code, data))
        msgpack_bytes = msgpack.dumps(msgpack.ExtType(code, data))
        assert msgspec_bytes == msgpack_bytes

    @pytest.mark.parametrize("typ", [bytearray, memoryview])
    def test_serialize_other_types(self, typ):
        buf = b"test"
        a = msgspec.encode(msgspec.Ext(1, buf))
        b = msgspec.encode(msgspec.Ext(1, typ(buf)))
        assert a == b

    @pytest.mark.parametrize("size", sorted({0, 1, 2, 4, 8, 16, *SIZES}))
    def test_roundtrip(self, size):
        data = b"x" * size
        code = 5

        buf = msgspec.encode(msgspec.Ext(code, data))
        out = msgspec.decode(buf)
        assert out.code == code
        assert out.data == data

    @pytest.mark.parametrize("size", sorted({0, 1, 2, 4, 8, 16, *SIZES}))
    def test_roundtrip_typed_decoder(self, size):
        dec = msgspec.Decoder(msgspec.Ext)

        ext = msgspec.Ext(5, b"x" * size)
        buf = msgspec.encode(ext)
        out = dec.decode(buf)
        assert out == ext

    def test_typed_decoder_skips_ext_hook(self):
        def ext_hook(code, data):
            assert False, "shouldn't ever get called"

        msg = [None, msgspec.Ext(1, b"test")]
        dec = msgspec.Decoder(List[Optional[msgspec.Ext]])
        buf = msgspec.encode(msg)
        out = dec.decode(buf)
        assert out == msg

    def test_ext_typed_decoder_error(self):
        dec = msgspec.Decoder(msgspec.Ext)
        with pytest.raises(msgspec.DecodingError, match="expected `Ext`"):
            assert dec.decode(msgspec.encode(1))

    @pytest.mark.parametrize("use_function", [True, False])
    def test_decoder_ext_hook(self, use_function):
        obj = {"x": range(10)}
        exp_buf = pickle.dumps(range(10))

        def enc_hook(x):
            return msgspec.Ext(5, pickle.dumps(x))

        def ext_hook(code, buf):
            assert isinstance(buf, memoryview)
            assert bytes(buf) == exp_buf
            assert code == 5
            return pickle.loads(buf)

        msg = msgspec.encode(obj, enc_hook=enc_hook)
        if use_function:
            out = msgspec.decode(msg, ext_hook=ext_hook)
        else:
            dec = msgspec.Decoder(ext_hook=ext_hook)
            out = dec.decode(msg)
        assert out == obj

    def test_decoder_ext_hook_bad_signature(self):
        msg = msgspec.encode(range(5), enc_hook=lambda x: msgspec.Ext(1, b"test"))
        with pytest.raises(TypeError):
            msgspec.decode(msg, ext_hook=lambda: None)

    def test_decoder_ext_hook_raises(self):
        class CustomError(Exception):
            pass

        def ext_hook(code, buf):
            raise CustomError

        msg = msgspec.encode(range(5), enc_hook=lambda x: msgspec.Ext(1, b"test"))
        with pytest.raises(CustomError):
            msgspec.decode(msg, ext_hook=ext_hook)

skip_windows = pytest.mark.skipif(
    os.name == "nt",
    reason="This test fails on windows due to bounds on the OS time handling routines",
)

class TestTimestampExt:
    def check(self, dt, msg):
        assert msgspec.encode(dt) == msg
        assert msgspec.decode(msg) == dt

    @skip_windows
    def test_timestamp32_lower(self):
        dt = datetime.datetime.fromtimestamp(0)
        msg = b"\xd6\xff\x00\x00\x00\x00"
        self.check(dt, msg)

    def test_timestamp32_upper(self):
        dt = datetime.datetime.fromtimestamp(2 ** 32 - 1)
        msg = b"\xd6\xff\xff\xff\xff\xff"
        self.check(dt, msg)

    @skip_windows
    def test_timestamp64_lower(self):
        dt = datetime.datetime.fromtimestamp(1e-6)
        msg = b"\xd7\xff\x00\x00\x0f\xa0\x00\x00\x00\x00"
        self.check(dt, msg)

    def test_timestamp64_upper(self):
        dt = datetime.datetime.fromtimestamp(2 ** 34) - datetime.timedelta(
            microseconds=1
        )
        msg = b"\xd7\xff\xeek\x18c\xff\xff\xff\xff"
        self.check(dt, msg)

    @skip_windows
    def test_timestamp96_lower(self):
        dt = datetime.datetime.fromtimestamp(-1e-6)
        msg = b"\xc7\x0c\xff;\x9a\xc6\x18\xff\xff\xff\xff\xff\xff\xff\xff"
        self.check(dt, msg)

    def test_timestamp96_upper(self):
        dt = datetime.datetime.fromtimestamp(2 ** 34)
        msg = b"\xc7\x0c\xff\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00"
        self.check(dt, msg)

    def test_tzinfo_kwarg(self):
        dec = msgspec.Decoder()
        assert dec.tzinfo is None

        dec = msgspec.Decoder(tzinfo=None)
        assert dec.tzinfo is None

        dec = msgspec.Decoder(tzinfo=datetime.timezone.utc)
        assert dec.tzinfo is datetime.timezone.utc

        with pytest.raises(TypeError, match="tzinfo"):
            msgspec.Decoder(tzinfo=1)

        msg = msgspec.encode(1)
        with pytest.raises(TypeError, match="tzinfo"):
            msgspec.decode(msg, tzinfo=1)

    @pytest.mark.parametrize("timestamp", [0, 0.001, 2 ** 32 - 1])
    def test_decode_with_tzinfo(self, timestamp):
        dt = datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc)

        msg = msgspec.encode(dt)

        dec = msgspec.Decoder(tzinfo=datetime.timezone.utc)

        assert dec.decode(msg) == dt
        assert msgspec.decode(msg, tzinfo=datetime.timezone.utc) == dt

class CommonTypeTestBase:
    """Test msgspec untyped encode/decode"""

    def test_none(self):
        self.check(None)

    @pytest.mark.parametrize("x", [False, True])
    def test_bool(self, x):
        self.check(x)

    @pytest.mark.parametrize("x", INTS)
    def test_int(self, x):
        self.check(x)

    @pytest.mark.parametrize("x", FLOATS)
    def test_float(self, x):
        self.check(x)

    @pytest.mark.parametrize("size", SIZES)
    def test_str(self, size):
        self.check(" " * size)

    @pytest.mark.parametrize("size", SIZES)
    def test_bytes(self, size):
        self.check(b" " * size)

    @pytest.mark.parametrize("size", SIZES)
    def test_dict(self, size):
        self.check({str(i): i for i in range(size)})

    @pytest.mark.parametrize("size", SIZES)
    def test_list(self, size):
        self.check(list(range(size)))

class TestDecodeArrayTypeUsesTupleIfHashableRequired:
    def test_decode_tuple_dict_keys_as_tuples(self):
        orig = {(1, 2): [1, 2, [3, 4]], (1, (2, 3)): [4, 5, 6]}
        data = msgspec.encode(orig)
        out = msgspec.decode(data)
        assert orig == out

    @pytest.mark.parametrize(
        "typ",
        [
            Dict[Tuple[int, Tuple[int, int]], List[int]],
            Dict[Tuple[int, Tuple[int, ...]], Any],
            Dict[Tuple, List[int]],
            Dict[Tuple[Any, ...], Any],
            Dict[Tuple[Any, Any], Any],
        ],
    )
    def test_decode_dict_key_status_forwarded_through_typed_tuples(self, typ):
        orig = {(1, (2, 3)): [1, 2, 3]}
        data = msgspec.encode(orig)
        out = msgspec.Decoder(typ).decode(data)
        assert orig == out

    def test_decode_tuple_set_keys_as_tuples(self):
        orig = {(1, 2), (3, (4, 5)), 6}
        data = msgspec.encode(orig)
        out = msgspec.decode(data, type=set)
        assert orig == out

    def test_decode_hashable_struct_in_key(self):
        class Test(msgspec.Struct):
            data: List[int]

            def __hash__(self):
                return hash(tuple(self.data))

        orig = {(1, Test([1, 2])): [1, 2]}
        data = msgspec.encode(orig)
        out = msgspec.Decoder(Dict[Tuple[int, Test], List[int]]).decode(data)
        assert orig == out

class TestUntypedDecoder(CommonTypeTestBase):
    """Check the untyped deserializer works for common types"""

    def check(self, x):
        enc = msgspec.Encoder()
        dec = msgspec.Decoder()
        assert_eq(dec.decode(enc.encode(x)), x)

class TestCompatibility(CommonTypeTestBase):
    """Test compatibility with the existing python msgpack library"""

    def check(self, x):
        msgpack = pytest.importorskip("msgpack")

        enc = msgspec.Encoder()
        dec = msgspec.Decoder()

        assert_eq(dec.decode(msgpack.dumps(x)), x)
        assert_eq(msgpack.loads(enc.encode(x)), x)


import discord
from discord.ext import commands
from discord.ext.commands import Bot
import time
import asyncio
from DB import SQLite as sql
from core import welcome as wel, stats

PREFIX = open("core/prefix.txt", "r").read().replace("\n", "")
client = Bot(command_prefix = "{0}".format(PREFIX))

choix_G = [[':regional_indicator_a:', '🇦', 0], [':regional_indicator_b:', '🇧', 0], [':regional_indicator_c:', '🇨', 0], [':regional_indicator_d:', '🇩', 0], [':regional_indicator_e:', '🇪', 0]]

admin = 0
Inquisiteur = 1
Joueurs = 2
Vasseaux = 3
rolesID = [
    [417451897729843223],
    [417451897729843223, 417451604141277185],
    [417451897729843223, 417451604141277185, 677534823694336001, 423606460908306433]
]
guildID = [
    634317171496976395, # Get Gems
    417445502641111051, # Bastion
    478003352551030796, # Test
    129364058901053440  # TopazDev
]

def permission(ctx, grade):
    roles = ctx.author.roles
    for role in roles :
        if role.id in rolesID[grade] or (ctx.guild.id in guildID and role.permissions.administrator):
            return True
    return False

def checkInfo(ID):
    if sql.newPlayer(ID, "bastion") == "Le joueur a été ajouté !":
        stats.countCo()
        return False
    return True

def nom_ID(nom):
    """Convertis un nom en ID discord """
    if len(nom) == 21:
        ID = int(nom[2:20])
    elif len(nom) == 22:
        ID = int(nom[3:21])
    elif len(nom) == 18:
        ID = int(nom)
    else:
        ID = -1
    return(ID)

# Commandes Gestion
class Gestion(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
        return

    @commands.command(pass_context=True)
    async def show_perm(self, ctx):
        """Montre les permissions et leur valeurs"""
        msg = "Voici tes roles :```"
        roles = ctx.author.roles
        for role in roles:
            msg += "~ {} à pour valeur :{}\n".format(role.name, role.permissions.value)
        msg += "```"
        await ctx.channel.send(msg)

    @commands.command(pass_context=True)
    async def getmember(self, ctx):
        """Update de la BDD"""
        if ctx.guild.id == wel.idBASTION:
            if permission(ctx, Inquisiteur):
                members = ctx.guild.members
                for member in members:
                    sql.newPlayer(member.id)
                await ctx.channel.send("la bdd est remplis !")
            else:
                ctx.send("tu n'as pas les droits")
        else:
            await ctx.channel.send("commande utilisable uniquement sur le discord `Bastion`")

    @commands.command(pass_context=True)
    async def supp(self, ctx, nb):
        """**[nombre]** | Supprime [nombre] de message dans le channel """
        suppMax = 40
        if permission(ctx, Inquisiteur):
            try :
                nb = int(nb)
                if nb <= suppMax :
                    await ctx.channel.purge(limit =nb)
                    msg = '{0} messages on été éffacé !'.format(nb)
                else:
                    msg = "On ne peut pas supprimer plus de {} messages à la fois".format(suppMax)
            except ValueError:
                msg = "Commande mal remplis"
        else :
            msg = "Tu ne remplis pas les conditions"
        await ctx.channel.send(msg)

    @client.command(pass_context=True)
    async def vote(self, ctx, *, args):
        """
        **[durée]//[thème du vote]//[choix 1]/[choix 2]/<etc> ** | Créé un vote pendant 1h !
        """
        if permission(ctx, Joueurs):
            choix = choix_G[:]
            args = args.split("//")
            temps = float(args[0])*3600
            question = args[1]
            props = args[2].split("/")
            desc = ""
            n = len(props)
            if n > 5:
                await ctx.channel.send("5 choix sont possible au maximum!")
                return(None)
            msg = discord.Embed(title = "Un nouveau vote est lancé !", color= 12745742, description = question)
            for i in range(n):
                desc += "{} {} : {} vote(s)\n".format(choix[i][0], props[i], choix[i][2])
            desc += ":x: annuler son vote\n"
            msg.add_field(name="les différents choix", value=desc, inline=False)
            mess = await ctx.channel.send(embed=msg)
            for i in range(len(props)):
                await mess.add_reaction(choix[i][1])
            await mess.add_reaction('❌')
            t_init = time.time()
            votant = {}
            global exit
            exit = True

            def check(reaction, user):
                if user == client.user :
                    return(False)
                if reaction.emoji == '🛑':
                    print(user.name)
                    if permission(ctx, Inquisiteur, user):
                        global exit
                        exit = False
                        return(False)
                    else:
                        print('pas les droits')
                        return(False)

                elif user in votant :
                    if reaction.emoji == '❌':
                        emoji = votant[user]
                        for i in range(n):
                            if emoji == choix[i][1]:
                                choix[i][2] -= 1
                        del votant[user]
                        return(True)
                    else:
                        return(False)
                else :
                    votant[user] = reaction.emoji
                    for i in range(n):
                        if reaction.emoji == choix[i][1]:
                            choix[i][2] += 1
                    return(True)
            while t_init + temps > time.time() and exit:
                print(exit)
                try :
                    reaction, user = await self.bot.wait_for('reaction_add', timeout=10, check = check)
                    msg = discord.Embed(title = "Un nouveau vote est lancé !", color= 12745742, description = question)
                    desc = ""
                    for i in range(n):
                        desc += "{} {} : {} vote(s)\n".format(choix[i][0], props[i], choix[i][2])
                    desc += ":x: annuler son vote\n"
                    msg.add_field(name="les différents choix", value=desc, inline=False)
                    await mess.edit(embed = msg)
                except asyncio.TimeoutError:
                    print('60 sec ont passé')
                    pass
            max = 0
            for i in range(n):
                if choix[i][2] > max :
                    max = choix[i][2]
                    gagnant_nom = props[i]
                    gagnant_votes = max
                elif choix[i][2] == max :
                    gagnant_nom = "égalité"
                    gagnant_votes = max

            msg2 = "Fin des votes !\nLe gagnant des votes : **{}** avec **{}** votes !".format(gagnant_nom, gagnant_votes)
            await ctx.channel.send(msg2)
        else:
            await ctx.send("tu n'as pas la permission de faire ça !")

def setup(bot):
    bot.add_cog(Gestion(bot))
    open("help/cogs.txt", "a").write("Gestion\n")


# tkinter for making gui programs

from tkinter import *
from PIL import Image, ImageTk

# To create the window/frame
class Window( Frame ):

    # Define initialization
    def __init__( dlgSelf, master = None ):
        Frame.__init__( dlgSelf, master )

        # making the main widget window
        dlgSelf.master = master

        dlgSelf.init_window()

    #initializing window and setting the tile as GUI
    def init_window( dlgSelf ):
        dlgSelf.master.title( "GUI" )

        # fill up the window and expand dimensions
        dlgSelf.pack( fill = BOTH, expand = 1 )

        #btnQuit = Button( dlgSelf, text="Quit", command = dlgSelf.client_exit)
        #btnQuit.place( x = 200, y = 130)

        # for menu bar and buttons
        menu = Menu( dlgSelf.master )

        dlgSelf.master.config( menu = menu )

        file = Menu( menu )
        file.add_command( label = 'Save' )
        file.add_command( label = 'Exit', command = dlgSelf.client_exit )
        menu.add_cascade(label = 'File', menu = file)

        edit = Menu( menu )
        edit.add_command( label = 'Show Image', command = dlgSelf.Show_Image ) #adding dlgSelf.ShowImage() will call the function if () are added
        edit.add_command( label = 'Show Text', command = dlgSelf.Show_Text )
        menu.add_cascade( label = 'Edit', menu=edit)

    def Show_Image( dlgSelf ):
        picLoad = Image.open('Leobeli.jpg')
        render = ImageTk.PhotoImage( picLoad )

        picImage = Label( dlgSelf, image = render )
        picImage.image = render
        picImage.place( x = 0, y = 0 )

    def Show_Text( dlgSelf ):
        lblText = Label( dlgSelf, text = 'Hey There beautiful!!')

        lblText.pack()

    #Defining an action procedure for event handling
    def client_exit( dlgSelf ):

        exit()

# root window
root = Tk()
root.geometry("400x300")

# window class and frame is root
application = Window( root )

# initializes and generates the window
root.mainloop


"""
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example 1:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Example 2:
Input: (5) + (5)
Output: 0 -> 1
Explanation: 5 + 5 = 10.
"""

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x, node=None):
         self.val = x
         self.next = node

    def list_vals(self):
        temp = self
        vals = []
        while temp:
            vals.append(temp.val)
            temp = temp.next
        return vals

def addTwoNumbers(l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """
    val = l1.val + l2.val
    lsum = temp = ListNode(val%10)
    carry = (val-val%10)/10

    while l1.next or l2.next:
        if not l1.next:
            while l2.next:
                val = l2.next.val + carry
                temp.next = ListNode(val%10)
                carry = (val-val%10)/10
                temp = temp.next
                l2 = l2.next

        elif not l2.next:
            while l1.next:
                val = l1.next.val + carry
                temp.next = ListNode(val%10)
                carry = (val-val%10)/10
                temp = temp.next
                l1 = l1.next

        else:
            val = l1.next.val + l2.next.val + carry
            temp.next = ListNode(val%10)
            carry = (val-val%10)/10
            temp = temp.next
            l1 = l1.next
            l2 = l2.next

    if carry==1:
        temp.next = ListNode(carry)

    return lsum

if __name__ == "__main__":
    print('Addition 1: [2,4,3] + [5,6,4] -> ' + str(addTwoNumbers(ListNode(2,ListNode(4,ListNode(3))), ListNode(5,ListNode(6,ListNode(4)))).list_vals()))
    print('Addition 1: [5] + [5] -> ' + str(addTwoNumbers(ListNode(5), ListNode(5)).list_vals()))


# Sliding Window Maximum
from collections import deque
from typing import List

def maxSlidingWindow(nums: List[int], k: int) -> List[int]:
    if not nums or k == 0:
        return list()

    if k == 1:
        return nums

    q = deque()
    result = list()

    for i in range(len(nums)):
        while q and q[0] < i - k + 1:
            q.popleft()

        while q and nums[i] > nums[q[-1]]:
            q.pop()

        q.append(i)

        if i >= k - 1:
            result.append(nums[q[0]])

    return result

if __name__ == "__main__":
    result1 = maxSlidingWindow([1, 3, -1, -3, 5, 3, 6, 7], 3)
    assert result1 == [3, 3, 5, 5, 6, 7]

    result2 = maxSlidingWindow([1], 1)
    assert result2 == [1]

    result3 = maxSlidingWindow([], 0)
    assert result3 == []

    result4 = maxSlidingWindow([1], 0)
    assert result4 == []


# Python code to create a GDX filename list for use in vSPD. Specify
# a start date and end date - see st and et, yyyy,mm,dd
# Note that after about October 2013, GDX file names end in _F (or
# perhaps _I or _P) and may also have an 'x' ahead of the _F.
# Code by Dr Dave Hume.

import pandas as pd
from datetime import datetime,date

st = datetime(2013,1,1)
et = datetime(2013,10,31)

def createGDXfilelist(start,end,filename):
    file = open(filename, "w")
    file.write("/ \n")
    days = pd.date_range(start=st,end=et).map(lambda x: 'FP_' + str(x.year) + str(x.month).zfill(2) + str(x.day).zfill(2) + '_F')
    days.tofile(file,sep="\r\n")
    file.write(" \n/")
    file.close()

createGDXfilelist(st,et,'vSPDfileList.inc')


import argparse
import os
import pathlib

parser = argparse.ArgumentParser()
parser.add_argument("slur")
args = parser.parse_args()

path = ("/srv/ra/audycje/" + args.slur)

pliki = os.listdir(path + "/powtorka/")
# print(pliki.st_size)
print(pliki)
for plik in pliki:
    # print(plikstat.st_size)
    pathplik = pathlib.Path(path + "/powtorka/" + plik)
    if pathplik.is_dir() is False:
        os.rename(path + "/powtorka/" + plik, path + "/archiwum/" + plik)
pliki = os.listdir(path + "/powtorka/powtorka_puszki")
for plik in pliki:
    os.remove(path+"/powtorka/powtorka_puszki/"+plik)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from telegram.ext import Updater, MessageHandler, Filters

from telegram_util import splitCommand, log_on_fail, autoDestroy, formatChat, matchKey
from db import Source, Subscription
import loop
from common import tele, debug_group
from iterateMessage import iterateMessage
import traceback as tb

def commandImp(msg):
	autoDestroy(msg)
	command, text = splitCommand(msg.text)
	if "s4_g" in command:
		return msg.reply_text(iterateMessage(msg.chat.id), quote=False)
	elif matchKey(command, ["s4_source_add", "s4_sa", "s4_a"]):
		autoDestroy(msg.reply_text(Source.add(text)))
	elif matchKey(command, ["s4_source_delete", "s4_sd", "s4_d"]):
		autoDestroy(msg.reply_text(Source.remove(text)))
	elif matchKey(command, ["s4_source_list", "s4_sl", "s4_l"]):
		pass # intentional
	elif matchKey(command, ["s4_sub", "s4_s"]):
		Subscription.add(msg.chat.id, text)
	else:
		return
	if matchKey(command, ["s4_source", "s4_sl", "s4_l", "s4_sa", "s4_a", "s4_sd", "s3_d"]):
		sources = ['[%s](t.me/%s)' % (chatname, chatname) for \
			chatname in Source.db.keys()]
		autoDestroy(msg.reply_text('Source list: \n' + '\n'.join(sources),
			parse_mode='Markdown',
			disable_web_page_preview=True))
	else:
		autoDestroy(msg.reply_text("success"))

def command(update, context):
	msg = update.effective_message
	try:
		commandImp(msg)
	except Exception as e:
		autoDestroy(msg.reply_text(str(e)))
		tb.print_exc()
		raise e

tele.dispatcher.add_handler(MessageHandler(Filters.command, command))

tele.start_polling()
tele.idle()


from LIDC_Project.Records.Loader.LIDC_Loader import LIDC_Loader_Npy
from sklearn.ensemble import AdaBoostClassifier
import numpy
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale

if __name__ == '__main__':
    for appoint in range(10):
        # savepath = 'E:/LIDC/Result-SVM/OriginCsv/Appoint-%d/' % appoint
        # if not os.path.exists(savepath):
        #     os.makedirs(savepath)

        trainData, trainLabel, testData, testLabel = LIDC_Loader_Npy(
            loadpath='E:/LIDC/Npy/LBP_P=24_R=3/Appoint-%d/' % appoint)

        totalNumber = numpy.sum(testLabel, axis=0)[0]

        trainData = numpy.reshape(trainData, newshape=[-1, 4096])
        testData = numpy.reshape(testData, newshape=[-1, 4096])
        trainLabel = numpy.argmax(trainLabel, axis=1)
        testLabel = numpy.argmax(testLabel, axis=1)
        # print(numpy.shape(trainData), numpy.shape(trainLabel), numpy.shape(testData), numpy.shape(testLabel))
        # print(trainData[0:5])
        totalData = numpy.concatenate((trainData, testData), axis=0)
        pca = PCA(n_components=10)
        pca.fit(totalData)

        trainData = pca.transform(trainData)
        testData = pca.transform(testData)

        totalData = numpy.concatenate((trainData, testData), axis=0)
        totalData = scale(totalData)
        trainData = totalData[0:len(trainData)]
        testData = totalData[len(trainData):]
        # print(trainData[0:5])

        clf = AdaBoostClassifier()
        clf.fit(trainData, trainLabel)
        # joblib.dump(clf, savepath + 'Parameter.m')
        result = clf.predict(testData)
        # probability = clf.predict_proba(testData)
        # print(probability[0:10])
        # exit()
        matrix = numpy.zeros((2, 2))
        for index in range(len(result)):
            matrix[testLabel[index]][result[index]] += 1
        print(appoint)
        for indexX in range(2):
            for indexY in range(2):
                if indexY != 0: print(',', end='')
                print(matrix[indexX][indexY], end='')
            print()

        # for threshold in range(101):
        #     counter = 0
        #     for index in range(len(probability)):
        #         if testLabel[index] == 0 and probability[index][0] <= threshold / 100:
        #             counter += 1
        #     print(counter / totalNumber)

# 1020.0,127.0,
# 129.0,1664.0,


from pymongo import MongoClient  # pylint: disable=E0401

MONGO_DB_HOST = 'localhost'
MONGO_DB_PORT = '27017'
DB_NAME = 'todays-news'

# instance
client = MongoClient("%s:%s" % (MONGO_DB_HOST, MONGO_DB_PORT))

def get_db(db=DB_NAME):
    db = client[db]
    return db


import json
import boto3
import os
#import botocore.session
from requests_html import HTMLSession
import requests

def lambda_handler(event,context):

  session = HTMLSession()
  r = session.get('https://dashboard.nonlive.spoc.cloud.otto.de/monitoring',verify=False)
  status = r.html.search('
{}
')[0]
  service = r.html.search('
{}
')[0]

  errorMessage = f'This is a critical alert message! Service {service} is critical.'

  destPhoneNumber = os.environ['destPhoneNumber']
  contactFlowId = os.environ['contactFlowId']
  instanceId = os.environ['instanceId']
  sourcePhoneNumber = os.environ['sourcePhoneNumber']

  connectclient = boto3.client('connect', region_name='eu-central-1')
  snsclient = boto3.client('sns')

  if status != 'OK':
    OutboundResponse = connectclient.start_outbound_voice_contact(
                        DestinationPhoneNumber=destPhoneNumber,
                        ContactFlowId=contactFlowId,
                        InstanceId=instanceId,
                        SourcePhoneNumber=sourcePhoneNumber,
                        Attributes={'Message': errorMessage }
    )
    response = snsclient.publish(
      PhoneNumber= destPhoneNumber,
      Message= errorMessage,
    )


# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import datetime

def get_article_list(period):
    # ПОЛУЧАЕМ СПИСОК ДАТ ЗА ПОЛ ГОДА
    date_list = list()
    base = datetime.datetime.today()
    i=0
    while i < period:
        a= (base - datetime.timedelta(days=i)).strftime("%Y/%m/%d")
        i=i+1
        date_list.append(a)
    #print(date_list)

    #ЛИСТ СТРАНИЦ СО СТАТЬЯМИ ПО КАЛЕНДАРНЫМ ДНЯМ
    url_list=list()
    i = len(date_list)-1
    while i >= 0:
        url_list.append('http://www.e1.ru/news/daily/' + date_list[i] +  '/list-section_id-73.html')
        i=i-1

    #print(url_list)
     #ВСЕ ССЫЛКИ НА СТАТЬИ ЗА ПОЛ ГОДА
    article_list=list()
    i=0
    while i<len(url_list):
        r = requests.get(url_list[i])
        soup = BeautifulSoup(r.text, 'html.parser')
        href = (soup.find_all('a',attrs={"class":"news"}))
        i=i+1
        j=0
        while j<len(href):
            if "section_id-73" in href[j]['href']:
                article_list.append('http://www.e1.ru'+href[j]['href'])
            j=j+1
    return(article_list)

  #  print(len(article_list))


#Импорт графической библиотеки
from tkinter import *
from tkinter import ttk
#Библиотека Python для генерации случайных чисел
import random
#Импорт модулей сортировок
from bubbleSort import bubbleSort
from insertSort import insertSort
from selectSort import selectSort
from mergeSort import mergeSort
from quickSort import quickSort
from shellSort import shellSort

#Настройки окна приложения
root = Tk()
root.title ('Визуализация алгоритмов сортировки.')
root.geometry("835x480+350+100")
root.config(bg="#F2F2F2")

#Глобальные переменные
selected_algorithm = StringVar()
array = []

def setArray():
    """Функция задает предустановленный массив"""
    global array
    array_size = int(sizeScale.get())
    array = [20, 18, 7, 6, 4, 1, 2, 31, 5, 10, 23, 10, 40, 10, 5,6, 17, 5, 10, 9]
    del array[array_size -1  : -1]
    demoArray(array,['#FB5560' for x in range(len(array))])

def generateArray():
    """Генерация случайного массива"""
    global array
    array_size = int(sizeScale.get())
    array = []
    for i in range(array_size):
        array.append(random.randrange(0,100))
    demoArray(array, ['#FB5560' for x in range (len(array))])

def createArray():
    """Генерация заданного пользователем массива"""
    global array
    array_size = int(sizeScale.get())
    unsplit_array = user_array.get().split()
    for i in unsplit_array:
        array.append(int(i))
    del array[array_size -1  : -1]
    demoArray(array,['#FB5560' for x in range(len(array))])

def demoArray (array, colorArray):
    """Отрисовка массива чисел на холсте"""
    canvas.delete('all')
    canvas_height = 220
    canvas_width = 770
    x_width = canvas_width / (len(array) + 1)
    offset = 5
    spacing = 15
    normalized_data  = [i / max(array) for i in array]
    for i, height in enumerate(normalized_data):
        x_0 = i * x_width + offset + spacing
        y_0 = canvas_height - height * 100
        x_1 = (i + 1) * x_width + offset
        y_1= canvas_height
        canvas.create_rectangle(x_0, y_0, x_1, y_1, fill=colorArray[i])
        canvas.create_text(x_0 + 2, y_0, anchor=SW, text=str(array[i]))
        canvas.create_text(125 , 30)
        root.update_idletasks()

def sorting():
    """Выбор сортировки из выпадающего списка"""
    global array
    sorting_speed = 0.2 #задаем скорость демонстрации в диапазоне от 0.1 до 1
    if (selected_algorithm.get() == "Сортировка пузырьком"):
        bubbleSort(array, demoArray, sorting_speed )
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Сортировка вставками"):
        insertSort(array, demoArray, sorting_speed )
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Сортировка выбором"):
        selectSort(array, demoArray, sorting_speed )
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Сортировка слиянием"):
        mergeSort(array, 0, len(array) - 1, demoArray, sorting_speed )
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Быстрая сортировка"):
        quickSort(array, 0, len(array) - 1, demoArray, sorting_speed )
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Сортировка Шелла"):
        shellSort(array, demoArray, sorting_speed )
        demoArray(array, ['#77E596' for element in range(len(array))])

#Отрисовка интерфея приложения и положения рабочей области
UI_frame = Frame(root, width=835, height=480, bg ='#F2F2F2')
UI_frame.grid(row=0, column=0, padx=10, pady=5)
canvas = Canvas(root, width=770, height=350,bg='#CECDD2')
canvas.place(x=420, y =350, anchor="c", height=250, width=750, bordermode=OUTSIDE)

#Отрисовка управляющих элементов
btn_set = Button(UI_frame, text='Готовый массив', command=setArray,
            bg='#ffffff', foreground='#000000')
btn_set.place(x=150, y=40, anchor="c", height=40, width=170, bordermode=OUTSIDE)

btn_generate =  Button(UI_frame, text='Сгенерировать массив', command=generateArray,
             bg='#ffffff', foreground='#000000')
btn_generate.place(x=150, y=100, anchor="c", height=40, width=170, bordermode=OUTSIDE)

btn_create =  Button(UI_frame, text='Задать массив', command=createArray,
             bg='#ffffff', foreground='#000000')
btn_create.place(x=150, y=160, anchor="c", height=40, width=170, bordermode=OUTSIDE)

algorithm_selector = ttk.Combobox(UI_frame, textvariable=selected_algorithm, values=["Сортировка пузырьком", "Сортировка вставками", "Сортировка выбором", "Сортировка слиянием", "Быстрая сортировка", "Сортировка Шелла"])
algorithm_selector.place(x=550, y=100, anchor="c", height=30, width=170)
algorithm_selector.current(0)

btn_start = Button(UI_frame, text='Сортировать', command=sorting,
             bg='#5CDC78', foreground='#000000')
btn_start.place(x=550, y=160, anchor="c", height=40, width=170, bordermode=OUTSIDE)

sizeScale = Scale(UI_frame, from_ = 10, to=20, length=100, digits=1, resolution=0.2, orient=HORIZONTAL, label = 'Размер массива')
sizeScale.place(x=350, y=40, anchor="c", height=60, width=150, bordermode=OUTSIDE)

label_user_array = Label(text = "Свой список через пробел")
label_user_array.place(x=600, y=25, anchor="c", height=20, width=300)
user_array = Entry(UI_frame,
             bg='#ffffff', foreground='#000000')
user_array.place(x=600, y=50, anchor="c", height=30, width=300, bordermode=OUTSIDE)

root.mainloop()


# Copyright 2017-2020 Lawrence Livermore National Security, LLC and other
# CallFlow Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: MIT

import pandas as pd

class RankHistogram:
    def __init__(self, state, name):
        self.graph = state.new_gf.graph
        self.df = state.new_gf.df
        self.entire_df = state.new_entire_gf.df
        self.name = name
        self.entry_funcs = {}
        self.result = self.run()

    def run(self):
        ret = []
        module = self.name.split("=")[0]
        func_in_module = self.df[self.df.module == module]["name"].unique().tolist()

        for idx, func in enumerate(func_in_module):
            ret.append(
                {
                    "name": func,
                    "time (inc)": self.df.loc[self.df["name"] == func][
                        "time (inc)"
                    ].tolist(),
                    "time": self.df.loc[self.df["name"] == func]["time"].tolist(),
                    "rank": self.df.loc[self.df["name"] == func]["rank"].tolist(),
                    "dataset": self.df.loc[self.df["name"] == func]["dataset"].tolist(),
                }
            )
        ret_df = pd.DataFrame(ret)
        return ret_df.to_json(orient="columns")


from flask import Flask, render_template, redirect, request
from flask_sqlalchemy import SQLAlchemy
from datetime import time
from sqlalchemy import Column, Integer, String, Text
import statistics
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from numpy import genfromtxt
from sqlalchemy.ext.declarative import declarative_base

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///formdata.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = 'True'

db = SQLAlchemy(app)

def Load_Data(file_name):
    data = genfromtxt(file_name, delimiter=';', dtype=str)
    print(data.tolist())
    return data.tolist()

Base = declarative_base()

class Price_History(Base):
    #Tell SQLAlchemy what the table name is and if there's any table-specific arguments it should know about
    __table_args__ = {'sqlite_autoincrement': True}
    #tell SQLAlchemy the name of column and its attributes:
    __tablename__ = 'STUDENTS'
    ID = Column(Integer, primary_key=True, nullable=False)
    SCHOOL = Column(String)
    SEX = Column(String)
    AGE = Column(Integer)
    ADRESS = Column(String)
    FAMSIZE = Column(String)
    TRAVELTIME = Column(Integer)
    STUDYTIME = Column(Integer)
    HIGHER = Column(String)
    FREETIME = Column(Integer)
    DALC = Column(Integer)
    WALC = Column(Integer)
    G3 = Column(Integer)

    def __init__(self,SCHOOL,SEX,AGE,ADRESS,FAMSIZE,TRAVELTIME,STUDYTIME,HIGHER,FREETIME,DALC,WALC,G3):
        self.SCHOOL = SCHOOL
        self.SEX = SEX
        self.AGE = AGE
        self.ADRESS = ADRESS
        self.FAMSIZE = FAMSIZE
        self.TRAVELTIME = TRAVELTIME
        self.STUDYTIME = STUDYTIME
        self.HIGHER = HIGHER
        self.FREETIME = FREETIME
        self.DALC = DALC
        self.WALC = WALC
        self.G3 = G3
'''
    def __repr__(self):
        return "<Price_History('%s','%s','%d','%s','%s','%d','%d','%s','%d','%d','%d','%d')>" % (self.SCHOOL,
        self.SEX, self.AGE, self.ADRESS, self.FAMSIZE, self.TRAVELTIME, self.STUDYTIME, self.HIGHER,
        self.FREETIME, self.DALC, self.WALC, self.G3)
'''
@app.route("/")
def welcome():
    return render_template('welcome.html')

@app.route("/raw")
def show_raw():
    fd = db.session.query(Price_History).all()
    return render_template('raw.html', formdata=fd)

@app.route("/result")
def show_result():
    fd_list = db.session.query(Price_History).all()

    # Some simple statistics for sample questions
    GPWantEducation = []
    MSWantEducation = []
    GPFree = []
    GPStudy = []
    GPTravel = []
    MSFree = []
    MSStudy = []
    MSTravel = []
    for el in fd_list:
        if(el.SCHOOL=='GP'):
            GPWantEducation.append(el.SCHOOL)
            GPFree.append(el.FREETIME)
            GPStudy.append(el.STUDYTIME)
            GPTravel.append(el.TRAVELTIME)
        elif(el.SCHOOL=='MS'):
            MSWantEducation.append(el.SCHOOL)
            MSFree.append(el.FREETIME)
            MSStudy.append(el.STUDYTIME)
            MSTravel.append(el.TRAVELTIME)
        else:
            print("School error")

    mean_GPTravel = statistics.mean(GPTravel)
    mean_GPFree = statistics.mean(GPFree)
    mean_GPStudy = statistics.mean(GPStudy)

    mean_MSTravel = statistics.mean(MSTravel)
    mean_MSFree = statistics.mean(MSFree)
    mean_MSStudy = statistics.mean(MSStudy)

    # Prepare data for google charts
    data = [['GP School', len(GPWantEducation)], ['MS School', len(MSWantEducation)]]
    GPdata = [['Free time [h]', mean_GPFree], ['Study time [h]', mean_GPStudy], ['Travel time [h]', mean_GPTravel]]
    MSdata = [['Free time [h]', mean_MSFree], ['Study time [h]', mean_MSStudy], ['Travel time [h]', mean_MSTravel]]
    return render_template('result.html', data=data, GPdata=GPdata, MSdata=MSdata)

@app.route("/result2")
def show_result2():
    fd_list = db.session.query(Price_History).all()

    # Some simple statistics for sample questions
    GPDALC = []
    GPWALC = []
    MSWALC = []
    MSDALC = []
    for el in fd_list:
        if(el.SCHOOL=='GP'):
            GPWALC.append(el.WALC)
            GPDALC.append(el.DALC)
        elif(el.SCHOOL=='MS'):
            MSWALC.append(el.WALC)
            MSDALC.append(el.DALC)
        else:
            print("School error")

    mean_GPWALC = statistics.mean(GPWALC)
    mean_GPDALC = statistics.mean(GPDALC)

    mean_MSWALC = statistics.mean(MSWALC)
    mean_MSDALC = statistics.mean(MSDALC)

    # Prepare data for google charts
    data = [['GP School Workday Alcohol Consumption', mean_GPDALC], ['GP School Weekend  Alcohol Consumption', mean_GPWALC],
            ['MS School Workday Alcohol Consumption', mean_MSDALC], ['MS School Weekend Alcohol Consumption', mean_MSWALC]]
    return render_template('result2.html', data=data)

@app.route("/result3")
def show_result3():
    fd_list = db.session.query(Price_History).all()

    # Some simple statistics for sample questions
    MDALC = []
    MWALC = []
    FWALC = []
    FDALC = []
    for el in fd_list:
        if(el.SEX=='M'):
            MWALC.append(el.WALC)
            MDALC.append(el.DALC)
        elif(el.SEX=='F'):
            FWALC.append(el.WALC)
            FDALC.append(el.DALC)
        else:
            print("Sex error")

    mean_MWALC = statistics.mean(MWALC)
    mean_MDALC = statistics.mean(MDALC)

    mean_FWALC = statistics.mean(FWALC)
    mean_FDALC = statistics.mean(FDALC)

    # Prepare data for google charts
    data = [['Female Workday Alcohol Consumption', mean_FDALC], ['Female Weekend  Alcohol Consumption', mean_FWALC],
            ['Male Workday Alcohol Consumption', mean_MDALC], ['Male Weekend Alcohol Consumption', mean_MWALC]]
    return render_template('result3.html', data=data)

if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))

    t = time()

    # Create the database
    engine = create_engine('sqlite:///formdata.db')
    if not(engine.dialect.has_table(engine.connect(), "STUDENTS")):
        Base.metadata.create_all(engine)

    # Create the session
    session = sessionmaker()
    session.configure(bind=engine)
    s = session()

    try:
        file_name = "studentDataSet.csv"
        data = Load_Data(file_name)

        for i in data:
            record = Price_History(**{
                'SCHOOL':i[0],
                'SEX':i[1],
                'AGE':int(i[2]),
                'ADRESS':i[3],
                'FAMSIZE':i[4],
                'TRAVELTIME':int(i[5]),
                'STUDYTIME':int(i[6]),
                'HIGHER':i[7],
                'FREETIME':int(i[8]),
                'DALC':int(i[9]),
                'WALC':int(i[10]),
                'G3':int(i[11])
            })
            s.add(record)  # Add all the records
        s.commit()  # Attempt to commit all the records
    except:
        s.rollback()  # Rollback the changes on error
    finally:
        app.run(host='0.0.0.0', port=port)
        s.close()  # Close the connection


import face_recognition
import cv2
import sys, os
import imageio
import matplotlib.pyplot as plt
import numpy as np

suffix = ('jpg', 'jpeg', 'bmp', 'png')
img_suffix = []
for s in suffix:
    img_suffix.append(s)
    img_suffix.append(s.upper())

img_suffix = tuple(img_suffix)

class Face_Search_Class:
    def __init__(self, imgpath):
        filelist = os.listdir(imgpath)

        self.face_names = []
        self.face_encodings = []
        for f in filelist:
            img = os.path.join(imgpath, f)
            if img.endswith(img_suffix) and os.path.isfile(img):
                image = face_recognition.load_image_file(img)

                if image is None:
                    print('image is None for file ',img)
                    continue

                face_encodings = face_recognition.face_encodings(image)[0]
                self.face_encodings.append(face_encodings)
                face_name = os.path.splitext(f)[0]
                self.face_names.append(face_name)

    def process(self, image_search_path, show=True):
        shrink_scale = 2.0
        image_search = cv2.imread(image_search_path)
        image = cv2.resize(image_search, (0, 0), fx=1.0 / shrink_scale, fy=1.0 / shrink_scale)
        face_locations = face_recognition.face_locations(image)
        if len(face_locations) == 0:
            print('cannot find face in image', image_search_path)
            return None

        face_encodings = face_recognition.face_encodings(image, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            # See if the face is a match for the known face(s)
            match = face_recognition.compare_faces(self.face_encodings, face_encoding)
            name = "Unknown"

            print(match.__class__)
            for idx in range(len(match)):
                if match[idx]:
                    name = self.face_names[idx]
            face_names.append(name)

        face_infos = []
        # Display the results
        for (top, right, bottom, left), name in zip(face_locations, face_names):
            # Scale back up face locations since the frame we detected in was scaled to 1/4 size
            top *= shrink_scale
            right *= shrink_scale
            bottom *= shrink_scale
            left *= shrink_scale

            locations = {'top': int(top), 'right': int(right), 'bottom': int(bottom), 'left': int(left)}
            face_name = {'name': name}

            face_info = {'location': locations, 'name': face_name}
            face_infos.append(face_info)

            left=int(left)
            top=int(top)
            right=int(right)
            bottom=int(bottom)
            # Draw a box around the face
            cv2.rectangle(image, (left, top), (right, bottom), (0, 0, 255), 2)

            # Draw a label with a name below the face
            cv2.rectangle(image, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
            font = cv2.FONT_HERSHEY_DUPLEX
            text_org=(left+6,min(bottom-6,0))

            print('type(image)',type(image))
            print('type(name)',type(name),name)
            print('type(text_org)',type(text_org))
            print('type(font)',type(font))
            cv2.putText(img=image, text=name, org=text_org, fontFace=font, fontScale=1.0, color=(255, 255, 255), thickness=1)

        return_data = {'image_path': image_search_path, 'face_infos': face_infos, 'labeled_image':image}
        print(return_data)

        if show:
            #cv2.imshow('labeled image',image)
            #cv2.waitKey(0)
            #img = mpimg.imread('stinkbug.png')
            imgplot = plt.imshow(image)
            plt.show()

        return return_data

if __name__ == '__main__':
    fsc=Face_Search_Class('data/train')
    for f in os.listdir('data/test'):
        image_search_path=os.path.join('data/test',f)
        if os.path.isfile(image_search_path) and f.endswith(img_suffix):
            fsc.process(image_search_path)


import json
from random import randint

from app.project.comment.models import ProjectComment
from tests.functional.user.auth.utils import sign_in
from tests.functional.bases.base_without_create_project_author import BaseWithoutCreateProjectAuthorTestCase
from tests.functional.project.utils import create_project, random_string, create_project_comment

class ProjectCommentCreating(BaseWithoutCreateProjectAuthorTestCase):

    def test_user_comment_persisted(self) -> None:
        with self.app.test_client() as client:
            user = sign_in(client)
            project = create_project()
            expected_comment_content = random_string(256)

            request_data = {'content': expected_comment_content}
            response = client.post(f'/projects/{project.id}/comments', data=request_data)

            assert response.status_code == 200

            actual_comment_id = json.loads(response.data)['id']
            actual_comment = ProjectComment.query.get(actual_comment_id)

            assert actual_comment.author_user_id == user.id
            assert actual_comment.project_id == project.id
            assert actual_comment.content == expected_comment_content

    def test_user_comment_reply_persisted(self) -> None:
        with self.app.test_client() as client:
            user = sign_in(client)
            project = create_project()
            parent_comment = create_project_comment(project.id)
            expected_comment_content = random_string(256)

            request_data = {'content': expected_comment_content, 'parent_comment_id': parent_comment.id}
            response = client.post(f'/projects/{project.id}/comments', data=request_data)

            assert response.status_code == 200

            actual_comment_reply = parent_comment.replies[0]

            assert actual_comment_reply.author_user_id == user.id
            assert actual_comment_reply.project_id == project.id
            assert actual_comment_reply.content == expected_comment_content

    def test_unauthorized_user_cannot_create_comment(self) -> None:
        with self.app.test_client() as client:
            project = create_project()

            request_data = {'content': random_string(256)}
            response = client.post(f'/projects/{project.id}/comments', data=request_data)

            assert response.status_code == 401

    def test_user_cannot_create_comment_without_content(self) -> None:
        with self.app.test_client() as client:
            sign_in(client)

            response = client.post(f'/projects/{create_project().id}/comments', data={})

            assert response.status_code == 400

    def test_reply_must_belong_to_same_project_as_parent_comment(self) -> None:
        with self.app.test_client() as client:
            sign_in(client)
            project = create_project()
            parent_comment = create_project_comment(project.id)
            another_project = create_project()

            request_data = {'content': random_string(256), 'parent_comment_id': parent_comment.id}
            response = client.post(f'/projects/{another_project.id}/comments', data=request_data)

            assert response.status_code == 400

    def test_user_cannot_leave_comment_on_nonexistent_project(self) -> None:
        with self.app.test_client() as client:
            sign_in(client)
            nonexistent_project_id = randint(1, 100)

            request_data = {'content': random_string(256)}

            response = client.post(f'/projects/{nonexistent_project_id}/comments', data=request_data)

            assert response.status_code == 404


from moviepy.editor import *
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime

def gene_image(width=500, height=200, factor=0.7):
    # 创建一个图片
    image = Image.new('RGBA', (width, height), '#AAAAAA')

    # 获取该图片的画笔，之后都通过该画笔进行绘画
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype('NotoSansCJK-Regular.ttc', size=96)
    # 写的字如果是中文需要指定字体
    # draw.text((0, 0), '高清', fill='red', align='center', font=font)
    text = '高清'
    imwidth, imheight = image.size
    font_width, font_height = draw.textsize(text, font)
    draw.text(
        ((imwidth - font_width - font.getoffset(text)[0]) / 2, (imheight - font_height - font.getoffset(text)[1]) / 2),
        text=text, font=font, fill=(255, 255, 255))
    image = addTransparency(image, factor)
    image_name = datetime.today().strftime('%Y%m%d%H%M%S') + '.png'
    image.save(image_name)
    return image_name

def addTransparency(img, factor=0.7):
    img = img.convert('RGBA')
    img_blender = Image.new('RGBA', img.size, (0, 0, 0, 0))
    img = Image.blend(img_blender, img, factor)
    return img

def test():
    clip:VideoFileClip = VideoFileClip('/home/elim/dev/视频录制/元宵晚会-彩排.mp4')
    # clip.write_videofile('cctv.mp4')
    # (1584, 886)
    size = clip.size
    print(size)
    img_width = 350
    img_height = 100
    img_x = size[0] - img_width - 50
    img_y = 80
    image_clip = ImageClip(gene_image(img_width, img_height, 1), duration=clip.duration, transparent=True).set_position((img_x, img_y))
    result = CompositeVideoClip([clip, image_clip])
    result.write_videofile('logo.result.mp4')

if __name__ == '__main__':
    test()

缩略图在右上角播放.py


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
import re
from setuptools import setup, find_packages

PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__))
PACKAGE_NAME = "webpack_loader_remote"

def read_file(*parts):
    file_path = os.path.join(PACKAGE_DIR, *parts)
    with open(file_path, "r", encoding="utf-8") as file:
        return file.read()

def get_version():
    match = re.search(
        r"^__version__ = ['\"]([^'\"]*)['\"]",
        read_file("src", PACKAGE_NAME, "__init__.py"),
        re.M,
    )
    if match:
        return match.group(1)
    raise RuntimeError("Unable to find version.")

setup(
    name=PACKAGE_NAME,
    version=get_version(),
    description="Load webpack stats from a local or remote file",
    long_description=read_file("README.md"),
    long_description_content_type="text/markdown",
    url="https://github.com/alexseitsinger/{}".format(PACKAGE_NAME),
    author="Alex Seitsinger",
    author_email="contact@alexseitsinger.com",
    package_dir={"": "src"},
    packages=find_packages("src", exclude=["tests"]),
    install_requires=["requests"],
    include_package_data=True,
    license="MIT License",
    keywords=["django", "webpack"],
    classifiers=[
        "Programming Language :: Python :: 3",
        "Framework :: Django",
        "Environment :: Web Environment",
        "License :: OSI Approved :: MIT License",
    ],
)


from math import sqrt
from math import atan2
import pygame # necesito instalarlo: desde una linea de comandos -> pip install pygame
import time
from vector import Vector
from point import Point
from polygon import Polygon
from represent import representLine, representPolygon
from graham_convex_hull_v3 import Poligono

def dotProduct(v1, v2):
    return (v1.x*v2.x)+(v1.y*v2.y)

def projectPolygonOntoAxis(a, axis):
    numerador = dotProduct(a, axis)
    #print("numerador", numerador)
    denominador = sqrt(axis.x**2+axis.y**2)
    #print("denominador", denominador)
    if(denominador !=0 ):
        magnitud = numerador/denominador
    if(denominador ==0):
        magnitud = 0
    unitario = Vector(axis.x/sqrt(axis.x**2+axis.y**2), axis.y/sqrt(axis.x**2+axis.y**2), (0,0))
    projection = (magnitud*unitario.x, magnitud*unitario.y)
    return projection, magnitud

def convexHull_SAT(a, b):
# 1- Calculo el convex hull de mis poligonos. Si los puntos del convex hull coinciden
# con los del poligono sé que es convex, sino, el poligno es concavo y mantengo el convex.
    new_a = a.grahamConvHull()
    new_b = b.grahamConvHull()
    pol_a = Polygon()
    pol_b = Polygon()
    for i in range(len(new_a)):
        pol_a.add(new_a[i])
    for i in range(len(new_b)):
        pol_b.add(new_b[i])

# 2- Calculo los ejes perpendiculares a los normales de los lados poligonos
    vectors_axis_a = pol_a.getSides()
    vectors_axis_b = pol_b.getSides()
    print("vectors_axis_a", vectors_axis_a)
    print("vectors_axis_b", vectors_axis_b)
    vectors_a = pol_a.getSides()
    vectors_b = pol_b.getSides()
    print("vectors_a", vectors_a)
    print("vectors_b", vectors_b)
#3- Aplico SAT para detectar colisiones
#3.1 - Proyeccion de todos los lados de cada poligono sobre cada eje
    array_ejes = [] #Array de ejes de separacion
    for i in range(len(vectors_axis_a)):
        for j in range(len(vectors_a)):
            (projection_a, magnitud) = projectPolygonOntoAxis(vectors_a[j], vectors_axis_a[i])
        for k in range(len(vectors_b)):
            (projection_b, magnitud) = projectPolygonOntoAxis(vectors_b[k], vectors_axis_a[i])
            print("Axis: ", vectors_axis_a[i])
            print("Projection_a is: ", projection_a[0], projection_a[1], magnitud)
            print("Projection_b is: ", projection_b[0], projection_b[1], magnitud)
            #print("En esta iteracion el eje de sepacion es: ", ejeSeparacion)
            #array_ejes.append(ejeSeparacion)
    for i in range(len(vectors_axis_b)):
        for j in range(len(vectors_a)):
            projection_a = projectPolygonOntoAxis(vectors_a[j], vectors_axis_b[i])
        for k in range(len(vectors_b)):
            projection_b = projectPolygonOntoAxis(vectors_b[k], vectors_axis_b[i])
            print("Axis: ", vectors_axis_b[i])
            print("Projection_a is: ", projection_a[0], projection_a[1])
            print("Projection_b is: ", projection_b[0], projection_b[1])
            #print("En esta iteracion el eje de sepacion es: ", ejeSeparacion[2])
            #array_ejes.append(ejeSeparacion)
    return pol_a, pol_b, array_ejes

######## Test ########
#Defino mi box a
a_a = Point(100, 100)
a_b = Point(200, 100)
a_c = Point (150, 150)
a=Poligono()
a.add(a_a)
a.add(a_b)
a.add(a_c)

#defino mi box b
b_a = Point(250, 100)
b_b = Point(300, 100) #(265, 145) concavo
b_c = Point(300, 200)
b_d = Point(250, 200)
b=Poligono()
b.add(b_a)
b.add(b_b)
b.add(b_c)
b.add(b_d)

#compruebo si los poligonos que he creado colisionan
(pol_a, pol_b, array_ejes) = convexHull_SAT(a, b)
print("Los ejes de separacion estan definidos por los siguientes vectores directores: ", array_ejes)

######## Representación polígonos ##########

pygame.init()
#Defino la altura y anchura de la ventana
size = [400, 300]
BLUE = ( 0, 0, 255) #defino el color en formato RGB
GREEN = (0, 255, 0)
RED = (255, 0, 0)
screen = pygame.display.set_mode(size)
poligono_a = []
for i in a.lista:
    i = [i.x, i.y]
    poligono_a.append(i)
representPolygon(screen, BLUE, poligono_a)
poligono_b = []
for i in b.lista:
    i = [i.x, i.y]
    poligono_b.append(i)
representPolygon(screen, BLUE, poligono_b)
array_polA = []
for i in pol_a.lista:
    i = [i.x, i.y]
    array_polA.append(i)
representPolygon(screen, GREEN, array_polA)
array_polB = []
for i in pol_b.lista:
    i = [i.x, i.y]
    array_polB.append(i)
representPolygon(screen, GREEN, array_polB)
pygame.display.flip()
time.sleep(5.5) #necesario para no cerrar la pantalla inmediatamente
pygame.quit()


# -*- coding: utf-8 -*-
"""
Robust Tensor Robust PCA
========================

Example on how to use :mod:`tensorly.decomposition.robust_pca` to perform Robust Tensor PCA.

"""
import matplotlib.pyplot as plt
from tensorly.datasets.yaleb import fetch_cropped_yaleb

dataset_path = '/data/tensorly_data/'
data = fetch_cropped_yaleb(dataset_path, zooming=0.3, max_n_subjects=5)

###########################################################################
# Accumulate a tensor containing all the data
X = np.concatenate([data[key]['images'] for key in data], axis=0)
print(X.shape)

###########################################################################
# Convert to float
X = X.astype(np.float64)
X -= X.mean()

###########################################################################
# Visualise the data

def visualise_images(X, n_images, n_columns, randomise=True):
    indices = np.arange(X.shape[0])
    np.random.shuffle(indices)
    indices = indices[:n_images]
    cmap = plt.cm.Greys_r
    n_rows = np.ceil(n_images / n_columns)
    fig = plt.figure(figsize=(2*n_columns, 2*n_rows))
    fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)

    # plot the digits: each image is 8x8 pixels
    for i, e in enumerate(indices):
        ax = fig.add_subplot(n_rows, n_columns, i + 1, xticks=[], yticks=[])
        ax.imshow(X[e], cmap=cmap, interpolation='nearest')

visualise_images(X, 12, 4)
plt.show()

###########################################################################
# Add noise
from tensorly.random.noise import add_noise

X = add_noise(X, noise='salt_pepper', percent=0.15, inplace=True, random_state=random_state)
visualise_images(X, 12, 4)
plt.show()

###########################################################################
# Apply robust pca
from tensorly.decomposition import robust_pca
low_rank_part, sparse_part = robust_pca(X, reg_E=0.04, learning_rate=1.2, n_iter_max=20)

###########################################################################
# Check the results
def visualise_rpca(X, low_rank_part, sparse_part, n_images=10):
    """A little helper function to visualise the result of tensor RPCA
    """
    indices = np.arange(X.shape[0])
    np.random.shuffle(indices)
    indices = indices[:n_images]

    fig = plt.figure(figsize=(10, 2*n_images))
    fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)

    # plot the digits: each image is 8x8 pixels
    for i, e in enumerate(indices):
        cmap = plt.cm.Greys_r

        ax = fig.add_subplot(n_images, 4, 4*i + 1, xticks=[], yticks=[])
        ax.imshow(X[e], cmap=cmap, interpolation='nearest')
        if not i:
            ax.set_title('Original')

        ax = fig.add_subplot(n_images, 4, 4*i + 2, xticks=[], yticks=[])
        ax.imshow(low_rank_part[e], cmap=cmap, interpolation='nearest')
        if not i:
            ax.set_title('Low-rank')

        ax = fig.add_subplot(n_images, 4, 4*i + 3, xticks=[], yticks=[])
        ax.imshow(sparse_part[e], cmap=cmap, interpolation='nearest')
        if not i:
            ax.set_title('Sparse')

        ax = fig.add_subplot(n_images, 4, 4*i + 4, xticks=[], yticks=[])
        ax.imshow(low_rank_part[e]+sparse_part[e], cmap=cmap, interpolation='nearest')
        if not i:
            ax.set_title('Reconstruction')

    return fig

visualise_rpca(X, low_rank_part, sparse_part, 6)
plt.show()


# -*- coding: utf-8 -*-
"""
Created on Tue Dec  3 18:07:38 2019

@author: ilvr2
"""

#%load_ext autoreload
#%autoreload 2

#| Load modules
from calibrator.data import Calibrator, SimCal
from calibrator.bayesian import GaussianLikelihood, NormalInverseGammaDistribution
from calibrator.model import Model, makeTheta

from getdist import plots, MCSamples
#%matplotlib

import numpy
import matplotlib.pyplot as plt

from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')

#---------------------
# BAYESIAN SCRIPT DOES NOT LIKE BEING PASSED 0'S IN FOR n. WILL LOOK INTO IN JANUARY 2020.
n = [0, 0, 0, 0, 0]

#SIMULATED DATA 1 -----------------------------------------------------------------------
#f = 'TS1'
#f = 'iTSM_Sim1'
f = 'data15'
cold = Calibrator(dataSet = f, inputType='cold')
r25 = Calibrator(dataSet = f, inputType='r25')
r100 = Calibrator(dataSet = f, inputType='r100')
gore5 = Calibrator(dataSet = f, inputType='gore5')
gore31 = Calibrator(dataSet = f, inputType='gore31')
gore81 = Calibrator(dataSet = f, inputType='gore81')
hot = Calibrator(dataSet = f, inputType='hot')
gore500 = Calibrator(dataSet = f, inputType='gore500')

simCold = SimCal(dataSet = f, inputType='cold', inputTemp = 298)
simHot = SimCal(dataSet = f, inputType='hot', inputTemp = 372.2)
simr25 = SimCal(dataSet = f, inputType='r25', inputTemp = 298)
simr100 = SimCal(dataSet = f, inputType='r100', inputTemp = 298)
simgore5 = SimCal(dataSet = f, inputType='gore5', inputTemp = 298)
simgore31 = SimCal(dataSet = f, inputType='gore31', inputTemp = 298)
simgore81 = SimCal(dataSet = f, inputType='gore81', inputTemp = 298)
simgore500 = SimCal(dataSet = f, inputType='gore500', inputTemp = 298)

#model = Model([cold, hot], n)
#g = plots.getSubplotPlotter()
#prior = model.sample(1000, prior=True)
#posterior = model.sample(1000)
#g.triangle_plot([posterior], filled=True)

#model = Model([cold, hot, r25, r100, gore5, gore31, gore81, gore500], n)
model = Model([simCold, simHot, simr25, simr100, simgore5, simgore31, simgore81, simgore500], n)
g = plots.getSubplotPlotter()
prior = model.sample(1000, prior=True)
posterior = model.sample(1000)
g.triangle_plot([posterior], markers = [250, 190, 90, 1200, 298], filled=True)

plt.subplots()
plt.plot(cold.freq/1e+6, model.T_ant(cold))
#plt.ylim(290, 300)
plt.title('$T_{ant}$ for TS1 Simulated Data Set')
plt.xlabel('Frequency in MHz')
plt.ylabel('Temperature in Kelvin')


from HashTable.MyLinearProb import LinearProbing
from List.DoublyLinkedList import DList
import Stack.MyStack as stack
import Queue.MyQueue as q
import Queue.MyDequeue as dq
import copy

def is_palindrome(str):
    s = stack.Stack()
    half = int(len(str) / 2)
    for i in range(half):
        s.push(str[i])

    if len(str) % 2 == 1:
        half += 1

    while s.size != 0:
        if s.pop() == str[half]:
            half += 1
        else:
            return False
    return True

def parentheses(str):
    s = stack.Stack()
    item = {'{': '}', '(': ')'}
    for i in range(len(str) - 1):
        if str[i] == '{' or str[i] == '(':
            s.push(str[i])
        if s.peek() is None:
            return False
        if item[s.peek()] == str[i + 1]:
            s.pop()
    return s.size == 0

def reverse_stack(item):
    tmp = copy.deepcopy(item)
    reverse = stack.Stack()
    for i in range(tmp.size):
        reverse.push(tmp.pop())
    return reverse

if __name__ == '__main__':
    t = LinearProbing(13)
    t.put(25, 'grape')
    t.put(37, 'apple')
    t.put(18, 'banana')
    t.put(55, 'cherry')
    t.put(22, 'mango')
    t.put(35, 'lime')
    t.put(50, 'orange')
    t.put(63, 'watermelon')
    print("탐색 결과:")
    print('50의 데이터 = ', t.get(50))
    print('63의 데이터 = ', t.get(63))
    print('Hash Table')
    t.print_table()