import matplotlib
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from neuro_py.stats.stats import confidence_intervals
import warnings

def plot_events(events, labels, cmap="tab20", gridlines=True, alpha=0.75, ax=None):
    """
    events: nested list of nelpy EpochArrays
    labels: labels related to each event

    example:

        # load sleep states
        state_dict = loading.load_SleepState_states(basepath)

        # make nelpy epoch arrays
        nrem_epochs = nel.EpochArray(state_dict['NREMstate'])
        wake_epochs = nel.EpochArray(state_dict['WAKEstate'])
        rem_epochs = nel.EpochArray(state_dict['REMstate'])

        # add to list
        events = []
        events.append(nrem_epochs)
        events.append(wake_epochs)
        events.append(rem_epochs)

        # plot
        plt.figure(figsize=(20,5))
        plot_events(events,['nrem','wake','rem'])

    Ryan H 2022
    """
    # get colormap
    cmap = matplotlib.cm.get_cmap(cmap)

    # set up y axis
    y = np.linspace(0, 1, len(events) + 1)

    # set up ax if not provided
    if ax is None:
        ax = plt.gca()

    # iter over each event
    for i, evt in enumerate(events):

        # add horizontal line underneath
        if gridlines:
            ax.axhline(y[i] + np.diff(y)[0] / 2, color="k", zorder=-100, alpha=0.1)

        # plot events
        for pair in range(evt.n_intervals):
            ax.axvspan(
                evt.starts[pair],
                evt.stops[pair],
                y[i],
                y[i + 1],
                alpha=alpha,
                color=cmap(i * 0.1),
            )

    ax.set_yticks(y[:-1] + np.diff(y)[0] / 2)
    ax.set_yticklabels(labels)

def plot_peth(peth: pd.DataFrame, ax=None, **kwargs) -> matplotlib.axes.Axes:
    """
    Plot a peth. Assumes that the index is time and the columns are trials/cells/etc.

    Parameters
    ----------
    peth : pd.DataFrame
        Peth to plot
    ax : matplotlib.axes.Axes, optional
        Axis to plot on, by default None
    **kwargs
        Keyword arguments to pass to seaborn.lineplot

    Returns
    -------
    matplotlib.axes.Axes
        Axis with plot

    Raises
    ------
    TypeError
        If peth is not a pandas dataframe

    Example
    -------
    >>> from neuro_py.plotting.events import plot_peth
    >>> from neuro_py.process import peri_event
    >>> from neuro_py.io import loading

    >>> st, cm = loading.load_spikes(basepath)
    >>> rippple_epochs = loading.load_ripples_events(basepath, return_epoch_array=True)

    >>> ripple_peth = peri_event.compute_psth(st.data, rippple_epochs.starts)
    >>> plot_peth(ripple_peth)

    """
    if ax is None:
        fig, ax = plt.subplots()

    # verify peth is a dataframe
    if not isinstance(peth, pd.DataFrame):
        raise TypeError("peth must be a pandas dataframe")

    # melt the dataframe so that the index is time and there is a column for each trial/cell/etc.
    peth_long = pd.melt(peth.reset_index(), id_vars=["index"], value_name="peth")

    # plot the peth as a lineplot with seaborn
    lineplot_ax = sns.lineplot(data=peth_long, x="index", y="peth", ax=ax, **kwargs)
    ax.set_xlabel("Time (s)")
    sns.despine(ax=ax)
    return lineplot_ax

def plot_peth_fast(peth: pd.DataFrame, ax=None,ci=.95, **kwargs) -> plt.Axes:
    """
    Plot a peth. Assumes that the index is time and the columns are trials/cells/etc.

    Less flexible, but faster version of plot_peth

    Parameters
    ----------
    peth : pd.DataFrame
        Peth to plot
    ax : plt.Axes, optional
        Axis to plot on, by default None
    **kwargs
        Keyword arguments to pass to ax.plot

    Returns
    -------
    plt.Axes
        Axis with plot

    Raises
    ------
    TypeError
        If peth is not a pandas dataframe

    Example
    -------
    >>> from neuro_py.plotting.events import plot_peth
    >>> from neuro_py.process import peri_event
    >>> from neuro_py.io import loading

    >>> st, cm = loading.load_spikes(basepath)
    >>> rippple_epochs = loading.load_ripples_events(basepath, return_epoch_array=True)

    >>> ripple_peth = peri_event.compute_psth(st.data, rippple_epochs.starts)
    >>> plot_peth_fast(ripple_peth)

    """
    if ax is None:
        fig, ax = plt.subplots()

    # verify peth is a dataframe
    if not isinstance(peth, pd.DataFrame):
        raise TypeError("peth must be a pandas dataframe")

    # plot the peth as a lineplot with matplotlib
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=RuntimeWarning)
        ax.plot(peth.index, np.nanmean(peth, axis=1), **kwargs)

    lower, upper = confidence_intervals(peth.values.T, conf=ci)
    ax.fill_between(peth.index, lower, upper, alpha=.5, **kwargs)

    ax.set_xlabel("Time (s)")
    sns.despine(ax=ax)

    return ax


import os
from os import environ
import tweepy

def auth():

    consumer_key = environ["CONSUMER_KEY"]
    consumer_secret = environ["CONSUMER_SECRET"]

    access_token = environ["ACCESS_TOKEN"]
    access_token_secret = environ["ACESS_TOKEN_SECRET"]

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    api = tweepy.API(auth)
    return api,auth

from tweepy.streaming import StreamListener
import time
import json

class MyStreamListener(tweepy.StreamListener):

    def on_data(self, data):

        tweet = json.loads(data)
        id_tweet = tweet["id_str"]

        if not tweet["text"].startswith("@") and not tweet["is_quote_status"] and not tweet["text"].startswith("RT @"):
            api.retweet(id_tweet)

api, auth = auth()

myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener = myStreamListener)

myStream.filter(track = ["skateboard", "skate", "skateur", "skates", "skater", "kickflip", "heelflip", "shov it", "skatos", "skateshop", "skatepark", "@aureliengiraud", "@Lask8boarderie", "@josephgarbaccio", "@redbullskate", "@biomeskateboard", "@rockslideshop", "@EDYNEclothing", "@vansskate", "@BrailleSkate"], languages=["fr"])


from prettytable import PrettyTable
import numpy as np
def init():
    Q = np.array([[5, 2, 8, 5], [4, 5, 9, 4], [4, 1, 7, 7], [4, 6, 9, 7], [1, 3, 4, 3], [0, 2, 3, 2], [1, 2, 4, 2],
                  [4, 3, 1, 0], [0, 0, 0, 0]])
    table_q = PrettyTable()
    table_q.field_names = ["x[i]", "z1", "z2", "z3", "z4"]
    for i in range(8):
        table_q.add_row([i+1,Q[i][0], Q[i][1], Q[i][2], Q[i][3]])
    beta=[]
    arr_trans=Q.transpose()
    beta = []
    for i in range(4):
        beta.append(arr_trans[i].max())
    table_q.add_row(["b",beta[0], beta[1], beta[2], beta[3]])
    print("Q:")
    print(table_q)
    print("R:")
    Q[8][0] = beta[0]
    Q[8][1] = beta[1]
    Q[8][2] = beta[2]
    Q[8][3] = beta[3]
    return Q

def R_matrix(Q):
    R=np.empty((8, 4))
    table_r = PrettyTable()
    table_r.field_names = ["x[i]", "z1", "z2", "z3", "z4"]
    for i in range(8):
        for j in range(4):
            R[i][j] = int(Q[8][j] - Q[i][j])
        table_r.add_row([i+1,R[i][0], R[i][1], R[i][2], R[i][3]])
    print(table_r)
    return R
def vald(Q):
    a=np.empty((8))
    table_vald = PrettyTable()
    table_vald.field_names = ["i", "a[i]"]
    for i in range(8):
        a[i]=(Q[i].min())
        table_vald.add_row([i+1, a[i]])
    print("1. Критерий Вальда: ")
    print(table_vald)
    max = a.max()
    number = []
    for i in range(8):
        if a[i]==max:
            number.append(i)
    for i in range(len(number)):
        print("Оптимальное решение по критерию Вальда: "+str(number[i]+1)+"e, значение x* = "+ str(a[number[i]]))
    return number

def maximum(Q):
    a=np.empty((8))
    table_max = PrettyTable()
    table_max.field_names = ["i", "a[i]"]
    for i in range(8):
        a[i]=(Q[i].max())
        table_max.add_row([i+1, a[i]])
    print("2. Критерий максимума: ")
    print(table_max)
    max = a.max()
    number = []
    for i in range(8):
        if a[i] == max:
            number.append(i)
    for i in range(len(number)):
        print("Оптимальное решение по критерию максимума: "+str(number[i]+1)+"e, значение x* = "+ str(a[number[i]]))
    return number

def savige(R):
    a=np.empty((8))
    table_sav = PrettyTable()
    table_sav.field_names = ["i", "a[i]"]
    for i in range(8):
        a[i]=(R[i].max())
        table_sav.add_row([i+1, a[i]])
    print("3. Критерий Сэвиджа: ")
    print(table_sav)
    sav = a.min()
    number = []
    for i in range(8):
        if a[i] == sav:
            number.append(i)
    for i in range(len(number)):
        print("Оптимальное решение по критерию Сэвиджа: "+str(number[i]+1)+"e, значение x* = "+ str(a[number[i]]))
    return number

def hurvic(Q, alpha):
    a=np.empty((8))
    table_hurv = PrettyTable()
    table_hurv.field_names = ["i", "a[i]"]
    for i in range(8):
        a[i]=round(alpha*(Q[i].min())+(1-alpha)*(Q[i].max())*10)/10
        table_hurv.add_row([i+1, a[i]])
    print("4. Критерий Гурвица: ")
    print(table_hurv)
    sav = a.max()
    number = []
    for i in range(8):
        if a[i] == sav:
            number.append(i)
    for i in range(len(number)):
        print("Оптимальное решение по критерию Гурвица: "+str((number[i])+1)+"e, значение x* = "+ str(a[number[i]]))
    return number

def laplas(Q):
    a = np.empty((8))
    table_sav = PrettyTable()
    table_sav.field_names = ["i", "a[i]"]
    for i in range(8):
        q_sum=0
        for j in range(4):
            q_sum+=Q[i][j]
        a[i] = 1/8 * q_sum
        table_sav.add_row([i + 1, a[i]])
    print("5. Критерий Лапласа: ")
    print(table_sav)
    sav = a.max()
    number = []
    for i in range(8):
        if a[i] == sav:
            number.append(i)
    for i in range(len(number)):
        print("Оптимальное решение по критерию Лапласа  : " + str(number[i] + 1) + "e, значение x* = " + str(a[number[i]]))
    return number

def bayes(Q, p):
    a = np.empty((8))
    table_sav = PrettyTable()
    table_sav.field_names = ["i", "a[i]"]
    for i in range(8):
        q_sum = -1
        for j in range(4):
            q_sum += p[j]*Q[i][j]
        a[i] = round(q_sum*10)/10
        table_sav.add_row([i + 1, a[i]])
    print("6. Критерий Байеса: ")
    print(table_sav)
    sav = a.max()
    number = []
    for i in range(8):
        if a[i] == sav:
            number.append(i)
    for i in range(len(number)):
        print("Оптимальное решение по критерию Байеса  : " + str(number[i] + 1) + "e, значение x* = " + str(a[number[i]]))
    return number

