import requests
from bs4 import BeautifulSoup

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
import django
django.setup()

from seoilNotice.models import SeoilNotice, EventInfo, BachelorNotice

# title경로 #contents > div > div.clearfix.con_wrap > div > table > tbody > tr:nth-child(1) > td.al > a > p
# date경로 #contents > div > div.clearfix.con_wrap > div > table > tbody > tr:nth-child(1) > td.al > a > time
# title = soup.find("td", {"class":"al"}).find("p").text

# title = soup.find_all("td", {"class": "al"})
# s = title[1]
# a.get_text(strip=True),

# semi_title1 = soup.find("td",{'class':'al'}).find('a').find('p').get_text(strip=True)
# semi_title2 = semi_title.find('a')
# html = requests.get("http://hm.seoil.ac.kr/65/76?page=1")

def seoil_notice(url, lastPage):
    result = []
    for page in range(lastPage):
        html = requests.get(f"{url}{page+1}")         #f-string
        soup = BeautifulSoup(html.text, 'html.parser')
        semi_title = soup.select('table > tbody > tr > td.al > a > p')
        date = soup.select('table > tbody > tr > td.al > a > time')
        links = soup.find_all('td', {"class": "al"})

        title_list = []

        '''title_dict = {}

        for t, d, l in semi_title, date, links:
            title_dict = {'title': t, 'date': d, 'links': l}'''

        for a in zip(semi_title, date, links):
            title_list.append(
                {
                    'title': a[0].get_text(strip=True),
                    'date': a[1].get_text(strip=True),
                    'link': "http://hm.seoil.ac.kr"+a[2].find("a").get('href'),
                }
            )

        for i in title_list:
            result.append(i)
    #title_dict = dict(title_list)

    #for i in title_list.items():
    #print(title_list[0]['title'], title_list[0]['date'], title_list[0]['link'])
    #print(title_list[9])
    return result

#seoil_notice("http://hm.seoil.ac.kr/65/76?page=", 10)

# https://armontad-1202.tistory.com/entry/%ED%81%AC%EB%A1%A4%EB%A7%81-%ED%81%AC%EB%A1%A4%EB%A7%81-%ED%95%9C-%EB%8D%B0%EC%9D%B4%ED%84%B0-Django-DB%EC%97%90-%EB%84%A3%EA%B8%B0
# https://hashcode.co.kr/questions/4802/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EC%86%8D-%EB%94%95%EC%85%94%EB%84%88%EB%A6%AC-%ED%98%95%ED%83%9C%EC%97%90-%EC%9A%94%EC%86%8C%EC%97%90%EC%84%9C-%EC%9B%90%ED%95%98%EB%8A%94-%EB%B0%B8%EB%A5%98-%EA%B0%92-%EC%B0%BE%EA%B8%B0
# 이 명령어는 이 파일이 import가 아닌 python에서 직접 실행할 경우에만 아래 코드가 동작하도록 합니다.
#title_list len == 20
if __name__ == '__main__':
    seoil_notice_list = seoil_notice("http://hm.seoil.ac.kr/65/76?page=", 1)
    seoil_event_list = seoil_notice("http://hm.seoil.ac.kr/65/69?page=", 1)
    seoil_bachelor_list = seoil_notice("http://hm.seoil.ac.kr/65/77?page=", 1)
    for i in seoil_notice_list:
        SeoilNotice(title=i['title'], date=i['date'], url=i['link']).save()

    for j in seoil_event_list:
        EventInfo(title=j['title'], date=j['date'], url=j['link']).save()

    for k in seoil_bachelor_list:
        BachelorNotice(title=k['title'], date=k['date'], url=k['link']).save()


from typing import Tuple

import hypothesis.extra.numpy as hnp
import hypothesis.strategies as st
import numpy as np
import pytest
from hypothesis import example, given, settings
from numpy.testing import assert_allclose

from mygrad import mem_guard_off, no_autodiff
from mygrad.math.misc.funcs import matmul
from mygrad.nnet.activations import sigmoid, tanh
from mygrad.tensor_base import Tensor
from tests.utils.errors import does_not_raise

gru_module = pytest.importorskip("mygrad.nnet.layers.gru")
gru = gru_module.gru

@settings(deadline=None)
@example(s0=np.array([[0.0, 0.0]]), dropout=0.0, out_constant=False)
@given(
    s0=st.none()
    | hnp.arrays(shape=(1, 2), dtype=float, elements=st.just(0))
    | hnp.arrays(shape=(1, 2), dtype=float, elements=st.just(0)).map(
        lambda x: Tensor(x)
    )
    | hnp.arrays(shape=(1, 2), dtype=float, elements=st.just(0)).map(
        lambda x: Tensor(x, constant=True)
    ),
    dropout=st.floats(0, 1, exclude_max=True),
    out_constant=st.booleans(),
)
@mem_guard_off
def test_nonconstant_s0_raises(s0, dropout: float, out_constant: bool):
    T, N, C, D = 5, 1, 3, 2
    X = Tensor(np.random.rand(T, N, C))
    Wz, Wr, Wh = Tensor(np.random.rand(3, D, D))
    Uz, Ur, Uh = Tensor(np.random.rand(3, C, D))
    bz, br, bh = Tensor(np.random.rand(3, D))

    with does_not_raise() if (
        out_constant or s0 is None or isinstance(s0, np.ndarray) or s0.constant
    ) else pytest.raises(ValueError):
        gru(
            X,
            Uz,
            Wz,
            bz,
            Ur,
            Wr,
            br,
            Uh,
            Wh,
            bh,
            s0=s0,
            dropout=dropout,
            constant=out_constant,
        )

@settings(deadline=None)
@given(out_constant=st.booleans())
@mem_guard_off
def test_all_constant(out_constant: bool):
    T, N, C, D = 5, 1, 3, 2
    X = Tensor(np.random.rand(T, N, C), constant=True)
    Wz, Wr, Wh = Tensor(np.random.rand(3, D, D), constant=True)
    Uz, Ur, Uh = Tensor(np.random.rand(3, C, D), constant=True)
    bz, br, bh = Tensor(np.random.rand(3, D), constant=True)

    gru(X, Uz, Wz, bz, Ur, Wr, br, Uh, Wh, bh, constant=out_constant).backward()

    assert X.grad is None

    assert Wz.grad is None
    assert Wr.grad is None
    assert Wh.grad is None

    assert Uz.grad is None
    assert Ur.grad is None
    assert Uh.grad is None

    assert bz.grad is None
    assert br.grad is None
    assert bh.grad is None

@settings(deadline=None)
@given(
    X=hnp.arrays(
        shape=hnp.array_shapes(max_side=5, min_dims=3, max_dims=3),
        dtype=float,
        elements=st.floats(-10, 10),
    ),
    D=st.sampled_from(list(range(1, 5))),
    dropout=st.sampled_from([0, 0.45]),
    dtypes=st.tuples(*[hnp.floating_dtypes(endianness="=", sizes=(32, 64))] * 4),
    data=st.data(),
)
@pytest.mark.filterwarnings("ignore: overflow encountered in exp")
@pytest.mark.filterwarnings("ignore: overflow encountered in sig")
@mem_guard_off
def test_gru_fwd(X, D, dropout, dtypes, data: st.DataObject):
    T, N, C = X.shape

    Wz, Wr, Wh = data.draw(
        hnp.arrays(
            shape=(3, D, D),
            dtype=dtypes[0],
            elements=st.floats(-10.0, 10.0, width=dtypes[0].itemsize * 8),
        ),
        label="Wz, Wr, Wh",
    )

    Uz, Ur, Uh = data.draw(
        hnp.arrays(
            shape=(3, C, D),
            dtype=dtypes[1],
            elements=st.floats(-10.0, 10.0, width=dtypes[1].itemsize * 8),
        ),
        label="Uz, Ur, Uh",
    )

    bz, br, bh = data.draw(
        hnp.arrays(
            shape=(3, D),
            dtype=dtypes[2],
            elements=st.floats(-10.0, 10.0, width=dtypes[2].itemsize * 8),
        ),
        label="bz, br, bh",
    )

    V = data.draw(
        hnp.arrays(shape=(D, C), dtype=float, elements=st.floats(-10.0, 10.0)),
        label="V",
    )

    s0 = np.zeros((N, D), dtype=dtypes[3])

    X = Tensor(X)
    X2 = X.__copy__()

    Wz = Tensor(Wz)
    Wz2 = Wz.__copy__()

    Uz = Tensor(Uz)
    Uz2 = Uz.__copy__()

    bz = Tensor(bz)
    bz2 = bz.__copy__()

    Wr = Tensor(Wr)
    Wr2 = Wr.__copy__()

    Ur = Tensor(Ur)
    Ur2 = Ur.__copy__()

    br = Tensor(br)
    br2 = br.__copy__()

    Wh = Tensor(Wh)
    Wh2 = Wh.__copy__()

    Uh = Tensor(Uh)
    Uh2 = Uh.__copy__()

    bh = Tensor(bh)
    bh2 = bh.__copy__()

    V = Tensor(V)
    V2 = V.__copy__()

    s0 = Tensor(s0)
    s2 = s0.__copy__()

    s = gru(X, Uz, Wz, bz, Ur, Wr, br, Uh, Wh, bh, dropout=dropout, constant=True)
    o = matmul(s[1:], V)
    ls = o.sum()

    assert s.constant is True

    if dropout:
        for d in [
            s.creator._dropUr,
            s.creator._dropUz,
            s.creator._dropUh,
            s.creator._dropWr,
            s.creator._dropWz,
            s.creator._dropWh,
        ]:
            assert np.all(np.logical_or(d == 1 / (1 - dropout), d == 0))

    stt = s2
    all_s = [s0.data]
    ls2 = 0
    if dropout:
        Wz2d = s.creator._dropWz * Wz2
        Wr2d = s.creator._dropWr * Wr2
        Wh2d = s.creator._dropWh * Wh2
    else:
        Wz2d = Wz2
        Wr2d = Wr2
        Wh2d = Wh2

    with no_autodiff:
        for n, x in enumerate(X2):
            if not dropout:
                z = sigmoid(matmul(x, Uz2) + matmul(stt, Wz2d) + bz2)
                r = sigmoid(matmul(x, Ur2) + matmul(stt, Wr2d) + br2)
                h = tanh(matmul(x, Uh2) + matmul((r * stt), Wh2d) + bh2)
            else:
                z = sigmoid(
                    (s.creator._dropUz[0] * matmul(x, Uz2)) + matmul(stt, Wz2d) + bz2
                )
                r = sigmoid(
                    (s.creator._dropUr[0] * matmul(x, Ur2)) + matmul(stt, Wr2d) + br2
                )
                h = tanh(
                    (s.creator._dropUh[0] * matmul(x, Uh2))
                    + matmul((r * stt), Wh2d)
                    + bh2
                )

            stt = (1 - z) * h + z * stt
            all_s.append(stt)
            o = matmul(stt, V2)
            ls2 += o.sum()

    tolerances = dict(atol=1e-5, rtol=1e-5)
    rec_s_dat = np.stack([i.data for i in all_s])

    assert_allclose(ls.data, ls2.data, **tolerances)

    assert_allclose(rec_s_dat, s.data, **tolerances)

    assert_allclose(Wz.data, Wz2.data, **tolerances)
    assert_allclose(Wr.data, Wr2.data, **tolerances)
    assert_allclose(Wh.data, Wh2.data, **tolerances)

    assert_allclose(Uz.data, Uz2.data, **tolerances)
    assert_allclose(Ur.data, Ur2.data, **tolerances)
    assert_allclose(Uh.data, Uh2.data, **tolerances)

    assert_allclose(bz.data, bz2.data, **tolerances)
    assert_allclose(br.data, br2.data, **tolerances)
    assert_allclose(bh.data, bh2.data, **tolerances)

    assert_allclose(V.data, V2.data, **tolerances)

    assert_allclose(X.data, X2.data, **tolerances)

    ls.clear_graph()
    ls2.clear_graph()

    for x in [s, Wz, Wr, Wh, bz, br, bh, X, Uz, Ur, Uh, V]:
        assert not x._ops

