from dash.dependencies import Input, Output
import plotly.graph_objs as go

import datetime
import time
from app import app
import pandas as pd
import joblib

df_dim = pd.read_csv('data/Dimension.csv', encoding='latin-1')
model = joblib.load("RF_model.pkl")

@app.callback(Output('output', component_property='children'),
              [Input('date1', 'date'),
               Input('Time', component_property='value'),
               Input('predict-dropdown', component_property='value'),
               Input('button', 'n_clicks')])
def update_data(date, tim, state, n_clicks):
    # date = date.strftime('%Y/%m/%d')
    if n_clicks is not None:
        Lat = df_dim.loc[df_dim['State'] == state, 'Latitude'].values[0]
        Long = df_dim.loc[df_dim['State'] == state, 'Longitude'].values[0]
        ts = datetime.datetime.strptime(date+' '+tim, '%Y-%m-%d %H:%M:%S')
        ts = int(time.mktime(ts.timetuple()))
        d = {'c1': [ts], 'c2': [Lat], 'c3': [Long]}
        x = pd.DataFrame(data=d)

        # model = joblib.load("model.pkl")
        answer = model.predict(x)[0]
        return "As per the calculations of our model, there is a probability of an earthquake occurring of magnitude {} and depth {} km".format(answer[0], answer[1])

# ############################### -------  EARTHQUAKE CALLBACKS  ------- ######################################## #

df_EQ = pd.read_csv('data/Consolidated_EQ.csv', encoding='latin-1')
df_EQ['Date'] = pd.to_datetime(df_EQ['Date'], errors='coerce')

# callback for Earthquake data table changing as per data picker
@app.callback(Output('datatable-Earthquake', 'data'),
              [Input('date-picker-earthquake', 'start_date'),
               Input('date-picker-earthquake', 'end_date')])
def update_data_1(start_date, end_date):
    df2 = df_EQ[(df_EQ['Date'] > start_date) & (df_EQ['Date'] < end_date)]
    df2 = df2.to_dict("rows")
    return df2

# callback for Earthquake Graph as per data table
@app.callback(Output('EarthquakeGraph', 'figure'),
              [Input('date-picker-earthquake', 'start_date'),
               Input('date-picker-earthquake', 'end_date')])

def update_graph_1(start_date, end_date):
    df2 = df_EQ[(df_EQ['Date'] > start_date) & (df_EQ['Date'] < end_date)]
    return {
        'data': [go.Scatter(
            x=df2['Date'],
            y=df2['Magnitude'],
            mode='markers'
        )],
        'layout': {
            'height': 225,
            'margin': {'l': 20, 'b': 30, 'r': 30, 't': 10},
            'xaxis':{
                'title': 'Date'
                },
            'yaxis': {
                'title': 'Magnitude',
                'side': 'right'
            }
        }
    }

# ############################### -------  HEALTH STATISTICS CALLBACKS  ------- ###################################### #

df_health = pd.read_csv('data/Delhi Health WP data 2017.csv', encoding='latin-1')

df_health['Reported Date'] = pd.to_datetime(df_health['Reported Date'], errors='coerce')

# callback for Health data table changing as per data picker
@app.callback(Output('datatable-Health', 'data'),
              [Input('date-picker-health', 'start_date'),
               Input('date-picker-health', 'end_date')])
def update_data_2(start_date, end_date):
    df3 = df_health[(df_health['Reported Date'] > start_date) & (df_health['Reported Date'] < end_date)]
    df3 = df3.to_dict("rows")
    return df3

# callback for Health Graph as per data table
@app.callback(Output('HealthGraph', 'figure'),
              [Input('date-picker-health', 'start_date'),
               Input('date-picker-health', 'end_date')])

def update_graph_2(start_date, end_date):
    df4 = df_health[(df_health['Reported Date'] > start_date) & (df_health['Reported Date'] < end_date)]
    grp = df4.groupby('Month')['Occurrence'].sum().sort_values()
    return {
        'data': [go.Bar(
                    x=grp.index,
                    y=grp,
                    marker=dict(
                        color=['#35af8a', '#00846e', '#4d6e81', '#00d2da', '#008695', '#35af8a', '#00846e', '#4d6e81',
                               '#00d2da', '#008695', '#35af8a', '#00846e', '#4d6e81'
                        ]),
                    )
                ],
        'layout': {
            'height': 225,
            'margin': {'l': 20, 'b': 30, 'r': 50, 't': 10},
            'xaxis':{
                'title': 'Month'
                },
            'yaxis': {
                'side': 'right'
            }
        }
    }

# callback for Health Graph as per data table
@app.callback(Output('HealthScatter', 'figure'),
              [Input('date-picker-health', 'start_date'),
               Input('date-picker-health', 'end_date')])

def update_graph_3(start_date, end_date):
    df5 = df_health[(df_health['Reported Date'] > start_date) & (df_health['Reported Date'] < end_date)]
    grp = df5.groupby('Disease')['Occurrence'].sum().sort_values()
    return {
        'data': [go.Bar(
                    y=grp.index,
                    x=grp,
                    orientation='h',
                    )
                ],
        'layout': {
            'height': 1500,
            'margin': {'l': 120, 'b': 30, 'r': 10, 't': 10},
            'xaxis':{
                'title': 'Reported Disease Count'
                }
            }
        }

# callback for Health Graph grouped by Month
@app.callback(Output('MonthGraph', 'figure'),
              [Input('health-dropdown', 'value')])

def update_graph_4(value):
    grp = df_health.groupby('Month')
    grp1 = grp.get_group(value)
    grp2 = grp1.groupby('Disease')['Occurrence'].sum().nlargest(5)
    grp2 = grp2.sort_values()
    return {
        'data': [go.Bar(
                    y=grp2.index,
                    x=grp2,
                    orientation='h',
                    marker=dict(
                        color=['#35af8a', '#00846e', '#4d6e81', '#00d2da', '#008695']),
                    )
                ],
        'layout': {
            'height': 300,
            'margin': {'l': 20, 'b': 30, 'r': 280, 't': 10},
            'xaxis': {
                'title': 'Reported Disease Count',
                },
            'yaxis': {
                # 'tickangle':315,
                'side': 'right'
            }
            }
        }

# callback for Health Graph grouped by Region
@app.callback(Output('RegionGraph', 'figure'),
              [Input('region-dropdown', 'value')])

def update_graph_5(value):
    grp = df_health.groupby('Final Zone')
    grp1 = grp.get_group(value)
    grp2 = grp1.groupby('Disease')['Occurrence'].sum().nlargest(5)
    grp2 = grp2.sort_values()
    return {
        'data': [go.Bar(
                    y=grp2.index,
                    x=grp2,
                    orientation='h',
                    marker=dict(
                        color=['#35af8a', '#4d6e81', '#008695', '#00846e', '#00d2da']),
                    )
                ],
        'layout': {
            'height': 300,
            'margin': {'l': 20, 'b': 30, 'r': 280, 't': 10},
            'xaxis': {
                'title': 'Reported Disease Count',
                },
            'yaxis': {
                # 'tickangle':315,
                'side': 'right'
            }
            }
        }


from Game.name_input import *
from Game.button import *

class Name_Gui:

    inputs = None
    gui = None
    btn = None
    mouse = None

    def __init__(self, gui):
        self.gui = gui
        self.inputs = []
        self.btn = Btn("Assets/BTN.png", "Ok!", gui, 500, 500)
        self.btn.set_location(gui.width/2 - self.btn.obj.width/2, 270)
        self.mouse = gui.get_mouse()
        first_x = 200
        first_y = 200
        for i in range(8):
            n = name_input(gui, first_x, first_y, "_", 40)
            first_x += n.size + 40
            self.inputs.append(n)

    def draw(self, level, name):
        self.gui.set_background_color((0, 0, 0))
        self.gui.draw_text("Type your name:", 300, 100, 40, (255, 255, 255))
        self.btn.draw()
        n = ""
        for i in self.inputs:
            i.draw()
            if i.letter != "_":
                n += i.letter
        if self.btn.mouse_over() and self.mouse.is_button_pressed(1):
            level[0] = 0
            name[0] = n


class Solution:

    def longestPalindrome(self, s: str) -> str:
        # 在所有字符中间插入#
        def transform(s):
            return '$#' + '#'.join(list(s)) + '#&'

        if s == '':
            return s
        # 初始化
        s = transform(s)
        p = [0 for _ in range(len(s)+1)]
        mr, id_ = 0, 0
        # 首尾是特殊字符，所以下标从1到len(s)-2
        for i in range(1, len(s)-1):
            # 计算p[i]
            p[i] = 1 if mr <= i else min(p[2*id_-i], mr - i)

            # 只有当前i已经摆脱id限制，或者是第三种情况时，才有可能继续延伸
            # 这个只是优化，不加这个判断一样可以运行
            if mr <= i or p[2*id_-i] == mr - i:
                while s[i - p[i]] == s[i + p[i]]:
                    p[i] += 1

                if i + p[i] > mr:
                    mr, id_ = i + p[i], i
        # 找到长度最长的下标
        id_ = p.index(max(p))
        # 获得整个回文的字符串
        palindromic = s[id_ - p[id_]+1: id_ + p[id_]]
        # 过滤掉#，还原为原字符
        return ''.join(filter(lambda x: x != '#', list(palindromic)))


