import matplotlib.pyplot as plt
from sklearn import datasets, svm, metrics
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split

digits = datasets.load_digits()
_, axes = plt.subplots(2, 5)
images_and_labels = list(zip(digits.images, digits.target))
for ax, (image, label) in zip(axes[0, :], images_and_labels[:5]):
    ax.set_axis_off()
    ax.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    ax.set_title('Training: %i' % label)

n_samples = len(digits.images)
data = digits.images.reshape((n_samples, -1))

X_train, X_test, y_train, y_test = train_test_split(data, digits.target, test_size=0.5, shuffle=False)
classifier = svm.SVC(kernel='rbf', gamma=0.001)
classifier.fit(X_train, y_train)

predicted = classifier.predict(X_test)

test_data = X_test.reshape((len(X_test),8,8))
images_and_predictions = list(zip(test_data, predicted))
for ax, (image, prediction) in zip(axes[1, :], images_and_predictions[:5]):
    ax.set_axis_off()
    ax.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    ax.set_title('Predict: %i' % prediction)

print("SVM분류 결과 %s:\n%s\n" % (classifier, metrics.classification_report(y_test, predicted)))
disp = metrics.plot_confusion_matrix(classifier, X_test, y_test)
disp.figure_.suptitle("Confusion Matrix")
print("혼동 행렬:\n%s" % disp.confusion_matrix)
print("정확도 : ", accuracy_score(y_test, predicted))

plt.show()

필기숫자 인식SVM.py

필기숫자 인식SVM.py


import cv2
import numpy as np

net = cv2.dnn.readNet("dnn_model/yolov4-tiny.weights", "dnn_model/yolov4-tiny.cfg")

model = cv2.dnn_DetectionModel(net)

model.setInputParams(size = (320, 320), scale = 1/255)

classNamesList = []

with open("dnn_model/classes.txt", "r") as fileObject:
    for className in fileObject.readlines():
        className = className.strip()
        classNamesList.append(className)

# print(classNamesList)
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

buttonPerson = False
buttonCell = False
buttonRemote = False

color = (200,0,200)
color1 = (200,0,200)
color2 = (200,0,200)

def clickButton(event, x, y, flags, params):
    global buttonPerson, buttonCell, buttonRemote, color, color1, color2
    if event == cv2.EVENT_LBUTTONDOWN:
        print(x,y)

        polygon = np.array([[(20, 20), (210, 20), (210, 70), (20, 70)]])
        polygon1 = np.array([[(20, 80), (220, 80), (210, 130), (20, 130)]])
        polygon2 = np.array([[(20, 140), (220, 140), (210, 190), (20, 190)]])

        isInside = cv2.pointPolygonTest(polygon, (x, y), False)
        isInside1 = cv2.pointPolygonTest(polygon1, (x, y), False)
        isInside2 = cv2.pointPolygonTest(polygon2, (x, y), False)

        if isInside > 0:
            print("inside")

            if buttonPerson is False:
                buttonPerson = True
                color = (0,255,0)
            else:
                buttonPerson = False
                color = (200,0,200)

            print("Person Button: ", buttonPerson)

        if isInside1 > 0:
            print("inside")

            if buttonCell is False:
                buttonCell = True
                color1 = (0,255,0)
            else:
                buttonCell = False
                color1 = (200,0,200)

            print("Cell Button: ", buttonCell)

        if isInside2 > 0:
            print("inside")

            if buttonRemote is False:
                buttonRemote = True
                color2 = (0,255,0)
            else:
                buttonRemote = False
                color2 = (200,0,200)

            print("Remote Button: ", buttonRemote)

# create window
cv2.namedWindow("Frame")
cv2.setMouseCallback("Frame", clickButton)