# There is an occasional overflow in the oracle sigmoid
# that is acceptable - reducing the input domain to ameliorate this
# would potentially mask real numerical issues
@settings(deadline=None)
@given(
    data=st.data(),
    X=hnp.arrays(
        shape=hnp.array_shapes(max_side=5, min_dims=3, max_dims=3),
        dtype=float,
        elements=st.floats(-10, 10),
    ),
    D=st.sampled_from(list(range(1, 5))),
    bp_lim=st.booleans(),
    dropout=st.sampled_from([0, 0.45]),
    U_constants=st.tuples(*[st.booleans()] * 3),
    W_constants=st.tuples(*[st.booleans()] * 3),
    b_constants=st.tuples(*[st.booleans()] * 3),
    X_constant=st.booleans(),
    V_constant=st.booleans(),
    dtypes=st.tuples(*[hnp.floating_dtypes(endianness="=", sizes=(32, 64))] * 4),
)
@pytest.mark.filterwarnings("ignore: overflow encountered in exp")
@pytest.mark.filterwarnings("ignore: overflow encountered in sig")
def test_gru_backward(
    data: st.DataObject,
    X: np.ndarray,
    D: int,
    bp_lim: bool,
    dropout: bool,
    U_constants: Tuple[bool, bool, bool],
    W_constants: Tuple[bool, bool, bool],
    b_constants: Tuple[bool, bool, bool],
    X_constant: bool,
    V_constant: bool,
    dtypes: Tuple[int, int, int, int],
):
    tolerances = dict(atol=1e-5, rtol=1e-5)
    T, N, C = X.shape

    Wz, Wr, Wh = data.draw(
        hnp.arrays(
            shape=(3, D, D),
            dtype=dtypes[0],
            elements=st.floats(-10.0, 10.0, width=dtypes[0].itemsize * 8),
        ),
        label="Wz, Wr, Wh",
    )

    Uz, Ur, Uh = data.draw(
        hnp.arrays(
            shape=(3, C, D),
            dtype=dtypes[1],
            elements=st.floats(-10.0, 10.0, width=dtypes[1].itemsize * 8),
        ),
        label="Uz, Ur, Uh",
    )

    bz, br, bh = data.draw(
        hnp.arrays(
            shape=(3, D),
            dtype=dtypes[2],
            elements=st.floats(-10.0, 10.0, width=dtypes[2].itemsize * 8),
        ),
        label="bz, br, bh",
    )

    V = data.draw(
        hnp.arrays(shape=(D, C), dtype=float, elements=st.floats(-10.0, 10.0)),
        label="V",
    )

    s0 = np.zeros((N, D), dtype=dtypes[3])

    X = Tensor(X, constant=X_constant)
    X2 = X.__copy__()

    Wz = Tensor(Wz, constant=W_constants[0])
    Wz2 = Wz.__copy__()

    Uz = Tensor(Uz, constant=U_constants[0])
    Uz2 = Uz.__copy__()

    bz = Tensor(bz, constant=b_constants[0])
    bz2 = bz.__copy__()

    Wr = Tensor(Wr, constant=W_constants[1])
    Wr2 = Wr.__copy__()

    Ur = Tensor(Ur, constant=U_constants[1])
    Ur2 = Ur.__copy__()

    br = Tensor(br, constant=b_constants[1])
    br2 = br.__copy__()

    Wh = Tensor(Wh, constant=W_constants[2])
    Wh2 = Wh.__copy__()

    Uh = Tensor(Uh, constant=U_constants[2])
    Uh2 = Uh.__copy__()

    bh = Tensor(bh, constant=b_constants[2])
    bh2 = bh.__copy__()

    V = Tensor(V, constant=V_constant)
    V2 = V.__copy__()

    s0 = Tensor(s0)
    s2 = s0.__copy__()

    # bp_lim = len(X) - 1 should behave the same as no bp-lim
    s = gru(
        X,
        Uz,
        Wz,
        bz,
        Ur,
        Wr,
        br,
        Uh,
        Wh,
        bh,
        dropout=dropout,
        constant=False,
        bp_lim=len(X) - 1 if bp_lim else None,
    )
    o = matmul(s[1:], V)
    ls = o.sum()

    stt = s2
    all_s = [s0.data]
    ls2 = 0
    if dropout:
        Wz2d = s.creator._dropWz * Wz2
        Wr2d = s.creator._dropWr * Wr2
        Wh2d = s.creator._dropWh * Wh2
    else:
        Wz2d = Wz2
        Wr2d = Wr2
        Wh2d = Wh2
    for n, x in enumerate(X2):
        if not dropout:
            z = sigmoid(matmul(x, Uz2) + matmul(stt, Wz2d) + bz2)
            r = sigmoid(matmul(x, Ur2) + matmul(stt, Wr2d) + br2)
            h = tanh(matmul(x, Uh2) + matmul((r * stt), Wh2d) + bh2)
        else:
            z = sigmoid(
                (s.creator._dropUz[0] * matmul(x, Uz2)) + matmul(stt, Wz2d) + bz2
            )
            r = sigmoid(
                (s.creator._dropUr[0] * matmul(x, Ur2)) + matmul(stt, Wr2d) + br2
            )
            h = tanh(
                (s.creator._dropUh[0] * matmul(x, Uh2)) + matmul((r * stt), Wh2d) + bh2
            )
        stt = (1 - z) * h + z * stt
        all_s.append(stt)
        o = matmul(stt, V2)
        ls2 += o.sum()

    ls.backward()
    ls2.backward()

    rec_s_grad = np.stack([i.grad for i in all_s[1:]])

    if not s.constant:
        assert_allclose(rec_s_grad, s.grad, **tolerances)
    else:
        assert s.grad is None

    if not Wz.constant:
        assert_allclose(Wz.grad, Wz2.grad, **tolerances)
    else:
        assert Wz.grad is None

    if not Wr.constant:
        assert_allclose(Wr.grad, Wr2.grad, **tolerances)
    else:
        assert Wr.grad is None

    if not Wh.constant:
        assert_allclose(Wh.grad, Wh2.grad, **tolerances)
    else:
        assert Wh.grad is None

    if not Uz.constant:
        assert_allclose(Uz.grad, Uz2.grad, **tolerances)
    else:
        assert Uz.grad is None

    if not Ur.constant:
        assert_allclose(Ur.grad, Ur2.grad, **tolerances)
    else:
        assert Ur.grad is None

    if not Uh.constant:
        assert_allclose(Uh.grad, Uh2.grad, **tolerances)
    else:
        assert Uh.grad is None

    if not bz.constant:
        assert_allclose(bz.grad, bz2.grad, **tolerances)
    else:
        assert bz.grad is None

    if not br.constant:
        assert_allclose(br.grad, br2.grad, **tolerances)
    else:
        assert br.grad is None

    if not bh.constant:
        assert_allclose(bh.grad, bh2.grad, **tolerances)
    else:
        assert bh.grad is None

    if not V.constant:
        assert_allclose(V.grad, V2.grad, **tolerances)
    else:
        assert V.grad is None

    if not X.constant:
        assert_allclose(X.grad, X2.grad, **tolerances)
    else:
        assert X.grad is None

    for x in [s, Wz, Wr, Wh, bz, br, bh, X, Uz, Ur, Uh, V]:
        assert not x._ops


# First we create start and end time for each event class
import pandas as pd
data = pd.read_csv("cleaned_data.csv")
res = dict()

# find start and end time of each event class
for _, row in data.iterrows():
    Project = row['Project']
    Activity = row['Activity']
    Person = row['Person']
    Date = pd.to_datetime(row['Date'], format = '%d/%m/%Y')
    Hours = row['Hours']

    if Project not in res:
        res[Project] = dict()
    if Activity not in res[Project]:
        res[Project][Activity] = dict()
    if Person not in res[Project][Activity]:
        res[Project][Activity][Person] = {'Start': '30/12/2022',
        'End': '01/01/2015','Hours': 0}
    if Date < pd.to_datetime(res[Project][Activity][Person]['Start']):
        res[Project][Activity][Person]['Start'] = Date
    if Date > pd.to_datetime(res[Project][Activity][Person]['End']):
        res[Project][Activity][Person]['End'] = Date
        res[Project][Activity][Person]['Hours'] += float(Hours)
        print('Project,Activity,Person,Start,End,Hours')

for Project in res:
    for Activity in res[Project]:
        for Person in res[Project][Activity]:
            str_ = str(Project) + ','+ str(Activity) +',' + str(Person) + ','+ \
            str(res[Project][Activity][Person]['Start']) + ',' + \
            str(res[Project][Activity][Person]['End']) +',' + \
            str(res[Project][Activity][Person]['Hours'])
            print(str_)
# ------------------ Use Excel and Power Query in the middle ------------------

# Then we add the start time and end time for each event based on the event
# classifier in the data via Excel and pivot based on the project, activity
# and person, afterwards, unpivot the table on the combination of the three
# values in Power Query. We use the unpivoted dataset to generate waiting nodes
# as follows.
# -----------------------------------------------------------------------------
import holidays # import holidays library to select waiting dates

data = pd.read_csv('unpivot.csv')
data = data.loc[data['Activity'] == 'AT1']

nl_holidays = holidays.NL()
def ho_weekends():
    for _, row in data.iterrows():
        Date = pd.to_datetime(row['Time'], format = '%Y-%m-%d')
        if Date in nl_holidays:
            print(Date)
    for _, row in data.iterrows():
        Date = pd.to_datetime(row['Time'], format = '%Y-%m-%d')
        if Date.weekday() > 4:
            print(Date)

ho_weekends()
data_normal = data.loc[-data['Date'].isin(ho_weekends)]
data_anomly = data.loc[data['Date'].isin(ho_weekends)]
data_anomly = data_anomly[data_anomly['Hours'] > 0]
data2 = pd.concat([data_normal, data_anomly]).sort_values('Date')

# select events in the interval of an event class
mask = (data2['Date'] >= data2['Start_Time']) & \
       (data['Date'] <= data2['End_Time'])
data2 = data2.loc[mask]
AT1 = data2["Activity" == "AT1"]
AT1.to_csv("AT1.csv")


from .functions import logInPavlovia, logOutPavlovia
from psychopy.localization import _translate
from psychopy.projects import pavlovia
from psychopy import prefs

import os
import wx
try:
    import wx.lib.agw.hyperlink as wxhl  # 4.0+
except ImportError:
    import wx.lib.hyperlink as wxhl # <3.0.2

resources = prefs.paths['resources']

class UserEditor(wx.Dialog):
    defStyle = wx.DEFAULT_DIALOG_STYLE #| wx.RESIZE_BORDER
    def __init__(self, parent=None, id=wx.ID_ANY, style=defStyle,
                 *args, **kwargs):

        wx.Dialog.__init__(self, parent, id,
                           *args, style=style, **kwargs)
        self.SetWindowStyle(wx.STAY_ON_TOP)  # this will be a modal dialog

        panel = wx.Panel(self, wx.ID_ANY, style=wx.TAB_TRAVERSAL)
        self.parent = parent
        pavSession = pavlovia.getCurrentSession()
        if pavSession.user:
            pavSession.gitlab.auth()
            self.user = pavSession.user
        else:
            self.user = logInPavlovia(parent=parent)
            if not self.user:
                return  # they were given a login but cancelled
        if type(self.user) != pavlovia.User:
            self.user = pavlovia.User(gitlabData=self.user)

        # create the controls
        userField = wxhl.HyperLinkCtrl(panel, id=wx.ID_ANY,
                                       label=self.user.url, URL=self.user.url)
        logoutBtn = wx.Button(panel, label="Logout")
        logoutBtn.Bind(wx.EVT_BUTTON, self.onLogout)
        nameLabel = wx.StaticText(panel, id=wx.ID_ANY, label=_translate("Full name:"))
        self.nameField = wx.StaticText(panel, wx.ID_ANY, self.user.name)
        if self.user.avatar:
            userBitmap = wx.Bitmap(self.user.avatar)
        else:
            userBitmap = wx.Bitmap(os.path.join(resources, "user128invisible.png"))
        # self.avatarBtn = wx.Button(panel, wx.ID_ANY, name="Avatar")
        # self.avatarBtn.SetBitmap(userBitmap)
        self.avatarBtn = wx.BitmapButton(panel, wx.ID_ANY,
                                         bitmap=userBitmap, name="Avatar")
        # self.avatarBtn.SetBitmap(userBitmap)

        org = self.user.organization or ""
        orgLabel = wx.StaticText(panel, wx.ID_ANY, _translate("Organization:"))
        self.orgField = wx.StaticText(panel, wx.ID_ANY, org, size=(300, -1))

        bio = self.user.bio or ""
        self.bioLabel = wx.StaticText(panel, wx.ID_ANY, _translate("Bio (250 chrs):"))
        self.bioField = wx.StaticText(panel, wx.ID_ANY, bio,
                                    style=wx.TE_MULTILINE)
        # submit/cancel
        buttonMsg = _translate("OK")
        updateBtn = wx.Button(panel, id=wx.ID_OK, label=buttonMsg)
        updateBtn.Bind(wx.EVT_BUTTON, self.submitChanges)
        # cancelBtn = wx.Button(panel, id=wx.ID_CANCEL, label=_translate("Cancel"))
        # cancelBtn.Bind(wx.EVT_BUTTON, self.onCancel)

        # layout
        userAndLogout = wx.BoxSizer(wx.VERTICAL)
        userAndLogout.Add(userField, 1, wx.ALL | wx.CENTER | wx.ALIGN_CENTER_VERTICAL, 5)
        userAndLogout.Add(logoutBtn, 0, wx.ALL | wx.CENTER | wx.ALIGN_CENTER_VERTICAL , 5)
        topRow = wx.BoxSizer(wx.HORIZONTAL)
        topRow.Add(userAndLogout, 1, wx.ALL | wx.CENTER, 5)
        topRow.Add(self.avatarBtn, 0, wx.ALL | wx.RIGHT, 5)

        fieldsSizer = wx.FlexGridSizer(cols=2, rows=5, vgap=10, hgap=10)
        fieldsSizer.AddMany([
            (nameLabel, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL),
            (self.nameField,0, wx.EXPAND),
            (orgLabel, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL),
            (self.orgField,0, wx.EXPAND),
            (self.bioLabel, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL),
            (self.bioField, 1, wx.EXPAND),
        ])

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer.Add(updateBtn, flag=wx.ALIGN_RIGHT)

        border = wx.BoxSizer(wx.VERTICAL)
        border.Add(topRow, 0, wx.ALL| wx.EXPAND, 5)
        border.Add(fieldsSizer, 1, wx.ALL | wx.EXPAND, 10)
        border.Add(btnSizer, 0, wx.ALIGN_RIGHT | wx.ALL, 5)
        panel.SetSizerAndFit(border)
        self.Fit()

    def onLogout(self, evt=None):
        logOutPavlovia(self.parent)
        self.user = None
        self.Close()

    def onCancel(self, evt=None):
        self.EndModal(wx.ID_CANCEL)

    def submitChanges(self, evt=None):
        # print("updating gitlab.pavlovia.org users from within PsychoPy not yet working")
        # isDirty = False
        # toCheck = {'name': self.nameField.GetValue,
        #            'organization': self.orgField.GetValue,
        #            'bio': self.bioField.GetValue,
        #            }
        # for field in toCheck:
        #     newVal = toCheck[field]()
        #     prev = getattr(self.user, field)
        #     if prev != newVal and not (prev is None and newVal==""):
        #         setattr(self.user, field, newVal)
        #         isDirty = True
        # if isDirty:
        #     # currently gives an error:
        #     # https://github.com/python-gitlab/python-gitlab/issues/547
        #     self.user.save()
        self.EndModal(wx.ID_OK)

    def onSetAvatar(self, event=None):
        print("Uploading a user image (avatar) from within PsychoPy is not yet supported. "
              "You can do that by going to the gitlab.pavlovia.org profile settings.")

    def onURL(self, evt):
        print(dir(evt))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date    : Feb-03-20 23:44