from django.conf.urls.defaults import *
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.decorators.cache import cache_page
from django.views.generic.base import TemplateView
from fanju.apis import v1_api, mobile_user_login, mobile_user_logout, mobile_user_register, weibo_user_login, checkemail
from fanju.decorators import restaurant_login_required, cache_page_for_anonymous
from fanju.views import upload_app
from fanju.views_common import list_tags, add_tag, add_like
from fanju.views import *
from django.conf import settings

import fanju.views_restaurant as rest

admin.autodiscover()
urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),
    url(r'^admin_tool/', include('admin_tools.urls')),
    #  (r'^grappelli/', include('grappelli.urls')),
    #    ('^get_restaurant_list_by_geo/$', get_restaurant_list_by_geo),
    #    ('^restaurant/(\d+)/$', get_restaurant),
    #    ('^restaurant/(\d+)/dish/recommendation/$', get_recommended_dishes),
    #    ('^restaurant/(\d+)/rating/$', restaurant_rating),
    #    ('^restaurant_tag/$', get_restaurant_tags),
    #    ('^restaurant_tag/(\d+)/restaurant/$', get_restaurants_with_tag),
    #    ('^region/$', get_regions),
    #    ('^region/(\d+)/restaurant/$', get_restaurants_in_region),
    #    ('^search_restaurant_list/$', restaurantList),
    ('^api/v1/login/$', mobile_user_login),
    ('^api/v1/logout/$', mobile_user_logout),
    ('^api/v1/weibo_user_login/$', weibo_user_login),
    ('^api/v1/checkemail/$', checkemail),
    ('^api/v1/register/$', mobile_user_register),
    #    ('^order/$', get_orders),
    #    ('^profile/$', get_user_profile),
    #    ('^profile/favorite/restaurant/(\d+)/$', favorite_restaurant),
    #    ('^profile/favorite/restaurant/$', favorite_restaurants),
    #    ('^search/restaurant/$', query_restaurant_from_google),

    #social
    #    ('^user/(\d+)/following/$', get_following),
    #    ('^user/(\d+)/following/remove/$', remove_following),
    #    ('^user/(\d+)/followers/$', followers),
    #    ('^user/(\d+)/following/recommendations/$', get_recommended_following),
    #    ('^user/(\d+)/messages/$', messages),
    #    ('^meal/(\d+)/participants/$', meal_participants),
    #    ('^user/(\d+)/invitation/$', view_or_send_meal_invitations),
    #    ('^user/(\d+)/invitation/(\d+)/$', accept_or_reject_meal_invitations),

    ######################below is used for website urls
    # meal
    url(r'^$', cache_page_for_anonymous(MealListView.as_view()), name="index"),
    url(r'^meal/$', cache_page_for_anonymous(MealListView.as_view()), name="meal_list"),
    url(r'^meal/(?P<meal_id>\d+)/$', MealDetailView.as_view(), name='meal_detail'),
    url(r'^order/cancel/(?P<order_id>\d+)/$', cancel_order, name='cancel_order'),
    url(r'^meal/add/$', login_required(MealCreateView.as_view()), name='create_meal'),

    url(r'^user/(?P<user_id>\d+)/meals/$', login_required(UserMealListView.as_view()), name="user_meal_list"),

    #menu
    url(r'^menu/$', login_required(MenuListView.as_view()), name="menu_list"),
    url(r'^menu/(?P<pk>\d+)/$', login_required(MenuDetailView.as_view()), name="menu_detail"),

    #ajax get menus
    #    url(r'^menu/$',login_required(get_menu), name='get_menu'),

    #comment

    #group
    #    url(r'^group/$', GroupListView.as_view(), name="group_list"),
    #    url(r'^group/(?P<pk>\d+)/$', GroupDetailView.as_view(), name='group_detail'),
    #    url(r'^group/add/$',login_required(GroupCreateView.as_view()), name='create_group'),
    #    url(r'^group/edit/(?P<pk>\d+)/$',login_required(GroupUpdateView.as_view()), name='edit_group'),
    #    url(r'^group/logo/edit/(?P<pk>\d+)/$',login_required(GroupLogoUpdateView.as_view()), name='edit_group_logo'),
    #    url(r'^group/(?P<pk>\d+)/join/$',login_required(join_group), name='join_group'),
    #    url(r'^group/(?P<pk>\d+)/leave/$',login_required(leave_group), name='leave_group'),
    #    url(r'^group/comment/add/$',login_required(create_group_comment), name='create_group_comment'),
    #    url(r'^group/comment/(?P<pk>\d+)/del/$',login_required(del_group_comment), name='del_group_comment'),
    #    url(r'^group/(?P<group_id>\d+)/comment/p/(?P<page>[0-9]+)/$', GroupCommentListView.as_view(),
    #        name='group_comment_list'),
    #    url(r'^group/(?P<group_id>\d+)/member/$', GroupMemberListView.as_view(), name='group_member_list'),
    #    url(r'^group/(?P<group_id>\d +)/member/p/(?P<page>[0-9]+)/$', GroupMemberListView.as_view(template_name="group/member_container.html"), name='more_group_member_list'),

    # order
    #    url(r'^meal/(?P<meal_id>\d+)/order/$',login_required(OrderCreateView.as_view()), name='create_order'),
    url(r'^meal/(?P<meal_id>\d+)/order/(?P<pk>\d+)/$', login_required(OrderDetailView.as_view()),
        name='order_detail'),
    url(r'^order/paying/(?P<order_id>\d+)/$', login_required(pay_order),
        name='pay_order'),
    url(r'^meal/(?P<meal_id>\d+)/order/status/', login_required(check_order_status), name="check_order_status"),

    url(r'^login/weibo/$', weibo_login, name='weibo_login'),
#    url(r'^bind/$', login_required(BindProfileView.as_view()), name='bind'),
    url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
    url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', kwargs={'login_url': "/"}, name="logout"),

    #account
    #    url(r'^user/register/$', RegisterView.as_view(), name='register'),
    url(r'^user/$', cache_page_for_anonymous(UserListView.as_view()), name="user_list"),
    url(r'^user/p/(?P<page>[0-9]+)/$', cache_page_for_anonymous(UserListView.as_view(template_name="profile/user_container.html")),
        name="more_user"),
    url(r'^profile/edit/$', login_required(ProfileUpdateView.as_view()), name='edit_basic_profile'),
    url(r'^user/(?P<pk>\d+)/$', login_required(ProfileDetailView.as_view()), name='user_detail'),
    url(r'profile/upload_avatar/$', login_required(UploadAvatarView.as_view()), name='upload_avatar'),
    url(r'user/info/$', login_required(get_user_info), name='get_user_info'),

    url(r'^follow/(?P<user_id>\d+)/$', login_required(follow), name='follow'),
    url(r'^unfollow/(?P<user_id>\d+)/$', login_required(un_follow), name='un_follow'),
    url(r'^follows/(?P<user_id>\d+)/$', login_required(FollowsView.as_view()), name='following_list'),

    #photo
    url(r'^photo/u/(?P<user_id>\d+)/$', login_required(PhotoListView.as_view()), name='photo_list'),
    url(r'^photo/upload/$', login_required(PhotoCreateView.as_view()), name='upload_photo'),
    url(r'^photo/(?P<pk>\d+)/$', login_required(PhotoDetailView.as_view()), name='photo_detail'),
    url(r'^photo/del/(?P<pk>\d+)/$', login_required(del_photo), name='del_photo'),
    url(r'^photo/request/(?P<host_id>\d+)/$', login_required(photo_request), name='photo_request'),

    url(r'^tag/$', login_required(list_tags), name='tag_list'),
    url(r'^tag/add/$', login_required(add_tag), name='add_tag'),

    url(r'^comment/(?P<comment_type>\w+)/(?P<target_id>\d+)/$', cache_page_for_anonymous()(CommentListView.as_view()), name='comment_list'),
    url(r'^comment/(?P<comment_type>\w+)/(?P<target_id>\d+)/add/$', login_required(add_comment), name='add_comment'),
    url(r'^comment/(?P<comment_type>\w+)/(?P<comment_id>\d+)/del/$', login_required(del_comment), name='del_comment'),

    url(r'^like/(?P<target_type>\w+)/(?P<target_id>\d+)/add/$', login_required(add_like), name='add_like'),

    #restaurant admin
    url(r'^restaurant/$', restaurant_login_required(rest.OrderCheckInView.as_view()), name="restaurant_admin"),

    url(r'^restaurant/chekin/$', restaurant_login_required(rest.OrderCheckInView.as_view()),
        name="restaurant_checkin"),
    url(r'^restaurant/order/use/$', restaurant_login_required(rest.use_order), name="restaurant_use_order"),

    url(r'^restaurant/order/today/$', restaurant_login_required(rest.TodayMealListView.as_view()), name="restaurant_today_meals"),

    url(r'^restaurant/dish/$', restaurant_login_required(rest.DishListView.as_view()), name="restaurant_dish_list"),
    url(r'^restaurant/dish/add/$', restaurant_login_required(rest.DishCreateView.as_view()),
        name="restaurant_dish_add"),
    url(r'^restaurant/dish/edit/(?P<pk>\d+)/$', restaurant_login_required(rest.DishUpdateView.as_view()),
        name="restaurant_dish_edit"),
    url(r'^restaurant/dish/del/(?P<dish_id>\d+)/$', restaurant_login_required(rest.del_dish),
        name="restaurant_dish_del"),
    url(r'^restaurant/dish_category/add/$', restaurant_login_required(rest.add_dish_category),
        name="add_dish_category"),

    url(r'^restaurant/order/$',
        restaurant_login_required(TemplateView.as_view(template_name="restaurant/order_history.html")),
        name="restaurant_order"),

    url(r'^restaurant/menu/$', restaurant_login_required(rest.MenuListView.as_view()), name="restaurant_menu_list"),
    url(r'^restaurant/menu/add/$', restaurant_login_required(rest.add_menu), name="add_menu"),
    url(r'^restaurant/menu/del/(?P<pk>\d+)/$', restaurant_login_required(rest.del_menu), name="del_menu"),
    url(r'^restaurant/menu/edit/(?P<pk>\d+)/$', restaurant_login_required(rest.edit_menu), name="edit_menu"),
    url(r'^restaurant/menu/copy/(?P<pk>\d+)/$', restaurant_login_required(rest.copy_menu), name="copy_menu"),
    url(r'^restaurant/menu/cover/edit/(?P<pk>\d+)/$', restaurant_login_required(rest.EditMenuCoverView.as_view()),
        name="edit_menu_cover"),

    #support
    url(r'^support/$', TemplateView.as_view(template_name="support/support.html"), name="support"),
    url(r'^faq/$', TemplateView.as_view(template_name="support/faq.html"), name="faq"),
    url(r'^faq/mobile/$', TemplateView.as_view(template_name="support/faq_mobile.html"), name="faq"),
    (r'^test/$', TemplateView.as_view(template_name="test.html")),

    # developer interfaces...
    ('^upload_app/$', upload_app),

    #pay
    url(r'^pay/alipay/direct/back/sync/$', handle_alipay_direct_sync_back, name="alipay_direct_sync_back"),
    url(r'^pay/alipay/direct/back/async/$', handle_alipay_direct_aysnc_back, name="alipay_direct_async_back"),
    url(r'^pay/alipay/app/back/sync/$', handle_alipay_app_sync_back, name="alipay_app_sync_back"),
    url(r'^pay/alipay/app/back/async/$', handle_alipay_app_async_back, name="alipay_app_async_back"),
    url(r'^pay/alipay/wap/back/sync/$', handle_alipay_wap_sync_back, name="alipay_wap_sync_back"),
    url(r'^pay/alipay/wap/back/async/$', handle_alipay_wap_async_back, name="alipay_wap_async_back"),

    url(r'^error/$', TemplateView.as_view(template_name='500.html'), name='error')
)

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()

