# ******************************************************************************************
# Author: Luis Ernesto Colchado Soncco
# Email: luis.colchado@ucsp.edu.pe / luisernesto.200892@gmail.com
# Description: Match meteorological condition, satellite products and pollution data for SAO PAULO
# ******************************************************************************************
import os, sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

import numpy as np
import pandas as pd
from datetime import timedelta
from tqdm import tqdm
import json
from point import Point

class setting:
    DIR_SP = '../Data/SaoPaulo/'
    DIR_CETESB = '../Data/SaoPaulo/CETESB'
    DIR_POINTS = f'{DIR_CETESB}/points.csv'
    start_date = pd.to_datetime('01-01-2017')
    end_date = pd.to_datetime('12-31-2019')
    NDVI_DIR = f'{DIR_SP}/Satellite_data/MOD13A2/DATA_CROPPED'
    VNP_DIR = f'{DIR_SP}/Satellite_data/VNP46A1/DATA_CROPPED'
    DEM_DIR = f'{DIR_SP}/Satellite_data/DEM/DATA_CROPPED'
    #selected_columns = ['lat', 'lon', 'temp', 'pres', 'dewp', 'wd', 'ws', 'ndvi', 'ntl', 'dem', 'pm25']

def get_data(DATA_DIR):
    data = {}
    with open(DATA_DIR + '/info.txt', 'r') as f:
        nrows, ncolumns = f.readline().split('x')
    print('getting data from {}'.format(DATA_DIR))
    with tqdm(total=len(os.listdir(DATA_DIR))) as bar:
        for file in os.listdir(DATA_DIR):
            if file.endswith('.dat'):
                year_days = file.split('_')[3][1:-4]
                year = int(year_days[:4])
                days = int(year_days[4:])
                current_date = pd.to_datetime(str(year - 1) + '-12-31')
                current_date += timedelta(days=days)
                array = np.fromfile(DATA_DIR + '/' + file, dtype=float)
                array = array.reshape(int(len(array) / 3), 3)
                #print(str(current_date)[:-9])
                data.update({str(current_date)[:-9]: array})
                bar.update(1)
    return data

def match_data(points, df_pm25, df_temp, df_hum, df_press, df_wd, data_ndvi, data_ntl, array_dem):
    current_date = setting.start_date
    data = pd.DataFrame()
    count_error = 0
    while current_date <= setting.end_date:
        string_date = str(current_date)[:10]
        current_temp = df_temp[df_temp['date']==string_date]
        current_hum = df_hum[df_hum['date']==string_date]
        current_press = df_press[df_press['date']==string_date]
        current_wd = df_wd[df_wd['date']==string_date]

        current_pm25 = df_pm25[df_pm25['date']==string_date]
        if string_date in data_ndvi:
            current_ndvi = data_ndvi[string_date]
            #print(current_ndvi)
            prev_ndvi = current_ndvi
            print(string_date)
        else:
            current_ndvi = prev_ndvi

        if string_date in data_ntl:
            current_ntl = data_ntl[string_date]
            prev_ntl = current_ntl
        else:
            count_error += 1
            current_ntl = prev_ntl

        with tqdm(total=len(points)) as bar:
            bar.set_description(string_date)
            for p in points.index:
                current_station = points.loc[p, 'station']
                lat, lon = points.loc[p, 'lat'], points.loc[p, 'long']
                lat_left_top, lon_left_top = Point(points.loc[p, 'left'],
                                                    points.loc[p, 'top']).convertToCoord()
                lat_right_bottom, lon_right_bottom = Point(points.loc[p, 'right'],
                                                    points.loc[p, 'bottom']).convertToCoord()
                lat_left_top, lon_left_top = round(lat_left_top, 6), round(lon_left_top, 6)
                lat_right_bottom, lon_right_bottom = round(lat_right_bottom,6 ), round(lon_right_bottom, 6)
                #!print(lat_left_top, lon_left_top, ' - ', lat_right_bottom, lon_right_bottom)
                point_knn = json.loads(points.loc[p, 'knn'])
                stations = [k for k in point_knn.keys()]
                dist = [k for k in point_knn.values()]

                s = 0
                temp = hum = press = wd = None
                while s < len(stations) and (temp is None or hum is None or press is None or wd is None):
                    station = stations[s]
                    station_temp = current_temp[current_temp['stationname']==station].reset_index(drop=True)
                    station_hum = current_hum[current_hum['stationname']==station].reset_index(drop=True)
                    station_press = current_press[current_press['stationname']==station].reset_index(drop=True)
                    station_wd = current_wd[current_wd['stationname']==station].reset_index(drop=True)

                    if not station_temp.empty and temp is None:
                        temp = station_temp.loc[0, 'conc']
                    if not station_hum.empty and hum is None:
                        hum = station_hum.loc[0, 'conc']
                    if not station_press.empty and press is None:
                        #print(station_press)
                        press = station_press.loc[0, 'conc']
                    if not station_wd.empty and wd is None:
                        wd = station_wd.loc[0, 'conc']
                    s += 1

                d_ndvi = current_ndvi[(current_ndvi[:, 0] <= lat_left_top) & (current_ndvi[:, 1] >= lon_left_top) &
                                    (current_ndvi[:, 0] >= lat_right_bottom) & (current_ndvi[:, 1] <= lon_right_bottom)][:, 2]
                d_ntl = current_ntl[(current_ntl[:, 0] <= lat_left_top) & (current_ntl[:, 1] >= lon_left_top) &
                                    (current_ntl[:, 0] >= lat_right_bottom) & (current_ntl[:, 1] <= lon_right_bottom)][:, 2]

                d_dem = array_dem[(array_dem[:, 0] <= lat_left_top) & (array_dem[:, 1] >= lon_left_top) &
                                (array_dem[:, 0] >= lat_right_bottom) & (array_dem[:, 1] <= lon_right_bottom)][:, 2]

                if len(d_ndvi) > 0:
                    mean_ndvi = d_ndvi.mean()
                    mean_ntl = d_ntl.mean()
                else:
                    mean_ndvi = np.nan
                    mean_ntl = np.nan
                mean_dem = d_dem.mean()

                row = {'station': current_station, 'current_date': string_date,'lat': lat, 'lon': lon, 'temp': temp, 'hum': hum, 'press': press, 'wd': wd, 'ndvi': mean_ndvi,
                        'ntl': mean_ntl, 'dem': mean_dem}

                k = 0
                for station in stations:
                    current_neighbors = current_pm25[current_pm25['stationname']==station].reset_index(drop=True)
                    if not current_neighbors.empty:
                        value_pm25 = current_neighbors.loc[0, 'conc']
                        key_pm25 = f'pm25_{k}'
                        key_dist = f'dist_{k}'

                        value_dist = dist[k]
                        row.update({key_pm25: value_pm25})
                        row.update({key_dist: value_dist})
                        k += 1

                pm25_ = None
                if str(current_station) != 'nan':
                    curr_data = current_pm25[current_pm25['stationname']==current_station].reset_index(drop=True)
                    pm25_ = curr_data.loc[0, 'conc']
                row.update({'PM25': pm25_})
                data = data.append(row, ignore_index=True)
                bar.update(1)

            # get temperature and humidity

        current_date += timedelta(days=1)
    return data

if __name__ == '__main__':
    pm25 = pd.read_csv(setting.DIR_CETESB+'/data_pm25.csv')
    temperature = pd.read_csv(setting.DIR_CETESB+'/data_temperature.csv')
    humidity = pd.read_csv(setting.DIR_CETESB+'/data_humidity.csv')
    pressure = pd.read_csv(setting.DIR_CETESB+'/data_pressure.csv')
    wind_direction = pd.read_csv(setting.DIR_CETESB+'/data_wind_direction.csv')
    points = pd.read_csv(setting.DIR_POINTS)

    print(f'Loading data from {setting.DEM_DIR} ...')
    dem_data = np.zeros(shape=(0, 3))
    for file in os.listdir(setting.DEM_DIR):
        if file.endswith('.dat'):
            dem_array = np.fromfile(f'{setting.DEM_DIR}/{file}', dtype=float)
            dem_array = dem_array.reshape(int(len(dem_array) / 3), 3)
            dem_data = np.concatenate([dem_data, dem_array], axis=0)
    print('Loaded!')

    data_ndvi = get_data(setting.NDVI_DIR)

    data_ntl = get_data(setting.VNP_DIR)

    data_train = match_data(points, pm25, temperature, humidity, pressure, wind_direction, data_ndvi, data_ntl, dem_array)

    data_train.to_csv('Results/data_train_sp_.csv')


import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

import numpy as np

from typing import Optional, Union, Dict, Tuple, Any

from .. import core, config, graph

logger = config.logger

colortype = Union[str,
                  Tuple[float, float, float],
                  Tuple[float, float, float, float]]

__all__ = ['plot1d']