while True:

    _, frame = cap.read()

    (clasIds, scores, bboxes) = model.detect(frame)

    for classId, score, bbox in zip(clasIds, scores, bboxes):

        score = round(score, 2)
        x, y, w, h = bbox
        objectName = classNamesList[classId]

        if objectName == "person" and buttonPerson is True:
            cv2.putText(frame, f"{objectName}",
                        (x-5, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)
            cv2.rectangle(frame, (x,y), (x+w, y+h), (0,255,255), 2)

        if objectName == "cell phone" and buttonCell is True:
            cv2.putText(frame, f"{objectName}",
                        (x-5, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)
            cv2.rectangle(frame, (x,y), (x+w, y+h), (0,255,255), 2)

        if objectName == "remote" and buttonRemote is True:
            cv2.putText(frame, f"{objectName}",
                        (x-5, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)
            cv2.rectangle(frame, (x,y), (x+w, y+h), (0,255,255), 2)

    # print(f"Class Id: {clasIds}\nSocres: {scores}\nBoundbox: {bboxes}")
    # Create BUtton
    # cv2.rectangle(frame, (20, 20),(210, 70), (200,0,200), -1)
    polygon = np.array([[(20, 20), (220, 20), (210, 70), (20, 70)]])
    cv2.fillPoly(frame, polygon, color)
    cv2.putText(frame, "Person", (30, 60), cv2.FONT_HERSHEY_PLAIN, 3, (255, 255, 255), 3)

    polygon1 = np.array([[(20, 80), (220, 80), (210, 130), (20, 130)]])
    cv2.fillPoly(frame, polygon1, color1)
    cv2.putText(frame, "Phone", (30, 120), cv2.FONT_HERSHEY_PLAIN, 3, (255, 255, 255), 3)

    polygon2 = np.array([[(20, 140), (220, 140), (210, 190), (20, 190)]])
    cv2.fillPoly(frame, polygon2, color2)
    cv2.putText(frame, "Remote", (30, 180), cv2.FONT_HERSHEY_PLAIN, 3, (255, 255, 255), 3)

    cv2.imshow("Frame",frame)

    key = cv2.waitKey(1)

    if key == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()


from django.http import HttpResponse
from django.views import View
from django.shortcuts import render
from cvolve.main import models

class OffersView(View):

    def get(self, request):
        user = models.User.objects.get(pk=request.user.id)
        offers = user.get_offers_sorted_by_distance(return_distances=True)
        first_offer = offers[0]
        other_offers = [o for o in offers if o.id != first_offer.id]

        return render(request, 'offers.html', {
            'first_offer': first_offer,
            'offers': other_offers
        })


# python3
import datetime
import queue
import numpy as np
import math
import matplotlib.pyplot as plt
import pandas

###############################################################################
# Definitions

bConsoleOutput = True   # Output to console vs output to file
iNumPeople = 15000   # Number of people to come to the park on a given day
iBins = 200     # Number of bins for generating pdf of arrival data
                # More bins = more precise numbers, takes WAY longer

##overrides everything for multiple simulations
bSuperMain = True   # Run multiple days, each with iSuperIncrement more people than the last
iSuperTimes = 30   # How many days to run

## Used for finding the 'magic number' of people per day
iSuperMax = 16000   # Max number of people to enter the park on any day
iSuperMin = 14000
iSuperIncrement = 10    # How much each day should increment people by

###############################################################################
# Output to File
def loadFile():
    f = open("project.console.txt",'w')
    f.write("Simulation ran on:  " + str(datetime.datetime.now())+'\n')
    return f

def makeLog():
    f = open('project.log.txt','w')
    return f

def makeLogSuper():
    f = open('project.log.super.txt','w')
    return f

def loadArriveData():
    ad = open('p.arriveData.txt','r')
    if(gateCloses - parkOpens > 840):
        print('The Park is open too long.  Change the time to be less than 14 hours.')
        return None
    adl = [(float(i)*60 - (parkOpens-480)) for i in ad.read().splitlines()]
    ad.close()

    n,bin,patch=plt.hist(adl,iBins,density=1)#Observed
    plt.close()
    return n,bin,patch

###############################################################################
# park data
#all attractions at Magic Kingdom, Disney World, USA
loc = []
#time between cars
carTime = []
#number of people in each car
rideSize = []
#closest ride to current ride
closestRide = []
#time to ride ride
rideTime = []

#time park opens
parkOpens = 540 #9am
#time gate closes
gateCloses = 1080 #6pm
#time park closes
parkCloses = 1085 #6:05pm give 5 minutes for people to finish current event

#current number of people in each line
lineSize = []
#total number of people who rode each ride
timesRidden = []
waitTimes = []

#fill above lists with data from 'p.RideData.txt'
def loadParkData():
    global loc
    global carTime
    global rideSize
    global closestRide
    global rideTime
    f = open('p.rideData.txt','r')
    df = pandas.read_csv(f,delimiter='\t')
    loc = df['Location'].tolist()
    carTime = df['CarTime'].tolist()
    rideSize = df['RideSize'].tolist()
    closestRide = df['ClosestRide'].tolist()
    rideTime = df['RideTime'].tolist()
    resetParkData()

def resetParkData():
    global lineSize
    global timesRidden
    global waitTimes
    lineSize.clear()
    timesRidden.clear()
    waitTimes.clear()
    for x in range(len(loc)):
        lineSize.append(0)
        timesRidden.append(0)
        waitTimes.append(0)

def printTimes():
    string = ''
    string += str(timesRidden[0]) + ' people entered the park.\n'
    string += str(timesRidden[1]) + ' people exited the park.\n'
    for x in range(2,len(loc)):
        string += '\'' + loc[x] + '\' was ridden ' + str(timesRidden[x]) + ' times.\n'
    return string

def printAverages():
    string = ''
    for x in range (2,len(loc)):
        string += '\'{}\' had an average waiting time of {:.2f}\n'.format(loc[x],waitTimes[x]/timesRidden[x])
    return string

def logTimes():
    string = ''
    for x in range(len(loc)):
        string += str(timesRidden[x]) + '\t'
    return string

def logAverages():
    string = ''
    for x in range (2,len(loc)):
        string += str('{:.2f}\t'.format(waitTimes[x]/timesRidden[x]))
    return string

###############################################################################
# Name Generator
# Entrirely Cosmetic
nameList = []
def loadNameList():
    global nameList
    f = open('p.name_list.txt','r')
    nameList = nameList + f.read().splitlines()
    f.close()

def genName():
    ind = rng.randint(0,len(nameList)-1)
    return nameList[ind]

###############################################################################
# Weight Generator
def genWeight():
    ##get weight data for area near park
    ##normal m=161.8 s=1.88
    return math.ceil(rng.normal(161.8,1.88))

###############################################################################
# Create RNG
seed = 0
rng = 0
def genRNG():
    global seed
    global rng
    seed = np.random.randint(0,2147483647)
    rng = np.random.RandomState()
    rng.seed(seed)

###############################################################################
# person class
personContainer = []
class person(object):
    def __init__(self, id, name, weight):
        self.id = id
        self.name = name
        self.weight = weight
        self.location = -1
        self.energy = 100
        self.time = 0
        self.numRides = 0

    def nextRide(self,location,time):
        self.location = location
        self.time = time

    def detEnergy(self):
        if(self.location > 1):
            self.energy -= math.ceil( ((self.weight / 100 - 1)**2 + 1) \
                * (self.time / (10 if self.time < 100 else 100)) )

    def print(self):
        if(self.location == -1):
            return '#' + str(self.id) + ':\t' + str(self.name) + ' [' \
                + str(self.weight) + ',' + str(self.energy) \
                + '] arrived'
        else:
            return '#' + str(self.id) + ':\t' + str(self.name) + ' [' \
                + str(self.weight) + ',' + str(self.energy) \
                + '] is at ' + str(loc[self.location])

    def log(self):
        if(self.location == -1):
            return str(self.id) + '\t' + str(self.energy) + '\t' \
                + str(lineSize[self.location]) + '\t' \
                + 'arrived'
        else:
            return str(self.id) + '\t' + str(self.energy) + '\t' \
                + str(lineSize[self.location]) + '\t' \
                + str(loc[self.location])

###############################################################################
# Determine Next Ride to go to
def nextRide(location,energy):
    if(location == -1): #if at entrance go to gate
        lineSize[0] += 1
        return 0
    if(energy <= 0):
        return 1 #go to exit to leave
    r = rng.random_sample()
    if(r >= 0.8): ##go to random ride
        ride = rng.randint(2,len(loc))
        lineSize[ride] += 1
        return ride
    elif(r < 0.3):   ## go to shortest line
        shortestRide = 2
        for x in range(2,len(lineSize)):
            if(lineSize[x] < lineSize[shortestRide]):
                shortestRide = x
        lineSize[shortestRide] += 1
        return shortestRide
    else:  ## go to closest ride
        ride = closestRide[location]
        lineSize[ride] += 1
        return ride

###############################################################################
# get line time
def lineTime(location):
    return carTime[location] * math.floor(lineSize[location] / rideSize[location])

###############################################################################
# custom List getindex
def pIndex(lst,item):
    for a in range(len(lst)):
        if item < lst[a+1]:
            return a

###############################################################################
# Driver
def main():
    global personContainer

    if (iNumPeople == 0): return 0
    if(len(nameList) < 2):
        loadNameList()
        loadParkData()
        genRNG()
    else:
        resetParkData()

    if(not bSuperMain):
        l = makeLog()
        if(bConsoleOutput):
            print("RNG seed used: ", seed)
            print('Generating arrival times; please wait...')
        else:
            f = loadFile()
            f.write("RNG seed used: %d\n\n"% seed)

    #rejection sampling to generate arrival data
    que = queue.PriorityQueue()
    n,bin,patch=loadArriveData()
    num = 0
    while (que.qsize() < iNumPeople):
        x = rng.random_sample()*(gateCloses-parkOpens)+parkOpens
        y = rng.random_sample()
        ind = pIndex(bin,x)
        if(ind == None): # something funky happened, 'x' is not in 'bin'
            continue
        if(y < n[ind]): # do not reject sample
            personContainer.append(person(num,genName(),genWeight()))
            que.put((x, personContainer[-1]))
            num += 1

    ##run queue, park closes at 2am
    worldClock = 0
    while( (not que.empty())  and worldClock < parkCloses ):
        next = que.get()
        p = next[1]
        worldClock = next[0]

        if(not bSuperMain):
            if(bConsoleOutput): print(p.print() + ' at %0.2f' % worldClock)
            else: f.write(p.print()+ ' at %0.2f\n' % worldClock)
            l.write('%.2f\t'%worldClock)
            l.write(p.log()+'\t'+logTimes()+str(que.qsize())   +'\n')

        if(p.location != -1):
            lineSize[p.location] -= 1
            timesRidden[p.location] += 1
            if(p.location > 1):
                p.numRides += 1
        p.detEnergy()
        loc = p.location
        nRide = nextRide(p.location,p.energy)
        if(loc == 1):
            continue
        elif(loc == -1):
            time = lineTime(nRide)
            p.nextRide(nRide,time)
            que.put((worldClock + time, p))
        else:
            time = lineTime(nRide)
            waitTimes[nRide] += time
            p.nextRide(nRide,time)
            que.put((worldClock + time + rideTime[loc], p))

    sum = 0
    for peep in personContainer:
        sum += peep.numRides
    sum /= len(personContainer)

    if(not bSuperMain):
        if(bConsoleOutput):
            print('\n%d people are still in the park at closing.'%que.qsize())
            print(printTimes(),end='')
            print('The average amount of rides ridden is %.2f rides.\n'%sum)
            print(printAverages(),end='')
        else:
            f.write('\n%d people are still in the park at closing.\n'%que.qsize())
            f.write(printTimes())
            f.write('The average amount of rides ridden is %.2f rides.\n'%sum)
            f.write(printAverages(),end='')
            f.close()
        l.close()

    return sum

###############################################################################
# super driver for multiple simulations
def superMain():
    global iNumPeople
    global personContainer
    log = makeLogSuper()

    for x in range(iSuperTimes):
#        iNumPeople = ((x * iSuperIncrement) % (iSuperMax - iSuperMin)) \
#                + iSuperMin  #range: [iSuperMin, iSuperMax]

        personContainer.clear()

        s = main()
#        log.write('%d\t%.2f\t' % (iNumPeople,s))
        log.write('%.2f\t' % (s))
        log.write(logAverages())
        log.write('\n')
#        print('%d\t%.2f' % (iNumPeople,s),end='\t')
        print('%d\t%.2f' % (x,s),end='\t')
        print(logAverages())

    log.close()

###############################################################################
# run program.
if(not bSuperMain):
    main()
else:
    superMain()


import sys
import os
from typing import List, Optional
from ..utils import read_file_as_int

def part_one(inputFile: str):
  lines = read_file_as_int(inputFile)
  prev : Optional[int] = None
  inc = 0
  dec = 0
  for i in lines:
    if prev != None:
      if i < prev:
        dec += 1
      elif i > prev:
        inc += 1
    prev = i
  return prev

def part_two(inputFile: str):
  lines = read_file_as_int(inputFile)
  idx = 0
  inc = 0
  for _ in lines:
    idx += 1
    if idx >= 4:
      a1 = lines[idx-4:idx-1]
      a2 = lines[idx-3:idx]
      if sum(a2) > sum(a1):
        inc += 1

  return inc


from mock import patch

from .util import V1TestCase, writeable_settings_stub

class TestTakeCommand(V1TestCase):
    get_workitem = patch('helga_versionone.get_workitem')
    get_user = patch('helga_versionone.get_user')

    def test_in_owners(self):
        self.get_workitem().Owners = [self.nick, 'fhqwhgads']
        self.get_user.return_value = self.nick

        return self._test_command(
            'take whatever',
            'Dude {0}, you already own it!'.format(self.nick),
        )

    def test_not_in_owners_write_fail(self):
        self.get_workitem().Owners = ['fhqwhgads']
        self.get_user.return_value = self.nick

        return self._test_command(
            'take whatever',
            'I would, but I\'m not allowed to write :('
        )

class TestTakeCommandWithWrite(V1TestCase):
    settings = patch('helga_versionone.settings', writeable_settings_stub)
    get_workitem = patch('helga_versionone.get_workitem')
    get_user = patch('helga_versionone.get_user')

    def test_not_in_owners_write_ok(self):
        w = self.get_workitem()
        w.Owners = ['fhqwhgads']
        self.get_user.return_value = self.nick

        d = self._test_command(
            'take whatever',
        )

        def check(res):
            # Check data and commit called
            self.assertEquals(
                w.Owners,
                [self.nick],
            )
            self.v1.commit.assert_called_once_with()
            self.assertAck()

        d.addCallback(check)
        return d


#!/usr/local/bin/python

import os
import sys
from datetime import datetime, timedelta
import requests
import argparse
import json
from pprint import pprint
from argparse import RawTextHelpFormatter
import  boto3
from botocore.exceptions import ClientError

PROD_AUTH_URL = "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize"
RECOMMENDATION = {'Recommendation': None, 'Details': None}
DEFAULT_HEADERS = {'Accept': 'application/json', 'Content-type': 'Application/json'}

class CommandFormatter(argparse.ArgumentDefaultsHelpFormatter,
                       argparse.RawDescriptionHelpFormatter):
    """Argparse formatter to display __doc__ string correctly"""
    pass

parser = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=RawTextHelpFormatter, add_help=False)
                                 # formatter_class=CommandFormatter, add_help=False)
parser.add_argument('-S', '--sddc-id', required=True, help='SDDC ID of the instance')
parser.add_argument('-I', '--ip-address', help='IP Address of instance')
parser.add_argument('-i', '--instance-id', help='Instance ID of instance')
parser.add_argument('-h', '--help', action='help')

def api_request(url, method='get', headers=None, data=None, params=None):
    if method == 'get':
        return requests.get(url, headers=headers, data=data, params=params)
    elif method == 'put':
        return requests.put(url, headers=headers, data=data, params=params)
    else:
        return requests.post(url, headers=headers, data=data, params=params)

def get_api_token(url=PROD_AUTH_URL, token=None):
    if not token:
        token = os.environ.get("VMC_REFRESH_TOKEN", None)
    if not token:
        print("Please set your VMC_REFRESH_TOKEN environment variable. Quitting")
        return None
    resp = api_request(url, method='post', headers={'Content-type': 'application/x-www-form-urlencoded'},
                       data={'refresh_token': token})
    if resp.status_code < 200 or resp.status_code > 202:
        print("Unable to obtain access token from refresh token. Quitting")
        return None
    return resp.json()['access_token']

def get_sddc_org_region(sddc_id):
    token = get_api_token()
    headers = DEFAULT_HEADERS
    headers.update({'csp-auth-token': token})
    url = 'https://vmc.vmware.com/vmc/api/operator/sddcs/{}'.format(sddc_id)
    resp = api_request(url, headers=headers)
    if resp.status_code < 200 or resp.status_code > 202:
        print("Unable to obtain SDDC with ID " + sddc_id + ". Quitting...")
        return None, None
    return (resp.json()['org_id'], resp.json()['resource_config']['sddc_manifest']['esx_ami']['region'],
        resp.json()['resource_config']['vpc_info']['id'])

def get_instance_data(sddc_id, org_id, region, vpc_id, ip_addr, inst_id):
    token = get_api_token()
    headers = DEFAULT_HEADERS
    headers.update({'csp-auth-token': token})
    url = 'https://vmc.vmware.com/vmc/api/operator/aws/credentials?orgId={}'.format(org_id)
    resp = api_request(url, method='post', headers=headers)
    if resp.status_code < 200 or resp.status_code > 204:
        print("Unable to obtain AWS credentials for Org " + org_id + " and sddc ID " + sddc_id)
        return None
    session_token = resp.json()['aws_credentials']['session_token']
    access_key = resp.json()['aws_credentials']['awsaccess_key_id']
    secret_key = resp.json()['aws_credentials']['awssecret_key']
    ec2_resource = boto3.resource('ec2', aws_access_key_id=access_key,
                                  aws_secret_access_key=secret_key, region_name=region,
                                  aws_session_token=session_token)

    filters = [{'Name': 'vpc-id', 'Values': [vpc_id]}]
    if ip_addr:
        filters.append({'Name': 'private-ip-address', 'Values': [ip_addr]})
    if inst_id:
        filters.append({'Name': 'instance-id', 'Values': [inst_id,]})

    r = ec2_resource.instances.filter(Filters=filters)
    header = True
    for item in r:
        if header:
            print('InstanceId', 'InstanceType', 'IPAddress', 'InstanceState', 'LaunchTime')
            header = False
        print(item.instance_id, item.instance_type, item.private_ip_address, item.state['Name'], str(item.launch_time))

if __name__ == '__main__':

    args = parser.parse_args()
    org_id, region, vpc_id = get_sddc_org_region(args.sddc_id)
    if not org_id:
        sys.exit(1)

    get_instance_data(args.sddc_id, org_id, region, vpc_id,
                      args.ip_address, args.instance_id)


import os
import cv2
import tensorflow as tf
try:
    from PIL import Image
except ImportError:
    import Image

import matplotlib.pyplot as plt
import numpy as np
UPLOAD_FOLDER = '/static/uploads/'
# import pytesseract
# pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

CATEGORIES = ["Black-grass","Charlock","Cleavers","Common Chickweed","Common wheat","Fat Hen","Loose Silky-bent","Maize","Scentless Mayweed","Shepherds Purse","Small-flowered Cranesbill","Sugar beet"]

def prepare(file):
    try:
        IMG_SIZE = 128
        IMG_SIZE_WIDTH=128
        img_array = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
        img_array = img_array / 255.0
        new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE_WIDTH))
        return new_array.reshape(-1, IMG_SIZE, IMG_SIZE_WIDTH, 1)

    except Exception as e:
        print(str(e))