# Standard bits...
urlpatterns += patterns('',
                        (r'^api/', include(v1_api.urls)),
)


from sys import argv
from requests import get
from threading import local
import concurrent.futures

def get_request(destination):
    get(destination)
    print(f"Successfull get request")

if __name__ == "__main__":
    local_thread, URL = local(), argv[1]

    while True:
        pool = concurrent.futures.ThreadPoolExecutor(max_workers=16)

        print("Starting requests...")
        for i in range(16):
            pool.submit(get_request, URL)

        pool.shutdown(wait=True)


from tkinter import  *

root=Tk()

height=500
width=700

x=(root.winfo_screenwidth()/2) - (width/2)
y=(root.winfo_screenheight()/2) - (height/2)

root.geometry(f'{width}x{height}+{int(x)}+{int(y)}')

root.mainloop()


from fastapi import APIRouter, Request

router = APIRouter()

@router.get("/")
async def home(req: Request):
    return "fastapi"

# @router.get("/items/{item_id}")
# def read_item(item_id: int, q: str | None):
#     return {"item_id": item_id, "q": q}


#!/usr/bin/python3

from typing import List
from typing import Dict

from datasets.aDataset import ADataset #class
from datasets.datasetML import DatasetML #class
from pandas.core.series import Series #class

from datasets.ml.ratings import Ratings #class

from portfolioDescription.aPortfolioDescription import APortfolioDescription #class

from portfolio.aPortfolio import APortfolio #class

from simulation.aSequentialSimulation import ASequentialSimulation #class

import pandas as pd
import numpy as np

from recommender.aRecommender import ARecommender #class

from pandas.core.frame import DataFrame #class

from history.aHistory import AHistory #class
from evaluationTool.aEvalTool import AEvalTool #class

from datasets.ml.behavioursML import BehavioursML #class

from simulation.tools.modelOfIndexes import ModelOfIndexes #class

class SimulationML(ASequentialSimulation):

    _ratingClass = Ratings
    _behaviourClass = BehavioursML

    @staticmethod
    def divideDataset(dataset:ADataset, behaviourDF:DataFrame,
                      divisionDatasetPercentualSize:int, testDatasetPercentualSize:int,
                      recomRepetitionCount:int):

        ratingsDF:DataFrame = dataset.ratingsDF
        usersDF:DataFrame = dataset.usersDF
        itemsDF:DataFrame = dataset.itemsDF

        # create train Dataset
        ratingsSortedDF:DataFrame = ratingsDF.sort_values(by=Ratings.COL_TIMESTAMP)
        numberOfRatings:int = ratingsSortedDF.shape[0]

        trainSize:int = (int)(numberOfRatings * divisionDatasetPercentualSize / 100)
        #print("trainSize: " + str(trainSize))
        trainRatingsDF:DataFrame = ratingsSortedDF[0:trainSize]

        datasetID:str = "ml1m" + "Div" + str(divisionDatasetPercentualSize)
        trainDataset:ADataset = DatasetML(datasetID, trainRatingsDF, usersDF, itemsDF)

        # create test Rating DataFrame
        testSize:int = (int)(numberOfRatings * testDatasetPercentualSize / 100)
        #print("testSize: " + str(testSize))
        testRatingsDF:DataFrame = ratingsSortedDF[trainSize:(trainSize + testSize)]

        # create test relevant Rating DataFrame
        testRelevantRatingsDF:DataFrame = testRatingsDF.loc[testRatingsDF[Ratings.COL_RATING] >= 4]

        # create behaviour dictionary of DataFrame indexed by recomRepetition
        recomRepetitionCountInDataset:int = behaviourDF[BehavioursML.COL_REPETITION].max() + 1

        testRepeatedBehaviourDict:dict = {}
        bIndexes:List[int] = list([recomRepetitionCountInDataset*i for i in testRatingsDF.index])
        for repetitionI in range(recomRepetitionCount):
            # indexes of behaviour
            indexes:List[int] = [vI+repetitionI for vI in bIndexes]
            behaviourDFI:DataFrame = DataFrame(behaviourDF.take(indexes).values.tolist(),
                        index=testRatingsDF.index, columns=behaviourDF.keys())
            testRepeatedBehaviourDict[repetitionI] = behaviourDFI

        return (trainDataset, testRelevantRatingsDF, testRelevantRatingsDF, testRepeatedBehaviourDict)

    @staticmethod
    def initEvaluationModel(dataset:ADataset):
        usersDF:DataFrame = dataset.usersDF

        # model with clicked ItemIDs for users
        clickedItems:dict[List[int]] = {}
        for indexI, rowI in usersDF.iterrows():
            clickedItems[rowI[Ratings.COL_USERID]] = []
        return clickedItems

    def iterateOverDataset(self, portfolios:List[APortfolio], portfolioDescs:List[APortfolioDescription],
                             portFolioModels:List[pd.DataFrame], evaluatonTools:List[AEvalTool],
                             histories:List[AHistory], testRatingsDF:DataFrame, testRelevantRatingsDF:DataFrame,
                             testBehaviourDict:Dict[int, DataFrame]):

        model:ModelOfIndexes = ModelOfIndexes(testRatingsDF, list(testRelevantRatingsDF.index), Ratings)

        portIds:List[str] = [portDescI.getPortfolioID() for portDescI in portfolioDescs]

        evaluations:List[dict] = [{} for i in range(len(portfolios))]

        counterI:int = 0

        currentDFIndexI:int
        nextIndexDFI:int
        for currentDFIndexI in list(testRatingsDF.index):

            counterI += 1
            if counterI  % 100 == 0:
                print("RatingI: " + str(counterI) + " / " + str(testRatingsDF.shape[0]))
                print("PortfolioIds: " + str(portIds))
                print("Evaluations: " + str(evaluations))

                self.computationFile.write("RatingI: " + str(counterI) + " / " + str(testRatingsDF.shape[0]) + "\n")
                self.computationFile.write("PortfolioIds: " + str(portIds) + "\n")
                self.computationFile.write("Evaluations: " + str(evaluations) + "\n")
                self.computationFile.flush()

            currentItemIdI:int = testRatingsDF.loc[currentDFIndexI][Ratings.COL_MOVIEID]
            currentRatingI:int = testRatingsDF.loc[currentDFIndexI][Ratings.COL_RATING]
            currentUserIdI:int = testRatingsDF.loc[currentDFIndexI][Ratings.COL_USERID]
            currentSessionIdI:int = None
            currentPageTypeI:object = None

            portfolioI:APortfolio
            for portfolioI in portfolios:

                dfI:DataFrame = DataFrame([testRatingsDF.loc[currentDFIndexI]], columns=testRatingsDF.keys())
                portfolioI.update(dfI, {})

            windowOfItemIDsI:int = model.getNextRelevantItemIDsExceptItemIDs(currentDFIndexI,
                                            self._clickedItems[currentUserIdI], self._windowSize)

            repetitionI:int
            for repetitionI in range(self._recomRepetitionCount):
                self.simulateRecommendations(portfolios, portfolioDescs, portFolioModels, evaluatonTools,
                                             histories, evaluations, currentDFIndexI, counterI, testRatingsDF.shape[0],
                                             currentUserIdI, currentSessionIdI, repetitionI,
                                             testRatingsDF, testBehaviourDict, windowOfItemIDsI, currentPageTypeI)

        return evaluations