# @Update  : Nov-08-20 00:29
# @Update  : Mar-04-21 19:29
# @Author  : Kan HUANG (kan.huang@connect.ust.hk)

"""train_keras.py
Train models using Keras.

Model list:
- tensorflow.keras.applications.ResNet50V2
"""

import os
import argparse
from datetime import datetime
import pickle

import tensorflow as tf
from tensorflow.keras.callbacks import CSVLogger, EarlyStopping, LearningRateScheduler, ModelCheckpoint, ReduceLROnPlateau
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import BinaryCrossentropy
from tensorflow.keras.metrics import Recall, Precision, TruePositives, FalsePositives, TrueNegatives, FalseNegatives, BinaryAccuracy, AUC
from utils.dir_utils import makedir_exist_ok
from models.keras_fn.fault_resnet import lr_schedule

def training_args():
    """parse arguments
    """
    parser = argparse.ArgumentParser()

    def string2bool(string):
        """string2bool
        """
        if string not in ["False", "True"]:
            raise argparse.ArgumentTypeError(
                f"""input(={string}) NOT in ["False", "True"]!""")
        if string == "False":
            return False
        elif string == "True":
            return True

    # Training parameters
    parser.add_argument('--pretrain', type=bool, dest='pretrain',
                        action='store', default=True, help='pretrain, if true, the model will be initialized by pretrained weights.')  # 已经完成的训练数
    parser.add_argument('--start_epoch', type=int, dest='start_epoch',
                        action='store', default=0, help='start_epoch, i.e., epoches that have been trained, e.g. 80.')  # 已经完成的训练数
    parser.add_argument('--batch_size', type=int, dest='batch_size',
                        action='store', default=16, help='batch_size, e.g. 16.')  # 16 for Mac, 64, 128 for server
    parser.add_argument('--train_epochs', type=int, dest='train_epochs',
                        action='store', default=150, help='train_epochs, e.g. 150.')  # training 150 epochs to fit enough

    parser.add_argument('--if_fast_run', type=string2bool, dest='if_fast_run',
                        action='store', default=False, help='if_fast_run, if True, the model will only be trained for 3 epochs.')

    parser.add_argument('--alpha', type=float, dest='alpha',
                        action='store', default=0.99, help='alpha for focal loss if this loss is used.')

    args = parser.parse_args()
    return args

def main():
    args = training_args()

    print(f"TensorFlow version: {tf.__version__}.")  # Keras backend

    # paths
    competition_name = "dogs-vs-cats-redux-kernels-edition"
    data_dir = os.path.expanduser(
        f"~/.kaggle/competitions/{competition_name}")

    # Input parameters
    IMAGE_WIDTH = IMAGE_HEIGHT = 128
    IMAGE_SIZE = (IMAGE_WIDTH, IMAGE_HEIGHT)
    IMAGE_CHANNELS = 3
    input_shape = (IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS)
    num_classes = 2

    # Load data
    from utils.data_utils import data_generators
    train_generator, validation_generator = data_generators(
        data_dir, target_size=IMAGE_SIZE, batch_size=args.batch_size)

    # Prepare model
    model_type = "ResNet50V2"

    from tensorflow.keras.applications import ResNet50V2
    model = ResNet50V2(
        include_top=True,
        weights=None,
        input_shape=input_shape,
        classes=num_classes
    )

    metrics = [
        Recall(name='recall'),
        Precision(name='precision'),
        TruePositives(name='tp'),  # thresholds=0.5
        FalsePositives(name='fp'),
        TrueNegatives(name='tn'),
        FalseNegatives(name='fn'),
        BinaryAccuracy(name='accuracy'),
        # AUC0(name='auc_good_0'),  # 以 good 为 positive 的 AUC
        AUC(name='auc_bad_1')  # 以 bad 为 positive 的 AUC
    ]

    model.compile(loss=BinaryCrossentropy(),
                  optimizer=Adam(learning_rate=lr_schedule(
                      args.start_epoch)),
                  metrics=metrics)

    # Resume training
    # model_ckpt_file = MODEL_CKPT
    # if os.path.exists(model_ckpt_file):
    #     print("Model ckpt found! Loading...:%s" % model_ckpt_file)
    #     model.load_weights(model_ckpt_file)

    # Prepare model model saving directory.
    prefix = os.path.join(
        "~", "Documents", "DeepLearningData", competition_name)
    current_time = datetime.now().strftime("%Y%m%d-%H%M%S")  # experiment time
    subfix = os.path.join(model_type, current_time)

    ckpt_dir = os.path.expanduser(os.path.join(prefix, subfix, "ckpts"))
    log_dir = os.path.expanduser(os.path.join(prefix, subfix, "logs"))
    makedir_exist_ok(ckpt_dir)
    makedir_exist_ok(log_dir)

    model_name = "%s.start-%d-epoch-{epoch:03d}-val_loss-{val_loss:.4f}-auc_bad_1-{auc_bad_1:.4f}.h5" % (
        model_type, args.start_epoch)
    filepath = os.path.join(ckpt_dir, model_name)

    # define callbacks
    # checkpoint = ModelCheckpoint(filepath=filepath, monitor="acc",verbose=1)

    file_writer = tf.summary.create_file_writer(
        log_dir + "/metrics")  # custom scalars
    file_writer.set_as_default()

    csv_logger = CSVLogger(os.path.join(
        log_dir, "training.log.csv"), append=True)
    tensorboard_callback = tf.keras.callbacks.TensorBoard(
        log_dir, histogram_freq=1)
    lr_scheduler = LearningRateScheduler(lr_schedule, verbose=1)
    callbacks = [csv_logger, tensorboard_callback, lr_scheduler]

    # Fit model
    epochs = 3 if args.if_fast_run else args.train_epochs
    history = model.fit(
        train_generator,
        epochs=epochs,
        validation_data=validation_generator,
        callbacks=callbacks,
        initial_epoch=args.start_epoch
    )

    # Save last model ckpt
    model.save_weights(f"./{model_type}-last_ckpt.h5")

    # Save history
    with open('./history', 'wb') as pickle_file:
        pickle.dump(history.history, pickle_file)

if __name__ == "__main__":
    main()


import cv2
import numpy as np
import sys
sys.path.append("/home/fyp/darknet")
import darknet as dn
import darknet_images as dni

def depth_cone_detect(depthimg, net, name):
  image_board = depthimg
  name = [name]
  image_board, detections = dni.image_detection_(image_board, net, name, 0.5)

  return detections

def cone_detect(image, mask, net, class_colors, name):
  name = [name]
  image_for = image
  new_image = cv2.bitwise_and(image_for,image_for, mask=mask)
  image_for, detections = dni.image_detection_(new_image, net, name, class_colors, 0.5)

  return detections, new_image

# def cone_detect(detected_both, image, mask, net, class_colors, name):
#     name = [name]
#     image_for = image
#     new_image = cv2.bitwise_and(image_for,image_for, mask=mask)
#     image_for, detections = dni.image_detection_(new_image, net, name, class_colors, 0.5)
#     # detected = image_for
#     # yolo_cones_center = []
#     # for label, confidence, bbox in detections:
#     #   left, top, right, bottom = dn.bbox2points_(bbox)
#     #   area = (right-left)*(bottom-top)
#     #   if area > 600:# and confidence > 0.6:
#     #     cv2.rectangle(detected, (left, top), (right, bottom), (255,0,100), 1)
#     #     cv2.putText(detected, "{} [{:.2f}]".format(label, float(confidence)),
#     #                 (left, top - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
#     #                 (255,0,100), 2)
#     #     #draw on the resized original image
#     #     cv2.rectangle(detected_both, (left, top), (right, bottom), (255,0,100), 1)
#     #     cv2.putText(detected_both, "{} [{:.2f}]".format(label, float(confidence)),
#     #                 (left, top - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
#     #                 (255,0,100), 1)

#     #     #get the centers of the bbox
#     #     centerx = int((left + right)/2)
#     #     centery = int((top + bottom)/2)
#     #     yolo_cones_center.append([centerx,centery])
#     #     cv2.drawMarker(detected, (centerx, centery), class_colors, cv2.MARKER_CROSS, 10,1,1 )

#     #     #draw on the resized original image
#     #     cv2.drawMarker(detected_both, (centerx, centery), class_colors, cv2.MARKER_CROSS, 10,1,1 )

#     # return detected_both, detected, yolo_cones_center, detections
#     return detections

def cone_connect(detected, detected_both, yolo_cones_center):
    yolo_cones_center = sorted(yolo_cones_center, key=lambda k:[k[1], k[0]], reverse=True)
    yolo_cones_center = yolo_cones_center[:3]
    yolo_slopes = []
    for i in range(len(yolo_cones_center)):
      if i != len(yolo_cones_center)-1:
        if yolo_cones_center[i][1] > yolo_cones_center[i+1][1]:

          cv2.line(detected, (yolo_cones_center[i][0],yolo_cones_center[i][1]) , (yolo_cones_center[i+1][0], yolo_cones_center[i+1][1]), (255,0,0), 1)

          #draw on the resized original image
          cv2.line(detected_both, (yolo_cones_center[i][0],yolo_cones_center[i][1]) , (yolo_cones_center[i+1][0], yolo_cones_center[i+1][1]), (255,0,0), 1)

          #get the slopes between yellow cones
          xdiff = (yolo_cones_center[i][0]) - (yolo_cones_center[i+1][0])
          ydiff = (yolo_cones_center[i][1]) - (yolo_cones_center[i+1][1])
          if xdiff != 0:
            sl = round(np.true_divide(ydiff, xdiff, out=None), 5)
          else:
            sl = 999
          yolo_slopes.append(sl)

    return detected_both, detected, yolo_slopes


import youtube_dl
import cv2
import os
from ydl_ops import ydl_opts

