# -*- coding: utf8 -*-
from Tkinter import *
import damaGrafico as dg
import engine2 as eg

class Window(Frame):

    def __init__(self, master=None):

        # Cria um novo frame.
        Frame.__init__(self, master)

        self.master = master
        self.init_window()

    def init_window(self):

        # muda o titulo
        self.master.title("Meu Jogo de Damas")

        self.pack(fill=BOTH, expand=1)

        # cria menu
        menu = Menu(self.master)
        self.master.config(menu=menu)
        quadro=Frame(root,width=200,height=50)
        quadro.pack()

        edit = Menu(menu)

        edit.add_command(label="Contra Player",command=self.comando1)
        edit.add_command(label="Contra Maquina",command=self.comando2)
        edit.add_command(label="Player 6x6",command=self.comando3)
        edit.add_command(label="Ver 2 'IA' Batalhando",command=self.comando4)

        menu.add_cascade(label="Jogar", menu=edit)

    #inicializa os 3 tipos de jogo
    def comando1(self):
        jogo1=dg.meuJogo(root)
        jogo1.iniciarJogo(contra=dg.JOGADOR)

    def comando2(self):
        jogo1=dg.meuJogo(root)
        jogo1.iniciarJogo(contra=dg.MAQUINA)
    def comando3(self):
        jogo1=dg.meuJogo(root)
        jogo1.iniciarJogo(contra=dg.JOGADOR,tipo=eg.TAB3_PADRAO)

    def comando4(self):
        jogo1=dg.meuJogo(root)
        jogo1.iniciarJogo(contra=dg.DESAFIO,tipo=eg.TAB_PADRAO)

root = Tk()
app = Window(root)

root.mainloop()


from tkinter import *
import platform

root = Tk()
root.geometry('800x600+800+300') # размеры
root.title('Текстовый редактор') #Заголовок

main_menu = Menu(root)
root.config(menu=main_menu)

main_menu.add_command(label="File")
main_menu.add_command(label="About")

if(platform.system() != 'Linux'):
    root.iconbitmap('practic/tx_sc/tx.ico') #иконка
else:
    root.iconbitmap('@practic/tx_sc/tx.xbm') #иконка

frame_text = Frame(root)
frame_text.pack(fill=BOTH, expand=1)

text_area = Text(frame_text, bg="#343D46", fg="#C6DEC1", padx=10, pady=10, wrap="word", insertbackground="#EDA756", selectbackground="#4E5A65", width=30, spacing3=10)
text_area.pack(fill=BOTH, expand=1, side=LEFT)

scroll = Scrollbar(frame_text, command=text_area.yview)
scroll.pack(fill=Y, side=LEFT)
text_area.config(yscrollcommand=scroll.set)

root.mainloop()


import math

def exp_queue_size(lambd,mu):
    rho = lambd/mu
    print(rho)
    exp_size = rho/ (1 - rho )
    return exp_size

def queue_size_prob (lambd,mu,queue_size):
    rho = lambd/mu
    if rho>=1:
        print("rho must be less than 1")
    return ((rho**queue_size))

arrivals_per_day=30
interarrival_time_avg=1/(arrivals_per_day/24)
service_time_avg=36/60
lambd=1/interarrival_time_avg
mu=1/service_time_avg
expected_size = exp_queue_size(lambd,mu)

print("expected queue size = ",round(expected_size,2),"trains")

queue_size=10
queue_prob= queue_size_prob(lambd,mu,queue_size)
print("the probability of exceeding queue size is",round(queue_prob,2))
new_arrivals_per_day=33
new_interarrival_time_avg=1/(arrivals_per_day/24)
lambd=1/new_interarrival_time_avg
lambd=11/480
mu=1/36
new_expected_size = exp_queue_size(lambd,mu)
print("expected queue size with ",new_arrivals_per_day,"arrivals per day is ",round(new_expected_size,2),"trains")
new_queue_prob= queue_size_prob(lambd,mu,queue_size)
print("probability of queue size exceeding ",queue_size,"arrivals per day is",round(new_queue_prob,2))


import requests

# truyền vào url website mình muốn thao tác
url = 'https://api.github.com/events'

r = requests.get(url=url)

# trạng thái truy cập trả về
#  200 thì trang web truy cập ổn định
# trả về 400 thì trang web ko thể truy cập
status = r.json

# lấy dữ liệu dạng json, json() là 1 kiểu dữ  liệu trong javascript
# ở đây là lấy ra actor của người đăng kí github mới nhất
data = r.json()[0]['actor']

print(status)
print(data)


"""RoomGeneratorFunction

Returns a unique ID for a chat room.

When doing this, it also:
 * Creates an SNS topic for posting messages to the room.
 * Sets the SNS topic's policy to allow subscription, publishing, and cleanup.
 * Sets up a CloudWatch log group for success / failure delivery notifications.
 * Sets the SNS topic to log success and failure content.
 * Creates a CloudWatch metric filter for the SNS message dwell time.

"""

from __future__ import print_function

import os
import json
import uuid
import time
import boto3
import zbase32
from apigateway_helpers.exception import APIGatewayException
from apigateway_helpers.headers import get_response_headers

room_duration_seconds = 7200 # 7200 seconds == Two hours

sns_client = boto3.client("sns")
sts_client = boto3.client("sts")
logs_client = boto3.client("logs")
sfn_client = boto3.client("stepfunctions")

def lambda_handler(event, context):
    print("Event: {}".format(json.dumps(event)))

    if "warming" in event and "{}".format(event["warming"]).lower() == "true":
        return {
            "message": "Warmed!"
        }

    room_log_event_processor_function_arn = os.environ["ROOM_LOG_EVENT_PROCESSOR_FUNCTION_ARN"]

    new_room_id = generate_new_room_id()

    new_topic_name = generate_room_sns_topic_name(new_room_id)

    sns_response = sns_client.create_topic(
        Name = new_topic_name
    )

    topic_arn = sns_response["TopicArn"]

    topic_attributes_to_set = [
        ("Policy", get_default_topic_policy(topic_arn)),
        ("SQSFailureFeedbackRoleArn", os.environ["SNS_FAILURE_FEEDBACK_ROLE"]),
        ("SQSSuccessFeedbackRoleArn", os.environ["SNS_SUCCESS_FEEDBACK_ROLE"])
    ]

    for each_topic_attribute_tuple in topic_attributes_to_set:
        sns_client.set_topic_attributes(
            TopicArn = topic_arn,
            AttributeName = each_topic_attribute_tuple[0],
            AttributeValue = each_topic_attribute_tuple[1]
        )

    sns_client.subscribe(
        TopicArn = topic_arn,
        Protocol = "lambda",
        Endpoint = room_log_event_processor_function_arn
    )

    message_object = {
        "identity-id": "SYSTEM",
        "author-name": "System Message",
        "message": "The room is now open.",
        "type": "ROOM_OPEN",
        "timestamp": int(time.time())
    }

    sns_client.publish(
        TopicArn = topic_arn,
        Message = json.dumps(message_object)
    )

    sns_log_group_name = get_sns_cloudwatch_log_group_name(event, new_room_id)

    logs_client.create_log_group(
        logGroupName = sns_log_group_name
    )

    logs_client.put_metric_filter(
        logGroupName = sns_log_group_name,
        filterName = "SNSRoomTopicDwellTime",
        filterPattern = "{ $.delivery.dwellTimeMs > 0 }",
        metricTransformations = [
            {
                "metricName": "DwellTimeMs",
                "metricNamespace": "WebChat-{}".format(event["requestContext"]["apiId"]),
                "metricValue": "$.delivery.dwellTimeMs"
            }
        ]
    )

    created_timestamp_seconds = int(time.time())

    room_config_object = {
        "created": created_timestamp_seconds,
        "duration": room_duration_seconds,
        "sns-topic-arn": topic_arn,
        "sns-log-group": sns_log_group_name
    }

    room_lifecycle_state_machine_arn = os.environ["ROOM_LIFECYCLE_STATE_MACHINE_ARN"]

    response = sfn_client.start_execution(
        stateMachineArn = room_lifecycle_state_machine_arn,
        name = new_room_id,
        input = json.dumps({
            "id": new_room_id,
            "config": room_config_object
        })
    )

    print("Room lifecycle state machine execution ARN: {}".format(response["executionArn"]))

    return {
        "id": new_room_id
    }

def generate_room_sns_topic_name(room_id):
    return "{}-{}".format(
        os.environ["PROJECT_GLOBAL_PREFIX"],
        room_id
    )

def generate_new_room_id():
    return zbase32.encode(uuid.uuid4().bytes).decode('utf-8') #zbase32.b2a(uuid.uuid4().bytes)

account_id = None
def get_own_account_id():
    global account_id

    if account_id is None:
        account_id = sts_client.get_caller_identity()["Account"]

    return account_id

def get_sns_cloudwatch_log_group_name(event, room_id):
    return "sns/{region}/{account_id}/{app_prefix}-{room_id}".format(
        region = os.environ["AWS_DEFAULT_REGION"],
        account_id = get_own_account_id(),
        app_prefix = os.environ["PROJECT_GLOBAL_PREFIX"],
        room_id = room_id
    )

def get_default_topic_policy(sns_topic_arn):
    return json.dumps({
        "Version": "2008-10-17",
        "Statement": [
            {
                "Sid": "AllowSubscriptionFromRoomSessionGenerator",
                "Effect": "Allow",
                "Principal": {
                    "AWS": os.environ["SUBSCRIBE_ROOM_TOPIC_ROLE"]
                },
                "Action": [
                    "sns:Subscribe",
                    "sns:Publish"
                ],
                "Resource": sns_topic_arn
            },
            {
                "Sid": "AllowPublishingByRoomMessagePoster",
                "Effect": "Allow",
                "Principal": {
                    "AWS": os.environ["PUBLISH_ROOM_TOPIC_ROLE"]
                },
                "Action": "sns:Publish",
                "Resource": sns_topic_arn
            },
            {
                "Sid": "AllowPublishingAndSubscribingBySelf",
                "Effect": "Allow",
                "Principal": {
                    "AWS": os.environ["OWN_FUNCTION_ROLE"]
                },
                "Action": [
                    "sns:Publish",
                    "sns:Subscribe"
                ],
                "Resource": sns_topic_arn
            },
            {
                "Sid": "AllowRoomLifecycleManagement",
                "Effect": "Allow",
                "Principal": {
                    "AWS": os.environ["ROOM_LIFECYCLE_FUNCTION_ROLE"]
                },
                "Action": "sns:SetTopicAttributes",
                "Resource": sns_topic_arn
            },
            {
                "Sid": "AllowCleanup",
                "Effect": "Allow",
                "Principal": {
                    "AWS": os.environ["DELETE_ROOM_TOPIC_ROLE"]
                },
                "Action": "sns:DeleteTopic",
                "Resource": sns_topic_arn
            }
        ]
    })

def proxy_lambda_handler(event, context):

    response_headers = get_response_headers(event, context)

    try:
        return_dict = lambda_handler(event, context)
    except APIGatewayException as e:
        return {
            "statusCode": e.http_status_code,
            "headers": response_headers,
            "body": json.dumps({
                "message": e.http_status_message
            })
        }

    return {
        "statusCode": 200,
        "headers": response_headers,
        "body": json.dumps(return_dict)
    }