def matrix(vald_list,max_list, sav_list, hurv_list, laplas_list, bayes_list):
    all_lists =np.zeros((8, 6))
    for i in range(len(vald_list)):
        all_lists[vald_list[i]][0] += 1
    for i in range(len(max_list)):
        all_lists[max_list[i]][1] += 1
    for i in range(len(sav_list)):
        all_lists[sav_list[i]][2] += 1
    for i in range(len(hurv_list)):
        all_lists[hurv_list[i]][3] += 1
    for i in range(len(laplas_list)):
        all_lists[laplas_list[i]][4] += 1
    for i in range(len(bayes_list)):
        all_lists[bayes_list[i]][5] += 1
    print("Матрица выбора:")
    matrix_table = PrettyTable()
    matrix_table.field_names = ["проект", "Вальда", "Максимума", "Сэвиджа", "Гурвица", "Лапласа", "Байеса", "Сумма"]
    sum = []
    for i in range(8):
        sum.append(0)
        for j in range(6):
            sum[i]+=all_lists[i][j]
        matrix_table.add_row(["x"+str(i+1), all_lists[i][0], all_lists[i][1], all_lists[i][2], all_lists[i][3], all_lists[i][4],
                              all_lists[i][5], sum[i]])
    print(matrix_table)

def main():
    Q = init()
    R = R_matrix(Q)
    alpha = 0.6
    p = [0.1, 0.4, 0.4, 0.1]
    vald_list = []
    max_list = []
    sav_list = []
    hurv_list = []
    laplas_list = []
    bayes_list = []
    vald_list = vald(Q)
    max_list = maximum(Q)
    sav_list = savige(R)
    hurv_list = hurvic(Q, alpha)
    laplas_list = laplas(Q)
    bayes_list = bayes(Q, p)
    matrix(vald_list, max_list, sav_list, hurv_list, laplas_list, bayes_list)
if __name__=="__main__":
    main()


__all__ = [
    "TimezoneServiceResource",
]

from txweb2.dav.http import ErrorResponse

from txweb2 import responsecode
from txdav.xml import element as davxml
from txweb2.dav.method.propfind import http_PROPFIND
from txweb2.dav.noneprops import NonePropertyStore
from txweb2.http import HTTPError
from txweb2.http import Response
from txweb2.http import XMLResponse
from txweb2.http_headers import MimeType
from txweb2.stream import MemoryStream

from twisted.internet.defer import succeed

from twistedcaldav import customxml
from twistedcaldav.customxml import calendarserver_namespace
from twistedcaldav.extensions import DAVResource,\
    DAVResourceWithoutChildrenMixin
from twistedcaldav.ical import tzexpand
from twistedcaldav.resource import ReadOnlyNoCopyResourceMixIn
from twistedcaldav.timezones import TimezoneException
from twistedcaldav.timezones import listTZs
from twistedcaldav.timezones import readTZ

from pycalendar.datetime import DateTime

class TimezoneServiceResource (ReadOnlyNoCopyResourceMixIn, DAVResourceWithoutChildrenMixin, DAVResource):
    """
    Timezone Service resource.

    Extends L{DAVResource} to provide timezone service functionality.
    """

    def __init__(self, parent):
        """
        @param parent: the parent resource of this one.
        """
        assert parent is not None

        DAVResource.__init__(self, principalCollections=parent.principalCollections())

        self.parent = parent
        self.cache = {}

    def deadProperties(self):
        if not hasattr(self, "_dead_properties"):
            self._dead_properties = NonePropertyStore(self)
        return self._dead_properties

    def etag(self):
        return succeed(None)

    def checkPreconditions(self, request):
        return None

    def checkPrivileges(self, request, privileges, recurse=False, principal=None, inherited_aces=None):
        return succeed(None)

    def defaultAccessControlList(self):
        return succeed(
            davxml.ACL(
                # DAV:Read for all principals (includes anonymous)
                davxml.ACE(
                    davxml.Principal(davxml.All()),
                    davxml.Grant(
                        davxml.Privilege(davxml.Read()),
                    ),
                    davxml.Protected(),
                ),
            )
        )

    def contentType(self):
        return MimeType.fromString("text/xml")

    def resourceType(self):
        return davxml.ResourceType.timezones

    def isCollection(self):
        return False

    def isCalendarCollection(self):
        return False

    def isPseudoCalendarCollection(self):
        return False

    def render(self, request):
        output = """

<title>Timezone Service Resource</title>

Timezone Service Resource.

</body
"""

        response = Response(200, {}, output)
        response.headers.setHeader("content-type", MimeType("text", "html"))
        return response

    http_PROPFIND = http_PROPFIND

    def http_GET(self, request):
        """
        The timezone service POST method.
        """

        # GET and POST do the same thing
        return self.http_POST(request)

    def http_POST(self, request):
        """
        The timezone service POST method.
        """

        # Check authentication and access controls
        def _gotResult(_):

            if not request.args:
                # Do normal GET behavior
                return self.render(request)

            method = request.args.get("method", ("",))
            if len(method) != 1:
                raise HTTPError(ErrorResponse(
                    responsecode.BAD_REQUEST,
                    (calendarserver_namespace, "valid-method"),
                    "Invalid method query parameter",
                ))
            method = method[0]

            action = {
                "list": self.doPOSTList,
                "get": self.doPOSTGet,
                "expand": self.doPOSTExpand,
            }.get(method, None)

            if action is None:
                raise HTTPError(ErrorResponse(
                    responsecode.BAD_REQUEST,
                    (calendarserver_namespace, "supported-method"),
                    "Unknown method query parameter",
                ))

            return action(request)

        d = self.authorize(request, (davxml.Read(),))
        d.addCallback(_gotResult)
        return d

    def doPOSTList(self, request):
        """
        Return a list of all timezones known to the server.
        """

        tzids = listTZs()
        tzids.sort()
        result = customxml.TZIDs(*[customxml.TZID(tzid) for tzid in tzids])
        return XMLResponse(responsecode.OK, result)

    def doPOSTGet(self, request):
        """
        Return the specified timezone data.
        """

        tzid = request.args.get("tzid", ())
        if len(tzid) != 1:
            raise HTTPError(ErrorResponse(
                responsecode.BAD_REQUEST,
                (calendarserver_namespace, "valid-timezone"),
                "Invalid tzid query parameter",
            ))
        tzid = tzid[0]

        try:
            tzdata = readTZ(tzid)
        except TimezoneException:
            raise HTTPError(ErrorResponse(
                responsecode.NOT_FOUND,
                (calendarserver_namespace, "timezone-available"),
                "Timezone not found",
            ))

        response = Response()
        response.stream = MemoryStream(tzdata)
        response.headers.setHeader("content-type", MimeType.fromString("text/calendar; charset=utf-8"))
        return response

    def doPOSTExpand(self, request):
        """
        Expand a timezone within specified start/end dates.
        """

        tzid = request.args.get("tzid", ())
        if len(tzid) != 1:
            raise HTTPError(ErrorResponse(
                responsecode.BAD_REQUEST,
                (calendarserver_namespace, "valid-timezone"),
                "Invalid tzid query parameter",
            ))
        tzid = tzid[0]
        try:
            tzdata = readTZ(tzid)
        except TimezoneException:
            raise HTTPError(ErrorResponse(
                responsecode.NOT_FOUND,
                (calendarserver_namespace, "timezone-available"),
                "Timezone not found",
            ))

        try:
            start = request.args.get("start", ())
            if len(start) != 1:
                raise ValueError()
            start = DateTime.parseText(start[0])
        except ValueError:
            raise HTTPError(ErrorResponse(
                responsecode.BAD_REQUEST,
                (calendarserver_namespace, "valid-start-date"),
                "Invalid start query parameter",
            ))

        try:
            end = request.args.get("end", ())
            if len(end) != 1:
                raise ValueError()
            end = DateTime.parseText(end[0])
            if end <= start:
                raise ValueError()
        except ValueError:
            raise HTTPError(ErrorResponse(
                responsecode.BAD_REQUEST,
                (calendarserver_namespace, "valid-end-date"),
                "Invalid end query parameter",
            ))

        # Now do the expansion (but use a cache to avoid re-calculating TZs)
        observances = self.cache.get((tzid, start, end), None)
        if observances is None:
            observances = tzexpand(tzdata, start, end)
            self.cache[(tzid, start, end)] = observances

        # Turn into XML
        result = customxml.TZData(
            *[customxml.Observance(customxml.Onset(onset), customxml.UTCOffset(utc_offset)) for onset, utc_offset in observances]
        )
        return XMLResponse(responsecode.OK, result)


import json
import logging
from os import environ
from dotenv import load_dotenv

class AppLog:

    def __init__(self):

        self.log_obj = logging.getLogger(environ.get('APP_NAME'))
        self.log_obj.setLevel(environ.get('LOG_LEVEL'))

        custom_format = '{'\
                            '"appname" : "%(name)s",'\
                            '"loglevel": "%(levelname)s",'\
                            '"message": "%(message)s"'\
                        '}'

        fh = logging.FileHandler(environ.get('LOG_FILE'))
        fh.setLevel(environ.get('LOG_LEVEL'))

        ch = logging.StreamHandler()
        ch.setLevel(environ.get('LOG_LEVEL'))

        #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        formatter = logging.Formatter(str(custom_format))
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)

        self.log_obj.addHandler(ch)
        self.log_obj.addHandler(fh)

    def info(self, msg):
        message = msg
        self.log_obj.info(message)

    def error(self, msg):
        message = msg
        self.log_obj.error(message)

    def debug(self, msg):
        message = msg
        self.log_obj.debug(message)

load_dotenv()

log = AppLog()


import pytest

from courses.notion import parse_properties

@pytest.mark.parametrize(
    "input_data, expected",
    [
        (
                {"id": {"type": "id", "id": "some_id"}},
                {"id": "some_id"},
        ),
        (
                {"title_field_name": {"type": "title", "title": [{"type": "text", "text": {"content": "content_value"}, "plain_text": "plain_text_value"}]}},
                {"title_field_name": "plain_text_value"},
        ),
        (
                {"select_field_name": {"type": "select", "select": {"id": "123456", "name": "select_value"}}},
                {"select_field_name": "select_value"},
        ),
        (
                {"multi_select_field_name": {
                    "type": "multi_select",
                    "multi_select": [
                        {"id": "123", "name": "multi_select_value_1"},
                        {"id": "456", "name": "multi_select_value_2"},
                    ],
                }},
                {"multi_select_field_name": ["multi_select_value_1", "multi_select_value_2"]},
        ),
        (
                {"formula_field_name": {
                    "type": "formula",
                    "formula": {
                        "type": "number",
                        "number": 123456
                    }
                }},
                {"formula_field_name": 123456},
        ),
        (
                {"number_field_name": {
                    "type": "number",
                    "number": "None"
                }},
                {"number_field_name": None},
        ),
        (
                {"number_field_name": {
                    "type": "number",
                    "number": 123
                }},
                {"number_field_name": 123},
        ),
        (
                {"rich_text_field_name": {
                    'type': 'rich_text',
                    'rich_text': [
                        {
                            'type': 'text',
                            'text': {
                                'content': 'content_value',
                            },
                            'plain_text': 'plain_text_value',
                        }
                    ]
                }},
                {"rich_text_field_name": "plain_text_value"},
        ),
        (
                {"url_field_name": {
                    "type": "url",
                    "url": "https://eduson.academy"
                }},
                {"url_field_name": "https://eduson.academy"},
        ),
        (
                {"checkbox_field_name": {'checkbox': True, 'type': 'checkbox'}},
                {"checkbox_field_name": True},
        ),
        (
                {"relation_field_name": {
                    'type': 'relation',
                    'relation': [
                        {'id': 'id1'},
                        {'id': 'id2'}
                    ],
                }},
                {"relation_field_name": ["id1", "id2"]},
        ),
    ]
)
def test_parse_properties(input_data, expected):
    result = parse_properties(input_data)
    assert result == expected