#Source: https://stackoverflow.com/questions/33311153/python-extracting-and-saving-video-frames
def process(fps, path):
    #use OpenCV video capture function
    vidcap = cv2.VideoCapture('video.mp4')
    success,image = vidcap.read()
    count = 0
    #for each frame successfully read
    while success:
        #fps dictates the number of frames generated per each second
        if (count % fps  == 0):
            frameNum = count / 30
            #we write to the image file to the specified path as a PNG
            cv2.imwrite(os.path.join(path,"frame-%d.png" % frameNum), image)
        success,image = vidcap.read()
        count += 1

#initializing function that prepares directory for processing
def initialize():
    #we check to see if a folder called 'frames' exists. If it doesn't, we create it. If it does, we clear it
    path = os.getcwd() + '/frames'
    if not os.path.exists(path):
        os.makedirs(path)
    for i in os.listdir(path):
        os.remove(os.path.join(path, i))
    return path

def run():
    print('           _______________________________\n /\\__/\\   / Video Frame Splitter for VRV  |\n( ° □ °) <  Developed by mattliu62 (2022) |\n(      )  \\_______________________________|')
    print('--------------------------------------------------')
    #checks to ensure link validity
    link = input('Enter valid VRV Link: ')
    link = link.strip()
    if 'vrv' not in link:
        print('Invalid link!')
        exit()
    fps = input('Enter video FPS: ')
    fps = 30 / 1
    subs = input('Enable Subtitles: ')
    if subs == 'yes':
        ydl_opts['format'] = 'bestvideo[format_id*=hardsub-en]'
    print('Initializing Download. Hang tight, this will take a while!')
    #utilize youtube_dl to download as MP4
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([link])
    print('Download complete! Initializing processing.')
    #initialize the directory
    path = initialize()
    #process the video into frames, passing in the desired frames and CWD
    process(int(fps), path)
    #remove the MP4 file
    os.remove('video.mp4')
    print('Successfully generated frames.')
    print('Mission Complete!')
    exit()

run()


import sys
import csv
import os
from io import StringIO
from time import sleep

def create_feature_list():
    dict_list = []

    #Create key:value pairs of possible descriptors and their matching
    #attribute names as used by the Spotify API
    danceability = {
        'dancy': ['min_danceability', .8],
        'groovy': ['min_danceability', .8],
        'rhythmic': ['min_danceability', .8],
        'danceable': ['min_danceability', .8],
        'funky': ['min_danceability', .8],
        'jiving': ['min_danceability', .8],
        'swaying': ['min_danceability', .8],
        'bouncy': ['min_danceability', .8],
        'dynamic': ['min_danceability', .8],
        'fluid': ['min_danceability', .8],
        'lethargic': ['max_danceability', .2],
        'static': ['max_danceability', .2],
        'stiff': ['max_danceability', .2],
        'rigid': ['max_danceability', .2],
        'lit': ['min_danceability', .8],
        'vibey': ['max_danceability', .6],
        'clubby': ['min_danceability', .8],
        'uptight': ['max_danceability', .2],
        'awkward': ['max_danceability', .2],
        'clunky': ['max_danceability', .2],
        'immobile': ['max_danceability', .2],
        'lit': ['min_danceability', .8],
        'chill': ['max_danceability', .3],
        'vibey': ['max_danceability', .6],
        'edgy': ['min_danceability', .8],
        'mellow': ['max_danceability', .3],
        'smooth': ['min_danceability', .8],
        'stiff': ['max_danceability', .2],
        'jamming': ['min_danceability', .8],
        'lazy': ['max_danceability', .2],
        'bopping': ['min_danceability', .8],
        'immobile': ['max_danceability', .1]
    }
    dict_list.append(danceability)

    duration = {
        'long': ['min_duration', 240000],
        'short': ['max_duration', 180000],
        'extended': ['min_duration', 300000],
        'brief': ['max_duration', 120000],
        'lengthy': ['min_duration', 270000],
        'compact': ['max_duration', 150000],
        'prolonged': ['min_duration', 320000],
        'fleeting': ['max_duration', 100000],
        'enduring': ['min_duration', 350000],
        'momentary': ['max_duration', 90000],
        'ephemeral': ['max_duration', 80000],
        'transient': ['max_duration', 70000],
        'marathon': ['min_duration', 400000],
        'snippet': ['max_duration', 60000],
        'epic': ['min_duration', 360000],
        'blip': ['max_duration', 50000],
        'sizable': ['min_duration', 280000],
        'quickie': ['max_duration', 90000],
        'lasting': ['min_duration', 340000]
    }
    dict_list.append(duration)

    energy = {
        'energetic': ['min_energy', .8],
        'hype': ['min_energy', .8],
        'lively': ['min_energy', .7],
        'intense': ['min_energy', .8],
        'low-energy': ['max_energy', .5],
        'vigorous': ['min_energy', .8],
        'powerful': ['min_energy', .8],
        'dynamic': ['min_energy', .8],
        'spirited': ['min_energy', .8],
        'passive': ['max_energy', .3],
        'mellow': ['max_energy', .4],
        'relaxed': ['max_energy', .3],
        'subdued': ['max_energy', .3],
        'lethargic': ['max_energy', .2],
        'amped': ['min_energy', .8],
        'chill': ['max_energy', .3],
        'explosive': ['min_energy', .9],
        'calm': ['max_energy', .2],
        'fiery': ['min_energy', .8],
        'serene': ['max_energy', .2],
        'wild': ['min_energy', .9],
        'gentle': ['max_energy', .3],
        'raucous': ['min_energy', .9],
        'peaceful': ['max_energy', .2],
        'pumped': ['min_energy', .8],
        'chilled': ['max_energy', .3],
        'thrilling': ['min_energy', .9],
        'calm': ['max_energy', .2],
        'banging': ['min_energy', .9],
        'serene': ['max_energy', .2],
        'fiery': ['min_energy', .9],
        'soothing': ['max_energy', .3],
        'electric': ['min_energy', .9],
        'zen': ['max_energy', .2],
        'kinetic': ['min_energy', .8],
        'tranquil': ['max_energy', .2]
    }
    dict_list.append(energy)

    instrumentalness = {
        'instrumental':['min_instrumentalness', .7],
        'lyric-less':['min_instrumentalness', .7],
        'non-vocal': ['min_instrumentalness', .7],
        'accompaniment': ['min_instrumentalness', .7],
        'melodic': ['min_instrumentalness', .7],
        'harmonic': ['min_instrumentalness', .7],
        'vocal': ['max_instrumentalness', .3],
        'sung': ['max_instrumentalness', .3],
        'lyrical': ['max_instrumentalness', .3],
        'voiced': ['max_instrumentalness', .3],
        'choral': ['max_instrumentalness', .3],
        'backing': ['min_instrumentalness', .7],
        'acapella': ['max_instrumentalness', .1],
        'symphonic': ['min_instrumentalness', .8],
        'vocal-heavy': ['max_instrumentalness', .2],
        'orchestral': ['min_instrumentalness', .8],
        'songful': ['max_instrumentalness', .2],
        'beatless': ['min_instrumentalness', .8],
        'sing-along': ['max_instrumentalness', .1],
        'rhythmless': ['min_instrumentalness', .8],
        'wordy': ['max_instrumentalness', .1]
    }
    dict_list.append(instrumentalness)

    liveness = {
        'live': ['min_liveness', .8],
        'raw': ['min_liveness', .8],
        'concert': ['min_liveness', .8],
        'gig': ['min_liveness', .8],
        'stage': ['min_liveness', .8],
        'real': ['min_liveness', .8],
        'studio': ['max_liveness', .2],
        'produced': ['max_liveness', .2],
        'synthesized': ['max_liveness', .2],
        'programmed': ['max_liveness', .2],
        'artificial': ['max_liveness', .2]
    }
    dict_list.append(liveness)

    loudness = {
        'loud': ['min_loudness', -10],
        'quiet': ['max_loudness', -20],
        'soft': ['max_loudness', -20],
        'booming': ['min_loudness', -5],
        'thunderous': ['min_loudness', -5],
        'deafening': ['min_loudness', -5],
        'muffled': ['max_loudness', -25],
        'hushed': ['max_loudness', -30],
        'whispered': ['max_loudness', -30],
        'faint': ['max_loudness', -35],
        'inaudible': ['max_loudness', -40],
        'blasting': ['min_loudness', -3],
        'murmuring': ['max_loudness', -40],
        'roaring': ['min_loudness', -4],
        'whispering': ['max_loudness', -35],
        'thumping': ['min_loudness', -6],
        'muted': ['max_loudness', -30],
        'ear-splitting': ['min_loudness', -2],
        'silenced': ['max_loudness', -45],
        'resounding': ['min_loudness', -5],
        'soundless': ['max_loudness', -50]
    }
    dict_list.append(loudness)

    mode = {'major': ['mode', 1],
            'minor': ['mode', 0]}
    dict_list.append(mode)

    popularity = {
        'popular': ['min_popularity', 80],
        'trending': ['min_popularity', 90],
        'underground': ['max_popularity', 25],
        'famous': ['min_popularity', 85],
        'obscure': ['max_popularity', 40],
        'well-known': ['min_popularity', 85],
        'unknown': ['max_popularity', 15],
        'noted': ['min_popularity', 80],
        'unrecognized': ['max_popularity', 35],
        'mainstream': ['min_popularity', 80],
        'niche': ['max_popularity', 45],
        'hit': ['min_popularity', 95],
        'obscure': ['max_popularity', 20],
        'chart-topper': ['min_popularity', 90],
        'undiscovered': ['max_popularity', 10],
        'famous': ['min_popularity', 85],
        'hidden-gem': ['max_popularity', 25],
        'blockbuster': ['min_popularity', 90],
        'rare': ['max_popularity', 15],
        'hot': ['min_popularity', 95],
        'unheard': ['max_popularity', 10]
    }
    dict_list.append(popularity)

    speechiness = {
        'spoken-word': ['min_speechiness', .7],
        'lyrical': ['min_speechiness', .5],
        'vocal': ['min_speechiness', .5],
        'talkative': ['min_speechiness', .7],
        'narrative': ['min_speechiness', .6],
        'conversational': ['min_speechiness', .7],
        'eloquent': ['min_speechiness', .5],
        'chatty': ['min_speechiness', .7],
        'musical': ['max_speechiness', .3],
        'instrumental': ['max_speechiness', .2],
        'melodic': ['max_speechiness', .3]
    }
    dict_list.append(speechiness)

    tempo = {
        'fast': ['min_tempo', 120],
        'slow': ['max_tempo', 80],
        'uptempo': ['min_tempo', 120],
        'downtempo': ['max_tempo', 70],
        'brisk': ['min_tempo', 130],
        'leisurely': ['max_tempo', 60],
        'rapid': ['min_tempo', 140],
        'languid': ['max_tempo', 50],
        'speedy': ['min_tempo', 150],
        'sluggish': ['max_tempo', 55],
        'quick': ['min_tempo', 135],
        'snail-paced': ['max_tempo', 45],
        'blazing': ['min_tempo', 160],
        'snail-like': ['max_tempo', 40],
        'hurried': ['min_tempo', 145],
        'plodding': ['max_tempo', 50],
        'rushed': ['min_tempo', 155],
        'strolling': ['max_tempo', 55],
        'breakneck': ['min_tempo', 150],
        'crawling': ['max_tempo', 45],
        'sprinting': ['min_tempo', 165],
        'ambling': ['max_tempo', 60]
    }
    dict_list.append(tempo)

    valence = {
        'happy': ['min_valence', .7],
        'sad': ['max_valence', .5],
        'upbeat': ['min_valence', .7],
        'joyous': ['min_valence', .7],
        'sorrowful': ['max_valence', .3],
        'cheerful': ['min_valence', .7],
        'melancholy': ['max_valence', .4],
        'gleeful': ['min_valence', .7],
        'gloomy': ['max_valence', .3],
        'elated': ['min_valence', .8],
        'depressed': ['max_valence', .2],
        'ecstatic': ['min_valence', .8],
        'dismal': ['max_valence', .2],
        'radiant': ['min_valence', .7],
        'mournful': ['max_valence', .3],
        'delighted': ['min_valence', .7],
        'heavy-hearted': ['max_valence', .2],
        'jubilant': ['min_valence', .8],
        'blue': ['max_valence', .3],
        'exhilarated': ['min_valence', .8],
        'woeful': ['max_valence', .2],
        'blissful': ['min_valence', .7],
        'downcast': ['max_valence', .2],
        'contented': ['min_valence', .7],
        'forlorn': ['max_valence', .2],
        'vibrant': ['min_valence', .7],
        'desolate': ['max_valence', .1],
        'optimistic': ['min_valence', .7],
        'pessimistic': ['max_valence', .2],
        'lighthearted': ['min_valence', .8],
        'heartbroken': ['max_valence', .1],
        'bubbly': ['min_valence', .8],
        'sullen': ['max_valence', .2],
        'sunny': ['min_valence', .7],
        'somber': ['max_valence', .3],
        'exuberant': ['min_valence', .8],
        'morose': ['max_valence', .2],
        'spirited': ['min_valence', .7],
        'doleful': ['max_valence', .3],
        'euphoric': ['min_valence', .8],
        'bleak': ['max_valence', .1],
        'chipper': ['min_valence', .7],
        'miserable': ['max_valence', .2],
        'buoyant': ['min_valence', .8],
        'lugubrious': ['max_valence', .1],
        'jolly': ['min_valence', .7],
        'glum': ['max_valence', .2],
        'beaming': ['min_valence', .8],
        'crestfallen': ['max_valence', .1],
        'mirthful': ['min_valence', .8],
        'despondent': ['max_valence', .2],
        'cheery': ['min_valence', .7],
        'moody': ['max_valence', .2],
        'sunny': ['min_valence', .8],
        'brooding': ['max_valence', .2],
        'uplifting': ['min_valence', .8],
        'gloomy': ['max_valence', .2],
        'sparkly': ['min_valence', .8],
        'sombre': ['max_valence', .2],
        'bright': ['min_valence', .7],
        'morose': ['max_valence', .3],
        'jolly': ['min_valence', .7],
        'melancholic': ['max_valence', .2],
        'joyful': ['min_valence', .8],
        'downbeat': ['max_valence', .3],
        'playful': ['min_valence', .7],
        'somber': ['max_valence', .2],
        'hopeful': ['min_valence', .7],
        'dreary': ['max_valence', .3],
        'peppy': ['min_valence', .8],
        'bleak': ['max_valence', .1]
    }
    dict_list.append(valence)

    return dict_list