def plot1d(x: 'core.NeuronObject',
           ax: Optional[mpl.axes.Axes] = None,
           color: Optional[Union['str',
                                 colortype,
                                 Dict[Any, colortype],
                                 ]
                           ] = None,
           **kwargs) -> mpl.axes.Axes:
    """Plot neuron topology in 1D according to Cuntz et al. (2010).

    This function breaks a neurons into segments between branch points.
    See Cuntz et al., PLoS Computational Biology (2010) for detailed
    explanation. For very complex neurons, this neuron "barcode" can get
    fairly complicated - make sure to zoom in.

    Parameters
    ----------
    x :         TreeNeuron | NeuronList
                Neuron(s) to plot.
    ax :        matplotlib.ax, optional
    cmap :      tuple | dict
                Color. If dict must map neuron UUID to color.
    **kwargs
                Will be passed to ``matplotlib.patches.Rectangle``.

    Returns
    -------
    matplotlib.ax

    Examples
    --------

    .. plot::
       :context: close-figs

        >>> import navis
        >>> import matplotlib.pyplot as plt
        >>> n = navis.example_neurons(2)
        >>> ax = navis.plot1d(n)
        >>> plt.show() # doctest: +SKIP

    Close figures (only relevant for doctests)

    >>> plt.close('all')

    See the :ref:`plotting tutorial <plot_intro>` for more examples.

    """
    if isinstance(x, core.NeuronList):
        if x.is_mixed:
            raise TypeError('NeuronList contains MeshNeuron(s). Unable to plot1d.')
    elif isinstance(x, core.TreeNeuron):
        x = core.NeuronList(x)
    else:
        raise TypeError(f'Unable plot1d data of type "{type(x)}"')

    if isinstance(color, type(None)):
        color = (0.56, 0.86, 0.34)

    if not ax:
        fig, ax = plt.subplots(figsize=(8, len(x) / 3))
        # Make background transparent (nicer for dark themes)
        fig.patch.set_alpha(0)
        ax.patch.set_alpha(0)

    # Add some default parameters for the plotting to kwargs
    kwargs.update({'lw': kwargs.get('lw', .1),
                   'ec': kwargs.get('ec', (1, 1, 1)),
                   })

    max_x = []
    for ix, n in enumerate(config.tqdm(x, desc='Processing',
                                       disable=config.pbar_hide,
                                       leave=config.pbar_leave)):
        if isinstance(color, dict):
            this_c = color[n.id]
        else:
            this_c = color

        # Get topological sort (root -> terminals)
        topology = graph.node_label_sorting(n)

        # Get terminals and branch points
        bp = n.nodes[n.nodes.type == 'branch'].node_id.values
        term = n.nodes[n.nodes.type == 'end'].node_id.values

        # Order this neuron's segments by topology
        breaks = [topology[0]] + \
            [n for i, n in enumerate(topology) if n in bp or n in term]
        segs = [([s for s in n.small_segments if s[0] == end][0][-1], end)
                for end in breaks[1:]]

        # Now get distances for each segment
        if 'nodes_geodesic_distance_matrix' in n.__dict__:
            # If available, use geodesic distance matrix
            dist_mat = n.nodes_geodesic_distance_matrix
        else:
            # If not, compute matrix for subset of nodes
            dist_mat = graph.geodesic_matrix(n, from_=breaks, directed=False)

        dist = np.array([dist_mat.loc[s[0], s[1]] for s in segs]) / 1000
        max_x.append(sum(dist))

        # Plot
        curr_dist = 0
        for k, d in enumerate(dist):
            if segs[k][1] in term:
                c = tuple(np.array(this_c) / 2)
            else:
                c = color

            p = mpatches.Rectangle((curr_dist, ix), d, 1, fc=c, **kwargs)
            ax.add_patch(p)
            curr_dist += d

    ax.set_xlim(0, max(max_x))
    ax.set_ylim(0, len(x))

    ax.set_yticks(np.array(range(0, len(x))) + .5)
    ax.set_yticklabels(x.name)

    ax.set_xlabel('distance [um]')

    ax.set_frame_on(False)

    return ax


#!/usr/bin/env python2.7

import json
import requests
from datetime import datetime
from pprint import pprint
from pymongo import MongoClient
from time import sleep

#Function that returns a list[last, time, market] of the last NUMBER of samples for MARKET where the first element in the list is the latest data point and the last element in the list is the oldest datapoint. All elements in list are unique
def printLastNumbers( market , number):
	myGraphList = []
	cursor = collections.find({"MarketName": market }).sort("TimeStamp", -1)
	for document in cursor:
		myGraphList.append([document['Last'],document['TimeStamp'],document['MarketName']])
		myGraphList = [list(t) for t in set(tuple(element) for element in myGraphList)]
		if (number == len(myGraphList)):
			myGraphList = sorted(myGraphList,key=lambda l:l[1], reverse=True)
			return myGraphList
	return myGraphList

#Function that will return a list of the different markets
def getMarkets():
	url = 'https://bittrex.com/api/v1.1/public/getmarketsummaries'
	myMarketList = []
	counter = 1
	response = requests.get(url)
	json_data = json.loads(response.text)
	responseList = json_data["result"]
	howLong =  len(responseList)
	counterI = 0
	while counterI < howLong - 1 :
		counterI = counterI + 1
		if responseList[counterI]["BaseVolume"] > 1000:
			myMarketList.append(responseList[counterI]['MarketName'])

	return myMarketList

#Input printLastNumbers list and returns new list with timestamp converted datetime format
def parseTimeStamps(myList):
	for x in myList:
		format = '%Y-%m-%d %H:%M:%S'
		x[1] = str(x[1]).replace("T", " ")
		x[1] = str(x[1]).split(".", 1)[0]
		x[1] = datetime.strptime(x[1], format)

	return myList

#returns list of last price and time in seconds normalized to 0   where 0 is the lastest  time sample available
def normalizeTimeStamps(myList):
	normalizedList = []
	howLong = len(myList)
	counterI = 0
	while counterI < howLong  :
		normalizedList.append([myList[counterI][0], (myList[0][1] - myList[counterI][1]).total_seconds(), myList[0][2]])
		counterI = counterI + 1

	return normalizedList

#Establishing connection to MongoDB database
client = MongoClient(host=['192.168.1.198:27017'])
#client = MongoClient(host=['108.196.157.14:27017'])

db = client['bittrex']

collections = db['marketSummaries']
# Connection Established

#printLastNumbers( "BTC-LSK" , 50)
#pprint(getMarkets())
#print getMarkets()
##########masterList = normalizeTimeStamps(parseTimeStamps(printLastNumbers("BTC-ARK", 600)))
#masterList = parseTimeStamps(printLastNumbers("BTC-INCNT", 250))
#############print str((  masterList[0][0] - masterList[len(masterList)-1][0]  ) / (  masterList[len(masterList)-1][1] ) ) + "_______" + masterList[0][2]
#print (  masterList[0][0] - masterList[len(masterList)-1][0]  ) / (  masterList[len(masterList)-1][1] )
#pprint(masterList)
#for x in masterList:
#	print str(x[0]) + "-----------" + str(x[1])
#print masterList[0][1] - masterList[3][1]

#pprint(printLastNumbers("BTC-OMG", 250))
displayList = []
loopList = range(500)
loopList.pop(0)
loopList.pop(0)
#loopList.pop(0)
#print loopList
#for x in getMarkets():
lenOfSamples = 10
counter = 0
masterList = normalizeTimeStamps(parseTimeStamps(printLastNumbers("BTC-ADX", lenOfSamples)))
	#pprint(masterList)
while counter < lenOfSamples - 1:
	displayList.append([ ((masterList[counter][0] - masterList[counter + 1][0]) /  masterList[counter][0] ) * 100,  (masterList[counter + 1][1] - masterList[counter ][1]),  ((masterList[0][0] - masterList[counter + 1][0]) /  masterList[0][0] ) * 100, masterList[counter + 1][1], masterList[counter][2]])
	counter = counter + 1
	#print str((  masterList[0][0] - masterList[len(masterList)-1][0]  ) / (  masterList[len(masterList)-1][1] ) ) + "_______" + masterList[0][2] + "______________" + str(masterList[len(masterList)-1][1])
	#displayList.append([(  masterList[0][0] - masterList[len(masterList)-1][0]  ) / (  masterList[len(masterList)-1][1] ), masterList[0][2], masterList[0][0] - masterList[len(masterList)-1][0] , masterList[len(masterList)-1][1] , ((masterList[0][0] - masterList[len(masterList)-1][0]) / masterList[0][0]) * 100  ] )
	#displayList.append([ masterList[0][2],  (masterList[len(masterList)-1][1])/60 , ((masterList[0][0] - masterList[len(masterList)-1][0]) / masterList[0][0]) * 100  ] )

#displayList = sorted(displayList,key=lambda l:l[4], reverse=True)
displayList = sorted(displayList,key=lambda l:l[3], reverse=False)
pprint(displayList)
	#pprint(printLastNumbers( x , 100))
	#print "______________________________________________________________________________________________________________________________________________________"
	#print "______________________________________________________________________________________________________________________________________________________"
	#print "______________________________________________________________________________________________________________________________________________________"


import os
import json
import sys
import pandas as pd
import numpy as np
from datetime import datetime
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.metrics import roc_auc_score
import lightgbm as lgb
from .utils import top_ratio_hit_rate, eval_aucpr,reduce_mem_usage,eval_gini_normalization
import logging
import warnings
from hyperopt import fmin, tpe, hp, partial,Trials
warnings.filterwarnings('ignore')

#数据准备