from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^main/', include('main.urls', namespace='main')),
    url(r'^wiki/', include('wiki.urls', namespace='wiki')),
    url(r'^story/', include('story.urls', namespace='story')),
    url(r'^record/', include('record.urls', namespace='record')),
    url(r'^account/', include('account.urls', namespace='account')),
    url(r'^.*', include('main.urls')),
]


# -*- coding: utf-8 -*-
"""
Created on Sat Nov  3 14:44:38 2018

@author: Administrator
"""
def ten_year_calc(num,start_date):
    yearLen = timedelta(days=365)
    for x in range(num):
        print(start_date + yearLen*x)

from datetime import date
from datetime import timedelta
import pandas as pd

d = date(2007, 11, 5)
print(d.isoformat())
ten_year_calc(10, d)

s= '4545,6565'.split(',')
print(s[0])

arr = []
arr.append(1)
arr.append(2)
print(arr)

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame()


import os
import argparse

class Parser():
    """
    获取命令行参数
    """
    def __init__(self, description):
        self.parser = argparse.ArgumentParser(description=description)
        self.args = None
        self._parse()

    def _parse(self):
        """
        设置文件路径
        """
        self.parser.add_argument(
            '--path', type=str, default=None,
            help='md文件的路径')
        self.args = self.parser.parse_args()

def add_anchor_tags(filepath):
    with open(filepath, 'r', encoding='utf-8') as file:
        content = file.readlines()

    anchor = []
    updated_content = []
    F = 1
    S = 1
    T = 1
    for line in content:
        if '#####' in line.split(' '):
            anchor.append(f"        - [{line.split('#####')[-1].strip()}](#{str(F-1)+'_'+str(S-1)+'_'+str(T)})  \n")
            updated_content.append(f"\n")
            T += 1
        elif '####' in line.split(' '):
            anchor.append(f"    - [{line.split('####')[-1].strip()}](#{str(F-1)+'_'+str(S)})  \n")
            updated_content.append(f"\n")
            S += 1
            T = 1
        elif '###' in line.split(' '):
            anchor.append(f"- [{line.split('###')[-1].strip()}](#{str(F)})  \n")
            updated_content.append(f"\n")
            F += 1
            S = 1
            T = 1
        updated_content.append(line)
    anchor[-1] += '\n'
    updated_content = anchor + updated_content    #最终处理好的md文件内容

    dirpath, filename = filepath[:-filepath[::-1].index('\\')], filepath.split('\\')[-1]
    filename2 = filename.split('.')[0] + 'Updated.md'
    with open(os.path.join(dirpath,filename2), 'w', encoding='utf-8') as file:
        file.writelines(updated_content)
    print(f'已经保存到 {os.path.join(dirpath,filename2)}')

# 调用示例
if __name__ == '__main__':
    filename = Parser(None).args.path
    add_anchor_tags(filename)
# python .\add_anchor.py --path .\docs\about_Python\其他.md


N, M = map(int, input().split())
tree_weight = list(map(int, input().split()))

def binary_search(array, target, start, end):
    # total = 0
    result = list()

    while start <= end:
        total = 0
        mid = (start + end) // 2

        for x in array:
            if x > mid:
                total += x - mid
        if total < M:
            end = mid - 1

        # total >= M 인 경우
        else:
            result.append(mid)
            start  = mid + 1

    return max(result)

result = binary_search(tree_weight, M, 0, max(tree_weight))
print(result)


import board
import busio
#### For the ada fruit libraries use sudo pip3 install adafruit-circuitpython-ads1x15
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
from time import sleep
import subprocess
import syslog
from datetime import datetime
import os

#################################################################################################
# Cron command to run this script every minute                                                  #
# */1 * * * * /usr/bin/python3 /scripts/ads1115/get_bat.py >/dev/null 2>&1                      #
#                                                                                #
# The code for interfacing with the ADS1115 came from the Adafruit example                      #
# located at: https://learn.adafruit.com/adafruit-4-channel-adc-breakouts/python-circuitpython  #
#################################################################################################

def get_battery():
    # Get the voltage of the battery by useing the ADS1115
    i2c = busio.I2C(board.SCL, board.SDA)
    ads = ADS.ADS1115(i2c)
    avg_bat = 0

    # Take three samples and average them
    for i in range(4):
        chan = AnalogIn(ads, ADS.P0)
        # Measuring with multimeter 2.043 was the correct multiplier for my splitter
        # this value should be updated for each build
        current_voltage = chan.voltage * 2.005
        avg_bat = avg_bat + current_voltage
    avg_bat = avg_bat/4

    # Return the average of the three battery samples
    return(avg_bat)

def os_announce(message):
    # Use wall and xmessage to announce any message passed to the function
    # to all logged in users.
    command = "/usr/bin/wall"
    try:
        subprocess.call([command, message])
    except Exception as e:
        print(e)
    # os.environ["DISPLAY"] = ':0.0'
    # os.environ["XAUTHORITY"] = '/home/pi/.Xauthority'
    # command = "xmessage"
    # try:
    #     subprocess.call([command, message])
    # except Exception as e:
    #     print(e)

def shutdown_system(message):
    # command = "shutdown"
    # arg1 = "-h"
    # arg2 = "-t 120"
    # subprocess.call([command, arg1, arg2, message])
    os.system('systemctl poweroff')

if __name__ == "__main__":
    current_bat = get_battery()
    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    if current_bat <= 6.4:
        # If the battery voltage is critical send a shutdown command and then
        # use wall to send a message to all users finally log the voltage and
        # warning to syslog
        message = 'Voltage is Critial.  System will is shutting down. Current Voltage = ' + \
            str(current_bat)
        syslog.syslog("[Critical] Battery Voltage is: %s" % current_bat)
        os_announce(message)
        shutdown_system(message)
    elif current_bat < 7.0 and current_bat > 6.6:
        # If the battery voltage is low use wall to send a message to all users
        # then log the voltage and warning to syslog
        message = 'BATTERY IS LOW! Current Voltage = ' + str(current_bat)
        syslog.syslog("[Error] Battery Voltage is: %s" % current_bat)
        os_announce(message)
    else:
        # If the battery isn't critical log the voltage every 5 minutes
        minute = int(datetime.now().strftime('%M')) % 5
        if minute == 0:
            syslog.syslog("Battery Voltage is: %s" % current_bat)


import pandas as pd
from sklearn.datasets import load_iris

def load_and_save_iris_data():
    # 加载 IRIS 数据集
    iris = load_iris()

    # 创建 DataFrame 并设置列名
    iris_data = pd.DataFrame(iris.data, columns=['sepal_length', 'sepal_width', 'petal_length', 'petal_width'])
    iris_data['target'] = iris.target

    # 添加索引作为列名
    iris_data.columns.name = 'index'

    # 保存为csv文件
    iris_data.to_csv('../dataset/iris_modified.csv', index=False)

def load_and_save_cancer_data():
    data = pd.read_csv('../dataset/wdbc.csv')

    column_names = ['ID number','Diagnosis',
                    'Mean Radius', 'Mean Texture', 'Mean Perimeter','Mean Area', 'Mean Smoothness',
                    'Mean Compactness','Mean Concavity','Mean Concave points', 'Mean Symmetry', 'Mean Fractal dimension',
                    'Radius SE', 'Texture SE', 'Perimeter SE','Area SE', 'Smoothness SE',
                    'Compactness SE','Concavity SE','Concave points SE', 'Symmetry SE', 'Fractal dimension SE',
                    'Worst Radius', 'Worst Texture', 'Worst Perimeter','Worst Area', 'Worst Smoothness',
                    'Worst Compactness','Worst Concavity','Worst Concave points', 'Worst Symmetry', 'Worst Fractal dimension']

    data.columns = column_names
    data.columns.name = 'index'

    data.to_csv('../dataset/cancer_modified.csv', index=False)

def main():
    load_and_save_iris_data()
    load_and_save_cancer_data()

if __name__ == '__main__':
    main()


from django.contrib.auth.decorators import login_required
from django.db.models import F
from django.http import HttpResponseRedirect, JsonResponse

from django.template.loader import render_to_string
from django.views.generic import UpdateView
from baskets.models import Basket
from mainapp.mixin import UserDipatchMixin, BaseClassContextMixin
from mainapp.models import Product

class BasketAddCreateView(UpdateView, UserDipatchMixin, BaseClassContextMixin):
    model = Basket
    template_name = 'mainapp/products.html'
    title = 'GeekShop | Добавление товара в корзину!'

    def post(self, request, *args, **kwargs):
        if request.is_ajax:
            user_select = request.user
            product = Product.objects.get(id=self.kwargs['id'])
            baskets = Basket.objects.filter(user=user_select,
                                            product=product).select_related()
            if not baskets.exists():
                Basket.objects.create(user=user_select, product=product,
                                      quantity=1)
            else:
                basket = baskets.first()
                basket.quantity = F('quantity') + 1
                basket.save()
            return JsonResponse(
                {'result': 1, 'object': f'{self.kwargs["id"]}',
                 'data': render_to_string(
                     'mainapp/includes/card.html',
                     {'product': product, 'request': request,
                      'user': request.user})})

@login_required
def basket_edit(request, id_basket, quantity):
    if request.is_ajax():
        basket = Basket.objects.get(id=id_basket)
        basket.quantity = quantity
        basket.save()

        baskets = Basket.objects.filter(user=request.user).select_related()
        context = {'baskets': baskets}
        result = render_to_string('baskets/basket.html', context)
        return JsonResponse({'result': result})

@login_required
def basket_remove(request, basket_id):
    Basket.objects.get(id=basket_id).delete()
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))


import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# 문제1
# simple3 파일을 읽어
# hx = wx + b
# w, b 값을 구하고 x가 5인 경우의 값을 예측하시오.

f = np.loadtxt("simple3.txt", dtype=np.int32, skiprows=1, delimiter=",")
print(f)

x = f[:, 0]
y = f[:, 1]

print(x)
print(y)

X = tf.placeholder(dtype=tf.float32)
Y = tf.constant(y, dtype=tf.float32)

# xaiver or he 알고리즘으로 적절한 초기값을 지정할 수 있다.
W = tf.Variable(1, dtype=tf.float32)
b = tf.Variable(1, dtype=tf.float32)

hx = W * X + b

cost = tf.reduce_mean(tf.square(hx - y))

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
train = optimizer.minimize(cost)

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

for i in range(100):
    _train, _cost = sess.run([train, cost], feed_dict={X: x})
    print(i, _cost)
    plt.plot(i, _cost, "ro")

print("W : ", sess.run(W))
print("b : ", sess.run(b))

print("X가 5인경우 값 : ", sess.run(hx, feed_dict={X: 5}))

# 문제2
# 위의 결과로 그래프를 그리시오.
# x축, y축 (hx)
plt.show()

plt.plot(x, sess.run(hx, feed_dict={X: x}))
plt.show()

# 문제3
# y = (5x +2 ) ^ 2를 미분하시오
# 코딩이 아닌 도출과정을 적으시오.

# 풀이 ==> 2 * (5x + 2) * 5 (편미분)


# This file contains some utilities for pre-processing the images:
#  - background image:
#    = re-scaling
#  - source image:
#    = mask generating
#    = re-scaling

import cv2
import numpy as np