from src import *
from data.data_loading import CocoStyleDataGenerator
from data.references import DATASETS

from keras.models import Sequential
from keras.layers import Conv2D, Flatten, Activation, Dense, Reshape
from keras.optimizers import SGD
from keras.losses import MSE
from keras.metrics import Accuracy

# libcudart.so.10.0
# libcublas.so.10.0
# libcufft.so.10.0
# libcurand.so.10.0
# libcusolver.so.10.0
# libcusparse.so.10.0
# libcudnn.so.7

if __name__ == "__main__":
    train_generator = CocoStyleDataGenerator(
        images_dir=DATASETS['coco']['train']['images'],
        labels_dir=DATASETS['coco']['train']['labels'],
        names_path=DATASETS['coco']['names']
    )
    test_generator = CocoStyleDataGenerator(
        images_dir=DATASETS['coco']['test']['images'],
        labels_dir=DATASETS['coco']['test']['labels'],
        names_path=DATASETS['coco']['names']
    )

    model = Sequential()
    model.add(Conv2D(
        filters=1024,
        kernel_size=(3, 3),
        activation='relu'
    ))
    model.add(Dense(4096))
    model.add(Dense(100 * 84))
    model.add(Reshape(target_shape=(100, 84)))
    model.add(Activation('softmax'))

    model.compile(
        optimizer=SGD(),
        loss=MSE,
        metrics=[Accuracy(), ]
    )

    model.fit_generator(
        generator=train_generator,
        validation_data=test_generator
    )


'''
작성일 : 23/5/23
작성자 : 김민채
목적 : 13주차 수업내 코딩 연습
'''

from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title('Show Image')

def showing1(event):
    label.configure(text='')
    img = Image.open('cat.gif')
    canvas.image = ImageTk.PhotoImage(img)
    canvas.create_image(0,0, image=canvas.image, anchot='nw')

def showing2(event):
    label.configure(text='')
    img = Image.open('dog.gif')
    canvas.image = ImageTk.PhotoImage(img)
    canvas.create_image(0,0, image=canvas.image, anchot='nw')

def resetCanvas(event):
    canvas.delete('all')
    label.configure(text='Disappear')
7
button1 = Button(root, text = 'Show cat')
button1.pack()

button2 = Button(root, text = 'Show dog')
button2.pack()

canvas = Canvas(root, width=500, height=400)
canvas.pack()

label = Label(root)
label.pack()

button1.bind('<Button-1>', showing1)
button1.bind('<Double-1>', resetCanvas)
button2.bind('<Button-1>', showing1)
button2.bind('<Double-1>', resetCanvas)

root.mainloop()


import pandas as py
import numpy as np

data = np.random.randint(10,100,75).reshape(15,5)
df = py.DataFrame(data,columns = ["Column1","Column2","Column3","Column4","Column5"])
result = df
result = df.columns
result = df.head() #ilk 5 kayıtı alır
result = df.head(10) #ilk 10 kayıtı alır
result = df.tail() # son 5 kayıtı alır
result = df.tail(10) #son 10 kayıtı alır

result = df["Column1"].head() # column1 in 5 elemanı
result = df.Column1.head() # alternatif
result = df[["Column1","Column2"]].head() #c1 ve c2 nin ilk beş elemanı

result = df[5:15][["Column1","Column2"]].head() #c1 ve c2 nin 5 den itirabern 5 elemanı
#FİLTRELEME
df_filter = df > 50
result = df[df_filter]
result = df[df%2==0]
df_filter2 = df["Column1"] > 50
result = df["Column1"][df_filter2]
result = df[(df["Column1"] > 50) & (df["Column2"] <= 70)]
result = df[(df["Column1"] > 50) | (df["Column2"] <= 70)]
result = df.query("Column1 >= 50 & Column1 % 2 ==0")[["Column1","Column2"]]

print(result)


import math
from decimal import Decimal
from unicodedata import decimal

class Pendulum():
    def __init__(self, n, g=9.8) -> None:
        self.thetas = [Decimal(3.1415/2)]*n
        self.thetaDots = [Decimal(0)]*n
        self.n = n
        self.g = -g

    def __matrix_vector_mul(self, matrix, vector):
        res = []
        for row in matrix:
            res.append(0)

            for i,col in enumerate(row):
                res[-1] += Decimal(col)*Decimal(vector[i])

        return res

    def A(self, thetas):
        mat = []
        for i in range(self.n):
            mat.append([])
            for j in range(self.n):
                mat[-1].append((self.n - max(i,j)) * math.cos(thetas[i] - thetas[j]))

        return mat.copy()

    def b(self, thetas, thetaDots):
        v = []
        for i in range(self.n):
            bi = 0
            for j in range(self.n):
                bi -= Decimal((self.n - max(i,j))) * Decimal(math.sin(thetas[i] - thetas[j])) * (thetaDots[j] ** 2)

            bi -= Decimal(self.g * (self.n-i)) * Decimal(math.sin(thetas[i]))
            v.append(bi)
        return v.copy()

    def f(self, thetas, thetaDots):
        A = self.A(thetas)
        b = self.b(thetas,thetaDots)
        return [thetaDots, self.__matrix_vector_mul(A,b)]

    def RK4(self, dt, thetas, thetaDots):
        dt = Decimal(dt)
        k1 = self.f(thetas, thetaDots)
        k2 = self.f([thetas[i] + k1[0][i]*dt/2 for i in range(self.n)], [thetaDots[i] + k1[1][i]*dt/2 for i in range(self.n)])
        k3 = self.f([thetas[i] + k2[0][i]*dt/2 for i in range(self.n)], [thetaDots[i] + k2[1][i]*dt/2 for i in range(self.n)])
        k4 = self.f([thetas[i] + k3[0][i]*dt for i in range(self.n)], [thetaDots[i] + k3[1][i]*dt for i in range(self.n)])

        thetaDeltas = [(k1[0][i] + k2[0][i]*2 + k3[0][i]*2 + k4[0][i])*dt/6 for i in range(self.n)]
        thetaDotDeltas = [(k1[1][i] + k2[1][i]*2 + k3[1][i]*2 + k4[1][i])*dt/6 for i in range(self.n)]

        return [[thetas[i]+thetaDeltas[i] for i in range(self.n)], [thetaDots[i]+thetaDotDeltas[i] for i in range(self.n)]]

    def update(self,dt):
        new_state = self.RK4(dt, self.thetas, self.thetaDots)
        self.thetas = new_state[0]
        self.thetaDots = new_state[1]

    def get_coordinates(self):
        x,y = 0,0
        coords = []
        for i in range(self.n):
            theta = self.thetas[i]
            x += math.sin(theta)
            y += math.cos(theta)
            coords.append((x,y))
        return coords.copy()


import scipy.io
import numpy as np
import common
import time
import os
import matplotlib.pyplot as plt
import FieldTrip2
import subprocess

output_directory = common.set_output_directory('prepare_cursor_gaze\\')

start = time.time()

mat = scipy.io.loadmat('..\\visual_input\\movie_cursor_eye\\test.mat')

cursor_xy = mat['CURSOR_XY2'][0, 0]
#np.save(file=output_directory + 'test.npy', arr=cursor_xy)
# #np.savetxt(fname=output_directory + 'test.npy', X=cursor_xy)
# del cursor_xy
# array = np.load(file=output_directory + 'test.npy', allow_pickle=True)
dimensions = cursor_xy.shape

class Number:
    axes = 2
    frames = 360
    trials = 480
    cursors = 3

Number.axes = dimensions[0]
Number.frames = dimensions[1]
Number.trials = dimensions[2]
Number.cursors = dimensions[3]
#
# cursor_xy = np.empty((Number.axes, Number.frames, Number.trials, Number.cursors))
# cursor_xy[:] = np.NaN
#
# for axis in range(0, Number.axes):
#     for frame in range(0, Number.frames):
#         for trial in range(0, Number.trials):
#             for cursor in range(0, Number.cursors):
#                 #print(array[axis, frame, trial, cursor])
#                 cursor_xy[axis, frame, trial, cursor] = array[axis, frame, trial, cursor]
#
# stop = time.time()
# print(stop-start)
# print('done!')