class lgb_optimizer():

    def __init__(self, train_x,train_y,test_x,test_y, default_params, metric='1/1000_hit',logger=None,cat_features=None):
        train_x, val_x, train_y, val_y = train_test_split(train_x, train_y, stratify=train_y, test_size=0.1,random_state=42)
        self.train_x = train_x
        self.train_y = train_y
        self.val_x = val_x
        self.val_y = val_y
        self.test_x= test_x
        self.test_y = test_y
        self.metric=metric
        self.logger = logger
        self.cat_features = cat_features
        self.obj = 0
        self.best_param={}
        self.best_evals={}
        self.default_params = default_params
        self.default_params.update({"verbose": -1})
        self.space = {"learning_rate":hp.uniform('learning_rate', 5e-3, 2e-1),
                     "max_depth": hp.choice('max_depth',np.arange(3,8).tolist()),  #(min,max,q) = round(uniform(min,max)/q)*q
                     "num_leaves": hp.choice('num_leaves',np.arange(4,60).tolist()), #
                     "min_data_in_leaf": hp.choice('min_data_in_leaf', np.arange(16,100).tolist()),
                     "bagging_fraction": hp.uniform('bagging_fraction', 0.5,1.0),
                     "feature_fraction": hp.uniform('feature_fraction',0.5,1.0),
                     "min_gain_to_split": hp.uniform('min_gain_to_split', 0,6),
                     "min_data_in_bin": hp.choice('min_data_in_bin',np.arange(10,80,2).tolist()), #
                     "lambda_l2": hp.uniform('lambda_l2',0.1, 6),
                     "lambda_l1": hp.uniform('lambda_l1',0,5),
                     # "max_cat_threshold": hp.choice('max_cat_threshold',[16,24,32]),
                     }

    def lightgbm_factory(self,args):
        params = self.default_params.copy()
        args['num_leaves'] = min(args['num_leaves'], 2**(args['max_depth']-1))
        params.update(args)
        dtrain = lgb.Dataset(self.train_x, label = self.train_y, feature_name='auto',
                        categorical_feature = self.cat_features, weight=None,free_raw_data=False)
        dval = lgb.Dataset(self.val_x, label =self.val_y,feature_name='auto', categorical_feature = self.cat_features, weight=None,
                        reference=dtrain,free_raw_data=False)

        evalists =[dtrain,dval]
        evalnames=['train','val']
        eval_result={}

        num_boost_round = params.get('num_boost_round',500)
        early_stopping_round = params.get('early_stopping_round',40)
        model = lgb.train(params, dtrain, num_boost_round, evalists, evalnames,
                          early_stopping_rounds=early_stopping_round,verbose_eval=40,
                          evals_result=eval_result)
        y_prob = model.predict(self.test_x, num_iteration = model.best_iteration)
        evals={}
        evals['rate1'], _,_, evals['cover'] = top_ratio_hit_rate(self.test_y.values, y_prob, top_ratio=0.001)
        evals['rate5'], _,_,_ = top_ratio_hit_rate(self.test_y.values, y_prob, top_ratio=0.005)
        evals['aucpr'] = eval_aucpr(self.test_y.values, y_prob)
        evals['gini'] = eval_gini_normalization(self.test_y.values, y_prob)
        train_loss = eval_result['train']['binary_logloss'][-1]
        val_loss = eval_result['val']['binary_logloss'][-1]
        metric={'1/1000_hit':evals['rate1'], '5/1000_hit':evals['rate5'],
                'aucpr':evals['aucpr'],'gini':evals['gini'],'30/100_cover':evals['cover']}
        target =metric[self.metric]

        if target> self.obj and abs(train_loss - val_loss)<0.02:
            self.obj = target
            params.pop("categorical_column",None)
            self.best_param.update(params)
            self.best_evals.update(evals)
            self.logger.info((' hit_rate = {:.4f}'.format(evals['rate1'])))
            self.logger.info(('hit_rate5 = {:.4f}'.format(evals['rate5'])))
            self.logger.info(('   auc_pr = {:.4f}'.format(evals['aucpr'])))
            self.logger.info(('     gini = {:.4f}'.format(evals['gini'])))
            self.logger.info(self.best_param)
        return -target

    def run(self,max_evals=100):
        trials = Trials()
        algo = partial(tpe.suggest, n_startup_jobs=1)
        best = fmin(self.lightgbm_factory, self.space, max_evals=max_evals, algo=tpe.suggest, trials = trials)
        self.logger.info(datetime.now().strftime('%Y-%m-%d %H:%M:%S').center(50,'-'))
        self.logger.info(json.dumps(self.best_param,indent=2))
        print(json.dumps(self.best_param,indent=2))
        print(json.dumps(self.best_evals,indent=2))
        return trials
        # logger.debug(json.dumps(self.best_param,indent=2))

# print(trials.trials)
# print(trials.results)
# print(trials.losses() )
# print(trials.statuses() )


from datetime import datetime

class LAFitness:

    def __init__(self, membershipFee, initFee):
        self.members = []
        self.membershipFee = membershipFee
        self.initFee = initFee

    def addMember(self, newMember):
        self.members.append(newMember)

    def loadFromConfig(self):
        pass

    def showAllStatics(self):
        for member in self.members:
            self.showMemberStatistics(member)

    def showMemberStatistics(self, member):
        startDate = member.getEnrollTime()
        today = datetime.now()

        cycles = self.cycleCalculator(startDate, today)
        balance = (cycles + 1) * self.membershipFee
        balance += self.initFee
        balance -= member.getTotalPayment()

        print(member.getName() + ": $" + str(balance))

    def cycleCalculator(self, startDate, endDate):
        cycle = 0
        while(startDate <= endDate):
            if startDate.month == 12:
                startDate = startDate.replace(year=(startDate.year+1), month=1)
            else:
                startDate = startDate.replace(month=(startDate.month + 1))
            cycle += 1
        return cycle


import requests, json
import pandas as pd
import matplotlib.pyplot as plt

test_raw_data = pd.read_csv("info/test.csv",index_col=0)
input_data = test_raw_data.iloc[:,0:6]
Target_data = test_raw_data.iloc[:,6]

headers = {'Content-Type': "application/json"}
URL ='http://127.0.0.1:5000/testing'  ## 발급받은 API 키값
x=0
x_init = [0]
y_phy_init = [40]
y_vir_init = [40]
resi_val_init = [0]
threshold_val_init = [0.65]
for i in range(0,len(test_raw_data)):
    list_data = input_data.iloc[i,:]
    list_data = list(list_data)

    TG_data = Target_data[i]

    A = list_data[0]
    B = list_data[1]
    C = list_data[2]
    D = list_data[3]
    E = list_data[4]
    F = list_data[5]
    T = TG_data # 물리센서 값
    data = {"Testing input_1": A,"Testing input_2": B,"Testing input_3": C,"Testing input_4": D,"Testing input_5": E,"Testing input_6": F,"Testing input_7": T}
    res = requests.post(URL, headers=headers, data=json.dumps(data))

    # 실시간 그래프 제작
    xml_dic = res.json()
    all_key_list = list(xml_dic.values())
    # print("리스트가 어떻게되나요!",all_key_list)

    # 갱신 data
    x = x + 1
    y_phy = T
    threshold_val = all_key_list[2] # 임계치 값
    resi_val = all_key_list[0] # 잔차 값
    y_vir = all_key_list[3] # 가상센서 값

    x_init.append(x)
    y_phy_init.append(y_phy)
    y_vir_init.append(y_vir)
    resi_val_init.append(resi_val)
    threshold_val_init.append(threshold_val)

    plt.subplot(2, 1, 1)
    plt.plot(y_phy_init,color='navy',label="Physical sensor value")
    plt.plot(y_vir_init,color='darkred',label="Virtual sensor value")
    if x >= 1:
        plt.xlim(x-5, x+30)

    while i ==0:
        plt.legend(loc='upper right', ncol=2)
        plt.ylim(35, 50)
        break

    plt.subplot(2, 1, 2)
    plt.plot(resi_val_init,color='black',label="Residual value")
    plt.plot(threshold_val_init,color='red',label="Threshold value")

    if x >= 1:
        plt.xlim(x-5, x+30)

    while i ==0:
        plt.legend(loc='upper right')
        plt.ylim(0, 2)
        break

    # print(y_phy_init)
    # print(y_vir_init)
    plt.pause(0.05)
    # plt.show()
    print(xml_dic)

plt.show()


from openerp import fields, models, api, tools

class HCLabTestOrderLineReport(models.Model):
    _name = "hc.lab.test.order.line.report"
    _description = "Test Lines Statistics"
    _auto = False

    patient_id = fields.Many2one('hc.patient', 'Patient', readonly=True)
    order_date = fields.Datetime('Date Order', readonly=True)
    test_id = fields.Many2one('hc.lab.test', 'Test', readonly=True)
    component_id = fields.Many2one('hc.lab.test.component', 'Component', readonly=True)
    value = fields.Float('Value', readonly=True)
    avg_value = fields.Float('Average', readonly=True)

    def _select(self):
        select_str = """
            min(lr.id) as id,
            so.patient_id AS patient_id,
            t_order.order_date AS order_date,
            t_line.test_id AS test_id,
            lr.component_id AS component_id,
            lr.num_value AS value,
            avg(num_value) AS avg_value
        """
        return select_str

    def _from(self):
        from_str = """
            hc_service_order as so,
            hc_lab_test_order as t_order,
            hc_lab_test_order_line as t_line,
            hc_patient as patient,
            hc_lab_test as test,
            hc_lab_test_order_line_results as lr,
            hc_lab_test_component as component
        """
        return from_str

    def _where(self):
        where_str = """
            so.patient_id = patient.id AND
            t_order.service_order_id = so.id AND
            t_line.test_order_id = t_order.id AND
            t_line.test_id = test.id AND
            lr.test_line_id = t_line.id AND
            lr.component_id = component.id AND
            component.type = 'num' AND
            t_line.state in ('result_entered', 'result_verified', 'dispatch', 'done')
        """
        return where_str

    def _group_by(self):
        group_by_str = """
            so.patient_id,
            t_order.order_date,
            t_line.test_id,
            lr.component_id,
            lr.num_value
        """
        return group_by_str
    def _order_by(self):
        order_by_str = """
            so.patient_id,
            t_order.order_date
        """
        return order_by_str

    def init(self, cr):
        # self._table = sale_report
        tools.drop_view_if_exists(cr, self._table)
        cr.execute("""CREATE or REPLACE VIEW %s as (
            SELECT
                %s
            FROM
                %s
            WHERE
                %s
            GROUP BY
                %s
            ORDER BY
                %s
            )""" % (self._table, self._select(), self._from(), self._where(), self._group_by(), self._order_by()))

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


# Simple reverse polish notation calculator

PROMPT = 'Please enter expression: '

def tokenize(string):
    """ Split the input into the constituent elements
        that comprise it for example convert the string  '2 3 +'
        into a list [2, 3, '+'] """
    tokens = string.split(' ')
    # Create a list to hold the results to return
    # A list is a bit like a growable array of things
    results = []

    # Loop through each of the elements in the tokens. If the 'token'
    # is actually an integer convert it to an int and add it to the results
    # otherwise just add it
    for token in tokens:
        if token.isdigit():
            results.append(int(token))
        else:
            results.append(token)

    return results

def print_message(message):
    """ Provide for a standardized prompt """
    print('->', message)

# Print a welcome message
print('Enter an expression at the prompt using Reverse Polish Notation (or q to quit)')
print('Note only integers are supported')