from itertools import permutations

def solution(n, weak, dist):
    #최소값 비교를 위해 9 할당
    answer = 9

    #반시계 방향 회전을 고려하기 위해 길이를 두 배로 늘려 일자 리스트로 구성
    length = len(weak)
    for i in range(length):
        weak.append(weak[i]+n)

    #친구 투입 경우의 수(순열)
    dist_perm = list(permutations(dist, len(dist)))

    #시작 포인트
    for start in range(length):
        #경우의 수마다 계산
        for dp in dist_perm:
            #투입하는 친구 수
            cnt = 1
            #투입한 사람의 마지막 위치
            end = weak[start] + dp[cnt-1]
            #모든 취약점이 도는지 확인
            for i in range(start, start+length):
                #마지막 위치가 취약점 위치보다 낮을 경우 친구 한 명 추가 투입
                if end < weak[i]:
                    cnt += 1
                    #투입할 수 있는 친구가 없다면 다음 경우의 수로 이동
                    if cnt > len(dist):
                        break
                    #다음 투입한 사람의 마지막 위치 계산
                    end = weak[i] + dp[cnt-1]
            #기존의 답보다 더 적은 인원을 투입했다면 answer값 변경
            answer = min(answer, cnt)

    #반복문 종료 후 answer가 투입 가능한 사람보다 클 경우 답 없음(-1) 리턴
    if answer > len(dist):
        return -1

    return answer


"""
  Tests for Verb endpoints
"""
# disabling pylint rules that conflict with pytest fixtures
# pylint: disable=unused-argument,redefined-outer-name,unused-import
import os
import json
import pytest
from copy import deepcopy
from fastapi import FastAPI
from fastapi.testclient import TestClient
from routes.verb import router
from testing.test_config import API_URL, TESTING_FOLDER_PATH
from schemas.schema_examples import BASIC_VERB_MODEL_EXAMPLE
from common.models import Verb
from common.testing.firestore_emulator import (firestore_emulator,
                                               clean_firestore)
from common.utils.http_exceptions import add_exception_handlers

app = FastAPI()
add_exception_handlers(app)
app.include_router(router, prefix="/learning-record-service/api/v1")

client_with_emulator = TestClient(app)

os.environ["FIRESTORE_EMULATOR_HOST"] = "localhost:8080"
os.environ["GOOGLE_CLOUD_PROJECT"] = "fake-project"

def test_post_and_get_verb(clean_firestore):
  verb_dict = deepcopy(BASIC_VERB_MODEL_EXAMPLE)

  url = f"{API_URL}/verb"
  resp = client_with_emulator.post(url, json=verb_dict)
  json_response = resp.json()
  verb_uuid = json_response["data"]["uuid"]

  assert resp.status_code == 200, "Status is not 200"
  assert json_response.get("success") is True, "Success not true"
  assert json_response.get(
      "message"
  ) == "Successfully created the verb", "Expected response not same"
  assert json_response.get("data").get("name") == verb_dict.get(
      "name"), "Expected response not same"

  url = f"{API_URL}/verb/{verb_uuid}"
  resp = client_with_emulator.get(url)
  json_response_get_req = resp.json()

  assert resp.status_code == 200, "Status code not 200"
  assert json_response_get_req.get("data") == json_response.get(
      "data"), "Expected response not same"

def test_get_verb_negative(clean_firestore):
  invalid_verb_uuid = "random_id"
  url = f"{API_URL}/verb/{invalid_verb_uuid}"
  response = {
      "success": False,
      "message": "Verb with uuid random_id not found",
      "data": None
  }
  resp = client_with_emulator.get(url)
  json_response = resp.json()

  assert resp.status_code == 404, "Status 404"
  assert json_response == response, "Expected response not same"

def test_delete_verb_positive(clean_firestore):
  verb_dict = deepcopy(BASIC_VERB_MODEL_EXAMPLE)

  url = f"{API_URL}/verb"
  resp = client_with_emulator.post(url, json=verb_dict)
  json_response = resp.json()
  verb_uuid = json_response["data"]["uuid"]

  url = f"{API_URL}/verb/{verb_uuid}"
  resp = client_with_emulator.delete(url)
  json_response_delete_req = resp.json()

  expected_data = {"success": True, "message": "Successfully deleted the verb"}
  assert resp.status_code == 200, "Status code not 200"
  assert json_response_delete_req == expected_data, "Expected response not same"

def test_delete_verb_negative(clean_firestore):
  invalid_verb_uuid = "random_id"
  url = f"{API_URL}/verb/{invalid_verb_uuid}"
  response = {
      "success": False,
      "message": "Verb with uuid random_id not found",
      "data": None
  }
  resp = client_with_emulator.delete(url)
  json_response = resp.json()

  assert resp.status_code == 404, "Status 404"
  assert json_response == response, "Expected response not same"

def test_update_verb_positive(clean_firestore):
  verb_dict = deepcopy(BASIC_VERB_MODEL_EXAMPLE)
  url = f"{API_URL}/verb"

  resp = client_with_emulator.post(url, json=verb_dict)
  json_response = resp.json()

  updated_data = json_response["data"]
  updated_data["name"] = "some random name"

  uuid = updated_data.get("uuid")
  url = f"{API_URL}/verb/{uuid}"
  resp = client_with_emulator.put(url, json=updated_data)
  json_response_update_req = resp.json()

  assert json_response_update_req.get("success") is True, "Success not true"
  assert json_response_update_req.get(
      "message"
  ) == "Successfully updated the verb", "Expected response not same"
  assert json_response_update_req.get("data").get(
      "name") == "some random name", "Expected response not same"

def test_update_verb_negative(clean_firestore):
  req_json = deepcopy(BASIC_VERB_MODEL_EXAMPLE)
  uuid = req_json["uuid"] = "random_id"
  response = {
      "success": False,
      "message": "Verb with uuid random_id not found",
      "data": None
  }

  url = f"{API_URL}/verb/{uuid}"
  resp = client_with_emulator.put(url, json=req_json)
  json_response = resp.json()

  assert resp.status_code == 404, "Status 404"
  assert json_response == response, "Expected response not same"

def test_import_verbs(clean_firestore):
  url = f"{API_URL}/verb/import/json"
  file_path = os.path.join(TESTING_FOLDER_PATH, "verbs.json")
  with open(file_path, "rb") as file:
    resp = client_with_emulator.post(url, files={"json_file": file})

  json_response = resp.json()

  assert resp.status_code == 200, "Success not 200"
  assert isinstance(json_response.get("data"), list), "Response is not a list"
  assert len(json_response.get("data")) > 0, "Empty list returned"

def test_get_verbs(clean_firestore):
  verb_dict = deepcopy(BASIC_VERB_MODEL_EXAMPLE)
  verb_dict["name"] = "Communicate"
  verb = Verb.from_dict(verb_dict)
  verb.uuid = ""
  verb.save()
  verb.uuid = verb.id
  verb.update()
  params = {"skip": 0, "limit": "30"}

  url = f"{API_URL}/verbs"
  resp = client_with_emulator.get(url, params=params)
  json_response = resp.json()
  assert resp.status_code == 200, "Status 200"
  saved_names = [i.get("name") for i in json_response.get(
    "data")["records"]]
  assert verb_dict["name"] in saved_names, "all data not retrieved"

def test_get_verbs_negative(clean_firestore):
  verb_dict = deepcopy(BASIC_VERB_MODEL_EXAMPLE)
  verb = Verb.from_dict(verb_dict)
  verb.uuid = ""
  verb.save()
  verb.uuid = verb.id
  verb.update()
  params = {"skip": "-1", "limit": "30"}

  url = f"{API_URL}/verbs"
  resp = client_with_emulator.get(url, params=params)
  json_response = resp.json()
  assert resp.status_code == 422, "Status not 422"
  assert json_response.get(
    "message"
  ) == "Validation Failed", \
    "unknown response received"


from collections import deque
from functools import reduce

from adventlib import *

DAY = 14

def knot(s):
    vals = [17, 31, 73, 47, 23]

    insn = [ord(i) for i in s] + vals
    skip = 0
    begin = 0
    lst = list(range(256))
    for rnd in range(64):
        for size in insn:
            sub = [0] * size
            for i in range(size):
                sub[i] = lst[(begin + i) % 256]
            sub = list(reversed(sub))
            for i, e in enumerate(sub):
                lst[(begin + i) % 256] = e
            begin += size + skip
            skip += 1

    sp = []
    for i in range(16):
        sp.append(reduce(lambda a, b: a ^ b, lst[i * 16 + 1: i * 16 + 16], lst[i * 16]))
    return sp

def p_add(a, b):
    return (a[0] + b[0], a[1] + b[1])

def main():
    inp = store_input(DAY)
    if inp is None:
        return
    inp = inp.rstrip("\n")
    used = 0
    m = {}
    s = set()

    for i in range(128):
        h = knot(inp + "-" + str(i))
        for j, e in enumerate(h):
            for jj in range(8):
                if e & 1 == 1:
                    m[(i, 8 * j + 7 - jj)] = 1
                    s.add((i, (8 * j + 7 - jj)))
                else:
                    m[(i, 8 * j + 7 - jj)] = 0
                e >>= 1

    def accessible(p):
        return m.get(p, 0) == 1

    def neighbors(curr):
        for neighbor in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
            p = p_add(curr, neighbor)
            if accessible(p):
                yield p

    grps = 0
    while s:
        grps += 1
        st = s.pop()
        queue = deque([st])
        while queue:
            c = queue.popleft()
            for n in neighbors(c):
                if n in s:
                    s.remove(n)
                    queue.append(n)

    print(grps)

if __name__ == '__main__':
    main()


import neuroglancer
import sys
from pathlib import Path

from neuroglancer2 import add_container, add_dacapo_snapshot

neuroglancer.set_server_bind_address("0.0.0.0")

if __name__ == "__main__":
    args = sys.argv[1:]
    snapshot_file = args[0]

    voxel_size = [4, 4, 4]

    dimensions = neuroglancer.CoordinateSpace(
        names=["z", "y", "x"], units="nm", scales=voxel_size
    )

    snapshot_files = snapshot_file.split(",")

    viewer = neuroglancer.Viewer()
    viewer.dimensions = dimensions

    with viewer.txn() as s:
        for snapshot_file in snapshot_files:
            path = snapshot_file.split("/")
            if path[-2] == "snapshots":
                add_dacapo_snapshot(s, Path(snapshot_file))
            else:
                add_container(s, Path(snapshot_file))

    print(viewer)
    input("Hit ENTER to quit!")


import json
from abc import ABC
from typing import Generator, Set, Type, cast

from aea.exceptions import AEAEnforceError, enforce