TRIAL = 1
CURSOR = 1

trajectory = np.transpose(cursor_xy[:, :, TRIAL, CURSOR])

plt.close('all')
plt.plot(trajectory[:, 0], trajectory[:, 1])
plt.xlim([-540, +540])
plt.ylim([-540, +540])

##

def close_buffers():
    try:
        subprocess.call("taskkill /F /IM buffer.exe /T")  # kill buffer
    except:
        print("buffer not running...")

    try:
        subprocess.call("taskkill /F /IM cmd.exe /T")  # kill cmd
    except:
        print("cmd not running...")

def buffer_trial(port, array):

    path_buffer_executable = "D:\\Network.Buffer.DRP.19.07.20\\realtimeHack.10.11.17\\buffer.exe"

    host = 'localhost'

    command = "start cmd /K " + path_buffer_executable + " " + host.__str__() + " " + port.__str__() + " -&"
    print(command)

    subprocess.Popen(command, shell=True)  # start buffer

    ftc = FieldTrip2.Client()  # create buffer object
    ftc.connect(host, port)  # connect to buffer
    ftc.putHeader(Number.axes, 0, FieldTrip2.DATATYPE_FLOAT32, None, None)  # put header - clears the buffer memory?

    ftc.putData(array.astype((np.float32)))  # put data

    hdr = ftc.getHeader()  # get header
    # print(hdr)  # print header

    D2 = ftc.getData((0, hdr.nSamples-1))  # get data
    # print(np.shape(D2))  # print data

    return(D2)

close_buffers()

CURSOR = 1
D2 = np.empty((2, Number.frames, 10))
D2[:] = np.nan

port = []

for TRIAL in range(0, 10):
    D2[:,:,TRIAL] = np.transpose(buffer_trial(port=TRIAL+1000, array=np.transpose(cursor_xy[:, :, TRIAL, CURSOR])))
    port.append(TRIAL+1000)

np.all(D2[:,:,:] == cursor_xy[:,:,0:10,1].astype(np.float32))


#!/usr/bin/env python3

import quine
from collections import Counter
from itertools import product

import math

# Brute force attempt to find good constants

def get_frequencies():
    pre = quine.prefixsection.generate()
    code = quine.codesection.generate(pre)
    from collections import Counter
    return Counter(code)

def find_representations(fixed_constants, weights):
    rep = dict((ord(c), (float("inf"), None)) for c in weights)
    # Assume cost of 4 for all fixed constants
    constants = dict((c, (4, "constant_%s" % c)) for c in fixed_constants)
    # Assume length of 5 for all adjectives and length 4 for the noun
    # used to generate powers of two. (add one to each adjective for spaces)
    for k in range(10):
        if 2**k not in constants:
            constants[2**k] = (6*k+4, "power_of_two_%s" % 2**k)
        if -2**k not in constants:
            constants[-2**k] = (6*k+4, "negative_power_of_two_%s" % 2**k)
    # constants
    rep.update(constants)

    uncovered_numbers = set(ord(c) for c in weights if ord(c) not in constants)
    while uncovered_numbers or changes:
        def add_number(x, cost, r):
            if x < 10000 and (x not in rep or rep[x][0] > cost):
                rep[x] = (cost, r)
                changes = True
        changes = False
        known_numbers = [(x, (cost, r)) for x, (cost, r) in rep.items()
                                          if cost < float("inf")]
        for x, (cost, r) in known_numbers:
            # twice x
            add_number(2*x, cost + 6, "twice " + r)
            # the cube of x
            add_number(x**3, cost + 12, "the cube of " + r)
            # the square of x
            add_number(x**2, cost + 14, "the square of " + r)
            if x > 0:
                # the factorial of x
                add_number(math.factorial(x), cost + 17, "the factorial of " + r)
                # the square root of x
                add_number(int(x**0.5), cost + 19, "the square root of " + r)

        for x1, (cost1, r1) in known_numbers:
            for x2, (cost2, r2) in known_numbers:
                # the sum of x and y
                add_number(x1 + x2, cost1 + cost2 + 16, "the sum of %s and %s" % (r1, r2))
                # the product of x and y
                add_number(x1 * x2, cost1 + cost2 + 20, "the product of %s and %s" % (r1, r2))
                # the difference between x and y
                add_number(x1 - x2, cost1 + cost2 + 28, "the difference between %s and %s" % (r1, r2))

        uncovered_numbers -= set(x for x, (cost, _) in rep.items()
                                       if cost < float("inf"))
    return rep

def main():
    frequencies = get_frequencies()
    frequencies.update("QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890")
    constants = [ord(c) for c, _ in frequencies.most_common(3)]
    best = None
    best_cost = float("inf")
    ints_to_cover = [ord(c) for c in frequencies]

    for c1 in range(1, 150):
        for c2 in range(c1 + 1, 150):
            print(c1,c2)
            representations = find_representations(constants + [c1, c2], frequencies)
            cost = sum(c * frequencies[chr(k)] for k, (c, _) in representations.items()
                                                    if k in ints_to_cover)
            if cost < best_cost:
                best_cost = cost
                best = representations

    for char, (cost, rep) in best.items():
        if char in ints_to_cover:
            print("    %s: \"%s\",%d" % (char, rep, cost))

if __name__ == "__main__":
    main()


#
# @lc app=leetcode.cn id=111 lang=python3
#
# [111] 二叉树的最小深度
#
# https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/description/
#
# algorithms
# Easy (42.69%)
# Likes:    289
# Dislikes: 0
# Total Accepted:    89K
# Total Submissions: 207.9K
# Testcase Example:  '[3,9,20,null,null,15,7]'
#
# 给定一个二叉树，找出其最小深度。
#
# 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
#
# 说明: 叶子节点是指没有子节点的节点。
#
# 示例:
#
# 给定二叉树 [3,9,20,null,null,15,7],
#
#    3
#   / \
#  9  20
#    /  \
#   15   7
#
# 返回它的最小深度  2.
#
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0

        cur = [(root,1)]

        while cur:
            node,depth = cur.pop(0)
            if node.left:
                cur.append((node.left,depth+1))
            if node.right:
                cur.append((node.right,depth+1))
            if not node.left and not node.right:
                return depth

# @lc code=end

    # def minDepth(self, root: TreeNode) -> int: 迭代
    #     if not root:
    #         return 0

    #     queue = [[root]]
    #     depth = 1
    #     while queue:
    #         nodes = queue.pop(0)
    #         children = []
    #         for cur in nodes:
    #             if not cur.left and not cur.right:
    #                 return depth
    #             if cur.left:
    #                 children.append(cur.left)
    #             if cur.right:
    #                 children.append(cur.right)
    #         depth += 1
    #         queue.append(children)
    #     return depth

    # def minDepth(self, root: TreeNode) -> int:#递归
    #     if not root:
    #         return 0
    #     if not root.left:
    #         return self.minDepth(root.right) + 1
    #     if not root.right:
    #         return self.minDepth(root.left) + 1
    #     return min(self.minDepth(root.right),self.minDepth(root.left)) + 1

111.二叉树的最小深度.py


# HC

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# imporing Mall_Customers with pandas
dataset = pd.read_csv('Mall_Customers.csv')

# selct our column of insterest (annual, spending score)
X = dataset.iloc[:, [3,4]].values

# using the dendrogram to find the optimal number of clusters
import scipy.cluster.hierarchy as sch
dendrogram = sch.dendrogram(sch.linkage(X, method='ward'))

plt.title('Dendrogram')
plt.xlabel('Customers')
plt.ylabel('Euclidean Distance')
plt.show()

# next step is to fit the K-Means algorithm to our data X.
from sklearn.cluster import AgglomerativeClustering
hc = AgglomerativeClustering(n_clusters=5, affinity='euclidean', linkage='ward')
y_hc = hc.fit_predict(X)

# visualizing the cluster
plt.scatter(X[y_hc == 0, 0], X[y_hc == 0, 1], s = 100, c = 'red', label = 'Careful')
plt.scatter(X[y_hc == 1, 0], X[y_hc == 1, 1], s = 100, c = 'blue', label = 'Standard')
plt.scatter(X[y_hc == 2, 0], X[y_hc == 2, 1], s = 100, c = 'green', label = 'Target')
plt.scatter(X[y_hc == 3, 0], X[y_hc == 3, 1], s = 100, c = 'cyan', label = 'Careless')
plt.scatter(X[y_hc == 4, 0], X[y_hc == 4, 1], s = 100, c = 'magenta', label = 'Sensible')
plt.title('Clusters of customers')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show()

Part 4 - Clustering/Section 22 - Hierarchical Clustering/hc.py


import torch
from torch.optim.lr_scheduler import MultiStepLR, CosineAnnealingLR, ExponentialLR, OneCycleLR