def create_genre_list():

    genres = ["acoustic", "afrobeat", "alt-rock", "alternative", "ambient",
            "anime", "black-metal", "bluegrass", "blues", "bossanova",
            "brazil", "breakbeat", "british", "cantopop", "chicago-house",
            "children", "chill", "classical", "club", "comedy", "country",
            "dance", "dancehall", "death-metal", "deep-house", "detroit-techno",
            "disco", "disney", "drum-and-bass", "dub", "dubstep", "edm",
            "electro", "electronic", "emo", "folk", "forro", "french",
            "funk", "garage", "german", "gospel", "goth", "grindcore",
            "groove", "grunge", "guitar", "hard-rock", "hardcore",
            "hardstyle", "heavy-metal", "hip-hop", "holidays", "honky-tonk",
            "house", "idm", "indian", "indie", "indie-pop", "industrial",
            "iranian", "j-dance", "j-idol", "j-pop", "j-rock", "jazz",
            "k-pop", "kids", "latin", "latino", "malay", "mandopop",
            "metal", "metal-misc", "metalcore", "minimal-techno",
            "movies", "mpb", "new-age", "new-release", "opera", "pagode",
            "party", "philippines-opm", "piano", "pop", "pop-film",
            "post-dubstep", "power-pop", "progressive-house", "psych-rock",
            "punk", "punk-rock", "r-n-b", "rainy-day", "reggae",
            "reggaeton", "road-trip", "rock", "rock-n-roll", "rockabilly",
            "romance", "salsa", "samba", "sertanejo",
            "show-tunes", "singer-songwriter", "ska", "sleep",
            "songwriter", "soul", "soundtracks", "spanish", "study",
            "summer", "swedish", "synth-pop", "tango", "techno", "trance",
            "trip-hop", "turkish", "work-out", "world-music"]

    return genres

def create_key_list():

    key_list = ['a', 'bb', 'c', 'c#', 'd', 'eb', 'e',
            'f', 'f#', 'g', 'g#']

    return key_list

def process_string(value):
    value = value.lower()

    # Check if the string contains 'from the' or 'by'
    if 'from' not in value and 'by' not in value and 'like' not in value:
        # Replace spaces with hyphens
        return value.replace(' ', '-')
    else:
        return value

def clean_input(input):

    csv_file = StringIO(input)
    reader = csv.reader(csv_file)
    #convert string of comma-separated values into list, remove spaces
    result_list = [process_string(element.strip()) for element in next(reader, [])]

    return result_list

def get_misc_features(term, trait_dict, dict_list):
    for dict in dict_list:
        for key in dict.keys():
            if term == key:
                pair = dict[key]
                trait_dict[pair[0]] = pair[1]

def get_genre(term, trait_dict, genres):
    for genre in genres:
        if term == genre:
            trait_dict['genre'] = term

def get_artist(term, trait_dict):
    if "by " in term:
        trait_dict['artist'] = term.replace("by ", "")

def get_similar_artist(term, trait_dict):
    if "like " in term:
        trait_dict['seed_artists'] = term.replace("like ", "")

def get_target_bpm(term, trait_dict):
    if "-bpm" in term:
        term = term.replace("-", " ")
        trait_dict['tempo'] = term.replace(" bpm", "")

def get_key(term, trait_dict, key_list):
    if "major" in term or "minor" in term:
       for key in key_list:
           if key in term:
               trait_dict['key'] = (key_list.index(key) + 1)

def get_time_signature(term, trait_dict):
    if "/4" in term:
        term = term.replace("-", " ")
        term = term.replace("/4", "")
        trait_dict['time-signature'] = term.replace("in ", "")

def get_features(clean_input):

    trait_dict = {}
    dict_list = create_feature_list()

    genres = create_genre_list()
    key_list = create_key_list()

    for term in clean_input:
        get_genre(term, trait_dict, genres)
        get_artist(term, trait_dict)
        get_similar_artist(term, trait_dict)
        get_target_bpm(term, trait_dict)
        get_key(term, trait_dict, key_list)
        get_time_signature(term, trait_dict)
        get_misc_features(term, trait_dict, dict_list)

    return trait_dict

def process_input(user_input):

    trait_dict = {}
    search_flag = True

    # params_test = {
    #     'seed_artists': 'carly rae jepsen',
    #     'type': 'track',
    #     'limit': 10,
    #     'min_tempo': 120,
    #     'max_valence': .7,
    #     'genre': 'hardcore'
    # }

    # params_test = {
    #     'min_valence': 0.7,
    #     'artist': 'arctic monkeys',
    #     'type': 'track',
    #     'limit': 30
    # }

    cleaned = clean_input(user_input)

    trait_dict = get_features(cleaned)
    trait_dict['type'] = 'track'
    trait_dict['limit'] = 50

    if 'seed_artists' in trait_dict.keys() or 'seed_genres' in trait_dict.keys():
        search_flag = False

    #Print parameters to other file

    temp_file_path = 'backend/temp_params.py'
    final_file_path = 'backend/params.py'

    # Write the trait dictionary to a temporary file
    with open(temp_file_path, 'w') as f:
        f.write('params = ')
        f.write(f'{trait_dict}')
        f.flush()
        f.close()

    # Delete the existing params.py file if it exists
    if os.path.exists(final_file_path):
        os.remove(final_file_path)

    # Rename the temp file to params.py
    os.rename(temp_file_path, final_file_path)

    print(f"Python script executed with user input: {trait_dict}")

    return search_flag


import mxnet as mx
import mxnet.ndarray as nd

from utils.common_utils import get_class_members_in_module
from mxnet_benchmarks.utils.ndarray_utils import get_mx_ndarray, nd_forward_backward_and_time
from mxnet_benchmarks.MXNetOperatorBenchmark import MXNetOperatorBenchmarkBase

""" Performance benchmark tests for MXNet NDArray Powers operations
1. sqrt
2. square

TODO:
1. As part of default tests, add broadcast operations for all below benchmarks. Ex: 1024 * 1024 OP 1024 * 1
2. Logging - Info, Error and Debug
3. Probably we can refactor the common logic of all these binary operations into a parent
   MXNetBinaryOperatorBenchmarkBase?
"""

class Sqrt(MXNetOperatorBenchmarkBase):
    """Helps to Benchmark Tensor Sqrt operation.

    By default benchmark both forward and backward element-wise Sqrt operation on a
    1024*1024 tensor of precision - 'float32'.

    """

    def __init__(self, ctx=mx.cpu(), warmup=10, runs=50, inputs=None):
        # Set the default Inputs
        default_parameters = {"data": (1024, 1024),
                              "data_initializer": nd.normal,
                              "run_backward": True,
                              "dtype": "float32"}

        super().__init__(ctx=ctx, warmup=warmup, runs=runs, default_parameters=default_parameters,
                         custom_parameters=inputs)

        self.data = get_mx_ndarray(ctx=self.ctx, in_tensor=self.inputs["data"],
                                   dtype=self.inputs["dtype"],
                                   initializer=self.inputs["data_initializer"],
                                   attach_grad=self.inputs["run_backward"])

    def run_benchmark(self):
        # Warm up, ignore execution time value
        _, _ = nd_forward_backward_and_time(F=nd.sqrt, runs=self.warmup, data=self.data)

        # Run Benchmarks
        exe_time, _ = nd_forward_backward_and_time(F=nd.logical_not, runs=self.runs, data=self.data)

        self.results["MX_Sqrt_Forward_Backward_Time"] = exe_time / self.runs

class Square(MXNetOperatorBenchmarkBase):
    """Helps to Benchmark Tensor Square operation.

    By default benchmark both forward and backward element-wise Square operation on a
    1024*1024 tensor of precision - 'float32'.

    """

    def __init__(self, ctx=mx.cpu(), warmup=10, runs=50, inputs=None):
        # Set the default Inputs
        default_parameters = {"data": (1024, 1024),
                              "data_initializer": nd.normal,
                              "run_backward": True,
                              "dtype": "float32"}

        super().__init__(ctx=ctx, warmup=warmup, runs=runs, default_parameters=default_parameters,
                         custom_parameters=inputs)

        self.data = get_mx_ndarray(ctx=self.ctx, in_tensor=self.inputs["data"],
                                   dtype=self.inputs["dtype"],
                                   initializer=self.inputs["data_initializer"],
                                   attach_grad=self.inputs["run_backward"])

    def run_benchmark(self):
        # Warm up, ignore execution time value
        _, _ = nd_forward_backward_and_time(F=nd.square, runs=self.warmup, data=self.data)

        # Run Benchmarks
        exe_time, _ = nd_forward_backward_and_time(F=nd.square, runs=self.runs, data=self.data)

        self.results["MX_Square_Forward_Backward_Time"] = exe_time / self.runs

# Utilities
def run_all_powers_operations_benchmarks(ctx, inputs):
    """Helper to run all Powers (sqrt, square) operator benchmarks. Just runs the benchmarks with default input values.
    This is just a utility to run benchmarks with all default input values.

    :return: list[dict], list of dictionary of benchmark results. Each item in the list is a dictionary of benchmark
                         results per operator.

    """
    power_operations_results = []

    members = get_class_members_in_module(__name__)

    for _, cls in members:
        benchmark_ref = cls(ctx=ctx, inputs=inputs)
        benchmark_ref.run_benchmark()
        benchmark_ref.print_benchmark_results()
        power_operations_results.append(benchmark_ref.get_benchmark_results())

    return power_operations_results


from flask import *
from app import app
from service.CustomerService import CustomerService
from service.UserService import UserService
from service.TableBookingService import TableBookingService
from service.CategoryService import CategoryService
from service.EmailService import EmailBTH

ALLOWED_EXTENSIONS = {'jpg', 'jpeg','png'}

import json
import base64

userService = UserService()
bookingService = TableBookingService()
customerService = CustomerService()
catService = CategoryService()

emailbth = EmailBTH()

@app.route('/adminpanel')
def adminPanel():
    if(session.get("email") is not None and session['user_type'] == 'Admin'):

        resultAllCustomers = viewAllCustomers()
        resultAllBookings = viewAllBookings()
        return render_template('admin_panel.html',custData=resultAllCustomers, bookingData= resultAllBookings)
    else:
        return render_template('index.html')

def viewAllCustomers():

    resultAllCustomers = userService.allCustomers()
    # customer_json_string = json.dumps(resultAllCustomers)

    session["allusers"] = resultAllCustomers

    return resultAllCustomers

def viewAllBookings():

    resultAllBookings = bookingService.getAllBookings()
    #booking_json_string = json.dumps(resultAllBookings)

    session["allbookings"] = resultAllBookings
    print(resultAllBookings)

    return resultAllBookings

@app.route('/changecustomerstatus', methods=['POST'])
def changeCustomerStatus():

    if (session.get("email") is not None and session['user_type'] == 'Admin'):
        postData = request.form
        print(postData)

        result = customerService.updateUserStatus(postData)
        print(result)

        return "1"

    else:
        return render_template('index.html')