from packages.elcollectooorr.contracts.basket.contract import BasketContract
from packages.elcollectooorr.contracts.basket_factory.contract import (
    BasketFactoryContract,
)
from packages.elcollectooorr.contracts.token_vault.contract import TokenVaultContract
from packages.elcollectooorr.contracts.token_vault_factory.contract import (
    TokenVaultFactoryContract,
)
from packages.elcollectooorr.skills.fractionalize_deployment_abci.models import Params
from packages.elcollectooorr.skills.fractionalize_deployment_abci.payloads import (
    BasketAddressesPayload,
    DeployBasketPayload,
    DeployDecisionPayload,
    DeployVaultPayload,
    PermissionVaultFactoryPayload,
    VaultAddressesPayload,
)
from packages.elcollectooorr.skills.fractionalize_deployment_abci.rounds import (
    BasketAddressRound,
    DeployBasketAbciApp,
    DeployBasketTxRound,
    DeployDecisionRound,
    DeployVaultAbciApp,
    DeployVaultTxRound,
    FinishedDeployBasketTxRound,
    FinishedDeployVaultTxRound,
    PermissionVaultFactoryRound,
    PostBasketDeploymentAbciApp,
    PostVaultDeploymentAbciApp,
    SynchronizedData,
    VaultAddressRound,
)
from packages.valory.contracts.gnosis_safe.contract import GnosisSafeContract
from packages.valory.protocols.contract_api import ContractApiMessage
from packages.valory.skills.abstract_round_abci.behaviours import AbstractRoundBehaviour
from packages.valory.skills.abstract_round_abci.behaviours import (
    BaseBehaviour as BaseState,
)
from packages.valory.skills.transaction_settlement_abci.payload_tools import (
    hash_payload_to_hex,
)

ONE_ETH = 10 ** 18
SAFE_GAS = 0

class FractionalizeDeploymentABCIBaseState(BaseState, ABC):
    """Base state behaviour for the Fractionalize Deployment abci skill."""

    @property
    def synchronized_data(self) -> SynchronizedData:
        """Return the synchronized data associated with this state."""
        return cast(SynchronizedData, super().synchronized_data)

    @property
    def params(self) -> Params:
        """Return the params."""
        return cast(Params, self.context.params)

class DeployDecisionRoundBehaviour(FractionalizeDeploymentABCIBaseState):
    """Behaviour for deciding whether a new basket & vault should be deployed"""

    matching_round = DeployDecisionRound

    def async_act(self) -> Generator:
        """Implement the act."""
        with self.context.benchmark_tool.measure(
            self.behaviour_id,
        ).local():
            deploy_decision = DeployDecisionRound.DECIDE_DONT_DEPLOY

            try:
                vault_addresses = self.synchronized_data.vault_addresses
                basket_addresses = self.synchronized_data.basket_addresses
                amount_spent = self.synchronized_data.amount_spent
                budget = self.params.budget_per_vault - (
                    0.15 * ONE_ETH
                )  # we leave a 0.15ETH margin

                if len(vault_addresses) == 0:
                    # no vaults are deployed, so a new one needs to get deployed
                    if len(basket_addresses) > 0:
                        # a basket is already deployed
                        # we need to deploy the vault
                        # this can happen on resync (restarting the service)
                        deploy_decision = DeployDecisionRound.DECIDE_SKIP_BASKET
                    else:
                        deploy_decision = DeployDecisionRound.DECIDE_DEPLOY_FULL

                elif amount_spent >= budget:
                    deploy_decision = DeployDecisionRound.DECIDE_DEPLOY_FULL

                else:
                    latest_vault = vault_addresses[-1]
                    status = yield from self._get_vault_state(latest_vault)

                    if status != 0:
                        # the state is not Inactive, the reserve has been met
                        deploy_decision = DeployDecisionRound.DECIDE_DEPLOY_FULL

                    if deploy_decision == DeployDecisionRound.DECIDE_DONT_DEPLOY:
                        tokens_left = yield from self._get_num_tokens_left(latest_vault)
                        if tokens_left == 0:
                            # if no tokens are left, the vault has sold out, deploy a new one
                            deploy_decision = DeployDecisionRound.DECIDE_DEPLOY_FULL

            except AEAEnforceError as e:
                self.context.logger.error(
                    f"Couldn't create the DeployDecisionRound payload, {type(e).__name__}: {e}."
                )

        with self.context.benchmark_tool.measure(
            self.behaviour_id,
        ).consensus():
            self.context.logger.info(f"Deploy new basket and vault? {deploy_decision}.")

            payload = DeployDecisionPayload(
                self.context.agent_address,
                deploy_decision,
            )

            yield from self.send_a2a_transaction(payload)
            yield from self.wait_until_round_end()

        self.set_done()

    def _get_vault_state(self, vault_address: str) -> Generator[None, None, int]:
        response = yield from self.get_contract_api_response(
            performative=ContractApiMessage.Performative.GET_STATE,
            contract_id=str(TokenVaultContract.contract_id),
            contract_callable="get_auction_state",
            contract_address=vault_address,
        )

        enforce(
            response is not None
            and response.state is not None
            and response.state.body is not None
            and "state" in response.state.body.keys()
            and response.state.body["state"] is not None,
            "response, response.state, response.state.body must exist",
        )

        data = cast(int, response.state.body["state"])

        return data

    def _get_num_tokens_left(self, vault_address: str) -> Generator[None, None, int]:
        response = yield from self.get_contract_api_response(
            performative=ContractApiMessage.Performative.GET_STATE,
            contract_id=str(TokenVaultContract.contract_id),
            contract_callable="get_balance",
            contract_address=vault_address,
            address=self.synchronized_data.safe_contract_address,
        )

        enforce(
            response is not None
            and response.state is not None
            and response.state.body is not None
            and "balance" in response.state.body.keys()
            and response.state.body["balance"] is not None,
            "response, response.state, response.state.body must exist",
        )

        data = cast(int, response.state.body["balance"])

        return data

class DeployBasketTxRoundBehaviour(FractionalizeDeploymentABCIBaseState):
    """Defines the DeployBasketTxRoundRound behaviour"""

    matching_round = DeployBasketTxRound

    def async_act(self) -> Generator:
        """Implement the act."""
        payload_data = ""

        with self.context.benchmark_tool.measure(
            self.behaviour_id,
        ).local():
            # we extract the project_id from the frozen set, and throw an error if it doest exist
            try:
                basket_data_str = yield from self._get_create_basket()
                basket_data = bytes.fromhex(basket_data_str[2:])
                tx_hash = yield from self._get_safe_hash(basket_data)

                payload_data = hash_payload_to_hex(
                    safe_tx_hash=tx_hash,
                    ether_value=0,
                    safe_tx_gas=SAFE_GAS,
                    to_address=self.params.basket_factory_address,
                    data=basket_data,
                )

            except AEAEnforceError as e:
                self.context.logger.error(
                    f"Couldn't create DeployBasketTxRound payload, {type(e).__name__}: {e}."
                )

        with self.context.benchmark_tool.measure(
            self.behaviour_id,
        ).consensus():
            payload = DeployBasketPayload(
                self.context.agent_address,
                payload_data,
            )

            yield from self.send_a2a_transaction(payload)
            yield from self.wait_until_round_end()

        self.set_done()

    def _get_safe_hash(self, data: bytes) -> Generator[None, None, str]:
        response = yield from self.get_contract_api_response(
            performative=ContractApiMessage.Performative.GET_STATE,  # type: ignore
            contract_address=self.synchronized_data.safe_contract_address,
            contract_id=str(GnosisSafeContract.contract_id),
            contract_callable="get_raw_safe_transaction_hash",
            to_address=self.params.basket_factory_address,
            value=0,
            data=data,
            safe_tx_gas=SAFE_GAS,
        )

        enforce(
            response.state.body is not None
            and "tx_hash" in response.state.body.keys()
            and response.state.body["tx_hash"] is not None,
            "contract returned and empty body or empty tx_hash",
        )

        tx_hash = cast(str, response.state.body["tx_hash"])[2:]

        return tx_hash

    def _get_create_basket(self) -> Generator[None, None, str]:
        response = yield from self.get_contract_api_response(
            performative=ContractApiMessage.Performative.GET_STATE,
            contract_id=str(BasketFactoryContract.contract_id),
            contract_callable="create_basket_abi",
            contract_address=self.params.basket_factory_address,
        )

        # response body also has project details
        enforce(
            response.state.body is not None
            and "data" in response.state.body.keys()
            and response.state.body["data"] is not None,
            "contract returned and empty body or empty data",
        )

        data = cast(str, response.state.body["data"])

        return data

class DeployTokenVaultTxRoundBehaviour(FractionalizeDeploymentABCIBaseState):
    """Defines the DeployBasketTxRoundRound behaviour"""

    matching_round = DeployVaultTxRound

    def async_act(self) -> Generator:
        """Implement the act."""
        payload_data = ""

        with self.context.benchmark_tool.measure(
            self.behaviour_id,
        ).local():
            # we extract the project_id from the frozen set, and throw an error if it doest exist
            try:
                mint_data_str = yield from self._get_mint_vault()
                mint_data = bytes.fromhex(mint_data_str[2:])
                tx_hash = yield from self._get_safe_hash(mint_data)

                payload_data = hash_payload_to_hex(
                    safe_tx_hash=tx_hash,
                    ether_value=0,
                    safe_tx_gas=SAFE_GAS,
                    to_address=self.params.token_vault_factory_address,
                    data=mint_data,
                )

            except AEAEnforceError as e:
                self.context.logger.error(
                    f"Couldn't create DeployVaultTxRound payload, {type(e).__name__}: {e}."
                )

        with self.context.benchmark_tool.measure(
            self.behaviour_id,
        ).consensus():
            payload = DeployVaultPayload(
                self.context.agent_address,
                payload_data,
            )

            yield from self.send_a2a_transaction(payload)
            yield from self.wait_until_round_end()

        self.set_done()

    def _get_safe_hash(self, data: bytes) -> Generator[None, None, str]:
        response = yield from self.get_contract_api_response(
            performative=ContractApiMessage.Performative.GET_STATE,  # type: ignore
            contract_address=self.synchronized_data.safe_contract_address,
            contract_id=str(GnosisSafeContract.contract_id),
            contract_callable="get_raw_safe_transaction_hash",
            to_address=self.params.token_vault_factory_address,
            value=0,
            data=data,
            safe_tx_gas=SAFE_GAS,
        )

        enforce(
            response.state.body is not None
            and "tx_hash" in response.state.body.keys()
            and response.state.body["tx_hash"] is not None,
            "contract returned and empty body or empty tx_hash",
        )

        tx_hash = cast(str, response.state.body["tx_hash"])[2:]

        return tx_hash

    def _get_mint_vault(self) -> Generator[None, None, str]:
        all_baskets = self.synchronized_data.basket_addresses
        latest_basket = all_baskets[-1]

        response = yield from self.get_contract_api_response(
            performative=ContractApiMessage.Performative.GET_STATE,
            contract_address=self.params.token_vault_factory_address,
            contract_id=str(TokenVaultFactoryContract.contract_id),
            contract_callable="mint_abi",
            name=f"El Collectooorr Vault #{len(all_baskets)}",
            symbol="ELC",
            token_address=latest_basket,
            token_id=0,
            token_supply=1000,
            list_price=0,
            fee=1,
        )

        # response body also has project details
        enforce(
            response.state.body is not None
            and "data" in response.state.body.keys()
            and response.state.body["data"] is not None,
            "contract returned and empty body or empty data",
        )

        data = cast(str, response.state.body["data"])

        return data