def fetch_optimizer(model, cfg):
    """ Create the optimizer and learning rate scheduler """
    # optimizer = optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wdecay, eps=args.epsilon)

    # scheduler = optim.lr_scheduler.OneCycleLR(optimizer, args.lr, args.num_steps+100,
    #     pct_start=0.05, cycle_momentum=False, anneal_strategy='linear')
    optimizer = build_optimizer(model, cfg)
    scheduler = build_scheduler(cfg, optimizer)

    return optimizer, scheduler

def build_optimizer(model, config):
    name = config.optimizer
    lr = config.canonical_lr

    if name == "adam":
        return torch.optim.Adam(model.parameters(), lr=lr, weight_decay=config.adam_decay, eps=config.epsilon)
    elif name == "adamw":
        if hasattr(config, 'twins_lr_factor'):
            factor = config.twins_lr_factor
            print("[Decrease lr of pre-trained model by factor {}]".format(factor))
            param_dicts = [
                {"params": [p for n, p in model.named_parameters() if "feat_encoder" not in n and 'context_encoder' not in n and p.requires_grad]},
                {
                    "params": [p for n, p in model.named_parameters() if ("feat_encoder" in n or 'context_encoder' in n) and p.requires_grad],
                    "lr": lr*factor,
                },
            ]
            full = [n for n, _ in model.named_parameters()]
            return torch.optim.AdamW(param_dicts, lr=lr, weight_decay=config.adamw_decay, eps=config.epsilon)
        else:
            return torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=config.adamw_decay, eps=config.epsilon)
    else:
        raise ValueError(f"TRAINER.OPTIMIZER = {name} is not a valid optimizer!")

def build_scheduler(config, optimizer):
    """
    Returns:
        scheduler (dict):{
            'scheduler': lr_scheduler,
            'interval': 'step',  # or 'epoch'
        }
    """
    # scheduler = {'interval': config.TRAINER.SCHEDULER_INTERVAL}
    name = config.scheduler
    lr = config.canonical_lr

    if name == 'OneCycleLR':
        # scheduler = OneCycleLR(optimizer, )
        if hasattr(config, 'twins_lr_factor'):
            factor = config.twins_lr_factor
            scheduler = OneCycleLR(optimizer, [lr, lr*factor], config.num_steps+100,
                pct_start=0.05, cycle_momentum=False, anneal_strategy=config.anneal_strategy)
        else:
            scheduler = OneCycleLR(optimizer, lr, config.num_steps+100,
                pct_start=0.05, cycle_momentum=False, anneal_strategy=config.anneal_strategy)
    # elif name == 'MultiStepLR':
    #     scheduler.update(
    #         {'scheduler': MultiStepLR(optimizer, config.TRAINER.MSLR_MILESTONES, gamma=config.TRAINER.MSLR_GAMMA)})
    #elif name == 'CosineAnnealing':
    #    scheduler = CosineAnnealingLR(optimizer, config.num_steps+100)
    #     scheduler.update(
    #         {'scheduler': CosineAnnealingLR(optimizer, config.TRAINER.COSA_TMAX)})
    # elif name == 'ExponentialLR':
    #     scheduler.update(
    #         {'scheduler': ExponentialLR(optimizer, config.TRAINER.ELR_GAMMA)})
    else:
        raise NotImplementedError()

    return scheduler


"""
Review Question 9
Create a class named quadratic, where a, b and c are data attributes
and the methods are
    a) __init__() to initialize the data attributes
    b) roots() to compute the quadratic equation
"""
import math

class Quadratic:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def roots(self):
        b2_4ac = self.b ** 2 - 4 * self.a * self.c
        if b2_4ac < 0:
            print("No real roots")
        else:
            x1 = (-self.b - math.sqrt(b2_4ac)) / (2 * self.a)
            x2 = (-self.b + math.sqrt(b2_4ac)) / (2 * self.a)
            print(f"The roots are {(x1, x2)}")

def main():
    quad = Quadratic(1, -5, 6)
    quad.roots()

if __name__ == "__main__":
    main()


import numpy as np
import pandas as pd
import riskfolio as rp
from statsmodels.tsa.stattools import grangercausalitytests
from tigramite import data_processing as pp
from tigramite import plotting as tp
from tigramite.pcmci import PCMCI
from tigramite.independence_tests.parcorr import ParCorr

def make_positive_definite(cov_matrix, epsilon=1e-2):
    eigvals, eigvecs = np.linalg.eigh(cov_matrix)

    if np.any(eigvals < epsilon):
        eigvals[eigvals < epsilon] = epsilon
        positive_definite_cov = np.dot(eigvecs, np.dot(np.diag(eigvals), eigvecs.T))
    else:
        positive_definite_cov = cov_matrix

    return positive_definite_cov

def equal_weights(returns):
    n_assets = returns.shape[1]
    w = np.full(n_assets, 1.0 / n_assets)
    w = pd.DataFrame(w, index=returns.columns, columns = ['weights'])
    return w

def random_weights(returns):
    n_assets = returns.shape[1]
    w = np.random.random(n_assets)
    w /= np.sum(w)
    w = pd.DataFrame(w, index=returns.columns, columns = ['weights'])
    return w

def mv_portfolio(returns, mv_conf, constraints = [None, None]):
    port = rp.Portfolio(returns=returns)

    print(f'\n{returns.index[0].date()}')
    print(f'{returns.index[-1].date()}')

    # # Add portfolio constraints
    # port.ainequality = constraints[0] # A
    # port.binequality = constraints[1] # B

    method_mu = mv_conf['method_mu']
    method_cov = mv_conf['method_cov']

    port.assets_stats(method_mu=method_mu, method_cov=method_cov, d=mv_conf['d_lib_const'])

    # port.cov = make_positive_definite(port.cov)

    # -------------------------------------------------------------- #
    # DPhil
    # port.cov = grangers_causation_matrix(Y, variables = Y.columns)
    # port.cov.reset_index(drop=True, inplace=True)
    # -------------------------------------------------------------- #

    # port.solvers = ['MOSEK']
    port.alpha = mv_conf['alpha']
    model= mv_conf['model'] # Could be Classic (historical), BL (Black Litterman) or FM (Factor Model)
    rm = mv_conf['rm'] # Risk measure used, this time will be variance
    obj = mv_conf['obj'] # Objective function, could be MinRisk, MaxRet, Utility or Sharpe
    hist = mv_conf['hist'] # Use historical scenarios for risk measures that depend on scenarios
    rf = mv_conf['rf'] # Risk free rate
    l = mv_conf['l'] # Risk aversion factor, only useful when obj is 'Utility'
    try:
        w = port.optimization(model=model, rm=rm, obj=obj, rf=rf, l=l, hist=hist)
        print(f'weights successfully calculated for {returns.index[0].date()}-{returns.index[-1].date()}')
    except:
        w = None
        print(f'weights index unsuccessful for {returns.index[0].date()}-{returns.index[-1].date()}. weights.tail(1).T used.\n')
    return w, port.cov

# -------------------------------------------------------------- #
# My DPhil Functions
# -------------------------------------------------------------- #

def grangers_causation_matrix(data, variables, maxlag, test='ssr_chi2test', verbose=False):
    df = pd.DataFrame(np.zeros((len(variables), len(variables))), columns=variables, index=variables)
    for c in df.columns:
        for r in df.index:
            test_result = grangercausalitytests(data[[r, c]], maxlag=maxlag, verbose=False)
            p_values = [round(test_result[i+1][0][test][1],4) for i in range(maxlag)]
            if verbose: print(f'Y = {r}, X = {c}, P Values = {p_values}')
            min_p_value = np.min(p_values)
            df.loc[r, c] = min_p_value
    df.columns = [var + '_x' for var in variables]
    df.index = [var + '_y' for var in variables]
    return df

def grangers_causation_matrix_portfolio(returns, mv_config, grangers_causation_matrix_config, constraints = [None, None]):

    port = rp.Portfolio(returns=returns)
    print(f'\n{returns.index[0].date()}')
    print(f'{returns.index[-1].date()}')

    # # Add portfolio constraints
    # port.ainequality = constraints[0] # A
    # port.binequality = constraints[1] # B

    method_mu = mv_config['method_mu']
    method_cov = mv_config['method_cov']
    port.assets_stats(method_mu=method_mu, method_cov=method_cov, d=mv_config['d_lib_const'])

    # -------------------------------------------------------------- #
    # DPhil
    port.cov = grangers_causation_matrix(returns, variables = returns.columns, maxlag = grangers_causation_matrix_config['maxlag'], test = grangers_causation_matrix_config['test'])
    port.cov.reset_index(drop=True, inplace=True)
    # -------------------------------------------------------------- #

    # port.solvers = ['MOSEK']
    port.alpha = mv_config['alpha']
    model= mv_config['model'] # Could be Classic (historical), BL (Black Litterman) or FM (Factor Model)
    rm = mv_config['rm'] # Risk measure used, this time will be variance
    obj = mv_config['obj'] # Objective function, could be MinRisk, MaxRet, Utility or Sharpe
    hist = mv_config['hist'] # Use historical scenarios for risk measures that depend on scenarios
    rf = mv_config['rf'] # Risk free rate
    l = mv_config['l'] # Risk aversion factor, only useful when obj is 'Utility'
    try:
        w = port.optimization(model=model, rm=rm, obj=obj, rf=rf, l=l, hist=hist)
        print(f'\nweights successfully calculated')
    except:
        w = None
        print(f'\nweights index unsuccessful. weights.tail(1).T used.\n')
    return w, port.cov