@app.route('/cancel_or_process_order', methods=['POST'])
def cancelOrder():

    if (session.get("email") is not None and session['user_type'] == 'Admin'):
        print("cancel_or_process_order")
        postData = request.form
        print(postData)
        purpose = postData.get("o_purpose")
        print(purpose)

        id = postData.get("o_id")
        print(id)

        result = emailbth.sendEmail(postData)
        print(result)
        bookingService.processBookingOrder(result, id)

        return "1"
    else:
        return render_template('index.html')

@app.route('/addNewCategory', methods=['POST'])
def newCategory():
    if (session.get("email") is not None and session['user_type'] == 'Admin'):
        print("cateeeee")
        postData = request.form
        print(postData)

        result = catService.saveFoodCategory(postData)
        print(result)
        return str(result)
    else:
        return render_template('index.html')

@app.route('/addMenu', methods=['POST', 'GET'])
def addMenuItem():
    if (session.get("email") is not None and session['user_type'] == 'Admin'):

        print("Menu Item")
        postData = request.form
        img_file = request.files['file']
        encr_img = base64.b64encode(img_file.read())

        if 'file' not in request.files:
            flash('No File Part in Request')
            return redirect(url_for('adminPanel'))

        if img_file.filename == '':
            flash('There is no selected Image')
            return redirect(url_for('adminPanel'))

        if img_file and checkFileExtension(img_file.filename):
            catService.saveMenuItem(postData, encr_img)
            flash('Menu Item Added Successfully...!')
            return redirect(url_for('adminPanel'))
        else:
            flash('Wrong File Selection...!')
            return redirect(url_for('adminPanel'))

def checkFileExtension(fileName):
    print("extension")
    return '.' in fileName and \
           fileName.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/allCategories',methods=['POST'])
def allCategories():
    if (session.get("email") is not None and session['user_type'] == 'Admin'):
        resultSet = catService.getAllCtegories()
        session['Categories'] = resultSet
        print(resultSet)
        return "None"
    else:
        return render_template('index.html')


import argparse
from queue import PriorityQueue

parser = argparse.ArgumentParser()
parser.add_argument("--input_file")
args = parser.parse_args()

class Vertex:
    def __init__(self, index):
        self.index = index

        self.group = self
        self.child = []

class Edge:
    def __init__(self, v1, v2, weight):
        self.v1 = v1
        self.v2 = v2
        self.weight = weight

    def __lt__(self, other):
        return self.weight < other.weight

def merge(v1: Vertex, v2: Vertex):
    if v1.group != v2.group:
        if len(v1.group.child) > len(v2.group.child):
            merge_(v1.group, v2)
        else:
            merge_(v2.group, v1)
        return True
    else:
        return False

def merge_(parent: Vertex, v2: Vertex):
    """
    merge v2 and v2's sub group to parent
    """
    for child in v2.child:
        merge_(parent, child)

    v2.group = parent
    v2.child = []

    parent.child.append(v2)

if __name__ == "__main__":
    with open(args.input_file, "r") as f:
        N = int(f.readline())

        vertices = [Vertex(i) for i in range(N+1)]
        edges = PriorityQueue()

        for line in f:
            v1, v2, weight = tuple(map(lambda x: int(x), line.split(" ")))

            edges.put(Edge(vertices[v1], vertices[v2], weight))

    result = []
    while not edges.empty():
        edge = edges.get()
        success = merge(edge.v1, edge.v2)

        if success:
            result.append(edge)

    for edge in result:
        print("v1: {} v2: {} weight: {}".format(edge.v1.index, edge.v2.index, edge.weight))


# Databricks notebook source
# MAGIC %md
# MAGIC ##### Welcome  to Azurelib Academy By Deepak Goyal
# MAGIC ##### You can master the Databricks here: www.adeus.azurelib.com
# MAGIC ##### Author of this blog: Arud Seka Berne S in

# COMMAND ----------

# MAGIC %md
# MAGIC ##### Welcome  to Azurelib Academy By Deepak Goyal
# MAGIC ##### You can master the Databricks here: www.adeus.azurelib.com
# MAGIC ##### Author of this blog: Arud Seka Berne S in

# COMMAND ----------

# MAGIC %md
# MAGIC ##### Welcome  to Azurelib Academy By Deepak Goyal
# MAGIC ##### You can master the Databricks here: www.adeus.azurelib.com
# MAGIC ##### Author of this blog: Arud Seka Berne S in

# COMMAND ----------

# MAGIC %md
# MAGIC ##### Welcome  to Azurelib Academy By Deepak Goyal
# MAGIC ##### You can master the Databricks here: www.adeus.azurelib.com
# MAGIC ##### Author of this blog: Arud Seka Berne S in

# COMMAND ----------

# MAGIC %md
# MAGIC #### Pyspark User Defined Functions in Azure Databricks

# COMMAND ----------

# MAGIC %md
# MAGIC ###### Gentle reminder:
# MAGIC In Databricks,
# MAGIC   - sparkSession made available as spark
# MAGIC   - sparkContext made available as sc
# MAGIC
# MAGIC In case, you want to create it manually, use the below code.

# COMMAND ----------

from pyspark.sql.session import SparkSession

spark = SparkSession.builder \
    .master("local[*]") \
    .appName("azurelib.com") \
    .getOrCreate()

sc = spark.sparkContext

# COMMAND ----------

# MAGIC %md
# MAGIC ##### a) Create manual PySpark DataFrame

# COMMAND ----------

data = [
    (1,"Nitheesh",22,"m","856 324 321"),
    (2,"Ranveer",21,"Male","7585543210"),
    (3,"Kritisha",24,"FM","9876543210 "),
    (4,"Madhu",26,"female","987 657 8954")
]

df = spark.createDataFrame(data, schema=["id","name","age","gender","mobile"])
df.printSchema()
df.show()

# COMMAND ----------

# MAGIC %md
# MAGIC ##### b) Create PySpark DataFrame by reading files

# COMMAND ----------

# replace the file_path with the source file location which you have downloaded.

df_2 = spark.read.format("csv").option("header", True).load(file_path)
df_2.printSchema()

# COMMAND ----------

# MAGIC %md
# MAGIC ##### Note: Here, I will be using the manually created dataframe

# COMMAND ----------

# MAGIC %md
# MAGIC ##### 1. Create and use a UDF

# COMMAND ----------

from pyspark.sql.functions import udf

# 1. Create function
def reformat_gender_udf(gender: str) -> str:
    first_char = gender[0].lower()
    output = "Male"
    if first_char == "f":
        output = "Female"
    return output

# 2. Register function using udf() method
reformat_gender = udf(reformat_gender_udf)

# 3. Apply function on top of Dataframe columns
df.withColumn("gender", reformat_gender("gender")).show()

# COMMAND ----------

# MAGIC %md
# MAGIC ##### 2. Using UDF on PySpark SQL

# COMMAND ----------

from pyspark.sql.types import StringType

# Register the user defined function
spark.udf.register("reformat_gender", reformat_gender_udf, StringType())

df.createOrReplaceTempView("sample")

spark.sql("""
SELECT id, name, age, reformat_gender(gender) AS gender, mobile
FROM sample
""").show()

# COMMAND ----------

# MAGIC %md
# MAGIC ##### 3. Using PySpark in-built functions

# COMMAND ----------

from pyspark.sql.functions import col, lower, when, substring

df.withColumn("gender",
              when(substring(lower(col("gender")), 1, 1) == "m", "Male")\
              .otherwise("Female")
             ).show()

# COMMAND ----------

from pyspark.sql.functions import col, trim, split, concat_ws, length, when, udf

df.withColumn("mobile",
             when(length(concat_ws("", split(trim(col("mobile")), " "))) != 10, None)\
              .otherwise(concat_ws("", split(trim(col("mobile")), " ")))
             ).show()

12. Pyspark User Defined Functions/Pyspark User Defined Functions - Notebook.py


from __future__ import print_function

from optparse import OptionParser
import os
import pdb
import random
import sys

import h5py
import numpy as np
import pandas as pd

import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from PIL import Image
import seaborn as sns

from basenji import plots

'''
basenji_sat_plot.py

Perform an in silico saturated mutagenesis of the given test sequences
using the given model.

Note:
 -Currently written assuming we have targets associated with each input sequence.
'''