class BasketAddressesRoundBehaviour(FractionalizeDeploymentABCIBaseState):
    """Behaviour of basket addresses round"""

    matching_round = BasketAddressRound

    def async_act(self) -> Generator:
        """Implement the act."""

        with self.context.benchmark_tool.measure(
            self.behaviour_id,
        ).local():
            # we extract the project_id from the frozen set, and throw an error if it doest exist
            try:
                basket_addresses = self.synchronized_data.basket_addresses
                vault_addresses = self.synchronized_data.vault_addresses
                if len(basket_addresses) == len(vault_addresses):
                    # this check is necessary if for some reason we have successfully deployed a basket,
                    # but we fail before deploying the vault
                    new_basket = yield from self._get_basket()
                    basket_addresses.append(new_basket)
                    self.context.logger.info(f"New basket address={new_basket}")

            except AEAEnforceError as e:
                self.context.logger.error(
                    f"Couldn't create BasketAddressRound payload, {type(e).__name__}: {e}."
                )

        with self.context.benchmark_tool.measure(
            self.behaviour_id,
        ).consensus():
            payload = BasketAddressesPayload(
                self.context.agent_address,
                json.dumps(basket_addresses),
            )

            yield from self.send_a2a_transaction(payload)
            yield from self.wait_until_round_end()

        self.set_done()

    def _get_basket(self) -> Generator[None, None, str]:
        response = yield from self.get_contract_api_response(
            performative=ContractApiMessage.Performative.GET_STATE,
            contract_address=self.params.basket_factory_address,
            contract_id=str(BasketFactoryContract.contract_id),
            contract_callable="get_basket_address",
            tx_hash=self.synchronized_data.final_tx_hash,
        )

        # response body also has project details
        enforce(
            response.state.body is not None
            and "basket_address" in response.state.body.keys(),
            "couldn't extract the 'basket_address' from the BaketFactoryContract",
        )

        data = cast(str, response.state.body["basket_address"])

        return data

class PermissionVaultFactoryRoundBehaviour(FractionalizeDeploymentABCIBaseState):
    """Defines the DeployBasketTxRoundRound behaviour"""

    matching_round = PermissionVaultFactoryRound

    def async_act(self) -> Generator:
        """Implement the act."""
        payload_data = ""

        with self.context.benchmark_tool.measure(
            self.behaviour_id,
        ).local():
            # we extract the project_id from the frozen set, and throw an error if it doest exist
            try:
                latest_basket = self.synchronized_data.basket_addresses[-1]

                is_permissioned = yield from self._is_basket_permissioned(latest_basket)
                if not is_permissioned:
                    # we only permission if necessary
                    basket_data_str = yield from self._get_permission_tx(latest_basket)
                    basket_data = bytes.fromhex(basket_data_str[2:])
                    tx_hash = yield from self._get_safe_hash(basket_data, latest_basket)

                    payload_data = hash_payload_to_hex(
                        safe_tx_hash=tx_hash,
                        ether_value=0,
                        safe_tx_gas=SAFE_GAS,
                        to_address=latest_basket,
                        data=basket_data,
                    )
                else:
                    payload_data = PermissionVaultFactoryRound.SKIP_PERMISSION

            except AEAEnforceError as e:
                self.context.logger.error(
                    f"Couldn't create PermissionVaultFactoryRound payload, {type(e).__name__}: {e}."
                )

        with self.context.benchmark_tool.measure(
            self.behaviour_id,
        ).consensus():
            payload = PermissionVaultFactoryPayload(
                self.context.agent_address,
                payload_data,
            )

            yield from self.send_a2a_transaction(payload)
            yield from self.wait_until_round_end()

        self.set_done()

    def _get_safe_hash(
        self, data: bytes, basket_address: str
    ) -> Generator[None, None, str]:
        response = yield from self.get_contract_api_response(
            performative=ContractApiMessage.Performative.GET_STATE,  # type: ignore
            contract_address=self.synchronized_data.safe_contract_address,
            contract_id=str(GnosisSafeContract.contract_id),
            contract_callable="get_raw_safe_transaction_hash",
            to_address=basket_address,
            value=0,
            data=data,
            safe_tx_gas=SAFE_GAS,
        )

        enforce(
            response.state.body is not None
            and "tx_hash" in response.state.body.keys()
            and response.state.body["tx_hash"] is not None,
            "contract returned and empty body or empty tx_hash",
        )

        tx_hash = cast(str, response.state.body["tx_hash"])[2:]

        return tx_hash

    def _get_permission_tx(self, basket_address: str) -> Generator[None, None, str]:
        response = yield from self.get_contract_api_response(
            performative=ContractApiMessage.Performative.GET_STATE,
            contract_id=str(BasketContract.contract_id),
            contract_callable="approve_abi",
            contract_address=basket_address,
            operator_address=self.params.token_vault_factory_address,
        )

        # response body also has project details
        enforce(
            response.state.body is not None
            and "data" in response.state.body.keys()
            and response.state.body["data"] is not None,
            "contract returned and empty body or empty data",
        )

        data = cast(str, response.state.body["data"])

        return data

    def _is_basket_permissioned(
        self, basket_address: str
    ) -> Generator[None, None, bool]:
        """Check whether the vault is already permissioned."""
        response = yield from self.get_contract_api_response(
            performative=ContractApiMessage.Performative.GET_STATE,
            contract_id=str(BasketContract.contract_id),
            contract_callable="get_approved_account",
            contract_address=basket_address,
            token_id=0,
        )

        # response body also has project details
        enforce(
            response.state.body is not None
            and "operator" in response.state.body.keys()
            and response.state.body["operator"] is not None,
            "contract returned and empty body or empty data",
        )

        operator = cast(str, response.state.body["operator"])

        return operator == self.params.token_vault_factory_address

class VaultAddressesRoundBehaviour(FractionalizeDeploymentABCIBaseState):
    """Behaviour of vault addresses round"""

    matching_round = VaultAddressRound

    def async_act(self) -> Generator:
        """Implement the act."""

        with self.context.benchmark_tool.measure(
            self.behaviour_id,
        ).local():
            try:
                vault_addresses = self.synchronized_data.vault_addresses
                new_vault = yield from self._get_vault()
                vault_addresses.append(new_vault)

                self.context.logger.info(f"Deployed new TokenVault at: {new_vault}.")
            except AEAEnforceError as e:
                self.context.logger.error(
                    f"Couldn't create VaultAddressesRoundBehaviour payload, {type(e).__name__}: {e}."
                )

        with self.context.benchmark_tool.measure(
            self.behaviour_id,
        ).consensus():
            payload = VaultAddressesPayload(
                self.context.agent_address,
                json.dumps(vault_addresses),
            )

            yield from self.send_a2a_transaction(payload)
            yield from self.wait_until_round_end()

        self.set_done()

    def _get_vault(self) -> Generator[None, None, str]:
        response = yield from self.get_contract_api_response(
            performative=ContractApiMessage.Performative.GET_STATE,
            contract_address=self.params.token_vault_factory_address,
            contract_id=str(TokenVaultFactoryContract.contract_id),
            contract_callable="get_vault_address",
            tx_hash=self.synchronized_data.final_tx_hash,
        )

        # response body also has project details
        enforce(
            response.state.body is not None
            and "vault_address" in response.state.body.keys(),
            "couldn't extract vault_address from the vault_factory",
        )

        data = cast(str, response.state.body["vault_address"])

        return data

class FinishedTokenVaultTxRoundBehaviour(FractionalizeDeploymentABCIBaseState):
    """Degenerate behaviour for a degenerate round"""

    matching_round = FinishedDeployVaultTxRound

    def async_act(self) -> Generator:
        """Simply log that the app was executed successfully."""
        self.context.logger.info(
            "Successfully executed Fractionalize Deployment TX app."
        )
        self.set_done()
        yield

class FinishedDeployBasketTxRoundBehaviour(FractionalizeDeploymentABCIBaseState):
    """Degenerate behaviour for a degenerate round"""

    matching_round = FinishedDeployBasketTxRound

    def async_act(self) -> Generator:
        """Simply log that the app was executed successfully."""
        self.context.logger.info("Successfully executed Basket Deployment TX.")
        self.set_done()
        yield

class DeployVaultRoundBehaviour(AbstractRoundBehaviour):
    """This behaviour manages the consensus stages for the Vault Deployment abci app."""

    initial_behaviour_cls = DeployTokenVaultTxRoundBehaviour
    abci_app_cls = DeployVaultAbciApp
    behaviours: Set[Type[BaseState]] = {
        DeployTokenVaultTxRoundBehaviour,
    }

    def setup(self) -> None:
        """Set up the behaviour."""
        super().setup()
        self.context.benchmark_tool.logger = self.context.logger

class DeployBasketRoundBehaviour(AbstractRoundBehaviour):
    """This behaviour manages the consensus stages for the Basket Deployment abci app."""

    initial_behaviour_cls = DeployDecisionRoundBehaviour
    abci_app_cls = DeployBasketAbciApp
    behaviours: Set[Type[BaseState]] = {
        DeployDecisionRoundBehaviour,
        DeployBasketTxRoundBehaviour,
    }

    def setup(self) -> None:
        """Set up the behaviour."""
        super().setup()
        self.context.benchmark_tool.logger = self.context.logger

class PostBasketDeploymentRoundBehaviour(AbstractRoundBehaviour):
    """This behaviour manages the consensus stages for the Basket Deployment abci app."""

    initial_behaviour_cls = BasketAddressesRoundBehaviour
    abci_app_cls = PostBasketDeploymentAbciApp
    behaviours: Set[Type[BaseState]] = {
        BasketAddressesRoundBehaviour,
        PermissionVaultFactoryRoundBehaviour,
    }

    def setup(self) -> None:
        """Set up the behaviour."""
        super().setup()
        self.context.benchmark_tool.logger = self.context.logger

class PostVaultDeploymentRoundBehaviour(AbstractRoundBehaviour):
    """This behaviour manages the consensus stages for the Vault Deployment abci app."""

    initial_behaviour_cls = VaultAddressesRoundBehaviour
    abci_app_cls = PostVaultDeploymentAbciApp
    behaviours: Set[Type[BaseState]] = {
        VaultAddressesRoundBehaviour,
    }

    def setup(self) -> None:
        """Set up the behaviour."""
        super().setup()
        self.context.benchmark_tool.logger = self.context.logger


#!/usr/bin/env python3
import argparse
import sys

import numpy as np
import sklearn.metrics
import sklearn.neural_network

parser = argparse.ArgumentParser()
# These arguments will be set appropriately by ReCodEx, even if you change them.
parser.add_argument("--batch_size", default=1, type=int, help="Batch size")
parser.add_argument("--data_size", default=50, type=int, help="Data size")
parser.add_argument("--kernel", default="rbf", type=str, help="Kernel type [poly|rbf]")
parser.add_argument("--kernel_degree", default=3, type=int, help="Degree for poly kernel")
parser.add_argument("--kernel_gamma", default=1.0, type=float, help="Gamma for poly and rbf kernel")
parser.add_argument("--iterations", default=200, type=int, help="Number of training iterations")
parser.add_argument("--l2", default=0.0, type=float, help="L2 regularization weight")
parser.add_argument("--learning_rate", default=0.01, type=float, help="Learning rate")
parser.add_argument("--plot", default=False, const=True, nargs="?", type=str, help="Plot the predictions")
parser.add_argument("--recodex", default=False, action="store_true", help="Running in ReCodEx")
parser.add_argument("--seed", default=42, type=int, help="Random seed")
# If you add more arguments, ReCodEx will keep them with your default values.
parser.add_argument("--nn_reference", default=False, action="store_true", help="Show NN solution too")