def PCMCI_wrapped(returns, mv_config, PCMCI_wrapped_causation_matrix_config, constraints = [None, None]):

    port = rp.Portfolio(returns=returns)
    print(f'\n{returns.index[0].date()}')
    print(f'{returns.index[-1].date()}')

    # # Add portfolio constraints
    # port.ainequality = constraints[0] # A
    # port.binequality = constraints[1] # B

    method_mu = mv_config['method_mu']
    method_cov = mv_config['method_cov']
    port.assets_stats(method_mu=method_mu, method_cov=method_cov, d=mv_config['d_lib_const'])

    # -------------------------------------------------------------- #
    # DPhil

    print('\nPCMCI\n')

    var_names = list(returns.columns)
    dataframe = pp.DataFrame(returns.values, var_names=var_names)
    alpha = PCMCI_wrapped_causation_matrix_config['pcmci_alpha']
    tau_max = PCMCI_wrapped_causation_matrix_config['pcmci_tau_max']

    if PCMCI_wrapped_causation_matrix_config['pcmci_cond_ind_test'] == 'ParCorr':
        pcmci_object = PCMCI(dataframe=dataframe, cond_ind_test=ParCorr())

    # results = pcmci_object.run_pcmci(tau_max=tau_max, pc_alpha=alpha)
    results = pcmci_object.run_pcmci(tau_max=tau_max, pc_alpha=None)

    # p-value omitting
    p_matrix = results['p_matrix']
    val_matrix = results['val_matrix']
    if PCMCI_wrapped_causation_matrix_config['pcmci_drop_val_below_alpha'] == True:
        val_matrix[p_matrix > alpha] = 0

    # --------- #
    # slice research !!

    # PCMCI_wrapped_causation_matrix_config['pcmci_relationships_slice']
    # simultanious slice: only current relationships ('0') - no lags
    # PCMCI_matrix = pd.DataFrame(val_matrix[:,:,PCMCI_wrapped_causation_matrix_config['pcmci_relationships_slice']])

    # Sum !
    sum_across_slices = val_matrix.sum(axis=2)
    PCMCI_matrix = pd.DataFrame(sum_across_slices)

    PCMCI_matrix.columns = returns.columns
    PCMCI_matrix.index = returns.columns

    if PCMCI_wrapped_causation_matrix_config['pcmci_plus_diag_cov'] == True:
        df2_diag = np.diag(port.cov)
        for i in range(len(PCMCI_matrix)):
            PCMCI_matrix.iat[i, i] += df2_diag[i]

    print('\n', PCMCI_matrix)

    port.cov = PCMCI_matrix
    port.cov.reset_index(drop=True, inplace=True)

    # -------------------------------------------------------------- #

    # port.solvers = ['MOSEK']
    port.alpha = mv_config['alpha']
    model= mv_config['model'] # Could be Classic (historical), BL (Black Litterman) or FM (Factor Model)
    rm = mv_config['rm'] # Risk measure used, this time will be variance
    obj = mv_config['obj'] # Objective function, could be MinRisk, MaxRet, Utility or Sharpe
    hist = mv_config['hist'] # Use historical scenarios for risk measures that depend on scenarios
    rf = mv_config['rf'] # Risk free rate
    l = mv_config['l'] # Risk aversion factor, only useful when obj is 'Utility'
    try:
        w = port.optimization(model=model, rm=rm, obj=obj, rf=rf, l=l, hist=hist)
        print(f'\nweights successfully calculated')
    except:
        w = None
        print(f'\nweights index unsuccessful. weights.tail(1).T used.\n')
    return w, port.cov


import numpy as np
import cv2
import matplotlib.pyplot as plt

original_image = cv2.imread('test/noise/right/081.png')

img = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)

vectorized = img.reshape((-1,3))
vectorized = np.float32(vectorized)

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 7
attempts=10
ret,label,center=cv2.kmeans(vectorized,K,None,criteria,attempts,cv2.KMEANS_PP_CENTERS)

center = np.uint8(center)

res = center[label.flatten()]
result_image = res.reshape((img.shape))

cv2.imwrite('result.jpg',result_image)


#pip install geocoder
import geocoder
#Modify this to your own lookup folder
lookups = 'D:/Documents/IPython/Datathon/MelbDatathon2017/lookups/'
df_patients=pd.read_csv('{}patients.txt'.format(lookups), sep = '\t')
pc=df_patients.postcode.unique()

df_pc=pd.DataFrame(columns=['postcode'])
df_pc.postcode=pc

gc=Nominatim(view_box=(112.467,-55.050,168.000,-9.133),country_bias='Australia')

def get_cor(postcode):
    s_t=clock()
    loc=None
    while loc is None:
        try:
            loc=geocoder.google('{}, Australia'.format(postcode))
        except:
            print ("error")

    e_t=clock()
    time.append(e_t-s_t)
    print('{}:{}'.format(len(time),time[-1]),end=' , ')
    print ('{}'.format(postcode),end=',')
    print('{},{}'.format(loc.lng,loc.lat))
    return '{}#{}#{}'.format(loc.address,loc.lng,loc.lat)

df_pc=df_pc[:]
time=[]

df_pc['address,lon,lat']=df_pc['postcode'].apply(lambda x: get_cor(x))

df_pc['address'],df_pc['lon'],df_pc['lat']=df_pc['address,lon,lat'].str.split('#').str
df_pc=df_pc.drop('address,lon,lat',1)

# df_pc.lon=df_pc.lon.astype(float)
# df_pc.lat=df_pc.lat.astype(float)
df_pc


#### Utils ####

# Takes in a regexp representing all files to read.
# Outputs a numpy.ndarray of rank-1 numpy.ndarrays.
#
# OUTPUT format:
# Outer array length is # of songs. Inner array lengths are song lengths.
# Each song is a numpy.ndarray of tuples (1-tuples for notes and k-tuples for chords).
def process_melodies_as_offsets(filepath = FILEPATH):
    # Identify which songs are valid (= 2 parts, without any chords in first part)... adjust size based on that
    original_files = list(glob.iglob(filepath, recursive = True))
    valid_files = []
    for file in original_files:
        success, _ = read_melody_as_pitch_offset_duration(file)
        if success:
            valid_files.append(file)

    # Process songs
    num_files = len(valid_files)
    songs_original, songs_as_pitches, songs_as_offsets = np.empty(num_files, dtype=object), np.empty(num_files, dtype=object), np.empty(num_files, dtype=object)
    first_notes = np.empty(num_files)
    for i in range(num_files):
        # First, read in each song as np-array of (pitch, offset, duration) tuples.
        _, melody = read_melody_as_pitch_offset_duration(valid_files[i])  # only added successfully-parsed files to valid_files
        songs_original[i] = np.array(melody)
        # Then, convert the song into pitch-only-tuples (1-tuple for note, k-tuple for chord).
        # We call _concat_chords to compress all notes with the same offset AND duration into chords.
        songs_as_pitches[i] = np.array([tuple(p) for p in _concat_chords(songs_original[i])]).flatten()  # processing as tuples for consistency but expecting all ints! should crash below if not ints
        song = songs_as_pitches[i]
        offsets = np.empty(song.shape[0]-1)
        for j in range(len(song)):
            if j == 0:
                first_notes[i] = song[j]
            else:
                offsets[j-1] = song[j] - song[j-1]
        songs_as_offsets[i] = np.array(offsets)
    print(songs_as_pitches[0])
    return first_notes, songs_as_offsets

def _concat_chords(arr):
    input_len = arr.shape[0]
    pitch, offset, duration = arr[:,0], arr[:,1], arr[:,2]
    pitch = pitch.astype(np.int32).tolist()  # must convert to native int type (see final case in Chord's _add_core_or_init)

    output = []
    # key idea: for every offset, maintain a dict that maps: duration --> list of pitches
    # each element of the map is a chord (or note, if only 1)
    i = 0
    output_notes = []
    while i < input_len:
        dd = defaultdict(list)
        if pitch[i] != 0:
            dd[duration[i]].append(pitch[i])
        while i+1 < input_len and offset[i+1] == 0:  # increment i and add next values to the map
            i += 1
            if pitch[i] != 0:
                dd[duration[i]].append(pitch[i])
        for pitches in dd.values():
            output.append(pitches)
        i += 1

    return output


R'''
Given a sorted array of n integers that has been rotated an unknown number of times, write code to find an element in the array. You may assume that the array was originally sorted in increasing order.
EXAMPLE
Input:find 5 in {l5, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14}
Output: 8 (the index of 5 in the array)
'''

def search_r(arr, key):
    R'''
    Author's O(logn) for distinct elements
    '''
    l, r = 0, len(arr) - 1
    while l <= r:
        mid = l + (r - l) // 2
        if key == arr[mid]:
            return mid

        if arr[l] < arr[mid]: # left side is normally ordered
            if key >= arr[l] and key < arr[mid]:
                r = mid - 1
            else:
                l = mid + 1
        elif arr[mid] < arr[l]: # right side is normally ordered
            if key > arr[mid] and key <= arr[r]:
                l = mid + 1
            else:
                r = mid - 1
        elif arr[l] == arr[mid]:
            if arr[mid] != arr[r]:
                l = mid + 1
            else: # Search both halves
                for i in range(len(arr)):
                    if arr[i] == key:
                        return key