def rescale(in_fname: str, out_fname: str, new_size: tuple, domain_axis: int) -> None:
    ''' A utility function for rescaling the image, encapsulated from `cv2.resize`.
        @param in_fname: <str>, the input filename
        @param out_fname: <str>, the input filename
        @param new_size: <tuple(height, width)>, the new size (pixels) of the image
        @param domain_axis: For free rescaling, set to -1. For equal-ratio rescaling, set to 0/1.  \
            For example, if you want new_size depends on axis=0, set it to 0.  \
            Then axis1 will be automatically adjusted by axis0.
    '''
    assert( len(new_size) == 2 )
    img = cv2.imread(in_fname)
    if domain_axis == -1:
        out_img = cv2.resize(img, new_size)
    elif domain_axis == 0:
        fy = new_size[0] / img.shape[0]
        out_img = cv2.resize(img, None, fx=fy, fy=fy)
    elif domain_axis == 1:
        fx = new_size[1] / img.shape[1]
        out_img = cv2.resize(img, None, fx=fx, fy=fx)
    cv2.imwrite(out_fname, out_img)

def generate_mask(in_fname: str) -> None:
    ''' A utility function to generate a mask of a given image. '''

    def callback(event, x, y, flags, param):
        ''' Callback function of the window. '''
        if event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
            cv2.circle(mask, (x, y), 8, (255, 255, 255), -1)
            cv2.circle(img, (x, y), 8, (255, 255, 255), -1)
            # print(x, y)
            cv2.imshow('mask gen', img)
        # elif event == cv2.EVENT_LBUTTONUP:
        #     cv2.destroyWindow('mask gen')
        #     cv2.namedWindow('mask gen')
        #     cv2.setMouseCallback('mask gen',callback)

    img = cv2.imread(in_fname)
    h, w, _ = img.shape
    mask = np.zeros((h, w, 3), dtype=np.uint8)

    cv2.namedWindow('mask gen')
    cv2.setMouseCallback('mask gen',callback)
    cv2.imshow('mask gen', img)

    while(True):
        if cv2.waitKey(20)&0xFF==ord('s'):
            cv2.destroyAllWindows()
            cv2.imwrite(in_fname.split('.')[0] + '_mask.jpg', mask)
            break
        elif cv2.waitKey(20)&0xFF==ord('q'):
            cv2.destroyAllWindows()
            break

# USE samples:
# rescale('imgs/1_original_src1.jpg', 'imgs/1_src1.jpg', (100, 400), 1)
# generate_mask('imgs/1_src1.jpg')


import copy
import random

class Hat:
    def __init__(self, **kwargs): ## here args are the colored balls
        # print(kwargs)
        self.contents = []
        for key, value in kwargs.items():
            self.contents.extend([key] * value)
        # print(self.contents)

    def draw(self, number_of_balls):
        if number_of_balls > len(self.contents):
            return self.contents
        removed_balls = []
        for i in range(number_of_balls):
            a_random_element = random.choice(self.contents)
            removed_balls.append(a_random_element)
            self.contents.remove(a_random_element)
        return removed_balls

def experiment(
        hat_obj: Hat,
        expected_balls: dict,
        num_balls_drawn: int,
        num_experiments: int
) -> float:

    success = 0

    for _ in range(num_experiments):
        hat_copy = copy.deepcopy(hat_obj)
        drawn_balls = hat_copy.draw(num_balls_drawn)

        # print(drawn_balls)
        # print(expected_balls)
        # print(hat_copy.contents)
        # print('----------------')

        flag = True
        for key, value in expected_balls.items():
            if drawn_balls.count(key) < value:
                flag = False
                break
        if flag:
            success += 1
    return success/num_experiments

if __name__ == '__main__':
    # obj = Hat(red=5, orange=4, black=1, blue=0, pink=2, striped=9)
    hat_obj = Hat(black=6, red=4, green=3)
    probability = experiment(hat_obj=hat_obj,
                    expected_balls={"red":2,"green":1},
                    num_balls_drawn=5,
                    num_experiments=2000)
    print(probability)


correct_answer = ["B", "D", "A", "A", "C", "A", "B", "A", "C", "D", "B", "C", "D", "A", "D", "C", "C", "B", "D", "A"]
stud_ans = []

ans_fObj = open("student_answer.txt", "r")

stud_ans_lst = ans_fObj.readlines()
for item in stud_ans_lst:
    stud_ans.append(item.rstrip('\n'))

print(stud_ans)
print(correct_answer)
ans_fObj.close()

correct = 0
wrong = 0
for item in range(20):

    if correct_answer[item] == stud_ans[item]:
        print("Question " , item+1, " - Correct")
        correct += 1
    else:
        print("Question " , item+1, " - Incorrect")
        wrong += 1

print("\nTotal Number of Correctly Answered Questions: ", correct)
print("Total Number of Incorrectly Answered Questions: ", wrong)

if correct >= 15:
    print("Student Passed")
else:
    print("Student Failed")


from flask import render_template, copy_current_request_context
from flask import appcontext_tearing_down
from app import app, socketio
from . import photobox

@app.route('/')
@app.route('/index')
def index():
    photobox.start()
    return render_template('index.html')

@app.route('/button')
def capture_button():
    photobox.start()
    return render_template('index.html', show_button=True)

@socketio.on('capture', namespace='/test')
def capture_image():
    photobox.capture_photo()

@socketio.on('connect', namespace='/test')
def test_connect():
    started = photobox.start()
    if not started:
        photobox.send_initial_photo_count()


import datetime
from Classes.Interface import LetterResult
from Wordle.WordList import LIST_OF_ANSWERS

def getHongKongDate():
    return (datetime.datetime.utcnow() + datetime.timedelta(hours=8)).date()

def getCorrectGuessOfDay() -> str:
    today = getHongKongDate()
    index = getDateOffset(today)
    return getGuessFromOffset(index)

def getDateOffset(date: datetime.date) -> int:
    start_day = datetime.date(2021, 6, 19)
    return (date - start_day).days

def getGuessFromOffset(offset: int) -> str:
    return LIST_OF_ANSWERS[offset % len(LIST_OF_ANSWERS)]

class Validator:
    def __init__(self, word: str = None) -> None:
        if(word == None):
            word = getCorrectGuessOfDay()

        self.answer = word.lower()

    def isValidAnswer(word: str | None) -> bool:
        return word == None or (len(word) == 5 and word.lower() in LIST_OF_ANSWERS)

    def validateGuess(self, guessStr: str) -> str:
        result = ['_'] * 5
        copyOfAnswer = [char for char in self.answer]
        guess = [char for char in guessStr]

        # First we check for correct word in correct position
        for i in range(5):
            if copyOfAnswer[i] == guess[i]:
                # If it is correct and in correct position, we change it to '*'
                result[i] = '1'
                copyOfAnswer[i] = '*'
                guess[i] = '*'

        # Next, we look for partials
        for i in range(5):
            if guess[i] == '*' or guess[i] not in copyOfAnswer:
                # We have already marked this as correct so do not recheck
                continue
            actualPosition = copyOfAnswer.index(guess[i])
            copyOfAnswer[actualPosition] = '*'
            result[i] = '0'

        return ''.join(result)

    def parseGuessResult(word: str, result: str) -> dict[str, LetterResult]:
        resultMap = {}
        for i in range(len(word)):
            letter = word[i]
            res = result[i]

            if letter in resultMap:
                existingResult : LetterResult = resultMap[letter]
                if res == "1":
                    if existingResult.status == "CORRECT":
                        existingResult.correctPositions.append(i)
                    elif existingResult.status == "PARTIAL" or existingResult.status == "MULTI_INSTANCE":
                        existingResult.status = "MULTI_INSTANCE"
                        existingResult.correctPositions.append(i)
                    else:
                        resultMap[letter] = LetterResult.newCorrectResult(i)
                        existingResult = resultMap[letter]
                        existingResult.incorrectPositions = [j for j in range(5)]
                        existingResult.incorrectPositions.remove(i)
                elif res == "0":
                    if existingResult.status == "CORRECT":
                        existingResult.status = "MULTI_INSTANCE"
                        existingResult.incorrectPositions.append(i)
                    elif existingResult.status == "PARTIAL" or existingResult.status == "MULTI_INSTANCE":
                        existingResult.incorrectPositions.append(i)
                    else:
                        print("Encountered issue where incorrect before partial")
                        raise Exception("INCORRECT BEFORE PARTIAL")
                else:
                    if existingResult.status == "CORRECT":
                        existingResult.incorrectPositions = list(
                                filter(lambda num: num not in existingResult.correctPositions, [j for j in range(5)])
                            )
                    elif existingResult.status == "PARTIAL" or existingResult.status == "MULTI_INSTANCE":
                        existingResult.incorrectPositions.append(i)
                continue

            if res == "1":
                resultMap[letter] = LetterResult.newCorrectResult(i)
            elif res == "0":
                resultMap[letter] = LetterResult.newPartialResult(i)
            else:
                resultMap[letter] = LetterResult.newIncorrectResult()
        return resultMap


#!/usr/bin/env python
import sys
moves = {"right": {"x": "+", "y": None},  "up": {"x": None, "y": "+"}, "left": {"x": "-", "y": None}, "down": {"x": None, "y": "-"}}
order = ("right", "up", "left", "down")

def move(action, pos):
    m = moves[order[action]]
    #print(m, order[action])
    if m["x"] == "+":
        pos["x"] = pos["x"] + 1
    if m["x"] == "-":
        pos["x"] = pos["x"] - 1
    if m["y"] == "+":
        pos["y"] = pos["y"] + 1
    if m["y"] == "-":
        pos["y"] = pos["y"] - 1

    return pos

def calc_grid(pos, grid):
    loc = [
        {"north": {"x": 0, "y": 1}},
        {"northeast": {"x": 1, "y": 1}},
        {"east": {"x": 1, "y": 0}},
        {"southeast": {"x": 1, "y": -1}},
        {"south": {"x": 0, "y": -1}},
        {"southwest": {"x": -1, "y": -1}},
        {"west": {"x": -1, "y": 0}},
        {"northwest": {"x": -1, "y": 1}},
    ]

    summ = 0
    for d in loc:
        for k, v in d.items():
            newpos = {}
            newpos["x"] = v["x"] + pos["x"]
            newpos["y"] = v["y"] + pos["y"]

            for g in grid:
                if newpos["x"] == g["x"] and newpos["y"] == g["y"]:
                    summ = summ + g["n"]

    return summ

def main():
    pos = {"x": 0, "y": 0, "n": 1}
    index = 0
    factor = 1
    tick = 1
    grid = []
    grid.append(pos.copy())
    num = 1
    while True:
        for _ in range(factor):
            pos = move(index, pos)
            summ = calc_grid(pos, grid)
            pos["n"] = summ
            grid.append(pos.copy())
            num = num + 1
            if summ > 289326:
                print(summ)
                sys.exit(0)

        if index == 3:
            index = 0
        else:
            index = index + 1

        if tick % 2 == 0:
            factor = factor + 1

        tick = tick + 1

main()


# 내 풀이
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
# 내 풀이가 아아주 조금 더 빨랐음(ㅋㅋㅋ)
def maxProfit(self, prices: List[int]) -> int:
    # 뒤에 숫자보다 앞에 숫자가 작으면 버려
    # 크면 빼서 갖고 있어
    min_price = prices[0]
    max_price = 0

    for i in range(1, len(prices)):
        if min_price > prices[i]:
            min_price = prices[i]
        else:
            max_price = max(max_price, prices[i] - min_price)

    return max_price