def ocr_core(filename):
    """
    This function will handle the core OCR processing of images.
    """
    # text = pytesseract.image_to_string(Image.open(filename), config="-c tessedit"
    #                                                                 "_char_whitelist=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    #                                                                 " --psm 10"
    #                                                                 " -l osd"
    #                                                                 " ")  # We'll use Pillow's Image class to open the image and pytesseract to detect the string in the image

    model = tf.keras.models.load_model("CNN.model")

    # print(image)
    # new code
    img = cv2.imread('./static/uploads/'+filename)
    plt.imshow(img)

    segmanted_img_name=filename[:-4]+"_segmanted"

    image_mask = create_mask_for_plant(img)
    image_segmented = segment_plant(img)
    image_sharpen = sharpen_image(image_segmented)

    cv2.imwrite(os.getcwd() + UPLOAD_FOLDER+segmanted_img_name+".png", image_sharpen)

    image = prepare('./static/uploads/' + segmanted_img_name+".png")  # your image path segmented image path

    #
    assert not isinstance(image, type(None)), 'image not found'
    #image1=prepare(image)
    prediction = model.predict([image])
    prediction = list(prediction[0])
    text= CATEGORIES[prediction.index(max(prediction))]  # -*- coding: utf-8 -*-

    return text  # Then we will print the text in the image

def create_mask_for_plant(image):
    image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

    sensitivity = 35
    lower_hsv = np.array([60 - sensitivity, 100, 40])
    upper_hsv = np.array([60 + sensitivity, 255, 255])

    mask = cv2.inRange(image_hsv, lower_hsv, upper_hsv)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

    return mask

def segment_plant(image):
    mask = create_mask_for_plant(image)
    output = cv2.bitwise_and(image, image, mask=mask)
    return output

def sharpen_image(image):
    image_blurred = cv2.GaussianBlur(image, (0, 0), 3)
    image_sharp = cv2.addWeighted(image, 1.5, image_blurred, -0.5, 0)
    return image_sharp

def segment(img):
    # image_mask = create_mask_for_plant(img)
    image_segmented = segment_plant(img)
    image_sharpen = sharpen_image(image_segmented)
    return image_sharpen


from django.urls import path, include
from rest_framework.routers import DefaultRouter

from recipe import views

router = DefaultRouter()
router.register('ingredients', views.IngrediendViewSet)
router.register('recipe', views.RecipeViewSet)

app_name = 'recipe'

urlpatterns = [
    path('', include(router.urls)),
    path('recipe_list/', views.RecipeList.as_view(), name='recipe_list'),
    path('rate_recipe/', views.RateRecipeView.as_view(), name='rate_recipe'),
    path('topingredients/', views.GetMoseUsedIngredientsTop.as_view(), name="topingredients")
]


# Needed
from docker import from_env
from unittest import TestCase

# Not Needed  (Example Only)
from typing import Iterable
from docker import DockerClient
from docker.models.containers import Container
from docker.models.images import Image
from pathlib import Path

class ExplainedExampleTest(TestCase):
	"""
	This class is an testing of a generated test class.
	This serves as a demonstration of the template.
	This class is not actually used.

	The type hints are not necessary, and do not need to be included in the generated test files;
	they are simply here to help explain this testing.
	"""
	# Class Attributes
	client:	DockerClient
	image:	Image
	logs:	Iterable

	# Instance Attributes
	container: Container

	@classmethod
	def setUpClass(cls):
		dockerfile = Path()									# variable
		dockerfile_dir = repr(str(dockerfile.parent))  		# inferred variable
		dockerfile_sub_path = repr(dockerfile.name)  		# inferred variable
		cls.client = from_env()								# Generated Line
		cls.image, cls.logs = cls.client.images.build(path=dockerfile_dir, dockerfile=dockerfile_sub_path, rm=True, forcerm=True)  # Generated Line

	@classmethod
	def tearDownClass(cls):
		cls.client.images.remove(image=cls.image.id, force=True)  # Generated Line

	def setUp(self):
		cls = type(self)  # could also have a class_name variable (instead of this line)  ;  Generated Line
		self.container = cls.client.containers.run(cls.image, detach=True, tty=True)  # Generated Line
		# use the line below instead of the line above if a mount point
		# self.container = cls.client.containers.create(cls.image, detach=True, volumes={'<path_in_main_container>': {'bind': '<path_inside_container>', 'mode': 'rw'}})
		# self.container.put_archive()  # insert files into the container

	def tearDown(self):
		# self.container.get_archive(...)	# extract a specific folder from the container
		# self.container.export(...)		# extract all files from the container
		self.container.remove(force=True)  	# Kill and Remove the container  ;  Generated Line

	def test_dont_verify(self):
		cmd = ...  					# variable ; line not generated
		self.container.exec_run(cmd, stdout=False, stderr=False)  # Generated Line

	def test_verify_no_output(self):
		cmd = ...  					# variable ; line not generated
		exit_code, output = self.container.exec_run(cmd, stdout=True, stderr=True)  # Generated Line
		self.assertFalse(output)  	# allows none or empty string (assertIsNone only allows none)  ;  Generated Line

	def test_verify_with_regex(self):
		cmd = ...  					# variable ; line not generated
		output_regex: str = ...  	# variable ; line not generated
		exit_code, output = self.container.exec_run(cmd, stdout=True, stderr=True)  # Generated Line
		self.assertRegex(output.decode(), output_regex)  # Generated Line


import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.cuda.amp as amp
from math import exp

# Dice and focal losses taken from (and slightly modified):
# https://github.com/CoinCheung/pytorch-loss/blob/master/focal_loss.py

# Focal-Tversky loss taken from:
# https://github.com/Mr-TalhaIlyas/Loss-Functions-Package-Tensorflow-Keras-PyTorch