arr = [9, 9, 1, 2, 3, 5, 9]
mid = search_r(arr, 1)
print(mid)


import pygame
from ..components import ui

# main menu screen
class Main_Menu:
  def __init__(self, parent, resources, load_map_selector, load_difficulty_change, load_map_creator):

    self.parent = parent
    self.resources = resources
    self.load_map_selector = load_map_selector
    self.load_difficulty_change = load_difficulty_change
    self.load_map_creator = load_map_creator

    self.screen_size = (parent.get_width(), parent.get_height())

    # images for buttons
    self.start_button_image = self.resources["start_button.png"]
    self.difficulty_button_image = self.resources["difficulty_button.png"]

    # set font
    self.font = pygame.font.SysFont("Arial", 18)

    self.buttons = []  # contains all buttons

    # position start button
    self.start_button = ui.Button(self.parent, self.resources["start_button.png"], (0, 0), self.load_map_selector)
    self.start_button.rect.centerx = self.screen_size[0]/2
    self.start_button.rect.top = 70
    self.buttons.append(self.start_button)

    # position change difficulty button
    self.difficulty_button = ui.Button(self.parent, self.resources["difficulty_button.png"], (0, 0), self.load_difficulty_change)
    self.difficulty_button.rect.centerx = self.screen_size[0]/2
    self.difficulty_button.rect.top = self.start_button.rect.bottom + 30
    self.buttons.append(self.difficulty_button)

    # create map creator button
    self.map_creator_button = ui.Button(self.parent, self.resources["map_creator_button.png"], (0, 0), self.load_map_creator)
    self.map_creator_button.rect.centerx = self.screen_size[0]/2
    self.map_creator_button.rect.top = self.difficulty_button.rect.bottom + 15
    self.buttons.append(self.map_creator_button)

    # reminder to turn on sound text
    sound_reminder_content = "Turn on sound for the best experience!"
    self.sound_reminder_text = self.font.render(sound_reminder_content, True, "black")
    self.sound_reminder_pos = self.sound_reminder_text.get_rect()
    self.sound_reminder_pos.centerx = self.screen_size[0]/2
    self.sound_reminder_pos.bottom = self.screen_size[1] - 30

  # called once per tick by main.py
  def update(self):
    self.handle_events()
    self.render()

  # handles events (mostly button press)
  def handle_events(self):
    # event handling
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        pygame.quit()

      # handle clicks on buttons
      if event.type == pygame.MOUSEBUTTONDOWN:
        if event.button == 1:
          for button in self.buttons:
            button.check_click(event.pos)

  # draws everything
  def render(self):
    self.parent.fill("burlywood1")
    for button in self.buttons:
      button.draw()
    self.parent.blit(self.sound_reminder_text, self.sound_reminder_pos)


import socket
import  os
import threading
import time
from email.utils import formatdate
import mimetypes
import random

class MyServer(threading.Thread):
    def __init__(self,client_connection,ip,port):
        threading.Thread.__init__(self)
        self.client_connection = client_connection
        self.ip = ip
        self.port = port

    def run(self):

        request = self.client_connection.recv(1024).decode('utf-8')
       # print(request)

        string_list = request.split(" ")
        method = string_list[0]
        resource = string_list[1]
        resource = resource[1:]

        #print(p)
        file_path = p + resource
        try:
            print("file:",file_path)
            f = open(file_path, 'rb')
            l = f.read()
            with my_lock:
                my_dict[resource] += 1
            f.close()

            print("Client {0} connected on port {1} requested for {2} count - {3}".format(self.ip, self.port,resource,my_dict[resource]))

            date = formatdate(timeval=None, localtime=False, usegmt=True)

            type = mimetypes.guess_type(file_path,True)
           # print(type[0])
            m=os.path.getmtime(file_path)
            m= formatdate(timeval=m,localtime=False,usegmt=True)
            r = "HTTP/1.1 200 OK\r\n"+"Content-Length: " + str(len(l))+ "\r\n" + "Content-Type: "+ type[0] +"; charset=utf-8\r\n"+"Date: "+date+"\r\n" + "Server: Mani v1.1\r\n"+"Last-Modified: "+m+"\r\n" + "\r\n";
           # print(r)
            r = r.encode("utf-8")
            self.client_connection.send(r+l);
           # print(r)
           # print(r.decode('utf-8'))
        except BaseException as e:
            print(e)
            header = 'HTTP/1.1 404 FILE NOT FOUND\n'
            type = 'text/html'
            header += 'Content-Type:' + type
            final_response = header.encode('utf-8')
            self.client_connection.send(final_response)
        self.client_connection.close()
script_loc = os.path.abspath(__file__)
script_dir = os.path.split(script_loc)[0]
p = os.path.split(script_dir)[0]
p += "/www/"
print(p)
HOST = ''
PORT = random.choice(range(1024,49150,100))

g = os.listdir(p)

print("Files List: {0}".format(g))
my_dict = {}
for v in g:
    my_dict[v] = 0

print(my_dict)

listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

listen_socket.bind((HOST, PORT))
threads = []

print ('Serving HTTP on port {0} ...'.format(PORT))
my_lock = threading.Lock()
while True:
    listen_socket.listen(5)
   # print(time.time())
    (client_connection, (ip,port) )= listen_socket.accept()
    t = MyServer(client_connection,ip,port)
    t.start()
    threads.append(t)

for t in threads:
    t.join()


import hashlib

from fastapi.testclient import TestClient
import pytest

from test.conftest import set_preferred_colourmap, unset_preferred_colourmap

class TestGetImage:
    @pytest.mark.parametrize(
        "record_id, channel_name, original_image, use_preferred_colourmap,"
        "lower_level, upper_level, colourmap_name, expected_image_md5sum",
        [
            pytest.param(
                "20220408164136",
                "N_COMP_FF_IMAGE",
                True,
                False,
                None,
                None,
                None,
                "9d2fc96084349c5bff10206ef4dfdf3e",
                id="Original image",
            ),
            pytest.param(
                "20220408002114",
                "N_LEG1_GREEN_NF_IMAGE",
                False,
                False,
                None,
                None,
                None,
                "97a854f18ef539f443a39c091c88df29",
                id="Image with default false colour settings",
            ),
            # repeat the above test but with the user's preferred colour map set to
            # check that the preference is used when no specific map is chosen
            pytest.param(
                "20220408002114",
                "N_LEG1_GREEN_NF_IMAGE",
                False,
                True,
                None,
                None,
                None,
                "002431ebfe4232121856ae88c15ad939",
                id="Image using user's preferred colourmap",
            ),
            pytest.param(
                "20220408002114",
                "N_LEG1_GREEN_NF_IMAGE",
                None,
                False,
                50,
                200,
                "jet_r",
                "707c50d0784e305f0f6d20fe39c93162",
                id="Image with all false colour params specified",
            ),
            # repeat the test above but with the user's preferred colour map set to
            # ensure that it is ignored and the specified colour map used
            pytest.param(
                "20220408002114",
                "N_LEG1_GREEN_NF_IMAGE",
                None,
                True,
                50,
                200,
                "jet_r",
                "707c50d0784e305f0f6d20fe39c93162",
                id="Image with all false colour params specified (ignoring "
                "user's pref)",
            ),
        ],
    )
    def test_valid_get_image(
        self,
        test_app: TestClient,
        login_and_get_token,
        record_id,
        channel_name,
        original_image,
        use_preferred_colourmap,
        lower_level,
        upper_level,
        colourmap_name,
        expected_image_md5sum,
    ):
        set_preferred_colourmap(test_app, login_and_get_token, use_preferred_colourmap)

        query_string = ""
        query_params_array = []

        if original_image is not None:
            # allow setting of "original_image=False"
            query_params_array.append(f"original_image={original_image}")
        if lower_level:
            query_params_array.append(f"lower_level={lower_level}")
        if upper_level:
            query_params_array.append(f"upper_level={upper_level}")
        if colourmap_name:
            query_params_array.append(f"colourmap_name={colourmap_name}")

        if len(query_params_array) > 0:
            query_string = "?" + "&".join(query_params_array)

        test_response = test_app.get(
            f"/images/{record_id}/{channel_name}{query_string}",
            headers={"Authorization": f"Bearer {login_and_get_token}"},
        )

        unset_preferred_colourmap(
            test_app,
            login_and_get_token,
            use_preferred_colourmap,
        )

        assert test_response.status_code == 200

        bytes_image = test_response.content

        image_checksum = hashlib.md5(bytes_image).hexdigest()
        assert expected_image_md5sum == image_checksum


# -*- coding: utf-8 -*-
"""
Project Euler Problem 1: Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def SumMul3or5BelowRange():
    counter=0
    for i in range(1000):
        if i%3==0 or i%5==0:
            counter +=i
    return counter
if __name__ == "__main__":
    print(SumMul3or5BelowRange())