def bookSoulution(self, prices: List[int]) -> int:
    profit = 0
    min_price = sys.maxsize
    for price in prices:
        min_price = min(min_price, price)
        profit = max(profit, price-min_price)
    return profit

algorithm/python/7장 배열/195p_주식을 사고팔기 가장 좋은 시점.py

195p_주식을 사고팔기 가장 좋은 시점.py


import torch.nn as nn
import torch.utils.checkpoint as cp
from annotator.uniformer.mmcv.cnn import (UPSAMPLE_LAYERS, ConvModule, build_activation_layer,
                      build_norm_layer, constant_init, kaiming_init)
from annotator.uniformer.mmcv.runner import load_checkpoint
from annotator.uniformer.mmcv.utils.parrots_wrapper import _BatchNorm

from annotator.uniformer.mmseg.utils import get_root_logger
from ..builder import BACKBONES
from ..utils import UpConvBlock

class BasicConvBlock(nn.Module):
    """Basic convolutional block for UNet.

    This module consists of several plain convolutional layers.

    Args:
        in_channels (int): Number of input channels.
        out_channels (int): Number of output channels.
        num_convs (int): Number of convolutional layers. Default: 2.
        stride (int): Whether use stride convolution to downsample
            the input feature map. If stride=2, it only uses stride convolution
            in the first convolutional layer to downsample the input feature
            map. Options are 1 or 2. Default: 1.
        dilation (int): Whether use dilated convolution to expand the
            receptive field. Set dilation rate of each convolutional layer and
            the dilation rate of the first convolutional layer is always 1.
            Default: 1.
        with_cp (bool): Use checkpoint or not. Using checkpoint will save some
            memory while slowing down the training speed. Default: False.
        conv_cfg (dict | None): Config dict for convolution layer.
            Default: None.
        norm_cfg (dict | None): Config dict for normalization layer.
            Default: dict(type='BN').
        act_cfg (dict | None): Config dict for activation layer in ConvModule.
            Default: dict(type='ReLU').
        dcn (bool): Use deformable convolution in convolutional layer or not.
            Default: None.
        plugins (dict): plugins for convolutional layers. Default: None.
    """

    def __init__(self,
                 in_channels,
                 out_channels,
                 num_convs=2,
                 stride=1,
                 dilation=1,
                 with_cp=False,
                 conv_cfg=None,
                 norm_cfg=dict(type='BN'),
                 act_cfg=dict(type='ReLU'),
                 dcn=None,
                 plugins=None):
        super(BasicConvBlock, self).__init__()
        assert dcn is None, 'Not implemented yet.'
        assert plugins is None, 'Not implemented yet.'

        self.with_cp = with_cp
        convs = []
        for i in range(num_convs):
            convs.append(
                ConvModule(
                    in_channels=in_channels if i == 0 else out_channels,
                    out_channels=out_channels,
                    kernel_size=3,
                    stride=stride if i == 0 else 1,
                    dilation=1 if i == 0 else dilation,
                    padding=1 if i == 0 else dilation,
                    conv_cfg=conv_cfg,
                    norm_cfg=norm_cfg,
                    act_cfg=act_cfg))

        self.convs = nn.Sequential(*convs)

    def forward(self, x):
        """Forward function."""

        if self.with_cp and x.requires_grad:
            out = cp.checkpoint(self.convs, x)
        else:
            out = self.convs(x)
        return out

@UPSAMPLE_LAYERS.register_module()
class DeconvModule(nn.Module):
    """Deconvolution upsample module in decoder for UNet (2X upsample).

    This module uses deconvolution to upsample feature map in the decoder
    of UNet.

    Args:
        in_channels (int): Number of input channels.
        out_channels (int): Number of output channels.
        with_cp (bool): Use checkpoint or not. Using checkpoint will save some
            memory while slowing down the training speed. Default: False.
        norm_cfg (dict | None): Config dict for normalization layer.
            Default: dict(type='BN').
        act_cfg (dict | None): Config dict for activation layer in ConvModule.
            Default: dict(type='ReLU').
        kernel_size (int): Kernel size of the convolutional layer. Default: 4.
    """

    def __init__(self,
                 in_channels,
                 out_channels,
                 with_cp=False,
                 norm_cfg=dict(type='BN'),
                 act_cfg=dict(type='ReLU'),
                 *,
                 kernel_size=4,
                 scale_factor=2):
        super(DeconvModule, self).__init__()

        assert (kernel_size - scale_factor >= 0) and\
               (kernel_size - scale_factor) % 2 == 0,\
               f'kernel_size should be greater than or equal to scale_factor '\
               f'and (kernel_size - scale_factor) should be even numbers, '\
               f'while the kernel size is {kernel_size} and scale_factor is '\
               f'{scale_factor}.'

        stride = scale_factor
        padding = (kernel_size - scale_factor) // 2
        self.with_cp = with_cp
        deconv = nn.ConvTranspose2d(
            in_channels,
            out_channels,
            kernel_size=kernel_size,
            stride=stride,
            padding=padding)

        norm_name, norm = build_norm_layer(norm_cfg, out_channels)
        activate = build_activation_layer(act_cfg)
        self.deconv_upsamping = nn.Sequential(deconv, norm, activate)

    def forward(self, x):
        """Forward function."""

        if self.with_cp and x.requires_grad:
            out = cp.checkpoint(self.deconv_upsamping, x)
        else:
            out = self.deconv_upsamping(x)
        return out

@UPSAMPLE_LAYERS.register_module()
class InterpConv(nn.Module):
    """Interpolation upsample module in decoder for UNet.

    This module uses interpolation to upsample feature map in the decoder
    of UNet. It consists of one interpolation upsample layer and one
    convolutional layer. It can be one interpolation upsample layer followed
    by one convolutional layer (conv_first=False) or one convolutional layer
    followed by one interpolation upsample layer (conv_first=True).

    Args:
        in_channels (int): Number of input channels.
        out_channels (int): Number of output channels.
        with_cp (bool): Use checkpoint or not. Using checkpoint will save some
            memory while slowing down the training speed. Default: False.
        norm_cfg (dict | None): Config dict for normalization layer.
            Default: dict(type='BN').
        act_cfg (dict | None): Config dict for activation layer in ConvModule.
            Default: dict(type='ReLU').
        conv_cfg (dict | None): Config dict for convolution layer.
            Default: None.
        conv_first (bool): Whether convolutional layer or interpolation
            upsample layer first. Default: False. It means interpolation
            upsample layer followed by one convolutional layer.
        kernel_size (int): Kernel size of the convolutional layer. Default: 1.
        stride (int): Stride of the convolutional layer. Default: 1.
        padding (int): Padding of the convolutional layer. Default: 1.
        upsample_cfg (dict): Interpolation config of the upsample layer.
            Default: dict(
                scale_factor=2, mode='bilinear', align_corners=False).
    """

    def __init__(self,
                 in_channels,
                 out_channels,
                 with_cp=False,
                 norm_cfg=dict(type='BN'),
                 act_cfg=dict(type='ReLU'),
                 *,
                 conv_cfg=None,
                 conv_first=False,
                 kernel_size=1,
                 stride=1,
                 padding=0,
                 upsample_cfg=dict(
                     scale_factor=2, mode='bilinear', align_corners=False)):
        super(InterpConv, self).__init__()

        self.with_cp = with_cp
        conv = ConvModule(
            in_channels,
            out_channels,
            kernel_size=kernel_size,
            stride=stride,
            padding=padding,
            conv_cfg=conv_cfg,
            norm_cfg=norm_cfg,
            act_cfg=act_cfg)
        upsample = nn.Upsample(**upsample_cfg)
        if conv_first:
            self.interp_upsample = nn.Sequential(conv, upsample)
        else:
            self.interp_upsample = nn.Sequential(upsample, conv)

    def forward(self, x):
        """Forward function."""

        if self.with_cp and x.requires_grad:
            out = cp.checkpoint(self.interp_upsample, x)
        else:
            out = self.interp_upsample(x)
        return out