# Focal-Tversky loss
class FocalTverskyLoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(FocalTverskyLoss, self).__init__()

    def forward(self, inputs, targets, smooth=1, alpha=0.5, beta=0.5, gamma=1.0):

        #comment out if your model contains a sigmoid or equivalent activation layer
        inputs = torch.sigmoid(inputs)

        #flatten label and prediction tensors
        inputs = inputs.view(-1)
        targets = targets.view(-1)

        #True Positives, False Positives & False Negatives
        TP = (inputs * targets).sum()
        FP = ((1 - targets) * inputs).sum()
        FN = (targets * (1 - inputs)).sum()

        tversky = (TP + smooth) / (TP + alpha * FP + beta * FN + smooth)
        focal_tversky = (1 - tversky) ** gamma

        return focal_tversky

# Generalized soft dice loss
class DiceLoss(nn.Module):
    def __init__(self, p=1, smooth=1, reduction='mean', weight=None):
        super(DiceLoss, self).__init__()
        self.p = p
        self.smooth = smooth
        self.reduction = reduction
        self.weight = None if weight is None else torch.tensor(weight).cuda()

    def forward(self, probs, label):
        '''
        args: probs: tensor of shape (N, C, H, W)
        args: label: tensor of shape(N, C, H, W)
        '''
        numer = torch.sum((probs * label), dim=(2, 3))
        denom = torch.sum(probs.pow(self.p) + label.pow(self.p), dim=(2, 3))
        if not self.weight is None:
            numer = numer * self.weight.view(1, -1)
            denom = denom * self.weight.view(1, -1)
        # numer = torch.sum(numer, dim=1)
        # denom = torch.sum(denom, dim=1)
        loss = 1 - (2 * numer + self.smooth)/(denom + self.smooth)
        if self.reduction == 'mean':
            loss = loss.mean()
        return loss

class FocalSigmoidLossFuncV2(torch.autograd.Function):
    '''
    compute backward directly for better numeric stability
    '''
    @staticmethod
    @amp.custom_fwd(cast_inputs=torch.float32)
    def forward(ctx, logits, label, alpha, gamma):

        probs = torch.sigmoid(logits)
        coeff = (label - probs).abs_().pow_(gamma).neg_()
        log_probs = torch.where(logits >= 0,
                F.softplus(logits, -1, 50),
                logits - F.softplus(logits, 1, 50))
        log_1_probs = torch.where(logits >= 0,
                -logits + F.softplus(logits, -1, 50),
                -F.softplus(logits, 1, 50))
        ce_term1 = log_probs.mul_(label).mul_(alpha)
        ce_term2 = log_1_probs.mul_(1. - label).mul_(1. - alpha)
        ce = ce_term1.add_(ce_term2)
        loss = ce * coeff

        ctx.vars = (coeff, probs, ce, label, gamma, alpha)

        return loss

    @staticmethod
    @amp.custom_bwd
    def backward(ctx, grad_output):
        '''
        compute gradient of focal loss
        '''
        (coeff, probs, ce, label, gamma, alpha) = ctx.vars

        d_coeff = (label - probs).abs_().pow_(gamma - 1.).mul_(gamma)
        d_coeff.mul_(probs).mul_(1. - probs)
        d_coeff = torch.where(label < probs, d_coeff.neg(), d_coeff)
        term1 = d_coeff.mul_(ce)

        d_ce = label * alpha
        d_ce.sub_(probs.mul_((label * alpha).mul_(2).add_(1).sub_(label).sub_(alpha)))
        term2 = d_ce.mul(coeff)

        grads = term1.add_(term2)
        grads.mul_(grad_output)

        return grads, None, None, None

class FocalLoss(nn.Module):

    def __init__(self,
                 alpha=0.25,
                 gamma=2,
                 reduction='mean'):
        super(FocalLoss, self).__init__()
        self.alpha = alpha
        self.gamma = gamma
        self.reduction = reduction

    def forward(self, logits, label):
        '''
        Usage is same as nn.BCEWithLogits:
            >>> criteria = FocalLoss()
            >>> logits = torch.randn(8, 19, 384, 384)
            >>> lbs = torch.randint(0, 2, (8, 19, 384, 384)).float()
            >>> loss = criteria(logits, lbs)
        '''
        loss = FocalSigmoidLossFuncV2.apply(logits, label, self.alpha, self.gamma)
        if self.reduction == 'mean':
            loss = loss.mean()
        if self.reduction == 'sum':
            loss = loss.sum()
        return loss

bce_loss_fn = nn.BCEWithLogitsLoss()
mse_loss_fn = nn.MSELoss()
mae_loss_fn = nn.L1Loss()
foc_loss_fn = FocalLoss(alpha=0.5, gamma=2.0, reduction='mean')  # FocalTverskyLoss()
dic_loss_fn = DiceLoss()

def loss_fn(E_seq, S_seq, S_seq_true, pred_flag=True, split_flag='train'):
    ''' Compute loss for a batch of sequences

    Args:
    -----
    '''

    n_frames = S_seq_true.shape[-1]
    device = S_seq_true.device
    S_seq_true = [S_seq_true[..., t] for t in range(n_frames)]
    time_weight = [1.0 if t > 0 else 0.0 for t in range(n_frames)]
    total_loss = torch.tensor(0.0, device=device)
    for t, (E, S, S_true) in enumerate(zip(E_seq, S_seq, S_seq_true)):

        # Sum of prediction error signals (self-supervised)
        # E[0] is next frame prediction error
        pred_loss = 0.0 if E is None else sum([torch.mean(e) for e in E])

        # Segmentation prediction loss (supervised)
        seg_loss = dic_loss_fn(S, S_true)  # + foc_loss_fn(S, S_true)

        # Account for prediction error only in training mode
        if pred_flag and not split_flag == 'train':
            frame_loss = seg_loss + pred_loss
        else:
            frame_loss = seg_loss  # (seg_loss if seg_loss > 0 else 0.0)

        # Weight loss differently for each frame
        if (split_flag == 'test' and t > 20) \
        or (split_flag == 'val' and t > 5) \
        or (split_flag == 'train' and t > 0):
            total_loss = total_loss + frame_loss * time_weight[t]

    return total_loss / n_frames


import matplotlib
matplotlib.use('TKAgg')
import matplotlib.pyplot as plt

from basic_funcs import load_results, load_dataset, delete_row_csr
import numpy as np
import pickle, random
from sklearn import linear_model
from sklearn.metrics import confusion_matrix
from baseline_model.class_imbalance import imba_tech
import recipe, config

def choose_query(distance, query_strategy):
  """
  This function implements the "query" step in the active learning cycle.
  Note that the batch size is 2.
  :param distance: a list or numpy array, including the distance of all documents to the SVM hyperplane
  :param query_strategy: string, describing which query strategy to be used. Options are:
  1. 'least_confidence'
  2. 'certainty_positive'
  3. 'certainty_positive_negative'
  :return: a list or numpy array with indices for the "selected" documents
  """

  # 'least_confidence' stands for the query strategy - uncertainty sampling
  if query_strategy == 'least_confidence':
    # Get absolute distance to the hyperplane
    abs_distance = np.absolute(distance)
    # Get indices of two documents whose "absolute" distance are the two smallest
    query_indices = np.argsort(abs_distance)[0:2]

  elif query_strategy == 'certainty_positive':
    # Get indices of two documents whose distance to the hyperplane are the two largest (i.e., the first and the second)
    query_indices = np.argsort(distance)[0:2]

  elif query_strategy == 'certainty_positive_negative':
    # Get indices of one documents whose distance to the hyperplane (distance can be negatives) is the smallest
    # and one documents whose distance is the largest (i.e., the first and last one in the order)
    query_indices = np.argsort(distance)[[0, -1]]

  else:
    # if no query strategy is applied, indices of two random documents are assigned
    query_indices = random.sample(range(1, len(distance)), 2)

  return query_indices

def run_query_strategy(partial_set, query_strategy, optimal_alpha, optimal_tol, imba_type, random_seed=None):
  """
  This function implements the active learning process for one dataset.
  :param partial_set: int, index of dataset, ranging from 1 to 5. Each dataset consists of five reviews
  :param query_strategy: string, 'least_confidence', 'certainty_positive' or 'certainty_positive_negative'
  :param optimal_alpha: float, the optimal value of alpha
  :param optimal_tol: float, the optimal value of tolerance
  :param imba_type: string, indicating class imbalance technique
  :param random_seed: int, the number used for the randomization
  :return:
  """

  # Initiate variables
  tp_r = 0
  num_of_iter = 0

  # Indices of documents that were queried and read by the reviewer
  reviewer_list = []
  tp_reviewer_list = []

  # Metrics to be recorded for each iteration in active learning
  number_query_docs = []
  yield_list = []
  burden_list = []

  X_train, y_train, X_u_pool, y_u_pool = load_dataset('partial', partial_set, recipe.STANDARD_TYPE)

  if imba_type == 'weighting':
    # Initiate SVM Model which enables setting class weight
    weight = int((len(y_train) - y_train.sum()) / y_train.sum())
    clf = linear_model.SGDClassifier(loss="hinge", penalty="l2", tol=optimal_tol, alpha=optimal_alpha,
                                     shuffle=True, random_state=1, max_iter=5000, class_weight={1: weight})

  else:
    # Initiate SVM Model
    clf = linear_model.SGDClassifier(loss="hinge", penalty="l2", tol=optimal_tol, alpha=optimal_alpha,
                                     shuffle=True, random_state=1, max_iter=5000)
    # Re-sample the training data due to the undersampling or oversampling - handle class imbalance
    X_train, y_train = imba_tech(X_train, y_train, imba_type, random_seed)

  # Train the model with the seed
  clf.fit(X_train, y_train)

  # Start Active Learning Loop!
  while len(y_u_pool) != 0:

    predictions = clf.predict(X_u_pool)

    ####################################################################################
    # Get confusion matrix for the test data
    cm = confusion_matrix(y_u_pool, predictions)

    # If only one element left in the confusion matrix, then ravel() cannot be used, so here divide it into two paths
    if len(cm) > 1:
      tn_u, fp_u, fn_u, tp_u = cm.ravel()

    else:
      fp_u = 0
      fn_u = 0
      tp_u = 0

    # Calculate Yield and Burden
    yield_al = (tp_r + tp_u)/(tp_r + tp_u + fn_u)
    burden_al = (len(reviewer_list) + tp_u + fp_u)/(len(reviewer_list) + len(y_u_pool))
    ###################################################################################

    # Obtain (or update) the distance (including both positive values and negative values) to the hyperplane
    distance = clf.decision_function(X_u_pool)

    # Record measurements, respectively meaning the number of selected samples, yield, and burden for each iteration
    number_query_docs.append(num_of_iter * 2)
    yield_list.append(yield_al)
    burden_list.append(burden_al)

    # Get indices of selected documents (numpy.array type) following query strategies
    query_indices = choose_query(distance, query_strategy)

    # The X and Y of the queried document
    X_update = X_u_pool[query_indices]  # scipy.sparse.csc.csc_matrix
    y_update = y_u_pool.iloc[query_indices]

    # List of Documents that are to be reviewed by the oracle (reviewer)
    reviewer_list = reviewer_list + list(query_indices)

    # list of "Relevant" Documents that are screened by the oracle (reviewer)
    for query_index in query_indices:
      if y_u_pool.iloc[query_index] == 1:
        tp_reviewer_list.append(query_index)

    # Remove X and y of query documents from Unlabelled pool
    X_u_pool = delete_row_csr(X_u_pool, query_indices)
    y_u_pool = y_u_pool.drop(y_u_pool.index[query_indices])

    # Update the Classifier by partial fit
    clf = clf.partial_fit(X_update, y_update, classes=[0, 1])

    # When the unlabelled pool is empty, stop the loop
    if len(y_u_pool) == 0:
      break

    tp_r = len(tp_reviewer_list)

    num_of_iter += 1

  # Create a dictionary to store the results
  result_obj = {
    'query_strategy': query_strategy,
    'query': number_query_docs,
    'yield': yield_list,
    'burden': burden_list,
  }

  # Store the result dictionary
  with open('../Consolidation/query_strategy/{}_{}_seed_{}_undersamp.pickle'.format(partial_set, query_strategy,
                                                                                random_seed), 'wb') as handle:
    pickle.dump(result_obj, handle, protocol=pickle.HIGHEST_PROTOCOL)

  return result_obj