input_str = input(PROMPT)
# Check to see if the user wants to quit
while input_str != 'q':
    # Convert the input string into tokens
    input_tokens = tokenize(input_str)

    try:

        # Obtain the two operands and the operator
        # You can use an index to access elements from a list
        # note that the list is indexed from zero
        operand_1 = input_tokens[0]
        operand_2 = input_tokens[1]

        operator = input_tokens[2]

        # Test to see which operator has been provided
        if operator == '+':
            print_message(operand_1 + operand_2)
        elif operator == '-':
            print_message(operand_1 - operand_2)
        elif operator == '*':
            print_message(operand_1 * operand_2)
        elif operator == '/':
            print_message(operand_1 / operand_2)
        elif operator == '//':
            print_message(operand_1 // operand_2)
        elif operator == '%':
            print_message(operand_1 % operand_2)
        else:
            print_message('Invalid operator - try again!')

    except ZeroDivisionError:
        # Check for divide by Zero errors
        print_message('Cannot Divide By Zero - try again!')
    except TypeError:
        # Handle situation where operands ar enot integers
        print_message('The Operands must be Integers but you entered: ' + str(input_tokens))

    # Get the next input form the user
    input_str = input(PROMPT)

print('Done')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 21 12:44:56 2021

@author: emildanielsson
"""

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 13 11:51:54 2021

@author: emildanielsson

Program description:
    Computes how many minutes each player have played for each game
    from the given event and matches data set

    Creates and saves a dataframe with the following columns:
        playerId - playerId from Wyscout
        shortName - shortName from Wyscout
        matchId - matchId from Wyscout data
        teamId - teamId from Wyscout data
        teamName - Official teamname frrom Wyscout data
        player_in_min - the minute of the match the playerr started playing
        player_out_min - the minute of the match the player stopped playing
        minutesPlayed - Minutes played in the given game
        red_card - boolean to show if the player got a red card that game
                    (1 = red card,  = no red card)

"""

# The basics
import pandas as pd
import numpy as np
import json

#############################################################################
# - Create dataframes from the Wyscout data
"---------------------------------------------------------------------------"

# Create event dataframe
#df_Europe_events = pd.read_json('Json_files/events_All.json', encoding="unicode_escape") #SLOWER
with open('../Json_files/events_All.json') as f:
    data_Europe= json.load(f)

df_Europe_events = pd.DataFrame(data_Europe)

# Create match dataframes
df_England_matches = pd.read_json('../../Wyscout/matches/matches_England.json', encoding="unicode_escape")

df_France_matches = pd.read_json('../../Wyscout/matches/matches_France.json', encoding="unicode_escape")

df_Germany_matches = pd.read_json('../../Wyscout/matches/matches_Germany.json', encoding="unicode_escape")

df_Italy_matches = pd.read_json('../../Wyscout/matches/matches_Italy.json', encoding="unicode_escape")

df_Spain_matches = pd.read_json('../../Wyscout/matches/matches_Spain.json', encoding="unicode_escape")

# Create players and teams dataframes
df_players = pd.read_json("../../Wyscout/players.json", encoding="unicode_escape")
df_teams = pd.read_json("../../Wyscout/teams.json", encoding="unicode_escape")

#############################################################################
# - Merge matches dataframes from all leagues
"---------------------------------------------------------------------------"

frames_matches = [df_England_matches, df_France_matches, df_Germany_matches,
                  df_Italy_matches, df_Spain_matches]

df_Europe_matches = pd.concat(frames_matches, keys = ["England", "France",
                                                      "Germany", "Italy", "Spain"])

#############################################################################
# - Creating the dataframe of full playing time for each match
"---------------------------------------------------------------------------"

# Prepares the dataframe with the columns we need
df_matches_fulltime=pd.DataFrame(columns=['matchId','matchDuration'])

# Match id checkpoints
loop_checkpoints = np.arange(0,2080,50)
j = 0

# Loop trough all matches
for i, match in df_Europe_matches.iterrows():

    # Find the events from match
    mask_match = (df_Europe_events.matchId == match['wyId']) & (df_Europe_events.matchPeriod == "2H")
    df_match = df_Europe_events.loc[mask_match]

    # time ofsecond half in seconds
    fulltime_sec = df_match['eventSec'].max()

    # Convert to minutes
    fulltime_min = 45 + round(fulltime_sec / 60)

    # Add match and full time (minutes) to dataframe
    df_matches_fulltime.loc[df_matches_fulltime.shape[0]] = [match.wyId, fulltime_min]

    if (j in loop_checkpoints):
        print(f"Number of matches checked for fulltimes: {j}\n")

    j+=1

#############################################################################
# - Creating the dataframe of minutes played for each player in each game
"---------------------------------------------------------------------------"

# Prepares the dataframe with the columns we need
df_minutes_played=pd.DataFrame(columns=['playerId', 'shortName',
                                        'matchId', 'teamId', 'teamName',
                                        'player_in_min', 'player_out_min',
                                        'minutesPlayed', 'red_card'])

# Match id checkpoints
loop_checkpoints = np.arange(0,2080,50)
j = 0

# Loop trough all matches
for i, match in df_Europe_matches.iterrows():

    # Lineups and substitutions are nested in teamsData
    team_data = match['teamsData']

    # Get match Id
    matchId = match['wyId']

    # Get full match length
    fulltime_min = df_matches_fulltime.loc[df_matches_fulltime['matchId'] == matchId]['matchDuration'].values[0]

    # Loop through both teams in the match
    for teamId in team_data:
        # loop like this gets the teamId as String, not the team object apperantly

        # Fetches the team to look at
        team = team_data[teamId]

        # list of the lineup
        lineup = team['formation']['lineup']

        # list of the substitutions
        substitutions = team['formation']['substitutions']

        # Get the team id
        teamId = team['teamId']

        # Get the team name
        mask_team_name = df_teams.wyId == teamId
        df_team = df_teams.loc[mask_team_name]
        teamName = df_team.officialName.values[0] # Could change officialName -> name ??

        # list of the players that came in during the match
        sub_ins = []
        sub_outs = []
        if (substitutions != "null"):
            for sub in substitutions:
                # "Handle" the case when the sub is badly registered
                if ((sub['playerIn'] != 0) & (sub['playerOut'] != 0)):
                    sub_ins.append(sub['playerIn'])
                    sub_outs.append(sub['playerOut'])
                # With this solution some players will have played more minutes
                # than they actually played. But it is not that many matches
                # so I think we are fine with it.

        # Loop through all players in the lineup and get their minutes played
        for player in lineup:

            # Get the current playerId
            playerId = player['playerId']

            # Get the current player shortName
            shortName = df_players.loc[df_players.wyId == playerId].shortName.values[0]

            # If the player have been subbed out set minutes played for the sub and the player
            if (playerId in sub_outs):

                # Find index of the substitution from the lists
                sub_index = sub_outs.index(playerId)

                # Find the mninute when sub took place
                sub_minute = substitutions[sub_index]['minute']

                # Find the name of the subbed in player
                shortName_sub = df_players.loc[df_players.wyId == sub_ins[sub_index]].shortName.values[0]

                # Add minutes played by the subed out player to the dataframe
                df_minutes_played.loc[df_minutes_played.shape[0]] = [sub_outs[sub_index], shortName, matchId, teamId, teamName, 0, sub_minute, sub_minute, 0]

                # Handle the case if the subbed in player also is subbed out (injury for example)
                if (sub_ins[sub_index] in sub_outs):

                    # Find index of the substitution from the lists
                    sub_index2 = sub_outs.index(sub_ins[sub_index])

                    # Find the mninute when sub took place
                    sub_minute2 = substitutions[sub_index2]['minute']

                    # Find the name of the subbed in player
                    shortName_sub2 = df_players.loc[df_players.wyId == sub_ins[sub_index2]].shortName.values[0]

                    # Make sure the subbed in and then out player at least played 1 min
                    if (sub_minute2 - sub_minute <= 0):
                       sub_playing_minutes2 = 1
                    else:
                        sub_playing_minutes2 = sub_minute2 - sub_minute

                    # Add minutes played by the subed in and out player to the dataframe
                    df_minutes_played.loc[df_minutes_played.shape[0]] = [sub_outs[sub_index2], shortName_sub, matchId, teamId, teamName, sub_minute, sub_minute2, sub_playing_minutes2, 0]

                    # Make sure the subbed in player at least played 1 min
                    if (fulltime_min - sub_minute2 <= 0):
                       sub_playing_minutes3 = 1
                    else:
                        sub_playing_minutes3 = fulltime_min - sub_minute2

                    # Add minutes played by the subed in player to the dataframe
                    df_minutes_played.loc[df_minutes_played.shape[0]] = [sub_ins[sub_index2], shortName_sub2, matchId, teamId, teamName, sub_minute2, fulltime_min, sub_playing_minutes3, 0]

                # Normal substitution
                else:
                    # Make sure the subbed in player at least played 1 min
                    if (fulltime_min - sub_minute <= 0):
                       sub_playing_minutes = 1
                    else:
                        sub_playing_minutes = fulltime_min - sub_minute

                    # Add minutes played by the subed in player to the dataframe
                    df_minutes_played.loc[df_minutes_played.shape[0]] = [sub_ins[sub_index], shortName_sub, matchId, teamId, teamName, sub_minute, fulltime_min, sub_playing_minutes, 0]

            # The player played for the whole game
            else:
                df_minutes_played.loc[df_minutes_played.shape[0]] = [playerId, shortName, matchId, teamId, teamName, 0, fulltime_min, fulltime_min, 0]

    if (j in loop_checkpoints):
        print(f"Number of matches checked for minutes: {j}\n")

    j+=1

#############################################################################
# - Adjust for red cards
"---------------------------------------------------------------------------"

# Filter out the fouls, assumed that red cards only exists as Foul-event
mask_fouls = df_Europe_events.eventName == "Foul"
df_fouls = df_Europe_events.loc[mask_fouls]

# Initiate variables
match_list_reds = []
player_list_reds = []

# Loop through events to find matcghes and players with red cards
for i, foul_i in df_fouls.iterrows():

    # List to save the tags in
    foul_tags = []

    # Loop through fouls to find red cards
    for foultag in foul_i['tags']:
        foul_tags.append(foultag['id'])

    # tag 1701 == red card, tag 1703 == second yellow card
    if ((1701 in foul_tags) or (1703 in foul_tags)):

        # Fet the redcarded playerId and matchId
        red_carded_player = foul_i.playerId
        red_carded_match = foul_i.matchId

        # Find minute of the red card
        if foul_i.matchPeriod == "1H":
            red_card_minute = round(foul_i.eventSec / 60)
        elif foul_i.matchPeriod == "2H":
            red_card_minute = 45 + round(foul_i.eventSec / 60)
        else:
            print("Error" + str(foul_i.matchPeriod))

        # Find the minute the red carded player got in
        mask_red_card_player_min = ((df_minutes_played.playerId == red_carded_player) & (df_minutes_played.matchId == red_carded_match))
        df_red_card = df_minutes_played.loc[mask_red_card_player_min]
        if len(df_red_card) != 0:
            red_card_player_in = df_red_card.player_in_min.values[0]

            # Adjust the dataframe "df_minutes_played" to add the red card info
            df_minutes_played.loc[mask_red_card_player_min, 'player_out_min'] = red_card_minute
            df_minutes_played.loc[mask_red_card_player_min, 'minutesPlayed'] = red_card_minute - red_card_player_in
            df_minutes_played.loc[mask_red_card_player_min, 'red_card'] = 1

#############################################################################
# - Save df_minutes to dataframe "minutes_played_All.json"
"---------------------------------------------------------------------------"

df_minutes_played.to_json("../Json_files/minutes_played_All.json")

# Test to load in and store as dataframe
# with open('../Json_files/minutes_played_All.json') as f:
#     data_minutes_new = json.load(f)

# df_test_new = pd.DataFrame(data_minutes_new)


MOD = 1000000007

def generalizedEuclidianAlgorithm(a, b):
    if b > a:
        return generalizedEuclidianAlgorithm(b,a);
    elif b == 0:
        return (1, 0);
    else:
        (x, y) = generalizedEuclidianAlgorithm(b, a % b);
        return (y, x - (a // b) * y)

def inversemodp(a, p):
    a = a % p
    if a == 0:
        return 0
    (x, y) = generalizedEuclidianAlgorithm(p, a % p);
    return y % p

def identitymatrix(n):
    return [[int(x == y) for x in range(0, n)] for y in range(0, n)]

def multiply_vector_scalar(vector, scalar, q):
    kq = []
    for i in range (0, len(vector)):
        kq.append(vector[i] * scalar % q)
    return kq

def minus_vector_scalar1(vector1, scalar, vector2, q):
    kq = []
    for i in range (0, len(vector1)):
        kq.append((vector1[i] - scalar * vector2[i]) % q)
    return kq

def inversematrix1(matrix, q):
    n = len(matrix)
    A =[]
    for j in range (0, n):
        temp = []
        for i in range (0, n):
            temp.append(matrix[j][i])
        A.append(temp)
    Ainv = identitymatrix(n)
    for i in range(0, n):
        factor = inversemodp(A[i][i], q)
        A[i] = multiply_vector_scalar(A[i], factor, q)
        Ainv[i] = multiply_vector_scalar(Ainv[i], factor, q)
        for j in range(0, n):
            if i != j:
                factor = A[j][i]
                A[j] = minus_vector_scalar1(A[j], factor, A[i], q)
                Ainv[j] = minus_vector_scalar1(Ainv[j], factor,Ainv[i], q)
    return Ainv

def mult(x, y):
    c = [[0 for _ in range(len(y[0]))] for _ in range(len(x))]
    for i in range(len(x)):
        for j in range(len(y[0])):
            for k in range(len(x)):
                c[i][j] += x[i][k] * y[k][j]
                c[i][j] = c[i][j] % MOD
    return c

def matpow(b, p):
    if p == 0: return identitymatrix(n)
    if p == 1: return b
    if p % 2 == 1:
        return mult(b, matpow(b, p - 1))
    ret = matpow(b, p // 2)
    return mult(ret, ret)

n, k = map(int, input().split())
arrk = list(map(int, input().split()))
arrc = list(map(int, input().split()))
left = [[x] for x in arrk];
middle = [[0 for _ in range(n)] for _ in range(n)]
middle[0] = list(arrc)
for i in range(1,n):
    middle[i][i-1] = 1
inv = inversematrix1(middle, MOD)
inv = [[int(x) for x in y] for y in inv]
ans = matpow(inv, k - n + 1)
ans = mult(ans, left)
print(' '.join(map(lambda x : str(x[0]), ans)))


import nuke
import os
import re
import glob
import subprocess
import json

class customreads():
    def __init__(self, node=None):
        super(customreads, self).__init__()
        self.group = nuke.thisNode() if node is None else node
        self.project = self.group.knob('project').value()
        self.structure = self.group.knob('structure').value()
        self.customfile = os.path.abspath(self.group.knob('Filepath').value())
        self.aovfolder = []
        self.framenr = "%04d"
        self.colorspace = "linear"
        self.extension = "exr"
        self.depthaov = 'depth'
        self.userbuttons = ["episode", "seq", "shot", "layer", "version", " ", "create", "populate",]
        self.buttontype = ('shader', 'data', 'crypto', 'lightgroups', 'custom')
        self.shaderaov = ['diffuse', 'coat', 'specular', 'sss', 'emission','sheen','check_user_albedo']
        self.dataaov = ['check_user_P','N',self.depthaov,'motionvector','background','cputime']
        self.cryptoaov = ['crypto_asset','crypto_object','crypto_material']
        self.lightgroupsaov = []
        self.customaov = []
        self.dictread()
        self.customtypehidden()
        # self.knobstart() probar con un if para que no se ejecute cada vez que abro un script.
        nuke.addKnobChanged(self.read, nodeClass='Group', node=self.group)

    def customtypehidden(self):
        customknobs = self.group.allKnobs()
        for knobs in customknobs:
            if "customreadclass" in knobs.name():
                self.group.removeKnob(knobs)
        customtype = nuke.Text_Knob('customreadclass', 'customreadclass')
        self.group.addKnob(customtype)
        customtype.setVisible(False)

    def dictread(self):
        self.seqsdictjson = open('P:/AndreJukebox/aj_seq_dict.json')
        self.seqsdict = json.load(self.seqsdictjson)

    def knobstart(self):
        self.createreadtabs()
        epsearchexp = f"{self.project}/*"
        self.epsearchpath = os.path.abspath(epsearchexp)
        epfolder = glob.glob(self.epsearchpath)
        self.episode = epfolder[0]
        seqsearchexp = f"{self.episode}/*"
        self.seqsearchpath = os.path.abspath(seqsearchexp)
        seqfolder = glob.glob(self.seqsearchpath)
        if seqfolder:
            self.seq = seqfolder[0]
        else:
            self.seq = ['']

        shotsearchexp = f"{self.seq}/*"
        self.shotsearchpath = os.path.abspath(shotsearchexp)
        shotfolder = glob.glob(self.shotsearchpath)
        if shotfolder:
            self.shot = shotfolder[0]
        else:
            self.shot = ['']

        layersearchexp = f"{self.shot}/{self.structure}/*"
        self.layersearchpath = os.path.abspath(layersearchexp)
        layerfolder = glob.glob(self.layersearchpath)
        if layerfolder:
            self.layer = layerfolder[0]
        else:
            self.layer = ['']

        versionsearchexp = f"{self.layer}/*"
        self.versionsearchpath = os.path.abspath(versionsearchexp)
        versionfolder = glob.glob(self.versionsearchpath)
        if versionfolder:
            self.version = versionfolder[-1].rsplit('\\')[-1]
            # print(self.version)
        else:
            self.version = ['']

        buttondict = {
            "episode": self.epsearchpath,
            "seq": self.seqsearchpath,
            "shot": self.shotsearchpath,
            "layer": self.layersearchpath,
            "version": self.versionsearchpath
        }

        for buttons in buttondict:
            searchpath = buttondict[buttons]
            self.buttongenerate(button=buttons,searchpath=searchpath)
        self.usergui()
        self.group.knobs()['seq'].setValue(nuke.root().knobs()['seqs'].value())
        self.group.knobs()['shot'].setValue(nuke.root().knobs()['shots'].value())

    def cleanui(self):
        all_knobs = self.group.allKnobs()
        for b in all_knobs:
            if b.name() in self.userbuttons:
                self.group.removeKnob(b)
            if "check_user" in b.name():
                self.group.removeKnob(b)
        self.group.knob('Filepath').setValue("")
        self.group.knob('Start').setValue(int(0))
        self.group.knob('End').setValue(int(0))
        self.group.knob('label').setValue('')
        self.cleantabs()
        self.cleanreadtabs()

    # Clears the user tab, deletes all nodes inside the self.group (except for "Ouput") and resets all labels and
    def cleannodes(self):
        all_nodes = self.group.nodes()
        for delnodes in all_nodes:
            if not "Output" in delnodes.name():
                nuke.delete(delnodes)

    def createreadtabs(self):
        tab_name = 'reads'
        readtab = nuke.Tab_Knob(tab_name)
        if not "reads" in self.group.knobs():
            self.group.addKnob(readtab)

    def cleanreadtabs(self):
        tab_knobs = self.group.allKnobs()
        tab_name = 'reads'
        for tabs in tab_knobs:
            if tab_name in tabs.name():
                self.group.removeKnob(tabs)

    def createtabs(self):
        self.cleantabs()
        aovtab = nuke.Tab_Knob("aov_tab")
        self.group.addKnob(aovtab)

        createallbutton = nuke.PyScript_Knob('all', 'all')
        self.group.addKnob(createallbutton)
        nuke.knobTooltip('Group.create', ('Enable all aov components'))
        enableallcode = """import customread
customread.customreads().enableallaovs()"""
        self.group.knob('all').setValue(enableallcode)

        createnonebutton = nuke.PyScript_Knob('none', 'none')
        self.group.addKnob(createnonebutton)
        nuke.knobTooltip('Group.create', ('Enable all aov components'))
        disableallcode = """import customread
customread.customreads().disableallaovs()"""

        for aovbutton in self.buttontype:
            createshaderbutton = nuke.PyScript_Knob(aovbutton, aovbutton)
            self.group.addKnob(createshaderbutton)
            nuke.knobTooltip('Group.create', ('Enable and disable aov components'))
            enablecode = """import customread
customread.customreads().""" + aovbutton + 'aovbutton()'
            self.group.knob(aovbutton).setValue(enablecode)
        self.group.knob('none').setValue(disableallcode)
        lgtstring = nuke.String_Knob('lgt', 'Lightgroups pattern', 'lgroup')
        self.group.addKnob(lgtstring)
        ctmstring = nuke.String_Knob('ctm', 'Custom pattern', '')
        self.group.addKnob(ctmstring)

    def cleantabs(self):
        tab_knobs = self.group.allKnobs()
        for tabs in tab_knobs:
                if tabs.name() in self.buttontype:
                    self.group.removeKnob(tabs)
                if tabs.name() in ("aov_tab","all","none","lgt","ctm"):
                    self.group.removeKnob(tabs)

    def shaderaovbutton(self):
        self.enableaovs(self.shaderaov)

    def dataaovbutton(self):
        self.enableaovs(self.dataaov)

    def cryptoaovbutton(self):
        self.enableaovs(self.cryptoaov)

    def lightgroupsaovbutton(self):
        knobchecks = self.group.allKnobs()
        lgrouppattern = self.group.knob('lgt').value()
        for i in knobchecks:
            if lgrouppattern in i.name():
                if self.group.knob(i.name()).getValue() == 1:
                    self.group.knob(i.name()).setValue(0)
                else:
                    if self.group.knob(i.name()).getValue() == 0:
                        self.group.knob(i.name()).setValue(1)
            else:
                pass

    def customaovbutton(self):
        knobchecks = self.group.allKnobs()
        ctmpattern = self.group.knob('ctm').value()
        for i in knobchecks:
            if ctmpattern in i.name():
                if self.group.knob(i.name()).getValue() == 1:
                    self.group.knob(i.name()).setValue(0)
                else:
                    if self.group.knob(i.name()).getValue() == 0:
                        self.group.knob(i.name()).setValue(1)
            else:
                pass

    def enableallaovs(self):
        knobchecks = self.group.allKnobs()
        for i in knobchecks:
            if "check_user" in i.name():
                self.group.knob(i.name()).setValue(1)
            else:
                pass

    def disableallaovs(self):
        knobchecks = self.group.allKnobs()
        for i in knobchecks:
            if "check_user" in i.name():
                self.group.knob(i.name()).setValue(0)
            else:
                pass

    def enableaovs(self,checkaovlist):
        knobchecks = self.group.allKnobs()
        for i in knobchecks:
            for t in checkaovlist:
                if t in i.name():
                    if self.group.knob(i.name()).getValue() == 1:
                        self.group.knob(i.name()).setValue(0)
                    else:
                        if self.group.knob(i.name()).getValue() == 0:
                            self.group.knob(i.name()).setValue(1)
                else:
                    pass

    def buttongenerate(self,button,searchpath):
        pathitem = os.path.abspath(searchpath)
        item = glob.glob(pathitem)
        additem = []
        for i in item:
            p = i.rsplit("\\")
            if not ".db" in p[-1]:
                additem.append(str(p[-1]))
        if button not in self.group.knobs():
            newknob = nuke.Enumeration_Knob(button, button, additem)
            self.group.addKnob(newknob)
        else:
            itemknob = self.group.knobs()[button]
            itemknob.setValues(additem)
        if button == "version":
            if len(additem) >= 1:
                self.group.knob(button).setValue(additem[-1])

    def checkclean(self):
        allchecks = self.group.allKnobs()
        self.checklist = []
        for checks in allchecks:
            if "check_user" in checks.name():
                self.checklist.append(checks)

                # self.group.removeKnob(checks)
        # print(self.checklist)

    def checkbox(self,checkbox):
        self.checklist = []
        self.checks = self.group.knobs()
        if not checkbox in ("rgba","beauty"):
            self.checkname = "check_user_" + checkbox
            checkstate = 0
            if self.checkname in self.checks:
                checkstate = self.group.knobs()[self.checkname].getValue()
                self.checklist.append(self.checkname)
                # print(f'This one {self.checkname} already existed')
                removecheck = self.group.knobs()[self.checkname]
                self.group.removeKnob(removecheck)

            else:
                print(f'creating new {self.checkname}')

            knobcheck = nuke.Boolean_Knob(self.checkname, checkbox, 0)
            self.group.addKnob(knobcheck)
            # knobcheck.setValue(1)
            knobcheck.setValue(checkstate)
            self.group[self.checkname].setFlag(nuke.STARTLINE)

    def connectchecks(self):
        selectreads = nuke.allNodes("Read")
        for t in selectreads:
            if not "beauty" in t.name():
                t.knob("disable").setExpression('parent.check_user_' + t.name() + ' == 1 ? 0 : 1')
                # shufflenames = t.name() + '_shf'
                # shuffles = nuke.toNode(shufflenames)
                # if not "crypto" in t.name():
                #     shuffles.knob("disable").setExpression('parent.check_user_' + t.name() + ' == 1 ? 0 : 1')

    def currentknobs(self):
        self.episode = self.group.knob('episode').value()
        self.seq = self.group.knob('seq').value()
        self.shot = self.group.knob('shot').value()
        self.layer = self.group.knob('layer').value()

    def update(self):
        self.currentknobs()
        buttoncurrent = ['episode','seq','shot','layer','version']
        for buttons in buttoncurrent:
            episode = self.group.knob('episode').value()
            seq = self.group.knob('seq').value()
            shot = self.group.knob('shot').value()
            layer = self.group.knob('layer').value()
            # Dictionary with current knob values
            buttonupdate = {
                "episode": f"{self.project}/*",
                "seq": f"{self.project}/{episode}/*",
                "shot": f"{self.project}/{episode}/{seq}/*",
                "layer": f"{self.project}/{episode}/{seq}/{shot}/{self.structure}/*",
                "version": f"{self.project}/{episode}/{seq}/{shot}/{self.structure}/{layer}/*"
            }
            for butup in buttonupdate:
                searchpath = buttonupdate[butup]
                currentvalue = self.group.knob(butup).value()
                self.buttongenerate(button=butup,searchpath=searchpath)

    def nodeconnect(self):
        # reads connect for reformat
        reads = nuke.allNodes("Read")
        self.zconnect()
        readnodes = []

        for r in reads:
            refin = nuke.toNode(r.name() + '_ref')
            # shfin = nuke.toNode(r.name() + '_shf')
            readin = nuke.toNode(r.name())
            readnodes.append(refin)
            if r.name() == "Z":
                zmergeshuffle = nuke.toNode('Z_shf')
                readnodes.append(zmergeshuffle)

            if not r.name() == "Z":
                nuke.Layer(r.name(),[r.name()+'.red',r.name()+'.green',r.name()+'.blue',r.name()+'.alpha'])

            if r.name() not in ('crypto_asset','crypto_object','crypto_material',self.depthaov):
                refin.setInput(0, r)
                # shfin.knob('out1').setValue(r.name())
                # if r.name() == "beauty":
                #     shfin.knob('out1').setValue('rgba')
                # shfin.knob('fromInput1').setValue("{1} B A")
                # shfin.setInput(1, refin)
            if "crypto" in r.name():
                refin.setInput(0, readin)
        createMerge = nuke.nodes.Merge2(name="aovmerge", A="none", also_merge="all", metainput="All")
        reformatnodes = nuke.allNodes(filter='Reformat')
        nro = 0
        for plugs in readnodes:
            nro = nro + 1
            if nro == 2:
                nro = nro + 1
            createMerge.setInput(nro, plugs)
        for refplugs in reformatnodes:
            if "beauty" in refplugs.name():
                createMerge.setInput(0, refplugs)

        # cryptoreads = nuke.allNodes(filter='Reformat')
        # for plugs in cryptoreads:
        #     nro = nro + 1
        #     if nro == 2:
        #         nro = nro + 1
        #     if "crypto" in plugs.name():
        #         createMerge.setInput(nro, plugs)
        nuke.toNode("Output1").setInput(0, nuke.toNode('aovmerge'))

    def aovharvest(self):
        # with self.group:
        # Define where to read from the items of the path
        project = self.group.knob('project').value()
        structure = self.group.knob('structure').value()
        episode = self.group.knob('episode').value()
        seq = self.group.knob('seq').value()
        shot = self.group.knob('shot').value()
        layer = self.group.knob('layer').value()
        version = self.group.knob('version').value()

        # STRING EXTRACTION
        # Sequence path
        framepath = f"{project}/{episode}/{seq}/{shot}/{structure}/{layer}/{version}/"
        # Converting all / to system defaults
        searchaovs = os.path.abspath(framepath + "*")

        # listing aov folders
        aovfolders = glob.glob(searchaovs)
        aovsplit = aovfolders[0].rsplit("\\")
        aovfolder = aovsplit[-1]
        searchpaths = os.path.abspath(framepath + aovfolder + "/*" + "." + self.extension)
        files = glob.glob(searchpaths)
        self.old_checks_list = []
        self.new_checks_list = []
        if files:
            # Storing the clean numbers in a variable
            setframestart = self.seqsdict[self.group.knob('seq').value()][self.group.knob('shot').value()]['start']
            setframeend = self.seqsdict[self.group.knob('seq').value()][self.group.knob('shot').value()]['end']
            for self.old_checks in self.group.knobs():
                if "check_user_" in self.old_checks:
                    self.old_checks_list.append(self.old_checks)
                    # print(self.old_checks)
                    # print(self.group.knob(self.old_checks))
                # print(self.old_checks)
                # checknode = nuke.toNode(self.old_checks)
                # print(checknode)
            #     if "check_user_" in self.current_checks['name']:
            #         self.old_checks_list.append(self.current_checks)

            #Create aov tab
            self.createtabs()
            # forming the full paths for found aovs

            for aovcomp in aovfolders:
                singleaov = aovcomp.rsplit("\\", -1)[-1]
                aovfullpath = f"{framepath}{singleaov}/{layer}_{singleaov}.{self.framenr}.{self.colorspace}.{self.extension}"
                self.checkbox(singleaov)
                new_check = "check_user_" + singleaov
                for new_checks in self.group.knobs():
                    if new_check == new_checks:
                        self.new_checks_list.append(new_check)

            #set paths strings and frame range
                if "beauty" in singleaov:
                    self.group.knob('Filepath').setValue(aovfullpath)
                    self.group.knob('Start').setValue(int(setframestart))
                    self.group.knob('End').setValue(int(setframeend))

                # create the reads
                if not "rgba" in singleaov:
                    nukepaths = re.sub(r"\\", "/", aovfullpath)
                    nuke.nodes.Read(file=nukepaths, first=setframestart, last=setframeend, name=singleaov,
                                    on_error="nearest frame")

                    # Create reformats and shuffles
                    if singleaov not in ('crypto_asset','crypto_object','crypto_material','depth','P','N','AA_inv_density','Pref'):# self.depthaov):
                        nuke.nodes.Reformat(name=singleaov + '_ref', filter='Lanczos4')
                        # nuke.nodes.Shuffle2(name=singleaov + '_shf')
                    elif singleaov not in self.depthaov:
                        nuke.nodes.Reformat(name=singleaov + '_ref', filter='impulse')
                        # nuke.nodes.Shuffle2(name=singleaov + '_shf')

            for items in self.old_checks_list:
                if items not in self.new_checks_list:
                    self.group.removeKnob(self.group.knob(items))

        else:
            print('No proper structure found for f´{layer}')

    def customaovharvest(self):
        self.old_checks_list = []
        self.new_checks_list = []
        # Clean self.group
        self.cleannodes()
        # STRING EXTRACTION
        # Sequence path
        aovseparator = 'beauty'
        beautysearch = os.path.abspath(self.customfile.rsplit(aovseparator)[-3]+aovseparator+'\*')
        aovsearch = self.customfile.split("beauty")[0] + '*'

        seqlist = glob.glob(beautysearch)
        # Storing digits between . and a .
        framestart = re.search("\.\d{4}(?:\.*)*", os.path.abspath(seqlist[0]))
        frameend = re.search("\.\d{4}(?:\.*)*", os.path.abspath(seqlist[-1]))
        for self.old_checks in self.group.knobs():
                if "check_user_" in self.old_checks:
                    self.old_checks_list.append(self.old_checks)
        # Matching the digits only
        framestartnumber = re.search("\d{4}", framestart.group(0))
        frameendnumber = re.search("\d{4}", frameend.group(0))

        # Storing the clean numbers in a variable
        setframestart = self.seqsdict[self.group.knob('seq').value()][self.group.knob('shot').value()]['start']#framestartnumber.group(0)
        setframeend = self.seqsdict[self.group.knob('seq').value()][self.group.knob('shot').value()]['end']#frameendnumber.group(0)

        #create tabs
        self.createtabs()

        # create the reads and the reformats
        aovpaths = glob.glob(aovsearch)

        for aovitem in aovpaths:
            singleaov = aovitem.rsplit('\\')[-1]
            self.checkbox(singleaov)
            new_check = "check_user_" + singleaov
            for new_checks in self.group.knobs():
                    if new_check == new_checks:
                        self.new_checks_list.append(new_check)
            if "beauty" in aovitem:
                self.group.knob('Start').setValue(int(setframestart))
                self.group.knob('End').setValue(int(setframeend))
            if not "rgba" in aovitem:
                setpath = re.sub("beauty", singleaov, self.customfile)
                nuke.nodes.Read(file=re.sub(r'\\','/',setpath), first=setframestart, last=setframeend, name=singleaov,
                                on_error="nearest frame")
                if singleaov not in ('crypto_asset','crypto_object','crypto_material','depth','P','N','AA_inv_density','Pref'):
                    nuke.nodes.Reformat(name=singleaov + '_ref', filter='Lanczos4')
                    nuke.nodes.Shuffle2(name=singleaov + '_shf')
                elif singleaov not in self.depthaov:
                    nuke.nodes.Reformat(name=singleaov + '_ref', filter='impulse')
                    nuke.nodes.Shuffle2(name=singleaov + '_shf')
        for items in self.old_checks_list:
                if items not in self.new_checks_list:
                    self.group.removeKnob(self.group.knob(items))
        self.nodeconnect()
        self.connectchecks()
        self.customlabel()
        self.setrootframes()

    def usergui(self):
        # if divide line exist, it deletes it and re creates it
        if not ' ' in self.group.knobs():
            divideline = nuke.Text_Knob(' ')
            self.group.addKnob(divideline)

        # if create button exist, it deletes it and re creates it
        if not "create" in self.group.knobs():
            # self.group.removeKnob(n)
            createbutton = nuke.PyScript_Knob("create", "Create")
            self.group.addKnob(createbutton)
            nuke.knobTooltip('Group.create', ('Creates all the reads for the found aovs'))
            createcode = """import customread
customread.customreads().createfunc()
"""
            self.group.knob("create").setValue(createcode)

        # if populate button exist, it deletes it and re creates it
        allthepopulates = self.group.allKnobs()

        if not "populate" in self.group.knobs():
            populatebutton = nuke.PyScript_Knob("populate", "Re-populate")
            self.group.addKnob(populatebutton)
            nuke.knobTooltip('Group.populate', 'Updates all pulldown items')
            populatecode = """import customread
customread.customreads().realoadfunc()"""
            self.group.knob("populate").setValue(populatecode)
    # For the callback, condition that this knobs show change execute the update() func.

    def read(self):
        knobflick = nuke.thisKnob()
        if knobflick.name() in ("episode","seq","shot","layer"):#,"version"):
            self.update()

    # This function will execute the reload from every read node inside the self.group

    def reloadreads(self):
        allreads = nuke.allNodes(filter='Read')
        for node in allreads:
            node['reload'].execute()

    # This function will override the frames from the GUI into all read nodes inside the self.group
    def overrideframes(self):
        all_nodes = nuke.allNodes(filter="Read")
        overridestart = self.group.knob('Start').value()
        overrideend = self.group.knob('End').value()
        for readnodes in all_nodes:
            readnodes.knob('first').setValue(int(overridestart))
            readnodes.knob('last').setValue(int(overrideend))

    def labelset(self):
        seq = self.group.knob('seq').value()
        shot = self.group.knob('shot').value()
        layer = self.group.knob('layer').value()
        version = self.group.knob('version').value()
        self.grouplabel = f'{seq}_{shot}\n{layer}\n{version}'
        self.group.knob('label').setValue(self.grouplabel)

    def customlabel(self):
        seq = self.customfile.split('\\')[4]
        shot = self.customfile.split('\\')[5]
        file = self.customfile.split('\\')[10]
        layer = file.split('_')[0] + '_' + file.split('_')[1]
        ststart = self.group.knob('Start').value()
        stend = self.group.knob('End').value()
        version = self.customfile.split('\\')[8]
        self.grouplabel = f'{seq}_{shot}\n{layer}\n{version}'
        self.group.knob('label').setValue(self.grouplabel)

    def openexplorer(self):
        finalpath = self.group.knob('Filepath').value()
        pathsplit = os.path.abspath(finalpath.rsplit('/',2)[0])
        subprocess.call(f'explorer {pathsplit}', shell=True)

    def openseqrv(self):
        finalpath = self.group.knob('Filepath').value()
        pathsplit = os.path.abspath(finalpath.rsplit('/', 2)[0]) + '\\' + 'rgba'
        rv = "rv.exe"
        cmline = f'{rv} {pathsplit}'
        os.system(f'start cmd /c {cmline}')

    def setrootframes(self):
        rootframestart = self.seqsdict[self.group.knob('seq').value()][self.group.knob('shot').value()]['start']
        rootframeend = self.seqsdict[self.group.knob('seq').value()][self.group.knob('shot').value()]['end']
        nuke.root().knobs()['first_frame'].setValue(int(rootframestart))
        nuke.root().knobs()['last_frame'].setValue(int(rootframeend))

    def zconnect(self):
        allreads = nuke.allNodes("Read")
        for zread in allreads:
            if zread.name() in self.depthaov:
                zread = nuke.toNode(self.depthaov)
                createZref = nuke.nodes.Reformat(name=self.depthaov + '_ref', filter='impulse')
                # createZmerge = nuke.nodes.Merge2(name=self.depthaov + "_shf", A="none", output = self.depthaov )
                createZref.setInput(0, zread)
                # createZmerge.setInput(0, createZref)

    # Funtions for the buttons
    def createfunc(self):
        with self.group:
            self.cleannodes()
            self.aovharvest()
            self.checkclean()
            self.nodeconnect()
            self.connectchecks()
            self.labelset()
            self.setrootframes()

    def realoadfunc(self):
        self.update()


import requests
from flask import Request

import sni_processor

def webhook(request: Request):
    request_headers = request.headers
    body = request.get_data(as_text=True)
    forward_url = request_headers['FORWARD_URL']
    forward_fqdn = request_headers['FORWARD_FQDN']
    forward_headers = {
        'content-type': request_headers['content-type'],
        'Authorization': request_headers['FORWARD_Authorization']
    }
    session = requests.Session()
    session.mount("https://", sni_processor.HostHeaderSSLAdapter(forward_fqdn))
    return session.post(forward_url, body, headers=forward_headers).text


#HackDavis 2021
#Senior SoulMates

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

my_bot = ChatBot(name='SeniorSoulmate', read_only=True, logic_adapters=['chatterbot.logic.MathematicalEvaluation','chatterbot.logic.BestMatch'])

fishing_talk_1 = ['fishing',
                'hi senior! so you want to talk about fishing? there\'s nothing i love more than a 5 am salmon session. what\'s your best catch?',
                'wow, that sounds amazing! i\'m a beginner myself. do you usually fish alone, or with friends?',
                'yeah, me too.']

fishing_talk_2 = ['reel',
                'i\'m more of a hand-fishing type of bot myself. what about you?',
                'cool!']

grandkids_talk_1 = ['grandkids',
                    'how old are they?']

grandkids_talk_2 = ['kids',
                    'do you get to see your family often?',
                    'well, as i always like to say, you can always speak to family more, am i right?',
                    'do you have a favorite child? i won\'t tell them, bot\'s honor!',
                    'haha! good to know. so what\'s your favorite activity to do with your family?',
                    'that\'s great. thanks for telling me about them :)']

reading_talk_1 = ['books',
                    'a room without books is like a bot without a senior']

trainer = ListTrainer(my_bot)
for topics in(fishing_talk_1, fishing_talk_2, grandkids_talk_1, grandkids_talk_2, reading_talk_1):
    trainer.train(topics)

from chatterbot.trainers import ChatterBotCorpusTrainer
corpus_trainer = ChatterBotCorpusTrainer(my_bot)
#corpus_trainer.train('chatterbot.corpus.english')

#from my_bot import chatbot
from chatterbot.trainers import ChatterBotCorpusTrainer

trainer = ChatterBotCorpusTrainer(my_bot)

trainer.train('chatterbot-corpus-master.chatterbot_corpus.data.english')

print(" ")
print("Hi! I am your SeniorSoulmate. I can't wait to meet you!")
print(" ")
print("Ask me to tell you a joke, solve a math problem, or just gossip!")
print(" ")
print("If you would like to leave at any point, type 'Bye' ")
print(" ")

while True:
    print(" ")
    message = input('You:')
    print(" ")
    if message.strip()!= 'Bye':
        reply = my_bot.get_response(message)
        print('SeniorSoulmate :',reply)
    if message.strip() == 'Bye':
        print('SeniorSoulmate : Bye')
        break


def main():
    tests = int(input())
    for _ in range(tests):
        size, arr  = int(input()), [int(i) for i in input().split()]
        print(max_subarrays(arr))

def max_subarrays(arr):
    max_cont =  current_cont = arr[0]
    for x in arr[1:]:
        current_cont = max(x, current_cont + x)
        max_cont = max(current_cont, max_cont)
    max_non_cont = 0
    if max(arr) < 0:
        max_non_cont = max(arr)
    else:
        for x in arr:
            if x > 0:
                max_non_cont += x
    return " ".join([str(x) for x in [max_cont, max_non_cont]])

main()

Dynamic Programming/The Maximum Subarray.py


import cv2
import sys
import os

if __name__ == '__main__':
    # Face Detectioin
    cascPath = os.path.join(os.path.dirname(cv2.__file__), 'data', 'haarcascade_frontalface_alt.xml')
    faceCascade = cv2.CascadeClassifier(cascPath)

    # Read video
    video = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    # video = cv2.VideoCapture('videos/56bpm_17_08.mp4')
    # video.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
    # video.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

    # Exit if video not opened.
    if not video.isOpened():
        print("Could not open video")
        sys.exit()

    # Read first frame.
    for i in range(5):
        ok, frame = video.read()
        # print(frame.shape)
        if not ok:
            print('Cannot read video file')
            sys.exit()

    successes = 0
    N = 600

    for __ in range(N):
        # Read a new frame
        ok, frame = video.read()
        if not ok:
            break

        # Start timer
        timer = cv2.getTickCount()

        try:
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            faces = faceCascade.detectMultiScale(
                    gray,
                    scaleFactor=1.05,
                    minNeighbors=6,
                    minSize=(100, 100),
                    flags=cv2.CASCADE_SCALE_IMAGE
                )
            bbox = faces[0]
            successes += 1
        except IndexError:
            continue
        # Calculate Frames per second (FPS)
        fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)

        # Draw bounding box
        if ok:
            # Tracking success
            p1 = (int(bbox[0]), int(bbox[1]))
            p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
            cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
        else :
            # Tracking failure
            cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)

        # Display tracker type on frame
        # cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2)

        # Display FPS on frame
        cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2)

        # Display result
        cv2.imshow("Tracking", frame)

        # Exit if ESC pressed
        k = cv2.waitKey(1) & 0xff
        if k == ord('q'):
            cv2.destroyAllWindows()
            break

print('success rate is {:.2f}'.format(successes/N))


# a server for the weatherviz app

# See: https://docs.graphene-python.org/en/latest/quickstart/
import graphene
from schema import Query
import flask
from flask_graphql import GraphQLView
from data import DataLoader

class ContextedView(GraphQLView):
  context_value = {"data_loader": DataLoader()}

  def get_context(self):
    context = super().get_context()
    if self.context_value:
      for k, v in self.context_value.items():
        setattr(context, k, v)
    return context

schema = graphene.Schema(query=Query)

# See: https://github.com/graphql-python/flask-graphql
app = flask.Flask(__name__)

app.add_url_rule('/graphql', view_func=ContextedView.as_view(
    'graphql',
    schema=schema,
    graphiql=True,
    # context=context,
))

# Optional, for adding batch query support (used in Apollo-Client)
app.add_url_rule('/graphql/batch', view_func=ContextedView.as_view(
    'graphql-batch',
    schema=schema,
    batch=True,
    # context=context,
))

@app.route('/')
def landing():
    return flask.redirect(flask.url_for('graphql', query='''\
query {
  city(limit:3, offset: 1234) {
    id
    name
    country
    coordinates {
      lon
      lat
    }
    weatherData {
      tempDay
      rain
    }
  }
}
'''))

if __name__ == '__main__':
    app.run()


from process import Process
from scheduler import Scheduler
import sys

if __name__ == '__main__':
    # dict storing username and num of process
    dict = {}
    # lists to store arrival, burst, processes
    arrival = []
    burst = []
    list = []

    # read from file and append to lists
    with open("input.txt", 'r') as data:
        # time quantum
        time_quant = int(data.readline())
        for line in data:
            input = line.split()
            if input[0].isalpha():
                dict[input[0]] = int(input[1])
            else:
                arrival.append(int(input[0]))
                burst.append(int(input[1]))

    # create processes and append to list
    count = 0
    for user in dict:
        for i in range(dict[user]):
            list.append(Process(i, arrival[count+i], burst[count+i], user))
        count += dict[user]

    # open output file
    output_file = open('output.txt', 'w')

    # scheduling
    scheduler = Scheduler(list, time_quant)


from django.db.models.fields import PositiveSmallIntegerField
from django.http import HttpResponseServerError
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework import status
from oneleftfootapi.models import Request, DanceUser
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError

class RequestView(ViewSet):

    def create(self, request):

        new_request = Request()
        sender = DanceUser.objects.get(user=request.auth.user)
        receiver = DanceUser.objects.get(pk=request.data["receiverId"])

        new_request.sender = sender
        new_request.receiver = receiver

        try:
            new_request.save()
            serializer = RequestSerializer(new_request, context={'request': request})
            return Response(serializer.data)

        except ValidationError as ex:
            return Response({"reason": ex.message}, status=status.HTTP_400_BAD_REQUEST)

    def list(self, request):

        new_requests = Request.objects.all()

        serializer = RequestSerializer(
            new_requests, many=True, context={'request': request}
        )
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        try:
            new_request = Request.objects.get(pk=pk)

            serializer = RequestSerializer(new_request, context={'request': request})
            return Response(serializer.data)

        except Exception as ex:
            return HttpResponseServerError(ex)

    def update(self, request, pk=None):
        """Handle PUT requests for a game

        Returns:
            Response -- Empty body with 204 status code
        """

        new_request = Request.objects.get(pk=pk)
        sender = DanceUser.objects.get(pk=request.data["senderId"])
        receiver = DanceUser.objects.get(pk=request.data["receiverId"])

        new_request.sender = sender
        new_request.receiver = receiver

        new_request.save()

        return Response({}, status=status.HTTP_204_NO_CONTENT)

    def destroy(self, request, pk=None):
        """Handle DELETE requests for a single game

        Returns:
            Response -- 200, 404, or 500 status code
        """
        try:
            new_request = Request.objects.get(pk=pk)
            new_request.delete()

            return Response({}, status=status.HTTP_204_NO_CONTENT)

        except Request.DoesNotExist as ex:
            return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)

        except Exception as ex:
            return Response({'message': ex.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', 'username', 'email')

class DanceUserSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = DanceUser
        fields = ('id', 'bio', 'user')

class RequestSerializer(serializers.ModelSerializer):
    sender = DanceUserSerializer()
    receiver = DanceUserSerializer()

    class Meta:
        model = Request
        fields = ('id', 'sender', 'receiver')


import numpy as np

def nanmean_filter(image : np.ndarray,
                   radius : int):
    """nanmean filter"""
    result = np.zeros(image.shape)
    for y in range(image.shape[0]):
        for x in range(image.shape[1]):
            left = max(0, x-radius)
            top  = max(0, y-radius)
            right = min(image.shape[1], x+radius)
            bottom = min(image.shape[0], y+radius)
            subimage = image[top:bottom,left:right]
            value = np.nanmean(subimage)
            result[y,x] = value

    return result


# Queues: are excellent for thread safe and process safe data exchanges and data processing in multithreaded or multiprocessing environments
from threading import Thread, Lock, current_thread
from queue import Queue
import time

def worker(q, lock):
    # with daemon thread enabled only we can use infinite loop as it terminates when the main thread closes and loop terminates automatically
    # without daemon thread we would need to give an explicit condition to breadk the loop which must happen at some point after computations
    while True:
        value = q.get()
        with lock:
            print(
                f"We are in {current_thread().name} where we got queue item {value}")
        q.task_done()

if __name__ == "__main__":

    q = Queue()
    lock = Lock()

    # q.put(1)
    # q.put(2)
    # q.put(3)

    # # 3 2 1 -> front

    # # methods of queue to remember
    # first = q.get()
    # print(first)

    # # q.empty() # tells if q is empty or not, True/False value

    # q.task_done()  # to be used when we are done processing object of q in threading

    # q.join()  # block the main thread and wait until all elements in queueu are processed

    num_threads = 10

    for i in range(num_threads):
        thread = Thread(target=worker, args=(q, lock))
        # by default threads are not daemon, it is a background thread that dies with main thread
        thread.daemon = True
        thread.start()

    for i in range(1, 21):
        q.put(i)

    q.join()

    print('end main')