@BACKBONES.register_module()
class UNet(nn.Module):
    """UNet backbone.
    U-Net: Convolutional Networks for Biomedical Image Segmentation.
    https://arxiv.org/pdf/1505.04597.pdf

    Args:
        in_channels (int): Number of input image channels. Default" 3.
        base_channels (int): Number of base channels of each stage.
            The output channels of the first stage. Default: 64.
        num_stages (int): Number of stages in encoder, normally 5. Default: 5.
        strides (Sequence[int 1 | 2]): Strides of each stage in encoder.
            len(strides) is equal to num_stages. Normally the stride of the
            first stage in encoder is 1. If strides[i]=2, it uses stride
            convolution to downsample in the correspondence encoder stage.
            Default: (1, 1, 1, 1, 1).
        enc_num_convs (Sequence[int]): Number of convolutional layers in the
            convolution block of the correspondence encoder stage.
            Default: (2, 2, 2, 2, 2).
        dec_num_convs (Sequence[int]): Number of convolutional layers in the
            convolution block of the correspondence decoder stage.
            Default: (2, 2, 2, 2).
        downsamples (Sequence[int]): Whether use MaxPool to downsample the
            feature map after the first stage of encoder
            (stages: [1, num_stages)). If the correspondence encoder stage use
            stride convolution (strides[i]=2), it will never use MaxPool to
            downsample, even downsamples[i-1]=True.
            Default: (True, True, True, True).
        enc_dilations (Sequence[int]): Dilation rate of each stage in encoder.
            Default: (1, 1, 1, 1, 1).
        dec_dilations (Sequence[int]): Dilation rate of each stage in decoder.
            Default: (1, 1, 1, 1).
        with_cp (bool): Use checkpoint or not. Using checkpoint will save some
            memory while slowing down the training speed. Default: False.
        conv_cfg (dict | None): Config dict for convolution layer.
            Default: None.
        norm_cfg (dict | None): Config dict for normalization layer.
            Default: dict(type='BN').
        act_cfg (dict | None): Config dict for activation layer in ConvModule.
            Default: dict(type='ReLU').
        upsample_cfg (dict): The upsample config of the upsample module in
            decoder. Default: dict(type='InterpConv').
        norm_eval (bool): Whether to set norm layers to eval mode, namely,
            freeze running stats (mean and var). Note: Effect on Batch Norm
            and its variants only. Default: False.
        dcn (bool): Use deformable convolution in convolutional layer or not.
            Default: None.
        plugins (dict): plugins for convolutional layers. Default: None.

    Notice:
        The input image size should be divisible by the whole downsample rate
        of the encoder. More detail of the whole downsample rate can be found
        in UNet._check_input_divisible.

    """

    def __init__(self,
                 in_channels=3,
                 base_channels=64,
                 num_stages=5,
                 strides=(1, 1, 1, 1, 1),
                 enc_num_convs=(2, 2, 2, 2, 2),
                 dec_num_convs=(2, 2, 2, 2),
                 downsamples=(True, True, True, True),
                 enc_dilations=(1, 1, 1, 1, 1),
                 dec_dilations=(1, 1, 1, 1),
                 with_cp=False,
                 conv_cfg=None,
                 norm_cfg=dict(type='BN'),
                 act_cfg=dict(type='ReLU'),
                 upsample_cfg=dict(type='InterpConv'),
                 norm_eval=False,
                 dcn=None,
                 plugins=None):
        super(UNet, self).__init__()
        assert dcn is None, 'Not implemented yet.'
        assert plugins is None, 'Not implemented yet.'
        assert len(strides) == num_stages, \
            'The length of strides should be equal to num_stages, '\
            f'while the strides is {strides}, the length of '\
            f'strides is {len(strides)}, and the num_stages is '\
            f'{num_stages}.'
        assert len(enc_num_convs) == num_stages, \
            'The length of enc_num_convs should be equal to num_stages, '\
            f'while the enc_num_convs is {enc_num_convs}, the length of '\
            f'enc_num_convs is {len(enc_num_convs)}, and the num_stages is '\
            f'{num_stages}.'
        assert len(dec_num_convs) == (num_stages-1), \
            'The length of dec_num_convs should be equal to (num_stages-1), '\
            f'while the dec_num_convs is {dec_num_convs}, the length of '\
            f'dec_num_convs is {len(dec_num_convs)}, and the num_stages is '\
            f'{num_stages}.'
        assert len(downsamples) == (num_stages-1), \
            'The length of downsamples should be equal to (num_stages-1), '\
            f'while the downsamples is {downsamples}, the length of '\
            f'downsamples is {len(downsamples)}, and the num_stages is '\
            f'{num_stages}.'
        assert len(enc_dilations) == num_stages, \
            'The length of enc_dilations should be equal to num_stages, '\
            f'while the enc_dilations is {enc_dilations}, the length of '\
            f'enc_dilations is {len(enc_dilations)}, and the num_stages is '\
            f'{num_stages}.'
        assert len(dec_dilations) == (num_stages-1), \
            'The length of dec_dilations should be equal to (num_stages-1), '\
            f'while the dec_dilations is {dec_dilations}, the length of '\
            f'dec_dilations is {len(dec_dilations)}, and the num_stages is '\
            f'{num_stages}.'
        self.num_stages = num_stages
        self.strides = strides
        self.downsamples = downsamples
        self.norm_eval = norm_eval
        self.base_channels = base_channels

        self.encoder = nn.ModuleList()
        self.decoder = nn.ModuleList()

        for i in range(num_stages):
            enc_conv_block = []
            if i != 0:
                if strides[i] == 1 and downsamples[i - 1]:
                    enc_conv_block.append(nn.MaxPool2d(kernel_size=2))
                upsample = (strides[i] != 1 or downsamples[i - 1])
                self.decoder.append(
                    UpConvBlock(
                        conv_block=BasicConvBlock,
                        in_channels=base_channels * 2**i,
                        skip_channels=base_channels * 2**(i - 1),
                        out_channels=base_channels * 2**(i - 1),
                        num_convs=dec_num_convs[i - 1],
                        stride=1,
                        dilation=dec_dilations[i - 1],
                        with_cp=with_cp,
                        conv_cfg=conv_cfg,
                        norm_cfg=norm_cfg,
                        act_cfg=act_cfg,
                        upsample_cfg=upsample_cfg if upsample else None,
                        dcn=None,
                        plugins=None))

            enc_conv_block.append(
                BasicConvBlock(
                    in_channels=in_channels,
                    out_channels=base_channels * 2**i,
                    num_convs=enc_num_convs[i],
                    stride=strides[i],
                    dilation=enc_dilations[i],
                    with_cp=with_cp,
                    conv_cfg=conv_cfg,
                    norm_cfg=norm_cfg,
                    act_cfg=act_cfg,
                    dcn=None,
                    plugins=None))
            self.encoder.append((nn.Sequential(*enc_conv_block)))
            in_channels = base_channels * 2**i

    def forward(self, x):
        self._check_input_divisible(x)
        enc_outs = []
        for enc in self.encoder:
            x = enc(x)
            enc_outs.append(x)
        dec_outs = [x]
        for i in reversed(range(len(self.decoder))):
            x = self.decoder[i](enc_outs[i], x)
            dec_outs.append(x)

        return dec_outs

    def train(self, mode=True):
        """Convert the model into training mode while keep normalization layer
        freezed."""
        super(UNet, self).train(mode)
        if mode and self.norm_eval:
            for m in self.modules():
                # trick: eval have effect on BatchNorm only
                if isinstance(m, _BatchNorm):
                    m.eval()

    def _check_input_divisible(self, x):
        h, w = x.shape[-2:]
        whole_downsample_rate = 1
        for i in range(1, self.num_stages):
            if self.strides[i] == 2 or self.downsamples[i - 1]:
                whole_downsample_rate *= 2
        assert (h % whole_downsample_rate == 0) \
            and (w % whole_downsample_rate == 0),\
            f'The input image size {(h, w)} should be divisible by the whole '\
            f'downsample rate {whole_downsample_rate}, when num_stages is '\
            f'{self.num_stages}, strides is {self.strides}, and downsamples '\
            f'is {self.downsamples}.'

    def init_weights(self, pretrained=None):
        """Initialize the weights in backbone.

        Args:
            pretrained (str, optional): Path to pre-trained weights.
                Defaults to None.
        """
        if isinstance(pretrained, str):
            logger = get_root_logger()
            load_checkpoint(self, pretrained, strict=False, logger=logger)
        elif pretrained is None:
            for m in self.modules():
                if isinstance(m, nn.Conv2d):
                    kaiming_init(m)
                elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
                    constant_init(m, 1)
        else:
            raise TypeError('pretrained must be a str or None')


# THIS SCRIPT WILL ALLOW HANDS-FREE CONTROL OF OUR VOLUME

# IMPORT MOUSE CONTROLS
from pynput.mouse import Button, Controller

# IMPORT SCREEN RESOLUTION SETTINGS
import tkinter

# IMPORT BASE DEPENDENCIES
import cv2 as cv2
import time
import numpy as np
import PoseTrackUpdated as PT

# cam settings
w, h = 640, 480

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cap.set(3, w)
cap.set(4, h)

ptime, ctime = 0, 0
detector = PT.pose_detector(detection_confidence=0.7, max_hands=1)

# INITIALIZE MOUSE INPUT
mouse = Controller()

# INITIALIZE SCREEN SPECIFICATIONS
root = tkinter.Tk()
root.withdraw()
WIDTH, HEIGHT = root.winfo_screenwidth(), root.winfo_screenheight()

# INITIALIZE BOUNDING BOX AREA
area_bb = 0