def test_query_strategy(partial_sets, optimal_alpha, optimal_tol):
  """
  Implement the run_query_strategy() function for different datasets with different query strategies.
  Tested strategies includes 'least_confidence', 'certainty_positive', and 'certainty_positive_negative'.
  Each model repeats five times using different random seeds for random undersampling technique.
  :param partial_sets: a list of integers, indicating different datasets;
  :param optimal_alpha: float, the optimal value of alpha
  :param optimal_tol: float, the optimal value of tolerance
  :return: List of results are stored.
  """

  # List of query strategies to be tested
  query_strategies = ['least_confidence', 'certainty_positive', 'certainty_positive_negative']

  # Seed list
  seeds = list(range(1, 6))

  for query_strategy in query_strategies:

    for partial_set in partial_sets:

      for seed in seeds:

        run_query_strategy(partial_set, query_strategy, optimal_alpha, optimal_tol,
                           imba_type=recipe.CLASS_IMBALANCE, random_seed=seed)

def plot_query_strategy():
  """
  This function makes a boxplot to represent the results of WSS@95 for different query strategies
  :return:
  """
  query_strategies = ['least_confidence', 'certainty_positive', 'certainty_positive_negative']

  partial_sets = [1, 2, 3, 4, 5]

  seeds = list(range(1, 6))

  # This list will be used for making a boxplot
  compare_query_strategy = []

  for query_strategy in query_strategies:

    ilist = []

    for partial_set in partial_sets:

      for seed in seeds:
        query_al, yield_al, burden_al = load_results(partial_set, query_strategy, random_seed=seed)

        # Get 1-burden when yield first stay at 100%
        yield_al = np.array(yield_al)
        index = np.where(yield_al == 1)[0]

        # Add (1-burden) to the list
        ilist.append(1 - burden_al[index[0]])

    compare_query_strategy.append(ilist)

  plt.figure()
  axes = plt.gca()
  axes.set_ylim([-0.1, 1])

  plt.boxplot(compare_query_strategy)

  plt.xticks((1, 2, 3), ('uncertainty', 'certainty \n(positive)', 'certainty \n (positive and negative)'))
  plt.ylabel('(1-Burden) at 100% Yield')

  color = ['r', 'g', 'b', 'k', 'c']

  # Plot each model as a point in the same graph
  for i in range(len(compare_query_strategy)):
    y = compare_query_strategy[i]

    x = list(np.random.normal(i + 1, 0.04, size=len(y)))

    for j in range(5):
      plt.scatter(x[5 * j: 5 * j + 5], y[5 * j: 5 * j + 5], c=color[j], alpha=0.6, s=16)

  # plt.show()
  plt.savefig(config.QUERY_STRATEGY_FIGURE)


import operator
import random
from statistics import mean

import matplotlib.pyplot as plt
import networkx as nx

# run single experiment estimating block propagation time

def estimate_block_propagation_time(n, m):
    # generate graph and compute shortest paths lenghts from node 0 to others
    graph = nx.barabasi_albert_graph(n, m)
    for (u, v, w) in graph.edges(data=True):
        w["weight"] = random.uniform(0.08, 16)
        # print(graph.edges[u,v]['weight'])
    shortest_paths = nx.single_source_dijkstra_path_length(graph, 0)
    return max(shortest_paths.items(), key=operator.itemgetter(1))[1]

# parameter m is how much connection committee member has
m = 3

# k is amount of experiments for averaging
k = 100

ydata = []
xdata = range(20, 200)
for n in xdata:
    data = [estimate_block_propagation_time(n, m) for _ in range(k)]
    # print(n, mean(data))
    ydata.append(mean(data))

plt.plot(xdata, ydata)
plt.ylabel("Propagation Time, Seconds")
plt.xlabel("Committee Size")
plt.show()


from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

data = []
stops = []
departure_times = []
arrival_times = []

def app_driver():
    url = "https://www.izban.com.tr/Sayfalar/SeferSaatleri.aspx?MenuId=22"
    options = Options()
    options.add_experimental_option('excludeSwitches', ['enable-logging'])
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=options)
    driver.get(url)
    return driver

def get_stops(all_stops):
    # get each individual stop name
    for stop in all_stops.find_elements(By.TAG_NAME, 'option'):
        stops.append(stop.text)
    return stops

def get_data(table):
    for row in table.find_elements(By.TAG_NAME, "tr"):
        data.append(row.text)
    return data

def split_times(times):
    for time in times:
        departure_times.append(time.split()[0])
        arrival_times.append(time.split()[1])
    return departure_times, arrival_times

def get_titles():
    return data[slice(3)]

def main():
    driver = app_driver()
    movement_stop_dd = driver.find_element(By.ID, 'ctl00_CPH_drpHareketDur')
    sleep(1)
    get_stops(movement_stop_dd)
    movement_station_select = Select(movement_stop_dd)
    movement_station_select.select_by_visible_text('Menemen')
    sleep(1)
    arrival_stop_dd = driver.find_element(By.ID, "ctl00_CPH_drpVarisDur")
    arrival_stop_select = Select(arrival_stop_dd)
    arrival_stop_select.select_by_visible_text('Alsancak')
    sleep(1)
    driver.find_element(By.ID, "ctl00_CPH_Goster").click()
    sleep(1)
    table = driver.find_element(By.TAG_NAME, "table")
    get_data(table)
    sleep(1)
    get_titles()
    split_times(data[slice(4, len(data)-1+1)])

    driver.quit()

main()


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name = 'index'),
    path('user/<int:user_id>', views.user_page, name = "base_user"),
    path('user/<int:user_id>/jar/<int:jar_id>', views.user_page, name = "user_jar"),
    #path('submit/', views.submit, name = "submit"),
]


'''

################## Emotion DETECTION ########################

'''
###################################################

########## Import Libraries ################

from utils.datasets import labels_fetch
from statistics import mode
import cv2
from utils.inference import faces_detect
from keras.models import load_model
from utils.preprocessor import input_preproc
import numpy as np
from utils.inference import offsets
from utils.inference import model_detection_loading
from utils.inference import bounding_box
from utils.inference import text_show

############ Needed Parameters for loading image and data files. ########################
path_emotion_model = '../trained_models/emotion_models/fer2013_XCEPTION.hdf5'
labels_emotion = labels_fetch('fer2013')
detection_model_path = '../trained_models/face_detection_models/haarcascade_frontalface.xml'

########### Needed Hyper-Parameters for bounding boxes at output screen ###################
labels_emotion = (20, 40)
window_frame = 10

################### Models Need to be loaded ################################
emotion_model = load_model(path_emotion_model, compile=False)
detected_face = model_detection_loading(detection_model_path)
#print("\n Emotion Classifier",emotion_model)

############ Shapes for inference to the input model which we are getting ###################
size_emotion_target = emotion_model.input_shape[1:3]

############### lists of calculated modes ######################
emotion_modes = []