def main(args):
    # Create a random generator with a given seed
    generator = np.random.RandomState(args.seed)

    # Generate an artifical regression dataset
    train_data = np.linspace(-1, 1, args.data_size)
    train_target = np.sin(5 * train_data) + generator.normal(scale=0.25, size=args.data_size) + 1

    test_data = np.linspace(-1.2, 1.2, 2 * args.data_size)
    test_target = np.sin(5 * test_data) + 1

    betas = np.zeros(args.data_size)

    # TODO: Perform `args.iterations` of SGD-like updates, but in dual formulation
    # using `betas` as weights of individual training examples.
    #
    # We assume the primary formulation of our model is
    #   y = phi(x)^T w + bias
    # and the loss in the primary problem is batched MSE with L2 regularization:
    #   L = sum_{i \in B} 1/|B| * [1/2 * (phi(x_i)^T w + bias - target_i)^2] + 1/2 * args.l2 * w^2
    #
    # For `bias`, use explicitly the average of the training targets, and do
    # not update it futher during training.
    #
    # Instead of using feature map `phi` directly, we use a given kernel computing
    #   K(x, y) = phi(x)^T phi(y)
    # We consider the following `args.kernel`s:
    # - "poly": K(x, y; degree, gamma) = (gamma * x^T y + 1) ^ degree
    # - "rbf": K(x, y; gamma) = exp^{- gamma * ||x - y||^2}
    #
    # After each iteration, compute RMSE both on training and testing data.
    train_rmses, test_rmses = [], []

    bias = np.mean(train_target)

    def kernel(x, y):
        if args.kernel == "poly":
            return (args.kernel_gamma * x * y + 1) ** args.kernel_degree
        if args.kernel == "rbf":
            return np.exp(-args.kernel_gamma * ((x - y) ** 2))

    K = np.array([[kernel(x, y) for x in train_data] for y in train_data])
    Ktest = np.array([[kernel(x, y) for x in train_data] for y in test_data])
    for iteration in range(args.iterations):
        permutation = generator.permutation(train_data.shape[0])

        # TODO: Process the data in the order of `permutation`, performing
        # batched updates to the `betas`. You can assume that `args.batch_size`
        # exactly divides `train_data.shape[0]`.
        for index in range(0, len(permutation), args.batch_size):
            batch = permutation[index:index + args.batch_size]
            assert len(batch) == args.batch_size

            betas[batch] -= args.learning_rate / args.batch_size * (K[batch] @ betas + bias - train_target[batch])
            betas -= args.learning_rate * args.l2 * betas

        # TODO: Append RMSE on training and testing data to `train_rmses` and
        # `test_rmses` after the iteration.
        train_rmses.append(sklearn.metrics.mean_squared_error(train_target, K @ betas + bias, squared=False))
        test_rmses.append(sklearn.metrics.mean_squared_error(test_target, Ktest @ betas + bias, squared=False))

        if (iteration + 1) % 10 == 0:
            print("Iteration {}, train RMSE {:.2f}, test RMSE {:.2f}".format(
                iteration + 1, train_rmses[-1], test_rmses[-1]))

    if args.plot:
        import matplotlib.pyplot as plt
        # If you want the plotting to work (not required for ReCodEx), compute the `test_predictions`.
        test_predictions = Ktest @ betas + bias

        plt.plot(train_data, train_target, "bo", label="Train target")
        plt.plot(test_data, test_target, "ro", label="Test target")
        plt.plot(test_data, test_predictions, "g-", label="Predictions")
        plt.legend()
        if args.nn_reference:
            for params in [{"activation": "tanh"}, {"activation": "relu"}]:
                plt.figure()
                mlp = sklearn.neural_network.MLPRegressor(hidden_layer_sizes=(500,), solver="lbfgs", alpha=0, max_iter=2000, **params).fit(np.expand_dims(train_data, -1), train_target)
                plt.plot(train_data, train_target, "bo", label="Train target")
                plt.plot(test_data, test_target, "ro", label="Test target")
                plt.plot(test_data, mlp.predict(np.expand_dims(test_data, -1)), "g-", label="Predictions")
                plt.legend()
        if args.plot is True: plt.show()
        else: plt.savefig(args.plot, transparent=True, bbox_inches="tight")

    return train_rmses, test_rmses

if __name__ == "__main__":
    args = parser.parse_args([] if "__file__" not in globals() else None)
    main(args)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
import django.core.validators
import taggit.managers

class Migration(migrations.Migration):

    dependencies = [
        ('events', '0018_auto_20161004_2009'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='is_published',
            field=models.BooleanField(default=True, verbose_name='szkic'),
        ),
        migrations.AlterField(
            model_name='event',
            name='is_featured',
            field=models.BooleanField(default=False, verbose_name='wyr\xf3\u017cniony'),
        ),
        migrations.AlterField(
            model_name='event',
            name='short_title',
            field=models.CharField(default=b'', max_length=255, verbose_name='tytu\u0142 promocyjny wydarzenia', blank=True),
        ),
        migrations.AlterField(
            model_name='event',
            name='tags',
            field=taggit.managers.TaggableManager(to='taggit.Tag', through='taggit.TaggedItem', blank=True, help_text='A comma-separated list of tags.', verbose_name='Tags'),
        ),
        migrations.AlterField(
            model_name='event',
            name='title',
            field=models.CharField(max_length=255, verbose_name='tytu\u0142 wydarzenia'),
        ),
        migrations.AlterField(
            model_name='event',
            name='title_fb_no',
            field=models.CharField(default=b'', max_length=255, null=True, verbose_name='tytu\u0142 na NIE obiektu FB', blank=True),
        ),
        migrations.AlterField(
            model_name='event',
            name='title_fb_yes',
            field=models.CharField(default=b'', max_length=255, null=True, verbose_name='tytu\u0142 na TAK obiektu FB', blank=True),
        ),
        migrations.AlterField(
            model_name='event',
            name='twitter_tag',
            field=models.CharField(default=b'', validators=[django.core.validators.RegexValidator(regex=b'^([^\\s]+)$', message='Tag twittera nie mo\u017ce zawiera\u0107 spacji', code=b'invalid_twitter_tag')], max_length=32, blank=True, null=True, verbose_name='tag twittera'),
        ),
    ]


# see README.md

from flask import Flask, request
from flask_cors import CORS
import lib
import pandas
import json

app = Flask(__name__)
CORS(app)

@app.route('/')
def root():
    return "see README.md"

@app.route('/view/<path:data>')
def testing(data):

    fileNames = ["Group_340", "Group_342",
                 "Group_343", "Group_349", "Group_416"]

    fileValues = []
    for fileName in fileNames:
        df = pandas.read_csv(f'csvfiles/{data}/{fileName}.csv')
        keys = []
        longvalues = []

        for name in df.columns:
            keys.append(name)

        for index, row in df.iterrows():
            value = []
            for key in keys:
                value.append(row[key])
            longvalues.append(value)

        fileValues.append(longvalues)

    # simulating ticks and retrieving snapshots every 0.1 sec
    # c++ backend
    snapshots = lib.testing(fileValues)

    # save the snapshots file to 'data'.json
    with open(f'csvfiles/{data}/data.json', 'w') as outfile:
        json.dump(snapshots, outfile)

    print("done")

    return snapshots

@app.route('/view_ft/<path:data>')
def view_ft(data):
    # open the json file
    with open(f'csvfiles/{data}/data.json') as json_file:
        data = json.load(json_file)
        return data


from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
import joblib
from fastapi import FastAPI

app = FastAPI()

# Load the pre-trained SVM model and TF-IDF vectorizer
svm_classifier = joblib.load("svm_model.pkl")
tfidf_vectorizer = joblib.load("tfidf_vectorizer.pkl")

# Create a templates object for rendering HTML
templates = Jinja2Templates(directory="templates")

class TextRequest(BaseModel):
    text: str

@app.get("/", response_class=HTMLResponse)
async def read_item(request):
    # Render the HTML page
    return templates.TemplateResponse("index.html", {"request": request})

@app.post("/predict/")
async def predict_emotion(request_data: TextRequest):  # Update the parameter name here
    text = request_data.text  # Use request_data
    # Vectorize the input text
    text_vectorized = tfidf_vectorizer.transform([text])
    # Make predictions
    prediction = svm_classifier.predict(text_vectorized)
    return {"emotion": prediction[0]}


import json

import pika

import os

import json

from main import Product, db, app

URL = os.environ.get('URL')

params = pika.URLParameters(URL)

connection = pika.BlockingConnection(parameters=params)

channel = connection.channel()

channel.queue_declare(queue='main')

def callback(ch, method, properties, body):
    print('received in main linux after db ')
    print(body)
    data = json.loads(body)

    if properties.content_type == 'product_created':
        product = Product(id=data['id'], title=data['title'], image=data['image'])
        db.session.add(product)
        db.session.commit()
        print('Product Created')
    elif properties.content_type == 'product_updated':
        product = Product.query.get(data['id'])
        product.title = data['title']
        product.image = data['image']
        db.session.commit()
        print('Product Updated')
    elif properties.content_type == 'product_deleted':
        product = Product.query.get(int(data))
        print(product)
        db.session.delete(product)
        db.session.commit()
        print('Product Deleted')

channel.basic_consume(queue='main', on_message_callback=callback, auto_ack=False)

print('Started Consuming')

channel.start_consuming()

channel.close()


# -*- coding: utf-8 -*-
"""
Created on Mon Dec  4 19:46:22 2017

@author: Renuka

Description: This scrapes and saves html files for all other establishments the user has given reviews for
"""
import time
import os.path
import requests
import csv