while cap.isOpened():
    ret, frame = cap.read()
    frame_flip = cv2.flip(frame, 1)
    img = detector.find_hands(frame_flip)
    lmark_li, bounding_box = detector.find_position(img)
    flag_set_vol = False
    if lmark_li:
        # print(lmark_li[5], lmark_li[8])

        # FILTER HAND CONTROL SO THAT WE CAN MAINTAIN CONSISTENCY IN VOLUME OUTPUT
        # find area of bounding box
        area_bb = (bounding_box[2] - bounding_box[0])*(bounding_box[3] - bounding_box[1])//100
        print('The bounding box area is:', area_bb)
        if area_bb < 900 and area_bb > 0:
            print('Valid Range')

            # TRACK CURSOR: GET COORDINATES OF LANDMARK OF CHOICE TO USE AS OUR CURSOR
            # here: we are trying the thumb as a cursor so that we can possibly use index and middle finger
            # as left and right click
            # OUR CURSOR POSITION THROUGH THE CAMERA
            cursor_x, cursor_y = lmark_li[4][1], lmark_li[4][2]
            print(cursor_x, cursor_y)

            # interpolate the cursor position according to the size of our webcam window into
            # the total resolution of our screen (this will require some testing)
            # OUR PROJECTED CURSOR POSITION ON THE ACTUAL DISPLAY
            cursor_position_x = np.interp(cursor_x, [60, 400], [0, WIDTH])
            cursor_position_y = np.interp(cursor_y, [130, 300], [0, HEIGHT])
            # print(cursor_position_x, cursor_position_y)

            # adjust coordinates of the cursor according to the interpolated cursor position
            # adjust variable to make movement of mouse smoother
            mouse_smoothness = 8
            cursor_position_x, cursor_position_y = mouse_smoothness*int(cursor_position_x/mouse_smoothness), mouse_smoothness*int(cursor_position_y/mouse_smoothness)

            mouse.position = (cursor_position_x, cursor_position_y)

            # print(mouse.position)
            # # track which fingers are up or down
            fingers = detector.fingers_up()
            print(fingers)
            # CLICK CURSOR: IMPLEMENT RIGHT CLICK AND LEFT CLICK
            if fingers[1] == 0 and fingers[0] != 0:
                # this is the index finger action for left click, release once finger goes back up
                mouse.press(Button.left)
                mouse.release(Button.left)
            if fingers[2] == 0 and fingers[1] != 0:
                # this is the middle finger action for right click, release once finger goes back up
                mouse.press(Button.right)
                mouse.release(Button.right)

            # IMPLEMENT SCROLLING if both right click and left click fingers are down
            if fingers[1] == 0 and fingers[2] == 0 and fingers[3] == 0 and fingers[4] == 0:
                mouse.scroll(0, -1)
            if fingers[1] == 0 and fingers[1] == 0 and fingers[3] == 0 and fingers[4] == 1:
                mouse.scroll(0, 1)
        else:
            print('Out of Range: please take your hand further away')

    ctime = time.time()
    fps = 1 / (ctime - ptime)
    ptime = ctime

    # img_final = cv2.flip(frame, 1)
    cv2.putText(img, f'FPS: {int(fps)}', (10, 70), cv2.FONT_HERSHEY_PLAIN,
                3, (255, 0, 255), 2)

    cv2.imshow('Frame', img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()


"""
 * Project name(项目名称)：Python_sys.exc_info方法
 * Package(包名):
 * File(文件名): test2
 * Author(作者）: mao
 * Author QQ：1296193245
 * GitHub：https://github.com/maomao124/
 * Date(创建日期)： 2022/3/29
 * Time(创建时间)： 10:56
 * Version(版本): 1.0
 * Description(描述)：
 """

import sys
import traceback

if __name__ == '__main__':
    try:
        a = 2 / 0
    except:
        print("异常类型：", sys.exc_info()[0])
        print("异常内容：", sys.exc_info()[1])
        traceback.print_tb(sys.exc_info()[2])


import warnings
warnings.filterwarnings('ignore')
import gym
import sys
sys.path.insert(0, './scripts/')
from simulation.agents import RLAgent

params = {
    'policy_frequency':     0.25,
    'simulation_frequency': 15,
    'save_history':         False,
    'offscreen_rendering':  False,
    'state_as_array':       True,
    'amplitude':            10000
}
env = gym.make('highway-v0', **params)
env.reset()

#%%
agent = RLAgent(env)
agent.load_model('/Users/rossgreen/PycharmProjects/simulation/scripts/models/dqn_params.h5f')

#%%
print(env.get_state())

#%%
agent.dqn.forward(env.get_state())

#%%
agent.dqn.forward()

#agent.test(nb_episodes=1, visualize=True, load_weights=True)


#Problem Statement
# Given a string, str, you are required to output an array containing all the possible permutations of that string. By permutation, we simply mean all the different arrangements of the characters of that string.
# Input#
# Your input will be a single string str.

# str = "abc"
# Output#
# Your function should return a list of all possible permutations of the string str.

# permutations(str) = ["abc", "acb", "bac", "bca", "cab", "cba"]
from os import stat
import string

def toString(list):
    return ''.join(list)

# Solution 1
# def permutations(list, start, end):
# #     #base case
#     if start == end:
#         return toString(list)
#     #recurse function
#     else:
#         for i in range(start, end+1):
#             list[start], list[i] = list[i], list[start]
#             permutations(list, start+1, end)
#             temp = list[start], list[i] = list[i], list[start]
#             return temp
# string = 'ABC'
# n = len(string)
# a = list(string)

# print(permutations(a, 0, n-1))

# def temp(list, s, e):
#     for i in range(s, e+1):
#         list[0], list[i] = list[i], list[0]
#         temp(list, s+1, e)
#         t = list[0], list[i] = list[i], list[0]
#         return t

# print(temp(['A', 'B', 'C'], 0, 2))

# Solution 2
def permutations(str) -> list :
    #base case
    if str is "":
        return [""]

    permutation = []
    for char in str:
    #recursive function/step
        subpermutation = permutations(str.replace(char, "", 1))
        for each in subpermutation:
            permutation.append(char + each)
    return permutation
    #return type must be a list

print(permutations('abcd'))


# Import packages
import os
import cv2
import numpy as np
import tensorflow as tf
import sys
import imutils
import time
import functools

from imutils.video import VideoStream
from imutils.video import FPS

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")

# Import utilites
from utils import label_map_util
from utils import visualization_utils as vis_util

#Initialise uARM swift pro api
sys.path.append(os.path.join(os.path.dirname(__file__), '../../..'))
from uarm.wrapper import SwiftAPI
from uarm.utils.log import logger
logger.setLevel(logger.DEBUG)

swift = SwiftAPI(filters={'hwid': 'USB VID:PID=2341:0042'})

#UI library
from tkinter import *
from tkinter import messagebox

# Name of the directory containing the object detection model we're using
MODEL_NAME = 'allfour_inference_graph'

# Grab path to current working directory
CWD_PATH = os.getcwd()

# Path to frozen detection graph .pb file, which contains the model that is used
# for object detection.
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')

# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,'data','labels_new.pbtxt')

# Number of classes the object detector can identify
NUM_CLASSES = 4

## Load the label map.
# Label maps map indices to category names, so that when our convolution
# network predicts `4`, we know that this corresponds to `medimix`.
# Here we use internal utility functions,
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

# Load the Tensorflow model into memory.

detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

    sess = tf.Session(graph=detection_graph)

# Define input and output tensors (i.e. data) for the object detection classifier

# Input tensor is the image
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

# Output tensors are the detection boxes, scores, and classes
# Each box represents a part of the image where a particular object was detected
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

# Each score represents level of confidence for each of the objects.
# The score is shown on the result image, together with the class label.
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')

# Number of objects detected
num_detections = detection_graph.get_tensor_by_name('num_detections:0')

# Initialize webcam feed

video = cv2.VideoCapture(0)
qret = video.set(3,1280)
ret = video.set(4,720)

#wait for camera to initialsie
time.sleep(2.0)

#uARM code for arm action, left and right

def arm_action(cust_no):
    if(cust_no == 1):
        print("Starting Robotic action - Customer 1")

        swift.reset(speed=100000, wait=True)
        swift.set_position(x=250, y=0, z=25, speed=100000,wait = True)
        swift.flush_cmd()
        swift.set_pump(True)
        swift.set_position(x=250, y=0, z=170, speed=100000,wait = True)
        swift.flush_cmd()
        swift.set_position(x=220, y=70, z=170, speed=100000,wait = True)
        swift.flush_cmd()
        swift.set_position(x=200, y=140, z=170, speed=100000,wait = True)
        swift.flush_cmd()
        swift.set_position(x=180, y=210, z=170, speed=100000,wait = True)
        swift.flush_cmd()
        swift.set_position(x=250, y=210, z=25, speed=100000,wait = True)
        swift.flush_cmd()
        swift.set_pump(False)
        swift.flush_cmd()
        swift.set_position(x=250, y=210, z=120, speed=100000,wait = True)
        swift.flush_cmd()
        swift.reset(speed=100000, wait=True)
        swift.flush_cmd()
        time.sleep(0.5)

    elif(cust_no ==2):
        print("Starting Robotic action - Customer 2")

        swift.reset(speed=100000, wait=True)
        swift.set_position(x=250, y=0, z=25, speed=100000,wait = True)
        swift.flush_cmd()
        swift.set_pump(True)
        swift.set_position(x=250, y=0, z=170, speed=100000,wait = True)
        swift.flush_cmd()
        swift.set_position(x=220, y=-70, z=170, speed=100000,wait = True)
        swift.flush_cmd()
        swift.set_position(x=200, y=-140, z=170, speed=100000,wait = True)
        swift.flush_cmd()
        swift.set_position(x=180, y=-210, z=170, speed=100000,wait = True)
        swift.flush_cmd()
        swift.set_position(x=250, y=-210, z=25, speed=100000,wait = True)
        swift.flush_cmd()
        swift.set_pump(False)
        swift.flush_cmd()
        swift.set_position(x=250, y=-210, z=120, speed=100000,wait = True)
        swift.flush_cmd()
        swift.reset(speed=100000, wait=True)
        swift.flush_cmd()
        time.sleep(0.5)

###################################################################
#HERE ARE ALL SORTING AND GUI UTILITIES

def sort(belt,list1):
    out = []
    for item in belt:
        if item in list1[0]:
            out.append(1)
            list1[0].remove(item)
        elif item in list1[1]:
            out.append(2)
            list1[1].remove(item)
        #elif item in list1[2]:
        #    out.append(3)
        #    list1[2].remove(item)
        #elif item in list1[3]:
        #    out.append(4)
        #    list1[3].remove(item)
        else:
            out.append('None');

    return out[0]
#def callback(event):
        #web

class FullScreenApp(object):
    def __init__(self, master, **kwargs):
        self.master=master
        pad=3
        self._geom='200x200+0+0'
        master.geometry("{0}x{1}+0+0".format(
            master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
        master.bind('<Escape>',self.toggle_geom)
    def toggle_geom(self,event):
        geom=self.master.winfo_geometry()
        print(geom,self._geom)
        self.master.geometry(self._geom)
        self._geom=geom

#Creating Form-------------------------------------------------------------------------------------------------------------
field1 = 'Customer 1', 'Items','Customer 2', 'Items'
cust_list = []

def fetch(entries):
    #print(entries)
   temp = []
   temp_final = []

   for entry in entries:
        temp.append(entry[1].get())

       #field = entry[0]
      #text  = entry[1].get()
   #if(cust1[1]):
   temp_final.append(temp[1].split(','))
   temp_final.append(temp[3].split(','))
   #temp_final.append(temp[5].split(','))
   #temp_final.append(temp[7].split(','))

  # if(cust2[0]):
        #cust2_final = cust2[1].split(',')

   #print(temp_final)
   #print(sort(belt,temp_final))

   #cust_list = temp_final.copy()
   cust_list.append(temp_final)
  # return cust_list

   root.destroy
   return temp_final

def makeform(root, fields):
   entries = []
   for field in fields:
      row = Frame(root)
      lab = Label(row, width=20, text=field, anchor='w',font=('Helvetica', '50'))
      ent = Entry(row,font=('Helvetica', '25'))
      row.pack(side=TOP, fill=X, padx=5, pady=15)
      lab.pack(side=LEFT)
      ent.pack(side=RIGHT, expand=YES, fill=X)
      entries.append((field, ent))

   return entries

def register_page():
   root1 = Tk()

   app=FullScreenApp(root1)
   ents = makeform(root1, field1)
   root1.bind('<Return>', (lambda event, e=ents: fetch(e)))
   b1 = Button(root1, text='Done',command=(lambda e=ents: fetch(e)), bd=1,bg = "green",height = 3, width=12,font=('Helvetica', '25') ).place(x=50,y=400)

   b2=Button(root1, text="Exit", bd=1,bg = "green", command = root1.destroy,height = 3, width=12,font=('Helvetica', '25') ).place(x=300,y=400)
   root1.mainloop()

#Home Page
#----------------------------------------------------------------------------------------------------------------
def close_window():
    root.destroy()

#When clicked on start
def start_command():
    cust_list_final=cust_list[0]
    print(cust_list_final)
    objects1 = {}
    a=[]
    fps = FPS().start()
    countnone=0
    countobj=0
#-----------
    while(True):
        #UI initialize

        #################

        # Acquire frame and expand frame dimensions to have shape: [1, None, None, 3]
        # i.e. a single-column array, where each item in the column has the pixel RGB value
        ret, frame = video.read()
        frame_expanded = np.expand_dims(frame, axis=0)

        #IMPORTANT STEP
        # Perform the actual detection by running the model with the image as input
        (boxes, scores, classes, num) = sess.run(
            [detection_boxes, detection_scores, detection_classes, num_detections],
            feed_dict={image_tensor: frame_expanded})

        #get scores

        objects = []

        #setting threshold value
        threshold= 0.80

        #looping in values obtained in classes

        for index, value in enumerate(classes[0]):
          object_dict = {}

          #If first element of scorep[] is higher than threshold,that means an object is present
          if scores[0, index] > threshold:
            object_dict[(category_index.get(value)).get('name').encode('utf8')] = \
                                scores[0, index]
            objects.append(object_dict)

            countobj=countobj+1 #increase obj flag
            countnone=0 #reset none flag

            #Map dictionary value and get the name of object
            if(object_dict.keys() != objects1.keys())  and countobj==10: #If object is consistent for 10 frames the  only go forward
             print(objects)

             for key in object_dict:
                if key in [b'pears']:
                    soap=['Pears']
                    arm_action(sort(soap,cust_list_final))
                    objects1 = object_dict.copy()
                elif key in [b'dove']:
                    soap=['Dove']
                    arm_action(sort(soap,cust_list_final))
                    objects1 = object_dict.copy()
                elif key in [b'moti']:
                    soap=['Moti']
                    arm_action(sort(soap,cust_list_final))
                    objects1 = object_dict.copy()
                elif key in [b'medimix']:
                    soap=['Medimix']
                    arm_action(sort(soap,cust_list_final))
                    objects1 = object_dict.copy()

            #If prediction scores are less tha  0.5, the  there is certainly no object present
          elif scores[0, 0]<0.5:

            countnone=countnone+1 #increase none flag

            if countnone==1000:   #if none flag is up for more than 1000 frames(1-2 secs), reset obj flag for new object to come
                countobj=0        #this prevents not detection of two consecutive same objects
                objects1={}

        # Draw the results of the detection as bounding box (aka 'visulaize the results')
        frame=vis_util.visualize_boxes_and_labels_on_image_array(
            frame,
            np.squeeze(boxes),
            np.squeeze(classes).astype(np.int32),
            np.squeeze(scores),
            category_index,
            use_normalized_coordinates=True,
            line_thickness=8,
            min_score_thresh=0.80)

        # All the results have been drawn on the frame, so it's time to display it.
        cv2.imshow('Object detector', frame)

        # Press 'q' to quit
        if cv2.waitKey(1) == ord('q'):
            break

        fps.update()

    fps.stop()

    print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
    print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

    # Clean up
    video.release()
    cv2.destroyAllWindows()

####################################################################
if __name__ == '__main__':
    #GUI STUFF, INITIAL DISPLAY SCREEN
    root = Tk()
    app=FullScreenApp(root)
    cwgt=Canvas(root)
    cwgt.pack(expand=True, fill=BOTH)
    title=Button(cwgt, text="AI Powered Robotic Arm", bd=1,bg = "yellow",height = 6, width=210,font=('Helvetica', '40')).place(x=0,y=0)
    #title.bind("<Button-1>",callback)
    image1=PhotoImage(file="final.png")
    cwgt.img=image1
    cwgt.create_image(5, 50, anchor=NW, image=image1)
    b1=Button(cwgt, text="Exit", bd=1,bg = "red", command = close_window,height = 3, width=10,font=('Helvetica', '15') ).place(x=1150,y=25)
    #cwgt.create_window(15,15, window=b1, anchor=NW)
    b2=Button(cwgt, text="Start", bd=1,bg = "green", command = start_command,height = 3, width=12,font=('Helvetica', '25') ).place(x=300,y=300)
    b3=Button(cwgt, text="Register", bd=1,bg = "Blue", command = register_page,height = 3, width=12,font=('Helvetica', '25') ).place(x=750,y=300)
    root.mainloop()


from queue import Queue
from time import sleep

#------------------------------------------------------------------------------
# System calls
#------------------------------------------------------------------------------
class SystemCall(object):
    ''' base class for more complex system calls'''
    def handle(self):
        pass

class GetTid(SystemCall):
    def handle(self):
        self.task.sendval = self.task.tid
        self.sched.schedule(self.task)

class NewTask(SystemCall):
    def __init__(self,target):
        self.target = target
    def handle(self):
        tid = self.sched.new(self.target)
        self.task.sendval = tid
        self.sched.schedule(self.task)

class KillTask(SystemCall):
    def __init__(self,tid):
        self.tid = tid
    def handle(self):
        task = self.sched.taskmap.get(self.tid,None)
        if task:
            task.target.close()
            self.task.sendval = True
        else:
            self.task.sendval = False
        self.sched.schedule(self.task)

#------------------------------------------------------------------------------
# Task class
#------------------------------------------------------------------------------
class Task(object):
    ''' Wrapper object for coroutines'''
    taskid = 0
    def __init__(self, target):
        Task.taskid += 1
        self.tid     = Task.taskid  # Task ID
        self.target  = target       # Target coroutine
        self.sendval = None         # Value to send
    def run(self):
        return self.target.send(self.sendval)

#------------------------------------------------------------------------------
# Our model OS
#------------------------------------------------------------------------------
class Scheduler(object):
    ''' Our operating system of sorts'''
    def __init__(self):
        ''' Set up a queue and a dictionary of tid:task entries'''
        self.ready = Queue() # FIFO array
        self.taskmap = {}

    def new(self, target):
        newtask = Task(target)
        self.taskmap[newtask.tid] = newtask
        self.schedule(newtask)
        return newtask.tid

    def schedule(self, task):
        self.ready.put(task)

    def exit(self,task):
        print(f"task {task.tid} terminated")
        del self.taskmap[task.tid]

    def mainloop(self):
        while self.taskmap: # i.e. while taskmap not empty
            task = self.ready.get() # Pull next item from front of array
            try:
                result = task.run()
                if isinstance(result, SystemCall):
                    result.task  = task # Record task responsible for sys call
                    result.sched = self # Record parent scheduler
                    result.handle()     # Carry out system call action
                    continue
            except StopIteration:
                self.exit(task)
                continue
            self.schedule(task)     # Put task back into back of array

if __name__ == '__main__':
    # A very simple generator
    def foo():
        mytid = yield GetTid()
        for i in range(0,10):
            print(f"I'm foo, with tid {mytid}")
            sleep(1)
            yield

    def bar():
        mytid = yield GetTid()
        for i in range(0,3):
            print(f"I'm bar, with tid {mytid}")
            sleep(1)
            yield

    sched = Scheduler()
    sched.new(foo())
    sched.new(bar())
    sched.mainloop()


from jinja2 import Environment, FileSystemLoader
from fastapi import HTTPException
from datetime import timedelta
from retry import retry

from constants import UNISWAP_TOKEN_ADDRESSES
from constants import UNISWAP_CONTRACT_ADDRESSES
from config import settings

import pandas as pd
import requests

class TransposeService:

    URL = "https://api.transpose.io/sql"
    TIMEFRAMES_HANDLED = {
        "1d": "day",
        "1h": "hour",
        "1m": "minute",
        "1s": "second",
    }

    def __init__(self, queries_path = ""):
        self.headers = {
            "Content-Type": "application/json",
            "X-API-KEY": settings.transpose_api_key,
        }

        if len(queries_path) != 0:
            self.queries_path = queries_path
        else:
            self.queries_path = "./app/services/queries/"

        self.jenv =  Environment(
            loader=FileSystemLoader(self.queries_path),
        )

    def _transform_timeframe(self, timeframe):
        if timeframe in TransposeService.TIMEFRAMES_HANDLED:
            return TransposeService.TIMEFRAMES_HANDLED[timeframe]
        else:
            raise ValueError("Timeframe not handled.")

    @retry(tries=3, delay=1, backoff=2)
    def _retryable_post(self, url, headers, json):
        return requests.post(
            url,
            headers = headers,
            json = json,
        )

    def retrieve_data_in_batch(self, start_date, end_date, timeframe, query):
        query_template = self.jenv.get_template(query)
        tf = self._transform_timeframe(timeframe)
        current_date = start_date
        seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
        seconds = 15 * seconds_per_unit["d"]
        data = []

        while (current_date <= end_date):
            print("\t", current_date, current_date + timedelta(seconds=seconds))
            query = query_template.render(
                start_date=current_date,
                end_date=current_date + timedelta(seconds=seconds),
                timeframe=tf,
                token_addresses=list(UNISWAP_TOKEN_ADDRESSES.keys()),
                contract_addresses=list(UNISWAP_CONTRACT_ADDRESSES.keys()),
            )

            response = self._retryable_post(
                TransposeService.URL,
                headers = self.headers,
                json = {
                    "sql": query,
                },
            )

            if response.status_code == 200:
                df = pd.DataFrame(response.json()["results"])
                df.index = pd.to_datetime(df["datetime"]).copy()
                df.drop(["datetime"], axis=1, inplace=True)

                data.append(df)

                current_date = current_date + timedelta(seconds=seconds)
            else:
                raise HTTPException(status_code=response.status_code, detail=response.json())

        return pd.concat(data)

    def retrieve_liquidity(self, start_date, end_date, timeframe):
        df = self.retrieve_data_in_batch(
            start_date, end_date, timeframe, "liquidity.sql",
        )

        df["contract_symbol"] = df["contract_address"].apply(lambda row: UNISWAP_CONTRACT_ADDRESSES[row.lower()])
        df.drop(["contract_address"], axis=1, inplace=True)

        return df

    def retrieve_swap_volumes(self, start_date, end_date, timeframe):
        df = self.retrieve_data_in_batch(
            start_date, end_date, timeframe, "swaps_volume.sql",
        )

        df["contract_symbol"] = df["contract_address"].apply(lambda row: UNISWAP_CONTRACT_ADDRESSES[row.lower()])
        df.drop(["contract_address"], axis=1, inplace=True)

        return df

    def retrieve_gas_price(self, start_date, end_date, timeframe):
        return self.retrieve_data_in_batch(
            start_date, end_date, timeframe, "gas_price.sql",
        )


import pyautogui
from PIL import Image,ImageGrab
import time
def hit(key):
    pyautogui.keyDown(key)
    return
# def takescreenshot():
    # image=ImageGrab.grab()

    # return image
def iscollide(data):
    for i in range(350,430):
        for j in range(540,560):
            if data[i,j]<100:
                hit("down")
                time.sleep(0.2)
                hit("up")
                return
    for i in range(470,500):
        for j in range(620,680):
            if data[i ,j]<100:
                hit("up")
                return

    return False

if __name__ == '__main__':
    print("starting dino game")
    # takescreenshot()
    time.sleep(3)
    while True:
        imag=ImageGrab.grab().convert('L')
        data=imag.load()
        iscollide(data)

        # for i in range(350,430):
        #     for j in range(540,560):
        #         data[i ,j]=1
        # for i in range(470,500):
        #     for j in range(620,680):
        #      data[i,j]=1

        # imag.show()
        # break


from PyQt5.QtWidgets import QMainWindow, QLabel, QPushButton, QMessageBox, QDialog, QTabWidget, QAbstractButton
from PyQt5.QtCore import Qt, QSize

from ui_MainWindow import Ui_MainWindow
from SharedImageBuffer import SharedImageBuffer
from CameraConnectDialog import CameraConnectDialog
from CameraView import CameraView
from Buffer import *
from Config import *

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        # Setup UI
        self.setupUi(self)
        # Create dict instead of QMap
        self.deviceUrlDict = dict()
        self.cameraViewDict = dict()
        # Set start tab as blank
        newTab = QLabel(self.tabWidget)
        newTab.setText("No camera connected.")
        newTab.setAlignment(Qt.AlignCenter)
        self.tabWidget.addTab(newTab, "")
        self.tabWidget.setTabsClosable(False)
        # Add "Connect to Camera" button to tab
        self.connectToCameraButton = QPushButton()
        self.connectToCameraButton.setText("Connect to Camera...")
        self.tabWidget.setCornerWidget(self.connectToCameraButton, Qt.TopLeftCorner)
        self.connectToCameraButton.released.connect(self.connectToCamera)
        self.tabWidget.tabCloseRequested.connect(self.disconnectCamera)
        # Set focus on button
        self.connectToCameraButton.setFocus()
        # Connect other signals/slots
        self.actionAbout.triggered.connect(self.showAboutDialog)
        self.actionQuit.triggered.connect(self.close)
        self.actionFullScreen.toggled.connect(self.setFullScreen)
        # Create SharedImageBuffer object
        self.sharedImageBuffer = SharedImageBuffer()
        # Camera number
        self.cameraNum = 0

    def connectToCamera(self):
        # We cannot connect to a camera if devices are already connected and stream synchronization is in progress
        if (self.actionSynchronizeStreams.isChecked()
                and len(self.deviceUrlDict) > 0
                and self.sharedImageBuffer.getSyncEnabled()):
            # Prompt user
            QMessageBox.warning(self, "pyqt5-cv2-multithreaded",
                                "Stream synchronization is in progress.\n\n"
                                "Please close all currently open streams "
                                "before attempting to open a new stream.",
                                QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        # Attempt to connect to camera
        else:
            # Get next tab index
            nextTabIndex = 0 if len(self.deviceUrlDict) == 0 else self.tabWidget.count()
            # Show dialog
            cameraConnectDialog = CameraConnectDialog(self, self.actionSynchronizeStreams.isChecked())
            if cameraConnectDialog.exec() == QDialog.Accepted:
                # Save user-defined device deviceUrl
                deviceUrl = cameraConnectDialog.getDeviceUrl()
                # Check if this camera is already connected
                if deviceUrl not in self.deviceUrlDict:
                    # Create ImageBuffer with user-defined size
                    imageBuffer = Buffer(cameraConnectDialog.getImageBufferSize())
                    # Add created ImageBuffer to SharedImageBuffer object
                    self.sharedImageBuffer.add(deviceUrl, imageBuffer, self.actionSynchronizeStreams.isChecked())
                    # Create CameraView
                    cameraView = CameraView(self.tabWidget, deviceUrl, self.sharedImageBuffer, self.cameraNum)

                    # Check if stream synchronization is enabled
                    if self.actionSynchronizeStreams.isChecked():
                        # Prompt user
                        ret = QMessageBox.question(self, "pyqt5-cv2-multithreaded",
                                                   "Stream synchronization is enabled.\n\n"
                                                   "Do you want to start processing?\n\n"
                                                   "Choose 'No' if you would like to open "
                                                   "additional streams.",
                                                   QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
                        # Start processing
                        if ret == QMessageBox.Yes:
                            self.sharedImageBuffer.setSyncEnabled(True)
                        # Defer processing
                        else:
                            self.sharedImageBuffer.setSyncEnabled(False)

                    # Attempt to connect to camera
                    if cameraView.connectToCamera(
                            cameraConnectDialog.getDropFrameCheckBoxState(),
                            cameraConnectDialog.getApiPreference(),
                            cameraConnectDialog.getCaptureThreadPrio(),
                            cameraConnectDialog.getProcessingThreadPrio(),
                            cameraConnectDialog.getEnableFrameProcessingCheckBoxState(),
                            cameraConnectDialog.getResolutionWidth(),
                            cameraConnectDialog.getResolutionHeight()):

                        self.cameraNum += 1
                        # Save tab label
                        tabLabel = cameraConnectDialog.getTabLabel()
                        # Allow tabs to be closed
                        self.tabWidget.setTabsClosable(True)
                        # If start tab, remove
                        if nextTabIndex == 0:
                            self.tabWidget.removeTab(0)
                        # Add tab
                        self.tabWidget.addTab(cameraView, '%s [%s]' % (tabLabel, deviceUrl))
                        self.tabWidget.setCurrentWidget(cameraView)
                        # Set tooltips
                        self.setTabCloseToolTips(self.tabWidget, "Disconnect Camera")
                        # Prevent user from enabling/disabling stream synchronization
                        # after a camera has been connected
                        self.actionSynchronizeStreams.setEnabled(False)
                        # Add to map
                        self.cameraViewDict[deviceUrl] = cameraView
                        self.deviceUrlDict[deviceUrl] = nextTabIndex
                    # Could not connect to camera
                    else:
                        # Display error message
                        QMessageBox.warning(self,
                                            "ERROR:",
                                            "Could not connect to camera. "
                                            "Please check device deviceUrl.")
                        # Explicitly delete widget
                        cameraView.delete()
                        # Remove from shared buffer
                        self.sharedImageBuffer.removeByDeviceUrl(deviceUrl)
                        # Explicitly delete ImageBuffer object
                        del imageBuffer
                # Display error message
                else:
                    QMessageBox.warning(self,
                                        "ERROR:",
                                        "Could not connect to camera. Already connected.")

    def disconnectCamera(self, index):
        # Local variable(s)
        doDisconnect = True

        # Check if stream synchronization is enabled,
        # more than 1 camera connected,
        # and frame processing is not in progress
        if (self.actionSynchronizeStreams.isChecked()
                and len(self.cameraViewDict) > 1
                and not self.sharedImageBuffer.getSyncEnabled()):
            # Prompt user
            ret = QMessageBox.question(self,
                                       "pyqt5-cv2-multithreaded",
                                       "Stream synchronization is enabled.\n\n"
                                       "Disconnecting this camera will cause frame "
                                       "processing to begin on other streams.\n\n"
                                       "Do you wish to proceed?",
                                       QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            # Do not disconnect
            if ret == QMessageBox.No:
                doDisconnect = False

        # Disconnect camera
        if doDisconnect:
            # Save deviceUrl of tabs
            nTabs = self.tabWidget.count()

            # Close tab
            self.tabWidget.removeTab(index)

            # get deviceUrl (key of dict)
            deviceUrl = self.getFromDictByTabIndex(self.deviceUrlDict, index)

            # Delete widget (CameraView) contained in tab
            self.cameraViewDict[deviceUrl].delete()

            # Remove from dict
            self.cameraViewDict.pop(deviceUrl)
            self.deviceUrlDict.pop(deviceUrl)

            # Update map (if tab closed is not last)
            if index != (nTabs - 1):
                self.updateDictValues(self.deviceUrlDict, index)

            # If start tab, set tab as blank
            if nTabs == 1:
                newTab = QLabel(self.tabWidget)
                newTab.setText("No camera connected.")
                newTab.setAlignment(Qt.AlignCenter)
                self.tabWidget.addTab(newTab, "")
                self.tabWidget.setTabsClosable(False)
                self.actionSynchronizeStreams.setEnabled(True)

    def showAboutDialog(self):
        QMessageBox.information(self, "About",
                                "Created by Nick D'Ademo\n\n"
                                "Contact: nickdademo@gmail.com\n"
                                "Website: www.nickdademo.com\n"
                                "Version: %s\n\n"
                                "Refactoring by Flyto\n\n" % APP_VERSION)

    def getFromDictByTabIndex(self, dic, tabIndex):
        for k, v in dic.items():
            if v == tabIndex:
                return k

    def updateDictValues(self, dic, tabIndex):
        for k, v in dic.items():
            if v > tabIndex:
                dic[k] = v - 1

    def setFullScreen(self, flag):
        if flag:
            self.showFullScreen()
        else:
            self.showNormal()

    def setTabCloseToolTips(self, tabs, tooltip):
        for item in tabs.findChildren(QAbstractButton):
            if item.inherits("CloseButton"):
                item.setToolTip(tooltip)


# coding: utf-8

"""
    Farsava API

    Farsava API. Speech Recognition and Text to Speech by applying powerful deep neural network models.  # noqa: E501

    OpenAPI spec version: 1.0.5
    Contact: amir@amerandish.com
    Generated by: https://openapi-generator.tech
"""

import pprint
import re  # noqa: F401

import six

class RecognitionAudioURI(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'uri': 'str'
    }

    attribute_map = {
        'uri': 'uri'
    }

    def __init__(self, uri=None):  # noqa: E501
        """RecognitionAudioURI - a model defined in OpenAPI"""  # noqa: E501

        self._uri = None
        self.discriminator = None

        self.uri = uri

    @property
    def uri(self):
        """Gets the uri of this RecognitionAudioURI.  # noqa: E501

        URI that points to a file that contains audio data bytes as specified in RecognitionConfig. The file must not be compressed (for example, gzip).   # noqa: E501

        :return: The uri of this RecognitionAudioURI.  # noqa: E501
        :rtype: str
        """
        return self._uri

    @uri.setter
    def uri(self, uri):
        """Sets the uri of this RecognitionAudioURI.

        URI that points to a file that contains audio data bytes as specified in RecognitionConfig. The file must not be compressed (for example, gzip).   # noqa: E501

        :param uri: The uri of this RecognitionAudioURI.  # noqa: E501
        :type: str
        """
        if uri is None:
            raise ValueError("Invalid value for `uri`, must not be `None`")  # noqa: E501

        self._uri = uri

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, RecognitionAudioURI):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        return not self == other


import warnings
warnings.filterwarnings("ignore")
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import Adam
import numpy as np
from Networks import SupervisedActor
from utils import crit_preprocessing
from sparse_tnsr_replay_buffer import ReplayBuffer
import pickle
from time import time, sleep
from multiprocessing import Pipe, Process, Queue

batch_size = 512
epochs = 50
num_workers = 6
q_size = 15

actor = SupervisedActor(name='supervised_actor_0509')
optimizer = Adam(params=actor.parameters())

train_buffer = ReplayBuffer(max_size=int(1e6), jnt_d=5, time_d=6,file='train_data')
train_buffer = train_buffer.load()
eval_buffer = ReplayBuffer(max_size=int(1e6), jnt_d=5, time_d=6,file='rrt_data10')
eval_buffer = eval_buffer.load()

q = Queue(maxsize=q_size)
q_val= Queue(maxsize=q_size)
def data_loader(buffer,eval_buffer):
    run = True
    wait_time = .1
    max_idle_time = 600
    max_iter = int(np.ceil(max_idle_time/wait_time))
    i = 0
    while run:
        if not q.full():
            states, actions, weights, _,_,_ = buffer.sample_buffer(batch_size)
            try:
                q.put([states,actions,weights],timeout=1)
            except:
                sleep(.1)
            i = 0
        elif not q_val.full():
            states,actions,weights,_,_,_ = eval_buffer.sample_buffer(batch_size)
            try:
                q_val.put([states,actions,weights],timeout=1)
            except:
                sleep(.1)
        else:
            # if i%100==0: print('idle',i)
            i+=1
            if i > int(max_iter): # stop runing after 10 seconds
                run = False
                print('exiting')
            sleep(wait_time)

def save_files(loss_hist,val_hist):
    loss_file = "loss_hist_0508.pkl"
    val_file = "val_hist_0508.pkl"
    file = open(loss_file,'wb')
    pickle.dump(loss_hist,file)
    file = open(val_file,'wb')
    pickle.dump(val_hist,file)

#admin
loss_hist = []
val_hist = []
best_loss = np.inf
n_batch = int(np.floor(train_buffer.mem_cntr/batch_size))
val_batch = int(np.floor(eval_buffer.mem_cntr/batch_size))
k = 0
keep_going = True
early_stop = 0

# setting up processes
print('starting processes')
processes = [Process(target=data_loader,args=(train_buffer,eval_buffer)) for _ in range(num_workers)]
for p in processes:
    p.start()
print('filling up q')
while not q.full():
    sleep(1)
print('filling up q_val')
while not q_val.full():
    sleep(1)

try:
    while k < epochs and keep_going:
        running_loss = 0
        print('...learning...', k)
        for i in range(n_batch):
            temp_loop = 0
            # t = time()
            while q.empty():
                # print('recovering')
                sleep(5)
            stuff = q.get()
            states,actions,weights = stuff[0],stuff[1],stuff[2]
            # print("loading time", time()-t)
            # t = time()
            x,jnt_err,jnt_dedt,w,a_ = crit_preprocessing(states,actions,weights)
            # print("preprocessing", time()-t)
            # t = time()
            optimizer.zero_grad()
            a = actor.forward(x,jnt_err,jnt_dedt,w)
            loss = F.mse_loss(a,a_)
            loss.backward()
            optimizer.step()
            # print("learning", time()-t)
            running_loss += loss.item()
        batch_loss = running_loss/n_batch
        loss_hist.append(batch_loss)

        running_loss = 0
        print('...eval...', k)
        for i in range(val_batch):
            with torch.no_grad():
                temp_loop = 0
                while q_val.empty():
                    # print('recovering')
                    sleep(5)
                stuff = q_val.get()
                states,actions,weights = stuff[0],stuff[1],stuff[2]
                x,jnt_err,jnt_dedt,w,a_ = crit_preprocessing(states,actions,weights)
                a = actor.forward(x,jnt_err,jnt_dedt,w)
                loss = F.mse_loss(a,a_)
                running_loss += loss.item()
        val_loss = running_loss/val_batch
        val_hist.append(val_loss)

        k+=1
        if val_loss <= best_loss:
            actor.save_checkpoint(save_as="chckptn_"+actor.name)
            save_files(loss_hist,val_hist)
        else:
            early_stop += 1
            if early_stop > 20:
                keep_going = False

        print('epoch',k,'training loss', batch_loss, 'val loss', val_loss)
    actor.save_checkpoint()
    save_files(loss_hist,val_hist)

    for p in processes:
        print('killing')
        p.kill()
except Exception as e:
    print(e)
    for p in processes:
        print('killing')
        p.kill()