################################################################################
# main
################################################################################
def main():
  usage = 'usage: %prog [options] <scores_file>'
  parser = OptionParser(usage)
  parser.add_option('-a', dest='activity_enrich',
      default=1, type='float',
      help='Enrich for the most active top % of sequences [Default: %default]')
  parser.add_option('-f', dest='figure_width',
      default=20, type='float',
      help='Figure width [Default: %default]')
  parser.add_option('-g', dest='gain',
      default=False, action='store_true',
      help='Draw a sequence logo for the gain score, too [Default: %default]')
  parser.add_option('-l', dest='plot_len',
      default=300, type='int',
      help='Length of centered sequence to mutate [Default: %default]')
  parser.add_option('-m', dest='min_limit',
      default=0.01, type='float',
      help='Minimum heatmap limit [Default: %default]')
  parser.add_option('-o', dest='out_dir',
      default='sat_plot', help='Output directory [Default: %default]')
  parser.add_option('-r', dest='rng_seed',
      default=1, type='float',
      help='Random number generator seed [Default: %default]')
  parser.add_option('-s', dest='sample',
      default=None, type='int',
      help='Sample N sequences from the set [Default:%default]')
  parser.add_option('-t', dest='targets_file',
      default=None, type='str',
      help='File specifying target indexes and labels in table format')
  (options, args) = parser.parse_args()

  if len(args) != 1:
    parser.error('Must provide scores HDF5 file')
  else:
    scores_h5_file = args[0]

  if not os.path.isdir(options.out_dir):
    os.mkdir(options.out_dir)

  np.random.seed(options.rng_seed)

  # determine targets
  targets_df = pd.read_table(options.targets_file)
  num_targets = targets_df.shape[0]

  # open scores
  scores_h5 = h5py.File(scores_h5_file)
  num_seqs = scores_h5['seqs'].shape[0]
  mut_len = scores_h5['scores'].shape[1]

  # determine plot region
  mut_mid = mut_len // 2
  plot_start = mut_mid - (options.plot_len//2)
  plot_end = plot_start + options.plot_len

  # plot attributes
  sns.set(style='white', font_scale=1)
  spp = subplot_params(options.plot_len)

  # determine sequences
  seq_indexes = np.arange(num_seqs)

  if options.sample and options.sample < num_seqs:
    seq_indexes = np.random.choice(seq_indexes, size=options.sample, replace=False)

  for si in seq_indexes:
    # read sequence
    seq_1hot = scores_h5['seqs'][si,plot_start:plot_end]

    # read scores
    scores = scores_h5['scores'][si,plot_start:plot_end,:,:]

    # reference scores
    ref_scores = scores[seq_1hot]

    for tii in range(num_targets):
      ti = targets_df['index'].iloc[tii]

      scores_ti = scores[:,:,ti]

      # compute scores relative to reference
      delta_ti = scores_ti - ref_scores[:,[ti]]

      # compute loss and gain
      delta_loss = delta_ti.min(axis=1)
      delta_gain = delta_ti.max(axis=1)

      # setup plot
      plt.figure(figsize=(options.figure_width, 4))
      ax_logo_loss = plt.subplot2grid(
          (3, spp['heat_cols']), (0, spp['logo_start']),
          colspan=spp['logo_span'])
      ax_sad = plt.subplot2grid(
          (3, spp['heat_cols']), (1, spp['sad_start']),
          colspan=spp['sad_span'])
      ax_heat = plt.subplot2grid(
          (3, spp['heat_cols']), (2, 0), colspan=spp['heat_cols'])

      # plot sequence logo
      plot_seqlogo(ax_logo_loss, seq_1hot, -delta_loss)
      if options.gain:
        plot_seqlogo(ax_logo_gain, seq_1hot, delta_gain)

      # plot SAD
      plot_sad(ax_sad, delta_loss, delta_gain)

      # plot heat map
      plot_heat(ax_heat, delta_ti.T, options.min_limit)

      plt.tight_layout()
      plt.savefig('%s/seq%d_t%d.pdf' % (options.out_dir, si, ti), dpi=600)
      plt.close()

def enrich_activity(seqs, seqs_1hot, targets, activity_enrich, target_indexes):
  """ Filter data for the most active sequences in the set. """

  # compute the max across sequence lengths and mean across targets
  seq_scores = targets[:, :, target_indexes].max(axis=1).mean(
      axis=1, dtype='float64')

  # sort the sequences
  scores_indexes = [(seq_scores[si], si) for si in range(seq_scores.shape[0])]
  scores_indexes.sort(reverse=True)

  # filter for the top
  enrich_indexes = sorted(
      [scores_indexes[si][1] for si in range(seq_scores.shape[0])])
  enrich_indexes = enrich_indexes[:int(activity_enrich * len(enrich_indexes))]
  seqs = [seqs[ei] for ei in enrich_indexes]
  seqs_1hot = seqs_1hot[enrich_indexes]
  targets = targets[enrich_indexes]

  return seqs, seqs_1hot, targets

def expand_4l(sat_lg_ti, seq_1hot):
  """ Expand

    In:
        sat_lg_ti (l array): Sat mut loss/gain scores for a single sequence and
        target.
        seq_1hot (Lx4 array): One-hot coding for a single sequence.

    Out:
        sat_loss_4l (lx4 array): Score-hot coding?

    """

  # determine satmut length
  satmut_len = sat_lg_ti.shape[0]

  # jump to satmut region in one hot coded sequence
  ssi = int((seq_1hot.shape[0] - satmut_len) // 2)

  # filter sequence for satmut region
  seq_1hot_sm = seq_1hot[ssi:ssi + satmut_len, :]

  # tile loss scores to align
  sat_lg_tile = np.tile(sat_lg_ti, (4, 1)).T

  # element-wise multiple
  sat_lg_4l = np.multiply(seq_1hot_sm, sat_lg_tile)

  return sat_lg_4l

def delta_matrix(seqs_1hot, sat_preds, satmut_len):
  """ Compute the matrix of prediction deltas

    Args:
        seqs_1hot (Lx4 array): One-hot coding of all sequences.
        sat_preds: (SMxLxT array): Satmut sequence predictions.
        satmut_len: Saturated mutagenesis region length.

    Returns:
        sat_delta (4 x L_sm x T array): Delta matrix for saturated mutagenesis
        region.

    Todo:
        -Rather than computing the delta as the change at that nucleotide's
        prediction,
            compute it as the mean change across the sequence. That way, we
            better
            pick up on motif-flanking interactions.
    """
  seqs_n = int(sat_preds.shape[0] / (1 + 3 * satmut_len))
  num_targets = sat_preds.shape[2]

  # left-over from previous version
  # we're just expecting one sequence now
  si = 0

  # initialize
  sat_delta = np.zeros((4, satmut_len, num_targets), dtype='float64')

  # jump to si's mutated sequences
  smi = seqs_n + si * 3 * satmut_len

  # jump to satmut region in preds (incorrect with target pooling)
  # spi = int((sat_preds.shape[1] - satmut_len) // 2)

  # jump to satmut region in sequence
  ssi = int((seqs_1hot.shape[0] - satmut_len) // 2)

  # to study across sequence length
  # sat_delta_length = np.zeros((4, satmut_len, sat_preds.shape[1], num_targets))

  # compute delta matrix
  for li in range(satmut_len):
    for ni in range(4):
      if seqs_1hot[ssi + li, ni] == 1:
        sat_delta[ni, li, :] = 0
      else:
        # to study across sequence length
        # sat_delta_length[ni,li,:,:] = sat_preds[smi] - sat_preds[si]

        # sat_delta[ni,li,:] = sat_preds[smi,spi+li,:] - sat_preds[si,spi+li,:]
        sat_delta[ni, li, :] = sat_preds[smi].sum(
            axis=0, dtype='float64') - sat_preds[si].sum(
                axis=0, dtype='float64')
        smi += 1

  # to study across sequence length
  """
    sat_delta_length = sat_delta_length.mean(axis=0)

    if not os.path.isdir('length'):
        os.mkdir('length')
    for ti in range(sat_delta_length.shape[2]):
        plt.figure()
        sns.heatmap(sat_delta_length[:,:,ti], linewidths=0, cmap='RdBu_r')
        plt.savefig('length/delta_length_s%d_t%d.pdf' % (si,ti))
        plt.close()
    """

  return sat_delta

def loss_gain(sat_delta, sat_preds_si, satmut_len):
  # compute min and max
  sat_min = sat_delta.min(axis=0)
  sat_max = sat_delta.max(axis=0)

  # determine sat mut region
  sm_start = (sat_preds_si.shape[0] - satmut_len) // 2
  sm_end = sm_start + satmut_len

  # compute loss and gain matrixes
  sat_loss = sat_min - sat_preds_si[sm_start:sm_end, :]
  sat_gain = sat_max - sat_preds_si[sm_start:sm_end, :]

  return sat_loss, sat_gain

def plot_heat(ax, sat_delta_ti, min_limit):
  """ Plot satmut deltas.

    Args:
        ax (Axis): matplotlib axis to plot to.
        sat_delta_ti (4 x L_sm array): Single target delta matrix for saturated mutagenesis region,
        min_limit (float): Minimum heatmap limit.
    """
  vlim = max(min_limit, abs(sat_delta_ti).max())
  sns.heatmap(
      sat_delta_ti,
      linewidths=0,
      cmap='RdBu_r',
      vmin=-vlim,
      vmax=vlim,
      xticklabels=False,
      ax=ax)
  ax.yaxis.set_ticklabels('ACGT', rotation='horizontal')  # , size=10)

def plot_predictions(ax, preds, satmut_len, seq_len, buffer):
  """ Plot the raw predictions for a sequence and target
        across the specificed saturated mutagenesis region.

    Args:
        ax (Axis): matplotlib axis to plot to.
        preds (L array): Target predictions for one sequence.
        satmut_len (int): Satmut length from which to determine
                           the values to plot.
        seq_len (int): Full sequence length.
        buffer (int): Ignored buffer sequence on each side
    """

  # repeat preds across pool width
  target_pool = (seq_len - 2 * buffer) // preds.shape[0]
  epreds = preds.repeat(target_pool)

  satmut_start = (epreds.shape[0] - satmut_len) // 2
  satmut_end = satmut_start + satmut_len

  ax.plot(epreds[satmut_start:satmut_end], linewidth=1)
  ax.set_xlim(0, satmut_len)
  ax.axhline(0, c='black', linewidth=1, linestyle='--')
  for axis in ['top', 'bottom', 'left', 'right']:
    ax.spines[axis].set_linewidth(0.5)

def plot_sad(ax, sat_loss_ti, sat_gain_ti):
  """ Plot loss and gain SAD scores.

    Args:
        ax (Axis): matplotlib axis to plot to.
        sat_loss_ti (L_sm array): Minimum mutation delta across satmut length.
        sat_gain_ti (L_sm array): Maximum mutation delta across satmut length.
    """

  rdbu = sns.color_palette('RdBu_r', 10)

  ax.plot(-sat_loss_ti, c=rdbu[0], label='loss', linewidth=1)
  ax.plot(sat_gain_ti, c=rdbu[-1], label='gain', linewidth=1)
  ax.set_xlim(0, len(sat_loss_ti))
  ax.legend()
  # ax_sad.grid(True, linestyle=':')

  ax.xaxis.set_ticks([])
  for axis in ['top', 'bottom', 'left', 'right']:
    ax.spines[axis].set_linewidth(0.5)

def plot_seqlogo(ax, seq_1hot, sat_score_ti, pseudo_pct=0.05):
  """ Plot a sequence logo for the loss/gain scores.

    Args:
        ax (Axis): matplotlib axis to plot to.
        seq_1hot (Lx4 array): One-hot coding of a sequence.
        sat_score_ti (L_sm array): Minimum mutation delta across satmut length.
        pseudo_pct (float): % of the max to add as a pseudocount.
    """

  satmut_len = len(sat_score_ti)

  # add pseudocounts
  sat_score_ti += pseudo_pct * sat_score_ti.max()

  # expand
  sat_score_4l = expand_4l(sat_score_ti, seq_1hot)

  plots.seqlogo(sat_score_4l, ax)

'''
def plot_weblogo(ax, seq, sat_loss_ti, min_limit):
  """ Plot height-weighted weblogo sequence.

    Args:
        ax (Axis): matplotlib axis to plot to.
        seq ([ACGT]): DNA sequence
        sat_loss_ti (L_sm array): Minimum mutation delta across satmut length.
        min_limit (float): Minimum heatmap limit.
    """
  # trim sequence to the satmut region
  satmut_len = len(sat_loss_ti)
  satmut_start = int((len(seq) - satmut_len) // 2)
  satmut_seq = seq[satmut_start:satmut_start + satmut_len]

  # determine nt heights
  vlim = max(min_limit, np.max(-sat_loss_ti))
  seq_heights = 0.1 + 1.9 / vlim * (-sat_loss_ti)

  # make logo as eps
  eps_fd, eps_file = tempfile.mkstemp()
  seq_logo(satmut_seq, seq_heights, eps_file, color_mode='meme')

  # convert to png
  png_fd, png_file = tempfile.mkstemp()
  subprocess.call(
      'convert -density 1200 %s %s' % (eps_file, png_file), shell=True)

  # plot
  logo = Image.open(png_file)
  ax.imshow(logo)
  ax.set_axis_off()

  # clean up
  os.close(eps_fd)
  os.remove(eps_file)
  os.close(png_fd)
  os.remove(png_file)
'''

def satmut_seqs(seqs_1hot, satmut_len):
  """ Construct a new array with the given sequences and saturated
        mutagenesis versions of them. """

  seqs_n = seqs_1hot.shape[0]
  seq_len = seqs_1hot.shape[1]
  satmut_n = seqs_n + seqs_n * satmut_len * 3

  # initialize satmut seqs 1hot
  sat_seqs_1hot = np.zeros((satmut_n, seq_len, 4), dtype='bool')

  # copy over seqs_1hot
  sat_seqs_1hot[:seqs_n, :, :] = seqs_1hot

  satmut_start = (seq_len - satmut_len) // 2
  satmut_end = satmut_start + satmut_len

  # add saturated mutagenesis
  smi = seqs_n
  for si in range(seqs_n):
    for li in range(satmut_start, satmut_end):
      for ni in range(4):
        if seqs_1hot[si, li, ni] != 1:
          # copy sequence
          sat_seqs_1hot[smi, :, :] = seqs_1hot[si, :, :]

          # mutate to ni
          sat_seqs_1hot[smi, li, :] = np.zeros(4)
          sat_seqs_1hot[smi, li, ni] = 1

          # update index
          smi += 1

  return sat_seqs_1hot

def subplot_params(seq_len):
  """ Specify subplot layout parameters for various sequence lengths. """
  if seq_len < 500:
    spp = {
        'heat_cols': 400,
        'sad_start': 1,
        'sad_span': 321,
        'logo_start': 0,
        'logo_span': 323
    }
  else:
    spp = {
        'heat_cols': 400,
        'sad_start': 1,
        'sad_span': 320,
        'logo_start': 0,
        'logo_span': 322
    }

  return spp

################################################################################
# __main__
################################################################################
if __name__ == '__main__':
  main()


"""Sorting Algorithms utils."""

# System imports
import os
import random
import string
import timeit

# Local imports
from config import (FILES_REPO, IN_REPO, LOGS_REPO, OUT_REPO, SEPARATOR,
                    STR_NUMBER, STR_SIZE)
from models import (Data, Heapsort, Insertionsort, Mergesort, Quicksort,
                    Radixsort, Selectionsort, Shellsort)

def create_folder(path):
    """Create a folder"""
    if not os.path.exists(path):
        os.mkdir(path)

def create_structure():
    """Generate folders structure."""
    create_folder(FILES_REPO)
    create_folder(IN_REPO)
    create_folder(OUT_REPO)
    create_folder(LOGS_REPO)

def generate_string(number, chars=string.ascii_lowercase+string.digits):
    """Generate a string."""
    return ''.join(random.choice(chars) for _ in range(number))

def generate_in_files(number, order, size):
    """Generate input files."""

    def get_crescent_data():
        return [index for index in range(0, number)]

    def get_decreasing_data():
        return [index for index in range(number-1, -1, -1)]

    def get_random_data():
        return random.sample(range(0, number), number)

    switcher = {
        "decreasing": lambda: get_decreasing_data(),
        "crescent": lambda: get_crescent_data(),
        "random": lambda: get_random_data()
    }

    data = []
    path = IN_REPO + str(number)
    create_folder(path)
    keys = switcher.get(order)()
    for key in keys:
        values = [generate_string(STR_SIZE) for _ in range(0, STR_NUMBER)]
        data.append({key: values})
    write_file(data, path, order)
    return get_data(number, order, size)

def generate_out_files(data, number):
    """Generate output files."""
    out_data = [{data[i].key: data[i].values} for i in range(0, number)]
    write_file(out_data, OUT_REPO, str(number))

def generate_log_file(algorithm, number, order, size, compares, moves, time):
    """Generate log file."""
    with open(LOGS_REPO + algorithm + '.log', 'a') as out_file:
        out_file.writelines(str(number) + SEPARATOR +
                            order.upper() + SEPARATOR +
                            size.upper() + SEPARATOR +
                            "COMPARES: " + str(compares) + SEPARATOR +
                            "MOVES: " + str(moves) + SEPARATOR +
                            "TIME: " + str(time) + os.linesep)
        out_file.close()

def get_data(number, order, size):
    """Get input data."""

    def get_large_data():
        data = []
        for d in file:
            spl = d.split(SEPARATOR)
            data.append(Data(int(spl[0]), spl[1]))
        return data

    def get_small_data():
        data = []
        for d in file:
            spl = d.split(SEPARATOR)
            data.append(Data(int(spl[0])))
        return data

    switcher = {
        "large": lambda: get_large_data(),
        "small": lambda: get_small_data()
    }

    try:
        path = IN_REPO + str(number)
        file = read_file(path, order)
    except IOError:
        raise
    return switcher.get(size)()

def read_file(repo, name):
    """Read JSON files."""
    with open(repo + '/' + name + '.txt') as file:
        data = [d.rstrip() for d in file.readlines()]
        file.close()
    return data

def write_file(data, repo, name):
    """Write JSON files."""
    with open(repo + '/'+ name + '.txt', 'w') as file:
        for d in data:
            key = list(d.keys())[0]
            value = list(d.values())[0]
            file.writelines(str(key) + SEPARATOR + str(value) + os.linesep)
        file.close()

def sorting_algorithm(data, name):
    """Execute sorting algotithms."""
    switcher = {
        "heapsort": lambda: Heapsort(),
        "insertionsort": lambda: Insertionsort(),
        "quicksort": lambda: Quicksort(),
        "mergesort": lambda: Mergesort(),
        "radixsort": lambda: Radixsort(),
        "selectionsort": lambda: Selectionsort(),
        "shellsort": lambda: Shellsort()
    }
    begin_time = timeit.default_timer()
    algorithm = switcher.get(name)()
    out_data = algorithm.run(data)
    end_time = timeit.default_timer()
    return algorithm, out_data, end_time - begin_time


import random
from IPython.display import clear_output

#display the board everytime

def print_board(board):

        clear_output()
        print(board[7]+"|"+board[8]+"|"+board[9])
        print("_____")
        print(board[4]+"|"+board[5]+"|"+board[6])
        print("_____")
        print(board[1]+"|"+board[2]+"|"+board[3])

#to take which player has which moves sign

def player_input():
    marker=" "
    while marker!="X" and marker!="O":
        marker=input("Player 1: Enter the choice (X or O)").upper()
        if marker not in ["X","O"]:
            continue
        if marker=="X":
            return ("X","O")
        else:
            return ("O","X")

#to place marker in board

def place_marker(board,marker,position):
    board[position]=marker

# to check whwther a player won

def win_check(board,mark):
        return ((board[1]==mark and board[2]==mark and board[3]==mark) or
        (board[4]==mark and board[5]==mark and board[6]==mark) or
        (board[7]==mark and board[8]==mark and board[9]==mark) or
        (board[1]==mark and board[4]==mark and board[7]==mark) or
        (board[2]==mark and board[5]==mark and board[8]==mark) or
        (board[3]==mark and board[6]==mark and board[9]==mark) or
        (board[7]==mark and board[5]==mark and board[3]==mark) or
        (board[9]==mark and board[5]==mark and board[1]==mark))

#chooses the player who go first

def choose_first():
    flip=random.randint(1,2)
    if(flip==1):
        return "Player 1"
    else:
        return "Player 2"

#check whether a position is empty

def space_check(board,position):
    return board[position]==" "

#check whether a board is full

def full_check(board):
    c=9
    for i in range(1,10):
        if space_check(board,i)==False:
            c=c-1
    if(c==0):

        return True
    else:

        return False

#takes input of position

def player_choice(board):
    position=0
    while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board,position):
        position=int(input("Enter a position: (1-9)"))

    return position

#to replay a game

def replay():
    res=""
    while res not in ["Y","N"]:
         res=input("Play again ? Enter[Y/N] ").upper()

    return res=="Y"

### MAIN Part

print ("WELCOME to Tic Tac Toe X/O!!!")

while True:

    board=[" "]*10
    player1_marker, player2_marker=player_input()
    turn=choose_first()
    print(turn +" will go first")

    play_game=input("Ready for a game ?? [Y/N]").upper()

    if play_game=="Y":
        game_on=True
    else:
        game_on=False

    while game_on:

        if turn=="Player 1":

            print_board(board)

            position=player_choice(board)

            place_marker(board,player1_marker,position)

            if win_check(board,player1_marker):
                print_board(board)
                print("Player 1 Won!!!")
                game_on=False
            else:
                if full_check(board):
                    print_board(board)
                    print("A Tie !!!")
                    game_on=False
                else:
                    turn="Player 2"

        else:
            print_board(board)

            position=player_choice(board)

            place_marker(board,player2_marker,position)

            if win_check(board,player2_marker):
                print_board(board)
                print("Player 2 Won!!!")
                game_on=False
            else:
                if full_check(board):
                    print_board(board)
                    print("A Tie !!!")
                    game_on=False
                else:
                    turn="Player 1"

    if not replay():
        break


from typing import List

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        candidate = -1
        cnt = 0
        for n in nums:
            if cnt == 0:
                candidate = n
            if n == candidate:
                cnt += 1
            else:
                cnt -= 1

        cnt = 0
        for n in nums:
            if n == candidate:
                cnt += 1
        return candidate if cnt * 2 > len(nums) else -1

if __name__ == '__main__':
    s = Solution()
    print(s.majorityElement([3, 2]))


from __future__ import annotations

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from werkzeug.middleware.proxy_fix import ProxyFix

db = SQLAlchemy()

def create_app() -> Flask:
    from .load import load_content

    app = Flask(__name__)
    app.config.from_mapping(
        SECRET_KEY="dev",
        SQLALCHEMY_DATABASE_URI="sqlite://",
        FORWARDED=dict(FOR=0, PROTO=0, HOST=0, PORT=0, PREFIX=0),
    )
    app.config.from_prefixed_env()

    db.init_app(app)

    from . import models, views

    with app.app_context():
        db.create_all()
        load_content(
            app,
            models.Page,
            {
                "blog": models.BlogPost,
                "people": models.Person,
                "projects": models.Project,
            },
        )

    app.register_blueprint(views.bp)

    forwarded = app.config["FORWARDED"]

    if forwarded["FOR"] > 0:
        app.wsgi_app = ProxyFix(
            app.wsgi_app,
            x_for=forwarded["FOR"],
            x_proto=forwarded["PROTO"],
            x_host=forwarded["HOST"],
            x_port=forwarded["PORT"],
            x_prefix=forwarded["PREFIX"],
        )

    return app


# -*- coding: utf-8 -*-
# This module is responsible for communicating with the outside of the yolo package.
# Outside the package, someone can use yolo detector accessing with this module.
import time
import os
import numpy as np

from axelerate.networks.common_utils.feature import create_feature_extractor
from axelerate.networks.classifier.data_gen import create_datagen
from axelerate.networks.common_utils.fit import train
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D, Dropout
from keras.preprocessing import image
from keras.applications.mobilenet import preprocess_input

def prepare_image(file, show=False, size=(224,224)):
    img = image.load_img(file, target_size=size)
    img_array = image.img_to_array(img)
    img_array_expanded_dims = np.expand_dims(img_array, axis=0)
    return preprocess_input(img_array_expanded_dims)

def get_labels(directory):
    labels = sorted(os.listdir(directory))
    return labels

def create_classifier(architecture, labels, input_size, layers, dropout):
    base_model=create_feature_extractor(architecture, input_size)
    x=base_model.feature_extractor.outputs[0]
    x=GlobalAveragePooling2D()(x)
    for layer in layers[0:-1]:
        x=Dense(layer,activation='relu')(x)
        x=Dropout(dropout)(x)
    x=Dense(layers[-1],activation='relu')(x)
    preds=Dense(len(labels),activation='softmax')(x)
    model=Model(inputs=base_model.feature_extractor.inputs[0],outputs=preds)
    network = Classifier(model,input_size,labels)

    return network

class Classifier(object):
    def __init__(self,
                 network,
                 input_size,
                 labels):
        self._network = network
        self._labels = labels
        self._input_size = input_size

    def load_weights(self, weight_path, by_name=False):
        if os.path.exists(weight_path):
            print("Loading pre-trained weights in", weight_path)
            self._network.load_weights(weight_path, by_name=by_name)
        else:
            print("Fail to load pre-trained weights-starting training from scratch")

    def predict(self, image):
        preprocessed_image = prepare_image(image,show=False,size=(self._input_size,self._input_size))
        start_time = time.time()
        pred = self._network.predict(preprocessed_image)
        elapsed_ms = (time.time() - start_time) * 1000
        predicted_class_indices=np.argmax(pred,axis=1)
        predictions = [self._labels[k] for k in predicted_class_indices]
        return elapsed_ms, predictions, pred[0][predicted_class_indices]

    def train(self,
              img_folder,
              nb_epoch,
              project_folder,
              batch_size=8,
              augumentation=False,
              learning_rate=1e-4,
              train_times=1,
              valid_times=1,
              valid_img_folder="",
              first_trainable_layer=None):

        train_generator, validation_generator = create_datagen(img_folder, valid_img_folder, batch_size, self._input_size, project_folder, augumentation)
        return train(self._network,'categorical_crossentropy',train_generator,validation_generator,learning_rate, nb_epoch,project_folder,first_trainable_layer)


import QOTDBot as Qb
from typing import List

class FakeSlackClient:

    @staticmethod
    def say(channel: str, response: str):
        Qb.ignore_unused_args(channel)
        print(response)

    @staticmethod
    def react(channel: str, timestamp: str, emoji: str):
        Qb.ignore_unused_args(channel, timestamp)
        print(":" + emoji + ":")

    @staticmethod
    def dev_log(response: str):
        print(response)

    @staticmethod
    def get_direct_channel(user_id: str):
        Qb.ignore_unused_args(user_id)
        return Qb.DEPLOY_CHANNEL

    @staticmethod
    def get_name_by_id(user_id: str):
        Qb.ignore_unused_args(user_id)
        return "Dana Foley"

    @staticmethod
    def parse_bot_commands(events: List[dict]):
        for event in events:
            if event["type"] == "member_joined_channel" and event["channel"] == Qb.QOTD_CHANNEL:
                FakeSlackClient.say(Qb.QOTD_CHANNEL,
                                    "Welcome " + fake_get_reference_by_id(event["user"]) + "! " + Qb.WELCOME_MESSAGE)

def fake_log(response: str):
    Qb.ignore_unused_args(response)
    pass

def fake_get_reference_by_id(user_id: str):
    Qb.ignore_unused_args(user_id)
    return "@dana.foley"

def fake_get_id_from_reference(user_id_reference: str):
    Qb.ignore_unused_args(user_id_reference)
    return Qb.DEVELOPER_ID

if __name__ == "__main__":
    # Overwrite production-based functions
    Qb.log = fake_log
    Qb.get_reference_by_id = fake_get_reference_by_id
    Qb.get_id_from_reference = fake_get_id_from_reference

    Qb.slack_client = FakeSlackClient()

    Qb.question_keeper = Qb.QuestionKeeper()
    Qb.score_keeper = Qb.ScoreKeeper(Qb.slack_client)
    Qb.command_keeper = Qb.CommandKeeper()
    Qb.poll_keeper = Qb.PollKeeper()

    # Remove command restrictions
    for c in Qb.command_keeper.commands_list:
        c.public_only = False
        c.private_only = False

    print("QOTD Bot pretending to be connected and running!")

    input_str = ""
    Qb.slack_client.parse_bot_commands([{
        "type": "member_joined_channel",
        "user": "W06GH7XHN",
        "channel": Qb.QOTD_CHANNEL,
        "channel_type": "G",
        "team": "T8MPF7EHL"
    }])
    while input_str != "exit":
        input_str = input("> ")
        event_to_handle = {"user": Qb.DEVELOPER_ID, "channel": Qb.DEVELOPER_CHANNEL, "text": input_str}

        Qb.command_keeper.handle_event(event_to_handle)


# Python's Libraries
import logging

class BaseError(Exception):

    def __init__(self, _message, _error=None, _logger=None, _source=None,):
        self.logger = _logger or logging.getLogger(__name__)

        self.message = _message
        self.source = _source
        self.error = _error

        self.logger.error(self.__get_FullErrorMsg())

        super().__init__(_message)

    def __get_FullErrorMsg(self):
        value = f'{self.message}'
        if self.source:
            value = f'{value} ({self.source})'

        if self.error:
            value = f'{value}: {self.error}'

        return value

    def __str__(self):
        return self.__get_FullErrorMsg()

class OffsetOutRange(BaseError):
    pass