def scrapeRest(Rname,uid,url):
    restId=url.replace('/biz/','')#get restaurant id
    #save html files under subfolder
    with open(os.path.join('others',uid+'__'+restId+ ".html"), "wb") as review_page:
        html=None
        pageLink="https://www.yelp.com"+url # url for page 1
        print(pageLink)
        for i in range(5): # try 5 times
            try:
                #use the browser to access the url
                response=requests.get(pageLink,headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', })
                html=response.content # get the html
                break # we got the file, break the loop
            except Exception as e:# browser.open() threw an exception, the attempt to get the response failed
                print ('failed attempt',i)
                time.sleep(2) # wait 2 sec
        time.sleep(2)
        #save the html
        review_page.write(html)
        review_page.close()

if __name__=='__main__':
    try:
        os.mkdir("others")
    except Exception:
        pass
    with open('Ofile.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            if row['Name']!='NA':
                scrapeRest(row['Restaurant'],row['Userid'],row['Link'])


from collections import defaultdict

students = defaultdict(set)

n = int(input())
count_array = [[] for _ in range(101)]

for i in range(n):
    n, m = input().split(' ')
    count_array[int(m)].append(n)

for i in count_array:
    if i :
        for j in i:
            print(j, end=' ')


#!/usr/bin/env python3
# coding=utf-8

## Zpracování záznamu cílové kamery
# @file OpenPose_process.py
# @brief scripr pro zpracování záznamu cílovou kamerou
# @author Jahoda Vojtěch

__author__ = "Jahoda Vojtěch"
__description__ = "scripr pro zpracování záznamu cílovou kamerou"

import json
import sys
import cv2
import os
from sys import platform
import argparse
import numpy as np
import argparse

def process_image(name: str,img: np.ndarray, json_save: bool = True, json_path: str = 'tmp/json') -> str:
    """
    Funkce pro zpracování cílového záznamu knihovnou OpenPose
    @param name         -> jméno souboru cílového záznamu
    @param img          -> vstupní obrázek pro cílový soubor
    @param json_save    -> přepínač ukládání JSON souboru
    @param json_path    -> složka na uložení JSON souborů
    @return             -> jméno uloženého JSON souboru

    @note tato funkce je inspirována příklady použití knihovny OpenPose pro Python knihovnu
    """
    # Import knihovny OpenPose pro Windows\Linus\OsX
    dir_path = os.path.dirname(os.path.realpath(__file__))

    try:
        # Windows Import
        if platform == "win32":
            #Zde musí pro windows být nastavena relativní cesta od tohoto souboru pro složky Release a Bin
            #Pro přesun knihovny OpenPose je zapotřebý tyto proměnné přepsat
            def_folder = '/OpenPose_lib/build'
            sys.path.append(dir_path + def_folder + '/python/openpose/Release')
            os.environ['PATH'] = os.environ['PATH'] + ';' + dir_path + \
                def_folder + '/x64/Release;' + dir_path + def_folder + '/bin;'
            import pyopenpose as op
        else:
            #Zde musí pro windows být nastavena relativní cesta od tohoto souboru pro složku python v přeložené knihovně OpenPose
            sys.path.append('/OpenPose_lib/build/python')
            from openpose import pyopenpose as op
    except ImportError as e:
        # chyba importu, pokud knihovna OpenPose není přelkožena jako python knihovna
        print('Error: OpenPose library could not be found. Did you enable `BUILD_PYTHON` in CMake?')
        raise e

    #nastavení relativní cesty k modelům OpenPose
    params = dict()
    params["model_folder"] = "OpenPose_lib/models/"

    # Starting OpenPose
    opWrapper = op.WrapperPython()
    opWrapper.configure(params)
    opWrapper.start()

    # Process Image
    datum = op.Datum()
    datum.cvInputData = img
    opWrapper.emplaceAndPop(op.VectorDatum([datum]))

    # uložení bodů do JSON souboru
    if json_save:
        js_data = datum.poseKeypoints.tolist()
        with open(os.path.join(json_path,name+'.json'), 'w+') as f:
            json.dump(js_data, f, separators=(',', ':'))

    return os.path.join(json_path,name+'.json')

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='získájní bodů postavy z knihovny OpenPose', usage='%(prog)s --in_file')

    parser.add_argument('--in_file', metavar='Soubor',
                        help='Cílový záznam ve formátu obrázku (JPG,PNG,JPEG...)')

    args = parser.parse_args()

    if not os.path.exists(args.in_file):
        print('[problem] tento soubor neexistuje - ', args.in_file)
        raise FileNotFoundError

    process_image(os.path.split(args.in_file)[1], cv2.imread(args.in_+file))


from collections import Counter

answer = []

while True:
    N, M = map(int, input().split())
    arr = []
    seconds = []
    if N == M == 0:
        break

    for i in range(N):
        arr += list(map(int, input().split()))

    val = Counter(arr).most_common()

    for v in val:
        if v[1] == val[1][1]:
            seconds.append(v[0])

    seconds.sort()
    answer.append(seconds)

for i in range(len(answer)):
    for j in range(len(answer[i])):
        print(answer[i][j], end=" ")
    print()

BOJ/구현/할아버지는 유명해!.py

할아버지는 유명해!.py


import ibm_db

from config import dsn_driver, dsn_database, dsn_hostname, dsn_port, dsn_protocol, dsn_uid , dsn_pwd, dsn_security

dsn = (
    "DRIVER={0};"
    "DATABASE={1};"
    "HOSTNAME={2};"
    "PORT={3};"
    "PROTOCOL={4};"
    "UID={5};"
    "PWD={6};"
    "SECURITY={7};"
).format(dsn_driver, dsn_database, dsn_hostname, dsn_port, dsn_protocol, dsn_uid , dsn_pwd, dsn_security)

try:
    conn = ibm_db.connect(dsn, "", "")
    print("Connected to database: ", dsn_database, "as user: ", dsn_uid, "on host: ", dsn_hostname)
except:
    print("Unable to connect: ", ibm_db.conn_errormsg())

# createQuery = "create view EMPSALARY as select EMP_ID, F_NAME, L_NAME, B_DATE, SEX, SALARY from EMPLOYEES"
# createStmt = ibm_db.exec_immediate(conn, createQuery)

# selectQuery = "select * from EMPSALARY"

# selectStmt = ibm_db.exec_immediate(conn, selectQuery)

# print(ibm_db.fetch_both(selectStmt))

createQuery = "create or replace view EMPSALARY as select EMP_ID, F_NAME, L_NAME, B_DATE, SEX, JOB_TITLE, MIN_SALARY, MAX_SALARY from EMPLOYEES, JOBS where EMPLOYEES.JOB_ID = JOBS.JOB_IDENT"
createStmt = ibm_db.exec_immediate(conn, createQuery)

selectQuery = "select * from EMPSALARY"

selectStmt = ibm_db.exec_immediate(conn, selectQuery)

print(ibm_db.fetch_both(selectStmt))

dropViewQuery = "drop view EMPSALARY"
dropViewStmt = ibm_db.exec_immediate(conn, dropViewQuery)

selectQuery = "select * from EMPSALARY"

selectStmt = ibm_db.exec_immediate(conn, selectQuery)

print(ibm_db.fetch_both(selectStmt))


import cv2
import numpy as np

if __name__ == "__main__":
    filename = "" # Load image
    img = cv2.imread(filename, cv2.IMREAD_COLOR) # Load color image

    # Create line
    cv2.line(img, (60,60), (105, 105), (255, 0, 255), 12)

    # Create rectangle
    cv2.rectangle(img, (45, 45), (175, 175), (0, 255, 0), 4)

    # Create circle
    cv2.circle(img, (105, 105), 55, (0, 0, 255),-1)

    # Create points for polygon
    pts = np.array([[10,5], [45, 84], [120, 145], [15, 125]], np.int32)
    cv2.polylines(img, [pts], True, (0, 255, 255), 3) # True means connect first and last points

    # Create text
    font = cv2.FONT_HERSHEY_SIMPLEX
    cv2.putText(img, "OpenCV", (0, 120), font, 1, (0, 0, 0), 2, cv2.LINE_AA)

    cv2.imshow("Image with drawing", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


from datetime import date

DOCUMENTS = {
    "2013gradBSC": {
        "title": "Ising-Ferromagnet auf Ad-HocNetzwerken",
        "short": "BSc",
        "pdf": "bachelorThesis.pdf",
        "type": "thesis",
        "date": date(2013, 9, 5),
    },
    "2014confDPG": {
        "title": "Ising-Ferromagnet on Proximity Graphs",
        "short": "DPG14",
        "pdf": "2014DPG.pdf",
        "contribution": "DY 41.46",
        "type": "poster",
        "date": date(2014, 4, 3),
    },
    "2015sschoolMCS": {
        "title": "Phase Transitions of Disordered Travelling Salesperson Problems solved with Linear Programming",
        "short": "MCS",
        "pdf": "2015MCS.pdf",
        "type": "poster",
        "date": date(2015, 9, 21),
    },
    "2015gradMSC": {
        "title": "Phase Transitions of Disordered Travelling Salesperson Problems solved with Linear Programming and Cutting Planes",
        "short": "MSc",
        "pdf": "masterThesis.pdf",
        "type": "thesis",
        "date": date(2015, 11, 6),
    },
    "2016confDPG": {
        "title": "Phase Transitions of Disordered Travelling Salesperson Problems solved with Linear Programming and Cutting Planes",
        "short": "DPG16",
        "pdf": "2016DPG.pdf",
        "contribution": "DY 44.7",
        "type": "talk",
        "date": date(2016, 3, 9),
    },
    "GL2016TSP": {
        "title": "Linear Programming by Example: The Travelling Salesperson Problem",
        "short": "GL2016TSP",
        "pdf": "Lecture2016_TSPbyExample.pdf",
        "type": "talk",
        "date": date(2016, 11, 11),
    },
    "2016CompPhys": {
        "title": "Convex Hulls of Self-Avoiding Random Walks: A Large-Deviation Study",
        "short": "CompPhys14",
        "pdf": "2016CompPhys.pdf",
        "type": "poster",
        "date": date(2016, 11, 25),
    },
    "2017confDPG_saw": {
        "title": "Convex Hulls of Self-Avoiding Random Walks: A Large-Deviation Study",
        "short": "DPG17",
        "pdf": "2017DPG.pdf",
        "contribution": "DY 60.1",
        "type": "poster",
        "date": date(2017, 3, 23),
    },
    "2017confDPG_high": {
        "title": "Convex Hulls of Random Walks in High Dimensions: A Large-Deviation Study",
        "short": "DPG17",
        "link": "https://dpg2017.schawe.me/",
        "contribution": "DY 18.1",
        "type": "talk",
        "date": date(2017, 3, 21),
    },
    "2017confCompPhys": {
        "title": "Linear Programming and Cutting Planes for Ground States and Excited States of the Traveling Salesperson Problem",
        "short": "CompPhys17",
        "pdf": "2017CompPhys.pdf",
        "type": "talk",
        "date": date(2017, 11, 30),
    },
    "2018confDPG": {
        "title": "Linear Programming and Cutting Planes for Ground States and Excited States of the Traveling Salesperson Problem",
        "short": "DPG18",
        "pdf": "2018DPG.pdf",
        "contribution": "DY 10.6",
        "type": "talk",
        "date": date(2018, 3, 12),
    },
    "2018confCCP": {
        "title": "Large Deviations of Convex Hulls of Self-Avoiding Random Walks",
        "short": "CCP18",
        "pdf": "2018CCP.pdf",
        "contribution": "115",
        "type": "talk",
        "date": date(2018, 8, 2),
    },
    "2019confDPG": {
        "title": "Ground-state energy distribution of noninteracting fermions with a random energy spectrum",
        "short": "DPG19",
        "pdf": "2019DPG.pdf",
        "contribution": "DY 21.1",
        "type": "talk",
        "date": date(2019, 4, 2),
    },
    "2019gradPHD_thesis": {
        "title": "Large Deviations of Convex Hulls of Random Walks and Other Stochastic Models",
        "short": "PhD",
        "pdf": "dissertation.pdf",
        "type": "thesis",
        "doi": "10.5281/zenodo.3377931",
        "date": date(2019, 3, 19),
    },
    "2019gradPHD_defense": {
        "title": "Large Deviations of Convex Hulls of Random Walks and Other Stochastic Models",
        "short": "PhD",
        "pdf": "disputation.pdf",
        "type": "talk",
        "date": date(2019, 3, 19),
    },
    "2020confR4": {
        # https://diggingintodata.org/awards/news/round-4-conference-2020
        "title": "Understanding opinion and language dynamics using massive data",
        "short": "R4",
        "pdf": "2020R4.pdf",
        "type": "poster",
        "date": date(2020, 1, 31),
    },
    "2020confDPG_hk": {
        "title": "Surprising Effects of Inhomogeneity on Opinion Dynamics",
        "short": "DPG20",
        "pdf": "2020DPG_hk.pdf",
        "contribution": "SOE 13.7",
        "type": "talk",
        "date": date(2020, 3, 19),
    },
    "2020confDPG_lis": {
        "title": "The entropy of the longest increasing subsequences: typical and extreme sequences",
        "short": "DPG20",
        "pdf": "2020DPG_lis.pdf",
        "contribution": "DY 40.4",
        "type": "talk",
        "date": date(2020, 3, 18),
    },
    "2020supp1SciRep_hk": {
        "title": "SI 1",
        "short": "hk_si1",
        "link": "https://github.com/surt91/hk_tree",
        "type": "code",
        "date": date(2020, 5, 19),
    },
    "2020supp2SciRep_hk": {
        "title": "SI 2",
        "short": "hk_si2",
        "pdf": "2020supp2SciRep_hk.pdf",
        "type": "text",
        "date": date(2020, 5, 19),
    },
    "2020confIC2S2_video": {
        "title": "When open mindedness hinders consensus",
        "short": "IC2S2",
        "link": "https://youtu.be/_oSSz4olovE",
        "type": "video",
        "date": date(2020, 7, 19),
    },
    "2020confIC2S2_poster": {
        "title": "When open mindedness hinders consensus",
        "short": "IC2S2",
        "pdf": "2020IC2S2_hk.pdf",
        "type": "poster",
        "date": date(2020, 7, 19),
    },
    "2020confCSW_video": {
        "title": "Collective effects of the cost of opinion change",
        "short": "CSW",
        "link": "https://www.youtube.com/watch?v=O6J9gkqqdAg&t=2760s",
        "type": "video",
        "date": date(2020, 7, 9),
    },
    "2020confCompPhys": {
        "title": "Collective effects of the cost of opinion change",
        "short": "CompPhys17",
        "pdf": "2020CompPhys.pdf",
        "type": "talk",
        "date": date(2020, 12, 3),
    },
    "2021suppHKdata": {
        "title": "Cluster configurations of the Hegselmann-Krause model on network ensembles",
        "short": "HKdata",
        "link": "https://doi.org/10.5281/zenodo.4288672",
        "type": "data",
        "date": date(2021, 5, 13),
    },
    "2021suppDWdata": {
        "title": "Cluster configurations of the Deffuant model on network ensembles",
        "short": "DWdata",
        "link": "https://doi.org/10.5281/zenodo.4701047",
        "type": "data",
        "date": date(2021, 5, 13),
    },
    "2021suppPRR_hknet_lat3": {
        "title": "SM 1",
        "description": "Video of the evolution of a Hegselmann-Krause model on a square lattice",
        "short": "lat3",
        "link": "https://data.schawe.me/lat3_eps015.mp4",
        "type": "video",
        "date": date(2021, 6, 14),
    },
    "2021suppPRR_hknet_lat4": {
        "title": "SM 2",
        "description": "Video of the evolution of a Hegselmann-Krause model on a square lattice",
        "short": "lat4",
        "link": "https://data.schawe.me/lat4_eps015.mp4",
        "type": "video",
        "date": date(2021, 6, 14),
    },
    "2021suppPRR_hknet_ba10": {
        "title": "SM 3",
        "description": "Video of the evolution of a Hegselmann-Krause model on a Barabási Albert Graph",
        "short": "ba10",
        "link": "https://data.schawe.me/ba10_eps015.mp4",
        "type": "video",
        "date": date(2021, 6, 14),
    },
    "2021confNetworks_video": {
        "title": "The Bridges to consensus -- Bounded confidence models in networked societies",
        "short": "Networks2021",
        "link": "https://youtu.be/FYlRGbq-rIA",
        "type": "video",
        "date": date(2021, 7, 7),
    },
    "2021confNetworks_slides": {
        "title": "The Bridges to consensus -- Bounded confidence models in networked societies",
        "short": "Networks2021",
        "pdf": "2021_networks_hknet.pdf",
        "type": "talk",
        "date": date(2021, 7, 7),
    },
    "2021confIC2S2_poster": {
        "title": "Information in times of COVID19: traditional media vs. online social networks",
        "short": "IC2S2",
        "pdf": "2021IC2S2_tnyt.pdf",
        "type": "poster",
        "date": date(2021, 7, 27),
    },
    "2021confSMR3624_talk": {
        "title": "Position distribution in a generalised run and tumble process",
        "short": "SMR3624",
        "link": "https://youtu.be/VTQAgXelS58?t=1731",
        "type": "talk",
        "date": date(2021, 9, 8),
    },
}


from ooflib.SWIG.common import guitop
from ooflib.SWIG.common import ooferror
from ooflib.common import debug
from ooflib.common.IO.GUI import gtklogger
from gi.repository import Gtk
from gi.repository import Pango

# A gtk.Button containing an image from the given stock item, (eg,
# gtk.STOCK_OK) and optional text.  If 'reverse' is true, the text
# will precede the image.

# For gtk3, stock_id is the name of a named icon. The possible names
# can be found with
#  it = Gtk.IconTheme()
#  it.list_icons()
# The button text needs to be provided with labelstr, if desired.
# gtk2 provided it automatically.

## TODO?: Many of the icons come in two flavors, "xxx" and
## "xxx-symbolic".  We could make using the symbolic versions an
## option. StockButton could check for the existence of the preferred
## version and fall back to the other version if the preferred one was
## not available.  Then we could delete the "-symbolic" everywhere
## that we spell it out in the code.

class StockButton(Gtk.Button):
    def __init__(self, icon_name, labelstr=None, reverse=False, markup=False,
                 align=None, **kwargs):
        assert isinstance(align, (type(None), Gtk.Align))
        debug.mainthreadTest()
        if debug.debug():
            it = Gtk.IconTheme()
            if not icon_name in it.list_icons():
                raise ooferror.ErrPyProgrammingError(
                    "Bad icon name: " + icon_name)

        if align is None:
            align = Gtk.Align.CENTER
        Gtk.Button.__init__(self, **kwargs)
        image = Gtk.Image.new_from_icon_name(icon_name, Gtk.IconSize.BUTTON)
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        self.markup = markup
        self.reverse = reverse
        if reverse:
            if labelstr:
                if markup:
                    self.label = Gtk.Label(halign=align)
                    self.label.set_markup(labelstr + ' ')
                else:
                    self.label = Gtk.Label(labelstr + ' ')
                hbox.pack_start(self.label, expand=True, fill=True, padding=0)
            hbox.pack_start(image, expand=False, fill=False, padding=0)
        else:                       # not reverse
            hbox.pack_start(image, expand=False, fill=False, padding=0)
            if labelstr:
                if markup:
                    self.label = Gtk.Label(halign=align)
                    self.label.set_markup(' ' + labelstr)
                else:
                    self.label = Gtk.Label(' ' + labelstr)
                hbox.pack_start(self.label, expand=True, fill=True, padding=0)
        self.add(hbox)

    def relabel(self, labelstr):
        if self.markup:
            if self.reverse:
                self.label.set_markup(labelstr + ' ')
            else:
                self.label.set_markup(' ' + labelstr)
        else:
            if self.reverse:
                self.label.set_text(labelstr + ' ')
            else:
                self.label.set_text(' ' + labelstr)

def prevButton(**kwargs):
    debug.mainthreadTest()
    button = StockButton('go-previous-symbolic', 'Prev', **kwargs)
    gtklogger.setWidgetName(button, "Prev")
    return button

def nextButton(**kwargs):
    debug.mainthreadTest()
    button = StockButton('go-next-symbolic', 'Next', reverse=True, **kwargs)
    gtklogger.setWidgetName(button, "Next")
    return button

#####################

# Find and return a gtk widget of type 'widgetclass' in the widget
# hierarchy rooted at 'root' (which must be a gtk widget).

def findChild(widgetclass, root):
    debug.mainthreadTest()
    if isinstance(root, Gtk.Container):
        for child in root.get_children():
            if isinstance(child, widgetclass):
                return child
            descendant = findChild(widgetclass, child)
            if descendant:
                return descendant

# findChildren is just like findChild, but it returns all matching
# child widgets.

def findChildren(widgetclasses, root):
    debug.mainthreadTest()
    kids = []
    if isinstance(root, Gtk.Container):
        for child in root.get_children():
            for widgetclass in widgetclasses:
                if isinstance(child, widgetclass):
                    kids.append(child)
                    break
            kids.extend(findChildren(widgetclasses, child))
    return kids

########################

# extra space around Paned handles because they're not visible enough
handle_padding = 5

########################

# Global CSS styles.

# addStyle might be called before the GUI is started, before the
# styles can be applied.  So it stores the styles that have been
# assigned too early and oofGUI.__init__ applies them after the main
# window has been created.

# See https://developer.gnome.org/gtk3/stable/chap-css-overview.html

styleStrings = []

def addStyle(stylestring):
    if not guitop.top():
        styleStrings.append(stylestring)
    else:
        guitop.top().addStyle(stylestring)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import messages
from django.shortcuts import render, HttpResponse, redirect
from .models import Course
# Create your views here.
def index(request):
    return render(request, "signup/index.html")

def courses(request):
    context = {
        "all_courses" : Course.objects.all(),
    }
    return render(request, "signup/index.html", context)

def add(request):
    validations = Course.objects.basic_validator(request.POST)
    if len(validations) == 0:
        Course.objects.create(
            name = request.POST['name'],
            desc = request.POST['desc'],
        )
        return redirect('/courses')
    else:
        for error in validations:
            messages.add_message(request, messages.INFO, error)
        return redirect('/')

def destroy(request, id):
    context = {
        "course" : Course.objects.get(id=id)

    }

    return render (request, "signup/destroy.html", context)

def no(request):
    return redirect ('/courses')

def yes(request, id):
    course = Course.objects.get(id=id)
    course.delete()

    return redirect ("/courses")


"""
UNDER DEVELOPMENT
This script allows you to control the ant using voice commands.
It listens for the wake word and awaits a command.
"""

import pyttsx3
import speech_recognition as sr
from ax12.movement import flip, rotate, walk, sit, stand, connect

WAKE = "tiger"

def speak(text):
    engine = pyttsx3.init()
    engine.say(text)
    engine.runAndWait()

def get_audio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source, duration=0.2)
        audio = r.listen(source)
        said = ""

        try:
            said = r.recognize_sphinx(audio)
            print(said)
        except Exception as e:
            print("Exception: " + str(e))

    return said.lower()

def main():

    servos = connect()

    while True:
        print("\nSay 'tiger' to wake . . .")
        text = get_audio()

        if text.count(WAKE) > 0:
            speak("hello")
            text = get_audio()
            print("COMMAND:", text)

            FLIP_STRS = ["flip", "show us a flip"]
            for phrase in FLIP_STRS:
                if phrase in text:
                    speak("sure")
                    flip(servos)

            LEFT_STRS = ["rotate to left", "rotate to the left",
                         "spin to the left", "spin left"]
            for phrase in LEFT_STRS:
                if phrase in text:
                    speak("yes sir")
                    rotate(servos, "CCW")

            RIGHT_STRS = ["rotate to right", "rotate to the right",
                          "spin to the right", "spin right"]
            for phrase in RIGHT_STRS:
                if phrase in text:
                    speak("spinning to the right now")
                    rotate(servos, "CW")

            ROTATE_STRS = ["rotate", "spin"]
            for phrase in ROTATE_STRS:
                if phrase in text:
                    speak("left or right")
                    text = get_audio()

                    LEFT_STRS = ["left"]
                    for phrase in LEFT_STRS:
                        if phrase in text:
                            speak("copy that")
                            rotate(servos, "CCW")

                    RIGHT_STRS = ["right"]
                    for phrase in RIGHT_STRS:
                        if phrase in text:
                            speak("spinning to right now")
                            rotate(servos, "CW")

            WALK_STRS = ["walk", "go"]
            for phrase in WALK_STRS:
                if phrase in text:
                    speak("here i go")
                    walk(servos)

            SIT_STRS = ["sit", "sit down"]
            for phrase in SIT_STRS:
                if phrase in text:
                    speak("okay")
                    sit(servos)

            STAND_STRS = ["stand", "stand up"]
            for phrase in STAND_STRS:
                if phrase in text:
                    speak("okay")
                    stand(servos)

if __name__ == "__main__":
    main()