############# Video Stream started here ###################
cv2.namedWindow('Emotion Detection Module')
cap_vid = cv2.VideoCapture('video.mp4')
#'http://192.168.1.107:8080/videos'
while True:
    cap_img = cap_vid.read()[1]
    grayscale_image = cv2.cvtColor(cap_img, cv2.COLOR_BGR2GRAY)
    color_image = cv2.cvtColor(cap_img, cv2.COLOR_BGR2RGB)
    detected_faces = faces_detect(detected_face, grayscale_image)

    for each_face in detected_faces:

        x1, x2, y1, y2 = offsets(each_face, labels_emotion)
        grayscale_face = grayscale_image[y1:y2, x1:x2]
        try:
            grayscale_face = cv2.resize(grayscale_face, (size_emotion_target))
        except:
            continue

        grayscale_face = input_preproc(grayscale_face, True)
        grayscale_face = np.expand_dims(grayscale_face, 0)
        grayscale_face = np.expand_dims(grayscale_face, -1)
        predicted_emotion = emotion_model.predict(grayscale_face)
        prob_emotion = np.max(predicted_emotion)
        arg_emotion = np.argmax(predicted_emotion)
        text_predicted_emotion = labels_emotion[arg_emotion]
        emotion_modes.append(text_predicted_emotion)

        if len(emotion_modes) > window_frame:
            emotion_modes.pop(0)
        try:
            emotion_mode = mode(emotion_modes)
        except:
            continue

        if text_predicted_emotion == 'angry':
            show_color = prob_emotion * np.asarray((255, 0, 0))
        elif text_predicted_emotion == 'sad':
            show_color = prob_emotion * np.asarray((0, 0, 255))
        elif text_predicted_emotion == 'happy':
            show_color = prob_emotion * np.asarray((255, 255, 0))
        elif text_predicted_emotion == 'surprise':
            show_color = prob_emotion * np.asarray((0, 255, 255))
        else:
            show_color = prob_emotion * np.asarray((0, 255, 0))

        show_color = show_color.astype(int)
        show_color = show_color.tolist()

        bounding_box(each_face, color_image, show_color)
        text_show(each_face, color_image, emotion_mode,
                  show_color, 0, -45, 1, 1)

    cap_img = cv2.cvtColor(color_image, cv2.COLOR_RGB2BGR)
    cv2.imshow('Emotion Detection Module', cap_img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap_vid.release()
cv2.destroyAllWindows()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
    This file is a part of the lor_neuro_rat project.
    Copyright (C) 2019 anonimous

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Please contact with me by E-mail: shkolnick.kun@gmail.com
"""
import json

from keras.preprocessing.text import text
from keras.preprocessing.sequence import pad_sequences
from keras.models import load_model
#==============================================================================
class LORTxtModel():
    """
    Обертка над моделью keras
    """
    def __init__(self, tokenizer_fname, model_fname, max_len, batch_size):
        """
        tokenizer_fname - имя файла токенизатора
        model_fname - имя файла модели
        """
        self.max_len = max_len
        self.batch_size = batch_size
        #Токенизатор
        with open(tokenizer_fname, 'r') as f:
            self.tok = text.tokenizer_from_json(json.load(f))
        #Модель
        self.mdl = load_model(model_fname)
        self.mdl._make_predict_function()
    #--------------------------------------------------------------------------
    def predict(self, X):
        """
        X - список со списакми токенов текстов
        Возвращает результаты работы модели с текстами из X
        """
        X_str = [' '.join(tokens) for tokens in X]
        X_seq = self.tok.texts_to_sequences(X_str)
        X_seq = pad_sequences(X_seq, maxlen=self.max_len)
        return self.mdl.predict(X_seq, verbose=0, batch_size=self.batch_size)


# -*- coding: utf-8 -*-
"""
Created on Sun Apr  7 11:37:48 2019

@author: Administrator
"""

import json
indices=[1,2,3,1,3,4,2,3,6,3,7,6,5,6,7,5,7,8,3,4,8,3,7,8,1,2,6,1,5,6,1,4,5,4,5,8,2,3,4,2,3,7,6,7,8,3,4,7]
new_indices=[]
for indice in indices:
    new_indices.append(indice-1)
print(new_indices)
filename="data_file.json"
data={
      "meshes": # meshes is a list
         [{"vertices":[0,0,0,1,0,0,1,1,0,0,1,0,0,0,-1,1,0,-1,1,1,-1,0,1,-1],
         "indices":new_indices,
         "uvCount":100,
         "position":[0.5,0.5,-0.5],
         "name":"cube1"}
         ]

      }
with open("data_file.json","w") as write_file:
    json.dump(data,write_file)
json_data = open(filename) # open json file to read
data1 = json.load(json_data) # load the data for parsing
vertice_array=data["meshes"][0]["vertices"]
print(vertice_array)
'''
,
          {"vertices":[0,0,0,1,0,0,1,1,0,0,1,0],
         "indices":[1-1,2-1,3-1,2-1,3-1,4-1],
         "uvCount":200,
         "position":[1,1,1],
         "name":"cube2"}
'''


import asyncio
import sys

async def checker(port, _ip='localhost'):
    try:
        reader, writer = await asyncio.co(_ip, port)

        print(f'Port {port} is open')
        writer.close()
    except Exception:
        print(f'Port {port} is close')

async def port_scanner(left, right):
    for port in range(left, right + 1):
        await checker(port)

def main():
    lo, hi = 0, 65_535
    left, right = tuple(map(int, sys.argv[1:]))
    if lo <= left and right <= hi:
        loop = asyncio.get_event_loop()
        tasks = [loop.create_task(checker(border_port)) for border_port in range(left, right)]
        loop.run_until_complete(asyncio.wait(tasks))
    else:
        print(f'Range [{left}, {right}] is incorrect.')

if __name__ == '__main__':
    main()


import argparse
import inspect
from typing import Literal, Union, get_args, get_origin

def add_args_from_cls(parser: argparse.ArgumentParser, cls):
    for k, v in inspect.signature(cls).parameters.items():
        arg_type = v.annotation

        if arg_type in (int, float, str):
            parser.add_argument(f"--{k}", type=arg_type, default=v.default)

        elif arg_type is bool:
            assert v.default is False
            parser.add_argument(f"--{k}", action="store_true")

        elif get_origin(arg_type) is Literal:
            literals = get_args(arg_type)
            assert all(isinstance(literal, str) for literal in literals)
            parser.add_argument(f"--{k}", default=v.default, choices=literals)

        # only for Optional[]
        elif get_origin(arg_type) is Union:
            args = get_args(arg_type)
            assert len(args) == 2 and args[1] is type(None)
            assert args[0] in (int, float, str)
            parser.add_argument(f"--{k}", type=args[0], default=v.default)

        elif get_origin(arg_type) is list:
            # NOTE: the default list is shared
            (item_type,) = get_args(arg_type)
            parser.add_argument(f"--{k}", type=item_type, nargs="+", default=[])

        else:
            raise ValueError(f"Unsupported type {arg_type}")

def cls_from_args(args: argparse.Namespace, cls):
    kwargs = {k: getattr(args, k) for k in inspect.signature(cls).parameters.keys()}
    return cls(**kwargs)


'''
import xlrd

FNAME = 'content_tracking_cb.xls'

book = xlrd.open_workbook(FNAME)
sheet = book.sheets()[1]
'''

content = []

'''
def capture_to_dict():

    rows = (sheet.row(rn) for rn in range(4, sheet.nrows) if sheet.cell(rn,0).value)

    for row in rows:
        content.append( {
            'headline': row[1].value,
            'source_URL': row[2].value,
            'full_text': row[3].value,
            'additional_info': row[4].value,
            } )
'''

import json
import os
import re

try:
    from articles.models import Article
except ImportError:
    pass

def parse_full_text(article):
    body = article['full_text'].strip()

    if '//' in body:
        ptype = 'slashed'
        chunks = body.split('//')
    elif '\n\n' in body:
        ptype = 'double n'
        chunks = body.split('\n\n')
    elif '\n' in body:
        ptype = 'single n'
        chunks = body.split('\n')
    else:
        ptype = 'none'
        chunks = (body.replace('. ', '.\n\n').replace(u'.\u201d', u'.\u201d\n\n')).split('\n\n')

    chunks = [chunk.strip() for chunk in chunks]

    chunk1 = chunks[0]
    if len(chunks)==2:
        chunk2 = chunks[1]
        chunk3 = ''
    else :
        ix = (len(chunks)-1)/2 + 1
        chunk2 = '\n\n'.join(chunks[1:ix])
        chunk3 = '\n\n'.join(chunks[ix:])

    article['chunk1'] = chunk1
    article['chunk2'] = chunk2
    article['chunk3'] = chunk3

    article['ptype'] = ptype

def split_info(article):
    tags = {
        'source': 'Source:',
        'references': 'Named sources or checkable facts:',
        'author': 'Author:',
        'tone': 'Tone:',
        }

    def index_(pat,s):
        try:
            return s.index(pat)
        except ValueError:
            return len(s)

    info = article['additional_info']

    items = []
    for k, pat in tags.items():
        items.append((index_(pat, info), k, pat))
    items = sorted(items, cmp=lambda a,b: a[0]-b[0])

    res = {}
    for ix, item in enumerate(items):
        try:
            span = info[item[0]+len(item[2]):items[ix+1][0]]
        except IndexError:
            span = info[item[0]+len(item[2]):]
        res[item[1]] = span.strip()

    pat = re.compile(r'\s*\(.+?\)')
    match = pat.match(res['tone'])
    if match:
        res['tone'] = (res['tone'][match.end():]).strip()

    article.update(res)

    return res

def collect_tones():

    tones = set()
    for article in content:
        tones.add(article['tone'])
    return tones

def create_articles():

    for article_info in content:
        article = Article()
        for key in article_info:
            try:
                setattr(article, key, article_info[key])
            except AttributeError:
                pass
        article.save()

if __name__=='__main__':
    with open('content.json', 'r') as f:
        content = json.load(f)
else:
    with open('utils/content.json', 'r') as f:
        content = json.load(f)


import json
import os

class Config(object):

    social_domains = ('buzzfeed.com', 'facebook.com', 'vk.com',
                      'pinterest.com', 'twitter.com', 'instagram.com',
                      'tumblr.com', 'disqus.com')

    def __init__(self):

        with open(
                os.path.dirname(os.path.realpath(__file__)) +
                '/configs.json') as file:
            self.config_file = json.load(file)

    def getConfigFile(self):
        return self.config_file


#first tests
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import matplotlib.pyplot as plt
"""
#identity in R^n
n = 1

model = Sequential()
model.add(Dense(n,input_dim=n))
model.summary()

model.compile(optimizer='sgd',loss='mean_squared_error')

data = np.array([np.random.random([n]) for i in range(100)])
data_t = data[:70]
labels_t = data[:70]
data_v = data[70:]
labels_v = data[70:]

history = model.fit(data_t,labels_t,batch_size = 20,epochs = 10,validation_data = (data_v,labels_v))
history_dict = history.history
loss_values = history_dict['loss']
val_loss_values = history_dict['val_loss']

epochs = range(1,len(loss_values)+1)
"""
"""
plt.plot(epochs,loss_values,'bo',label='Training loss')
plt.plot(epochs,val_loss_values,'b',label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
"""
"""
linsp = np.linspace(0,1,5)
#test_data = np.array([[i,j] for i in linsp for j in linsp]) ##n = 2
test_data = np.array([i for i in linsp])
print("evaluate")
print(model.evaluate(test_data,test_data,batch_size = 5))
print("predict")
print(test_data)
pred = model.predict(test_data,batch_size = 1)
print(pred)

A,b = model.get_weights()
print("poids A, b =", A,b)

"#accurate model for identity
truemodel = Sequential()
truemodel.add(Dense(n,input_dim=n))
truemodel.set_weights([np.identity(n),np.zeros_like(b)])
"""
"""
#graph for n = 1
plt.plot(linsp,linsp,label = 'y=x')
for x in data :
    plt.plot(x,x,'-x')
plt.plot(linsp,pred,label = 'prediction')
plt.legend()
plt.show()

"""
eps = 0.3
linsp = np.linspace(-2,2,1000)
y = np.zeros(1000)
print(-1*eps)
for i in range(1000):
    if linsp[i]>0 :
        y[i] = 1
    elif linsp[i]>(-1*eps) :
        y[i] = 1/eps*linsp[i]+1

plt.plot(linsp,y)
plt.show()


from flask import Flask
from flask import render_template #引入模板插件
from flask import request, jsonify, render_template, Response

app = Flask(__name__,
static_folder='./dist',  #设置静态文件夹目录
template_folder = "./dist",
static_url_path="")  #设置vue编译输出目录dist文件夹，为Flask模板文件目录

@app.route('/')
def index():
    return render_template('index.html',name='index') #使用模板插件，引入index.html。此处会自动Flask模板文件目录寻找index.html文件。

if __name__ == '__main__':
    app.run(
      debug=True,  # 调试打开
      host='0.0.0.0',  # ip
      port=5000,  # 端口
      ssl_context='adhoc',  # 默认SSL证书，实现https
      threaded=True,  # 多线程
    )


import serial
import MySQLdb

port = serial.Serial("/dev/ttyACM0", "115200")

db = MySQLdb.connect("localhost", "external", "dyn148467^^@", "test1425")
curs = db.cursor()

while True:
        try:
            data = port.readline()
            print("weight: ")
            print(data)

            curs.execute( "SELECT * FROM cosmetics WHERE 'lip_balm' LIKE %s", [data] )

            db.commit()

        except KeyboardInterrupt:
                break

port.close()
db.close()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import io
import textwrap
import os
import sys
import time

from PyPDF2 import PdfFileReader, PdfFileWriter
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas

packet = io.BytesIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=A4)
can.setFont("Helvetica", 12)
x = 64.14

day = input("Enter day: ")
can.drawString(96.14, 674.804, day)

date = input("Enter Date: ")
can.drawString(374.58, 674.804, date)

# Function call for writing content
def write(content, x, y):
    if len(content) > 80:
        y_diff = 0
        # Wrap the texts within 80 characters per line
        wrap_content = textwrap.wrap(content,
                                     width=80,
                                     break_on_hyphens=False)

        for i in wrap_content[:5]:
            # However, only first 5 lines of texts are allowed
            # Print each line with 20 pixels difference in y-coord
            can.drawString(x, y-y_diff, i)
            y_diff += 20

    else:
        can.drawString(x, y, content)

# Getting user input
weekly_report = input("Industrial Training Weekly Report: ")
student_name = input("Your name: ")

# Write the input to the canvas, and save it
write(weekly_report, x, y=622.004)
write(student_name, x=104.14, y=318.33599999999996)
write(date, x=99.14, y=288.936)
can.save()

# move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(open("main_docs/weekly.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)

# set file name
fname = input("Set your file name here leh: ")

# finally, write "output" to a real file
outputStream = open("output/weekly/{}.pdf".format(fname), "wb")
output.write(outputStream)
outputStream.close()


import sqlite3, json, datetime

def create(fromTimestamp, toTimestamp, database, group):
    # Prepare output file
    appfocusFile = open('output/data/appinFocus.js', 'w', encoding="utf-8")
    appfocusFile.write('var appfocusData = [')

    # Read bundle id to app name translation file
    bundlefile = open('bundlenames.json', 'r').read()
    bundletranslation = json.loads(bundlefile)

    cur = database.cursor()
    appFocus = cur.execute("SELECT * \
                             FROM APOLLO \
                             WHERE Activity = 'Application In Focus' \
                             AND Key >= '{0}' AND Key <= '{1}' \
                             ORDER BY Key".format(fromTimestamp.strftime('%Y-%m-%d %H:%M:%S'),
                                                  toTimestamp.strftime('%Y-%m-%d %H:%M:%S')))

    # Initialise array for coloring occurances of an app in the same color
    colors = ['#f94144', '#f3722c', '#f8961e', '#f9844a', '#f9c74f',
              '#90be6d', '#43aa8b', '#4d908e', '#577590', '#277da1']

    # Initialize variables for iterating
    output = ''
    counter = 0
    bundleDict = {}
    print("Parsing app focus data... ")
    for event in appFocus:
        eventData = json.loads(event[2])  # Load data about the event
        bundle = eventData["BUNDLE ID"]
        if bundle not in bundleDict.keys():
            bundleDict[bundle] = colors[counter % len(colors) - 1] # Assign color to an app the first time it occurs
            counter += 1
        color = bundleDict[bundle]

        if bundle in bundletranslation.keys():  # Search bundle id in translation file to show app name
            appname = bundletranslation[bundle]
        else:
            appname = bundle

        # Ignore WebKit.GPU as it holds almost no info but crowds the visualisation
        if bundle == 'com.apple.WebKit.GPU':
            continue

        timezone = datetime.timedelta(hours=eventData["GMT OFFSET"])
        start = datetime.datetime.strptime(eventData["START"], '%Y-%m-%d %H:%M:%S') + timezone
        end = datetime.datetime.strptime(eventData["END"], '%Y-%m-%d %H:%M:%S') + timezone

        startString = start.strftime('%Y-%m-%d %H:%M:%S')
        endString = end.strftime('%Y-%m-%d %H:%M:%S')

        if startString == endString:
            displaytype = 'point'
            appname = ''
        else:
            displaytype = 'range'# If no time range is given, switch type to point

        title = "App Focus
{0}
{1} - {2}
".format(bundle, startString, endString)
        title += "LAUNCH REASON: {0}".format(eventData["LAUNCH REASON"])

        output += "{" + \
                  "start: '{0}', " \
                  "end: '{1}', " \
                  "type:'{2}', " \
                  "group:{3}, " \
                  "content: '{4}', " \
                  "style: 'background-color:{5}', " \
                  "title: '{6}'" \
                  .format(startString, endString, displaytype, group, appname, color, title) \
                  + "},\n"

    appfocusFile.write(output[:-2] + "]")
    appfocusFile.close()
    return 0


# -*- coding: utf-8  -*-
# -*- author: jokker -*-

import torch.nn as nn

class InverteResidual(nn.Module):

    def __init(self, inp, oup, stride, expend_ratio):
        super(InverteResidual, self).__init__()

        self.stride = stride
        hidden_dim = round(inp * expend_ratio)
        self.conv = nn.Sequential(
            nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),
            nn.BatchNorm2d(hidden_dim),
            nn.ReLU6(inplace=True),
            #
            nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
            nn.BatchNorm2d(hidden_dim),
            nn.ReLU6(inplace=True),
            #
            nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
            nn.BatchNorm2d(oup),
        )

    def forward(self, x):
        return x + self.conv(x)

if __name__ == "__main__":

    pass


import numpy as np
import pandas as pd
from collections import Counter

# 生成所需的数据
df = pd.DataFrame({
    'x1': pd.Series([1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]),
    'x2': pd.Series(['S', 'M', 'M', 'S', 'S', 'S', 'M', 'M', 'L', 'L', 'L', 'M', 'M', 'L', 'L']),
    'y': pd.Series([-1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1]),
})

prov = {}
x = (2, 'S')
# 使用极大似然估计计算先验概率和条件概率
c = Counter(df['y'])
prov[1] = c[1] / df['y'].shape[0]
prov[-1] = c[-1] / df['y'].shape[0]
for key in dict(prov):
    # 计算后验概率
    a1 = np.sum(np.sum(df.loc[:, ['x1', 'y']] == [x[0], key], axis=1) == 2) / c[key]
    a2 = np.sum(np.sum(df.loc[:, ['x2', 'y']] == [x[1], key], axis=1) == 2) / c[key]
    prov[key] = prov[key] * a1 * a2
ans = 0
val = 0
for key in dict(prov):
    if prov[key] > val:
        ans = key
        val = prov[key]
print(ans)


import urllib.request
from bs4 import BeautifulSoup

url='https://finance.naver.com/item/board.nhn?code=000660'
html=urllib.request.urlopen(url)

bsobj=BeautifulSoup(html,'html.parser')

divs=bsobj.find_all ('td',{'class':'title'})

for div in divs:
    print(div.text)

savename="tete.csv"
with open(savename, 'a') as f:
    for i in range(1,100):
        f.write(div[i].text)
        print("complete")


import sys

# * ========================================================
# * @Title       : 7562
# * @Path        : python\02_Solved\boj\f.DFS와BFS\7562.py
# * @Link        : https://www.acmicpc.net/problem/7562
# * @Description : 나이트의 이동
# * @Date        : 2021-08-09 12:13:19
# * --------------------------------------------------------
# * @Author      : Inseong-so(https://github.com/inseong-so)
# * ========================================================

# 복습용, 함수화할 부분

def solution(N, knight):
    from collections import deque
    board = [[0 for _ in range(N)] for _ in range(N)]

    dx = [-1, -2, -2, -1, 1, 2, 2, 1]
    dy = [-2, -1, 1, 2, 2, 1, -1, -2]

    queue = deque()
    x, y = knight[0]
    # 방문 처리
    board[x][y] = 1
    queue.append([x, y])

    while queue:
        lx, ly = queue.popleft()
        if lx == knight[1][0] and ly == knight[1][1]:
            break
        for i in range(8):
            nx, ny = lx + dx[i], ly + dy[i]
            if nx >= 0 and nx < N and ny >= 0 and ny < N and board[nx][ny] == 0:
                board[nx][ny] = board[lx][ly] + 1
                queue.append([nx, ny])

    print(board[knight[1][0]][knight[1][1]] - 1)

# T
for _ in range(int(input())):
    N = int(input())
    knight = []
    for _ in range(2):
        knight.append(list(map(int, sys.stdin.readline().split())))
    solution(N, knight)

def test_01(capfd):
    N = 8
    knight = [
        [0, 0],
        [7, 0]
    ]
    solution(N, knight)
    out, err = capfd.readouterr()
    assert out == '5\n'

def test_02(capfd):
    N = 100
    knight = [
        [0, 0],
        [30, 50]
    ]
    solution(N, knight)
    out, err = capfd.readouterr()
    assert out == '28\n'

def test_03(capfd):
    N = 10
    knight = [
        [1, 1],
        [1, 1]
    ]
    solution(N, knight)
    out, err = capfd.readouterr()
    assert out == '0\n'

def test_04(capfd):
    N = 8
    knight = [
        [0, 0],
        [7, 7]
    ]
    solution(N, knight)
    out, err = capfd.readouterr()
    assert out == '6\n'

# 숏코딩;
def short():
    for __ in range(int(input())):
        n = int(input())
        sx, sy = map(int, input().split())
        ex, ey = map(int, input().split())
        if sx > ex:
            (sx, sy), (ex, ey) = (ex, ey), (sx, sy)
        if sy > ey:
            sy = (n-1)-sy
            ey = (n-1)-ey
        dx, dy = ex-sx, ey-sy
        if dx > dy:
            sx, sy = sy, sx
            ex, ey = ey, ex
            dx, dy = dy, dx
        ans = max((dy+1)//2, (dx+dy+2)//3)
        ans += dx+dy+ans & 1
        d = dx, dy
        if d == (0, 1):
            ans = 3
        elif d == (0, 3):
            if n == 4 and sx in (0, 3):
                ans = 5
            else:
                ans = 3
        elif d == (1, 1):
            m1x, m1y = sx+2, sy-1
            m2x, m2y = sx-1, sy+2
            if 0 <= m1x < n > m1y >= 0 or 0 <= m2x < n > m2y >= 0:
                ans = 2
            else:
                ans = 4
        elif d == (2, 2):
            ans = 4
        print(ans)


#!/usr/bin/env python3

'''
Script to map animation triggers to groups. Prints groups that match the trigger map for any triggers
passed in as arugments on the command line
'''

REL_MAP_PATH='../../resources/assets/cladToFileMaps/AnimationTriggerMap.json'

import os
import sys
import json

scriptPath = os.path.dirname(os.path.realpath(__file__))
mapPath = os.path.join(scriptPath, REL_MAP_PATH)

triggerMap = {}

with open(mapPath, 'r') as infile:
    J = json.load(infile)
    for pair in J:
        trigger = pair["CladEvent"]
        group = pair["AnimName"]
        triggerMap[trigger] = group

# print("loaded {} mappings".format(len(triggerMap)))

for arg in sys.argv[1:]:
    if arg in triggerMap:
        print(triggerMap[arg])
    else:
        print("ERROR: {} not found in map".format(arg))


from dataclasses import dataclass
from django.db.models import Aggregate, Model
from typing import Dict, Type

# using prefix to avoid name conflicts.
ANNOTATION_PREFIX = 'annotation__'
ANNOTATION_LIST_PREFIX = 'annotation_list__'

@dataclass
class Annotation:
    """
    The Annotation class is used to retrieve the annotation value for a given model instance. If the annotation value
    has already been calculated and stored in the instance, it is retrieved directly. If the annotation value has not
    yet been calculated, it is fetched using the provided model. This allows for efficient retrieval of annotation
    values without the need to recalculate them every time they are accessed.
    """

    name: str
    annotation: Aggregate
    model: Type[Model]
    annotation_prefix: str = ANNOTATION_PREFIX

    def __post_init__(self):
        self.annotation_name = '{0}{1}'.format(self.annotation_prefix, self.name)

    def get_annotation_expression(self):
        return {self.annotation_name: self.annotation}

    def get_annotation_value(self, instance):
        return getattr(instance, self.annotation_name, None)

    def get_attribute(self, instance):
        annotation_value = self.get_annotation_value(instance)
        # check if annotation has been annotated.
        if annotation_value is not None:
            return annotation_value

        # fetch annotation.
        instance = self.model.objects.filter(pk=instance.pk).annotate(
            **self.get_annotation_expression()
        ).first()
        return self.get_annotation_value(instance)

@dataclass
class AnnotationList:
    """
    The AnnotationList class allows the storage and retrieval of multiple annotations as a dictionary, where the keys
    represent the names of the annotations and the values represent the annotated value. It functions similarly to the
    Annotation class, but is designed to handle multiple annotations at once. It can be used to fetch all the stored
    annotations at once.
    """

    annotations: Dict[str, Aggregate]
    model: Type[Model]

    def __post_init__(self):
        self.children = [
            Annotation(
                name=name,
                annotation=annotation,
                model=self.model,
                annotation_prefix=ANNOTATION_LIST_PREFIX,
            )
            for name, annotation in self.annotations.items()
        ]

    def get_annotation_expression(self):
        result = {}
        for child in self.children:
            result.update(child.get_annotation_expression())
        return result

    def get_annotation_value(self, instance):
        return {
            child.name: child.get_annotation_value(instance)
            for child in self.children
        }

    def get_attribute(self, instance):
        annotation_value = self.get_annotation_value(instance)
        # check if annotations has been annotated.
        if all(annotation_value.values()):
            return annotation_value

        # fetch annotations.
        instance = self.model.objects.filter(pk=instance.pk).annotate(
            **self.get_annotation_expression()
        ).first()
        return self.get_annotation_value(instance)


from .base_agent import BaseAgent
import math
import numpy as np
from collections import defaultdict

class QlearningAgent(BaseAgent):

    ## Learning related constants
    MIN_EXPLORE_RATE = 0.01
    MIN_LEARNING_RATE = 0.1

    def get_explore_rate(self, t, MIN_EXPLORE_RATE=MIN_EXPLORE_RATE):
        return max(MIN_EXPLORE_RATE, min(1, 1.0 - math.log10((t + 1) / 25)))

    def get_learning_rate(self, t, MIN_LEARNING_RATE=MIN_LEARNING_RATE):
        return max(MIN_LEARNING_RATE, min(0.5, 1.0 - math.log10((t + 1) / 25)))

    def q_init(self, gamma, alpha, epsilon):
        """Initialize qlearning parameters"""
        self.Q = defaultdict(float)
        self.gamma = gamma
        self.alpha = alpha
        self.epsilon = epsilon

    def state_init(self, high, low):
        """Initialize function approximation paramaters"""
        self.num_buckets = (1, 1, 6, 3)
        self.num_actions = self.action_space.n

        self.state_bounds = list(zip(low, high))
        self.state_bounds[1] = [-0.5, 0.5]
        self.state_bounds[3] = [-math.radians(50), math.radians(50)]

    def __init__(self, action_space,
                 high, low,
                 gamma=0.99, alpha=0.5, epsilon=0.5):
        """Initialize the agent"""

        super(QlearningAgent, self).__init__(action_space)
        self.q_init(gamma, alpha, epsilon)
        self.state_init(high, low)

    def act(self, state):
        """Take an action"""
        if np.random.random()<self.epsilon:
            i = np.random.randint(0, self.num_actions)
        else:
            s1 = self.state_to_bucket(state)
            vals = [v for ((s, a), v) in self.Q.items() if s == s1]

            if len(vals) <= 0:
                i = np.random.randint(0, self.num_actions)
            else:
                i = np.argmax(vals)

        return i

    def learn(self, state, action, reward, next_state):
        """Learn with qlearning"""

        s1, s2 = self.state_to_bucket(state), self.state_to_bucket(next_state)
        self.Q[(s1, action)] += 0
        for a in range(self.num_actions):
            self.Q[(s2, a)] += 0

        vals = [v for ((s, a), v) in self.Q.items() if s == s2]
        max_q = max(vals)
        td_target = reward + self.gamma * max_q
        td_delta = td_target - self.Q[(s1, action)]
        self.Q[(s1, action)] += self.alpha * td_delta

    def state_to_bucket(self, state):
        """Function approximation"""
        bucket_indice = []
        for i in range(len(state)):
            if state[i] <= self.state_bounds[i][0]:
                bucket_index = 0
            elif state[i] >= self.state_bounds[i][1]:
                bucket_index = self.num_buckets[i] - 1
            else:
                # Mapping the state bounds to the bucket array
                bound_width = self.state_bounds[i][1] - self.state_bounds[i][0]
                offset = (self.num_buckets[i] - 1) * self.state_bounds[i][0] / bound_width
                scaling = (self.num_buckets[i] - 1) / bound_width
                bucket_index = int(round(scaling * state[i] - offset))
            bucket_indice.append(bucket_index)
        return tuple(bucket_indice)