def uncompress(s):
  i = 0
  j = 0
  output = []
  numbers = "0123456789"
  while j < len(s):
    if s[j] in numbers:
      j += 1
    else:
      num = int(s[i:j])
      output.append(s[j] * num)
      j += 1
      i = j
  return "".join(output)

print(uncompress("2c3a1t"))


import numpy as np
import dlib
import cv2
import src.image.utils as utils
import threading

class ObjectTracker:
    def __init__(self, replace=None, daemon=False, scale_factor=1):
        self.CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
                        "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
                        "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
                        "sofa", "train", "tvmonitor"]
        self.prototxt = 'resources/object_tracker/model2/deploy.prototxt'
        self.model = 'resources/object_tracker/model2/mobilenet_iter_73000.caffemodel'

        self.net = cv2.dnn.readNetFromCaffe(self.prototxt, self.model)
        print("Model loading finished")
        self.confidence = 0.4
        self.labels_to_find = ['person']
        self.image_dim = None
        self.image_center = None
        self.tracker = None
        self.label = None
        self.scale_factor = scale_factor
        self.replace = replace
        self.daemon = daemon
        self.object_center = None
        self.object_offset = None
        self.reset_tracker_limit = 20
        self.tracker_count = 0
        self.current_frame = None
        self.current_cropped_frame = None
        self.detection = None

    def run_thread(self, frame):
        t = threading.Thread(
            target=self.track_and_detect,
            daemon=True,
            args=(frame,)
        )
        t.start()

    def track_and_detect(self, frame):
        if not self.image_center:
            (self.image_dim, self.image_center) = utils.get_frame_center(frame)

        w, h = self.image_dim

        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        if self.tracker is None:
            print('trying to track')
            blob = cv2.dnn.blobFromImage(frame, 0.007843, (w, h), 127.5)
            print('got blob')
            # pass the blob through the network and obtain the detections
            # and predictions
            self.net.setInput(blob)

            try:
                detections = self.net.forward()
            except:
                print('error')
                detections = []

            print('forwarded')
            print('detections', len(detections))

            if len(detections) > 0:
                # find the index of the detection with the largest
                # probability -- out of convenience we are only going
                # to track the first object we find with the largest
                # probability; future examples will demonstrate how to
                # detect and extract *specific* objects
                i = np.argmax(detections[0, 0, :, 2])
                # grab the probability associated with the object along
                # with its class label
                conf = detections[0, 0, i, 2]
                self.label = self.CLASSES[int(detections[0, 0, i, 1])]
                if self.label in self.labels_to_find:
                    print('confidence', conf)

                if conf > self.confidence and self.label in self.labels_to_find:
                    # compute the (x, y)-coordinates of the bounding box
                    # for the object
                    box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
                    (startX, startY, endX, endY) = box.astype("int")
                    # construct a dlib rectangle object from the bounding
                    # box coordinates and then start the dlib correlation
                    # tracker
                    self.tracker = dlib.correlation_tracker()
                    rect = dlib.rectangle(startX, startY, endX, endY)
                    self.tracker.start_track(rgb, rect)
                    # if self.replace:
                    #     cv2.rectangle(frame, (startX, startY), (endX, endY),
                    #                   (0, 255, 0), 1)
                    #     cv2.putText(frame, self.label, (startX, startY - 15),
                    #                 cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 1)
        else:
            self.tracker.update(rgb)
            pos = self.tracker.get_position()

            start_x = int(pos.left())
            start_y = int(pos.top())
            end_x = int(pos.right())
            end_y = int(pos.bottom())

            self.object_center = utils.get_object_center((start_y, end_x, end_y, start_x))
            self.object_offset = utils.get_center_offset(self.object_center, self.image_center)

            cropped_start_x = 0 if start_x < 0 else start_x
            cropped_start_y = 0 if end_y < 0 else start_y
            cropped_end_x = w if end_x > w else end_x
            cropped_end_y = h if start_y > w else end_y

            self.current_cropped_frame = frame[cropped_start_y: cropped_end_y, cropped_start_x: cropped_end_x]

            if self.replace:
                cv2.line(frame, self.object_center, self.image_center, (0, 255, 0), 2)
                # draw the bounding box from the correlation object tracker
                # cv2.rectangle(frame, (start_x, start_y), (end_x, end_y),
                #               (0, 255, 0), 1)
                # cv2.putText(frame, self.label, (startX, startY - 15),
                #             cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 1)

            self.handle_tracker_reset()

        self.current_frame = frame

        if self.current_cropped_frame is not None:
            return self.current_cropped_frame

        return frame

    def handle_tracker_reset(self):
        if self.tracker_count >= self.reset_tracker_limit:
            self.tracker = None

        self.tracker_count = self.tracker_count + 1


import torch.nn.functional as F

from transformers_multihead_attn_tutorial.model.transformer_predictor import TransformerPredictor

class AnomalyPredictor(TransformerPredictor):

    def _calculate_loss(self, batch, mode="train"):
        img_sets, _, labels = batch
        preds = self.forward(img_sets,
                             add_positional_encoding=False)  # No positional encodings as it is a set, not a sequence!
        preds = preds.squeeze(dim=-1)  # Shape: [Batch_size, set_size]
        loss = F.cross_entropy(preds, labels)  # Softmax/CE over set dimension
        acc = (preds.argmax(dim=-1) == labels).float().mean()
        self.log("%s_loss" % mode, loss)
        self.log("%s_acc" % mode, acc, on_step=False, on_epoch=True)
        return loss, acc

    def training_step(self, batch, batch_idx):
        loss, _ = self._calculate_loss(batch, mode="train")
        return loss

    def validation_step(self, batch, batch_idx):
        _ = self._calculate_loss(batch, mode="val")

    def test_step(self, batch, batch_idx):
        _ = self._calculate_loss(batch, mode="test")


# __coding:utf-8__
'''
@Author  : Sun
@Time    :  下午5:55
@Software: PyCharm
@File    : anhui.py
'''

import re
import time
import scrapy
import datetime
import logging
import requests
import json

from common.dbtools import DatabaseAgent
from job.items import IndustrialItem
from job.models.industrial import Industrial
from common.common import is_exits

class shandong(scrapy.Spider):
    name = 'shandong'
    header = {'Cache-Control': 'max-age=0', 'Origin': 'http://www.aheic.gov.cn', 'Upgrade-Insecure-Requests': '1',
              'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36',
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
              'Referer': 'http://www.sheitc.gov.cn/zxgkxx/index.htm', 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
              'Cookie': '_sheitc=jinasgKzas; _gscu_1260451812=302449692ovey868; _gscbrs_1260451812=1; gwideal_date=day; gwdshare_firstime=1530244999495; _gscs_1260451812=t30258567798d7510|pv:12'}
    area = "shandong"
    origin = "shandong"
    url = 'http://www.sdeic.gov.cn/gentleCMS/f_articlesearch/getSearchArticleListForNameorContent.do'
    keys = ['工业互联网','工业App']

    def start_requests(self):
        for key in self.keys:
            res_page = requests.post(
                url=self.url,
                headers=self.header,
                data={"siteid": "934369d9-7c20-45e0-a919-08ed9d557a1d","pageIndex":"1","pageSize":"15","name":key,"sitePubUrl":"/","number":"","time":"","channelid":""},
            )
            page = int(json.loads(res_page.content)['result']['pagecount'])
            for p in range(1,page+1):
                res = requests.post(
                    url=self.url,
                    headers=self.header,
                    data={"siteid": "934369d9-7c20-45e0-a919-08ed9d557a1d", "pageIndex": p, "pageSize": "15",
                          "name": key, "sitePubUrl": "/", "number": "", "time": "", "channelid": ""},
                )
                try:
                    json.loads(res.content)['result']['articleList']
                except:
                    continue
                for data in json.loads(res.content)['result']['articleList']:
                    data['PUBURL'] = 'http://www.sdeic.gov.cn' + data['PUBURL']
                    yield scrapy.Request(
                        url=data['PUBURL'],
                        headers=self.header,
                        callback=lambda response,key=key,data=data: self.save_data(response,key,data)
                    )

    def save_data(self,response,key,data):
        # article = response.xpath()
        db_agent = DatabaseAgent()
        s = IndustrialItem()
        s['title'] = data['NAME']
        if key == "工业App" and ("工业" not in s['title'] or ("App" not in s['title'] and "APP" not in s[
            'title'] and "app" not in s['title'])):
            pass
        else:
            pattern = re.compile(r'发布时间：(.*?) ')
            date = pattern.search(response.body.decode("utf8")).group(1)
            date = datetime.datetime.strptime(date, "%Y-%m-%d")
            s['time'] = int(time.mktime(date.timetuple()))
            s['area'] = self.area
            s['origin'] = self.origin
            s['keyword'] = key
            s['url'] = data['PUBURL']
            s['nature'] = data['CHANNELNAME']
            if is_exits(s["title"], s["url"]):
                try:
                    db_agent.add(
                        kwargs=dict(s),
                        orm_model=Industrial
                    )
                    logging.info("-----------add success------------")
                except Exception as e:
                    logging.info(e)
                    logging.info("-----------add error------------")
                    pass
        yield s


from enum import Enum
from logic.core import var
from clevr import Size, Shape, Material, Color
from itertools import permutations, chain, count
from .clause import Clause
from .caption import top

# hint enumeration - coarse-grained choices during search
Hint = Enum("Hint", "left right front behind size shape color material")

# for i/o purposes
def stringToHint(str):
    return Hint[str]

# defining split b/t relations and attributes
def isRelation(hint):
    return hint in [
        Hint.left,
        Hint.right,
        Hint.front,
        Hint.behind
    ]
def isAttribute(hint):
    return not isRelation(hint)

# given a hint and arguments, refine to get clauses
def refineRelation(hint, x, y):
    if hint is Hint.left:
        yield Clause("left", x, y)
    elif hint is Hint.right:
        yield Clause("right", x, y)
    elif hint is Hint.front:
        yield Clause("front", x, y)
    elif hint is Hint.behind:
        yield Clause("behind", x, y)

def refineAttribute(hint, x):
    if hint is Hint.size:
        for size in Size:
            yield Clause("size", x, size)
    elif hint is Hint.shape:
        for shape in Shape:
            yield Clause("shape", x, shape)
    elif hint is Hint.color:
        for color in Color:
            yield Clause("color", x, color)
    elif hint is Hint.material:
        for material in Material:
            yield Clause("material", x, material)

# for constructing fresh variables
def freshVariable(variables):
    for i in count(0):
        proposal = var(f"_.{i}")
        if proposal not in variables:
            return proposal

def refineHint(hint, variablesInUse):
    # split hint based on relation/attribute
    if isRelation(hint):
        # generate the canonical fresh variable
        fresh = freshVariable(variablesInUse)
        # generate all permutations of variables
        for x, y in permutations(chain(variablesInUse, [fresh]), 2):
            yield from refineRelation(hint, x, y)
    # if we're an attribute, don't need fresh var
    else:
        for x in variablesInUse:
            yield from refineAttribute(hint, x)

def refineCaption(caption, hint):
    variables = set(caption.variables())
    for clause in refineHint(hint, variables):
        yield caption & clause

def refine(hints):
    captions = [ top() ]
    # refine for each hint
    for hint in hints:
        captions = chain(*map(lambda c: refineCaption(c, hint), captions))
    # then spit out the result
    yield from captions

def refineWithEvidence(hints, target, scene):
    captions = [ top() ]
    for hint in hints:
        proposals = chain(*map(lambda c: refineCaption(c, hint), captions))
        captions = filter(lambda c: target in c.evaluate(scene), proposals)
    yield from captions

def greedyPick(captions, target, scene):
    caption, imgSize = None, len(scene.objects)
    # pick caption with smallest image containing target
    for proposal in captions:
        image = set(proposal.evaluate(scene))
        if target in image and len(image) < imgSize:
            caption, imgSize = proposal, len(image)
    # return the best
    return caption

def refineGreedy(hints, target, scene):
    caption = top()

    for hint in hints:
        try:
            caption = greedyPick(refineCaption(caption, hint), target, scene)
        except:
            pass

    yield caption


import os
import sys
import warnings
warnings.filterwarnings('ignore')

# change this property
NOMEROFF_NET_DIR = os.path.abspath('../../')

DATASET_NAME = "options_test"
VERSION = "2020_08_20_tensorflow_v2"

LOG_DIR = os.path.join(NOMEROFF_NET_DIR, "logs/")
PATH_TO_DATASET = os.path.join(NOMEROFF_NET_DIR, "datasets/", DATASET_NAME)
RESULT_PATH = os.path.join(NOMEROFF_NET_DIR, "models/", 'numberplate_{}_{}.h5'.format(DATASET_NAME, VERSION))

sys.path.append(NOMEROFF_NET_DIR)

from NomeroffNet import OptionsDetector

# definde your parameters
class MyNpClassificator(OptionsDetector):
    def __init__(self):
        OptionsDetector.__init__(self)
        # outputs 1
        self.CLASS_STATE = ["garbage", "filled", "not filled", "empty"]

        # outputs 2
        self.CLASS_REGION = ["xx-unknown", "eu-ua-2015", "eu-ua-2004", "eu-ua-1995", "eu", "xx-transit", "ru", "kz", "eu-ua-ordlo-dnr", "eu-ua-ordlo-lnr", "ge"]

        # output 3
        self.CLASS_COUNT_LINE = ["0", "1", "2"]

        self.EPOCHS           = 100
        self.BATCH_SIZE       = 1 # 64

        self.HEIGHT         = 64
        self.WEIGHT         = 295

# initialize region detector.
npClassificator = MyNpClassificator()
npClassificator.prepare(PATH_TO_DATASET, verbose=1)

# train
model = npClassificator.train(LOG_DIR, cnn="simple")

npClassificator.test()

npClassificator.save(RESULT_PATH)


import os
from os.path import dirname as up
import pathlib
import sys

filepath = pathlib.Path(__file__).resolve()
mymi_dir = up(up(up(up(filepath))))
sys.path.append(mymi_dir)
from mymi import config

keep_n = 1
for_real = False

modelspath = config.directories.models
models = os.listdir(modelspath)
for model in models:
    runspath = os.path.join(modelspath, model)
    runs = os.listdir(runspath)
    for run in runs:
        ckptspath = os.path.join(runspath, run)
        ckpts = os.listdir(ckptspath)

        # Remove 'last.ckpt'
        if 'last.ckpt' in ckpts:
            ckpts.remove('last.ckpt')

        # Sort and highlight those to delete.
        ckpts = sorted(ckpts)
        ckpts_to_delete = ckpts[:-keep_n]

        for ckpt in ckpts_to_delete:
            if for_real:
                print(f'{model}:{run}:{ckpt}')
                ckptpath = os.path.join(ckptspath, ckpt)
                os.remove(ckptpath)
            else:
                print(f'{model}:{run}:{ckpt}')


from arango import ArangoClient
from arango_orm import Database

from datetime import datetime

from User import User

from UserRepo import UserRepo

import soundcloud

clientS = soundcloud.Client(client_id=app.config["APY_KEY"])

client = ArangoClient(protocol='http', host='localhost', port=8529)
test_db = client.db('soundcloud', username='root', password='')

db = Database(test_db)

user = clientS.get('/users/pierrock')
print(user.id)

userRepo = UserRepo(db=db)

#userRepo.sc_to_db(user)

#userObj = userRepo.from_db_by_id(str(user.id))
userObj = userRepo.from_db_by_username(user.username)
userObj.display()

#clientS.get('/users/'+str(user.id)+'/playlists')
pgsize=10
playlists = clientS.get('/users/21381146/playlists' , limit=pgsize)

for playlist in playlists :
    print(str(playlist.id) + " - " + playlist.title)

try:
       while playlists.next_href != None:
            playlists = client.get(playlists.next_href , limit=pgsize, order='id',
                linked_partitioning=1)
            for playlist in playlists :
                print(str(playlist.id) + " - " + playlist.title)

except AttributeError as e:
            print('Exception found!: ' + str(e))

#db = Database(test_db)

#trackRepo = TrackRepo(db=db)
#trackRepo.write(tracky)

#t = Track()
#t = Track(title='test', _key='12311', genre='pop', created_at=datetime(year=2016, month=9, day=12, hour=20, minute=30, second=10))
#t.convert(soundcloudTrack=tracky)
#db.add(t)

#print(t.title)


# -*- coding: utf-8 -*-
import argparse
import glob
import logging
import logging.handlers
import os
import platform
import sys
import traceback
import warnings
from datetime import datetime

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from wordcloud import WordCloud
from collections import Counter
import seaborn as sns
from urllib.parse import quote_plus
import configparser
import pymysql
import zipfile
import requests
import pytz
from sqlalchemy.dialects.mysql import insert
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, DateTime, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Float
from sqlalchemy.dialects.mysql import DOUBLE
from sqlalchemy import Table, Column, Integer, String, MetaData
from sqlalchemy import Column, Numeric
from sqlalchemy import create_engine, Table, MetaData
from sqlalchemy.dialects.mysql import insert as mysql_insert

# =================================================
# 사용자 매뉴얼
# =================================================
# [소스 코드의 실행 순서]
# 1. 초기 설정 : 폰트 설정
# 2. 유틸리티 함수 : 초기화 함수 (로그 설정, 초기 변수, 초기 전달인자 설정) 또는 자주 사용하는 함수
# 3. 주 프로그램 :부 프로그램을 호출
# 4. 부 프로그램 : 자료 처리를 위한 클래스로서 내부 함수 (초기 변수, 비즈니스 로직, 수행 프로그램 설정)
# 4.1. 환경 변수 설정 (로그 설정) : 로그 기록을 위한 설정 정보 읽기
# 4.2. 환경 변수 설정 (초기 변수) : 입력 경로 (inpPath) 및 출력 경로 (outPath) 등을 설정
# 4.3. 초기 변수 (Argument, Option) 설정 : 파이썬 실행 시 전달인자 설정 (pyhton3 *.py argv1 argv2 argv3 ...)
# 4.4. 비즈니스 로직 수행 : 단위 시스템 (unit 파일명)으로 관리 또는 비즈니스 로직 구현

# =================================================
# 1. 초기 설정
# =================================================
warnings.filterwarnings("ignore")

plt.rc('font', family='Malgun Gothic')
plt.rc('axes', unicode_minus=False)
# sns.set(font="Malgun Gothic", rc={"axes.unicode_minus": False}, style='darkgrid')

# 그래프에서 마이너스 글꼴 깨지는 문제에 대한 대처
mpl.rcParams['axes.unicode_minus'] = False

# =================================================
# 2. 유틸리티 함수
# =================================================
# 로그 설정
def initLog(env=None, contextPath=None, prjName=None):
    if env is None: env = 'local'
    if contextPath is None: contextPath = os.getcwd()
    if prjName is None: prjName = 'test'

    saveLogFile = "{}/{}_{}_{}_{}_{}_{}.log".format(
        contextPath if env in 'local' else os.path.join(contextPath, 'resources', 'log', prjName)
        , platform.system()
        , platform.machine()
        , platform.architecture()[0]
        , platform.node()
        , prjName
        , datetime.now().strftime("%Y%m%d")
    )

    os.makedirs(os.path.dirname(saveLogFile), exist_ok=True)

    # logger instance 생성
    log = logging.getLogger(prjName)

    if len(log.handlers) > 0:
        return log

    # format 생성
    format = logging.Formatter('%(asctime)s [%(name)s | %(lineno)d | %(filename)s] [%(levelname)-5.5s] %(message)s')

    # handler 생성
    streamHandler = logging.StreamHandler()
    fileHandler = logging.FileHandler(saveLogFile)

    # logger instance에 format 설정
    streamHandler.setFormatter(format)
    fileHandler.setFormatter(format)

    # logger instance에 handler 설정
    log.addHandler(streamHandler)
    log.addHandler(fileHandler)

    # logger instance로 log 기록
    log.setLevel(level=logging.INFO)

    return log

#  초기 변수 설정
def initGlobalVar(env=None, contextPath=None, prjName=None):
    if env is None: env = 'local'
    if contextPath is None: contextPath = os.getcwd()
    if prjName is None: prjName = 'test'

    # 환경 변수 (local, 그 외)에 따라 전역 변수 (입력 자료, 출력 자료 등)를 동적으로 설정
    # 즉 local의 경우 현재 작업 경로 (contextPath)를 기준으로 설정
    # 그 외의 경우 contextPath/resources/input/prjName와 같은 동적으로 구성
    globalVar = {
        'prjName': prjName
        , 'sysOs': platform.system()
        , 'contextPath': contextPath
        , 'resPath': contextPath if env in 'local' else os.path.join(contextPath, 'resources')
        , 'cfgPath': contextPath if env in 'local' else os.path.join(contextPath, 'resources', 'config')
        , 'inpPath': contextPath if env in 'local' else os.path.join(contextPath, 'resources', 'input', prjName)
        , 'figPath': contextPath if env in 'local' else os.path.join(contextPath, 'resources', 'fig', prjName)
        , 'outPath': contextPath if env in 'local' else os.path.join(contextPath, 'resources', 'output', prjName)
        , 'movPath': contextPath if env in 'local' else os.path.join(contextPath, 'resources', 'movie', prjName)
        , 'logPath': contextPath if env in 'local' else os.path.join(contextPath, 'resources', 'log', prjName)
        , 'mapPath': contextPath if env in 'local' else os.path.join(contextPath, 'resources', 'mapInfo')
        , 'sysPath': contextPath if env in 'local' else os.path.join(contextPath, 'resources', 'config', 'system.cfg')
        , 'seleniumPath': contextPath if env in 'local' else os.path.join(contextPath, 'resources', 'config', 'selenium')
        , 'fontPath': contextPath if env in 'local' else os.path.join(contextPath, 'resources', 'config', 'fontInfo')
    }

    return globalVar

#  초기 전달인자 설정
def initArgument(globalVar, inParams):
    # 원도우 또는 맥 환경
    if globalVar['sysOs'] in 'Windows' or globalVar['sysOs'] in 'Darwin':
        inParInfo = inParams

    # 리눅스 환경
    if globalVar['sysOs'] in 'Linux':
        parser = argparse.ArgumentParser()

        for i, argv in enumerate(sys.argv[1:]):
            if not argv.__contains__('--'): continue
            parser.add_argument(argv)

        inParInfo = vars(parser.parse_args())

    log.info("[CHECK] inParInfo : {}".format(inParInfo))

    for key, val in inParInfo.items():
        if val is None: continue
        # 전역 변수에 할당
        globalVar[key] = val

    # 전역 변수
    for key, val in globalVar.items():
        if env not in 'local' and key.__contains__('Path') and env and not os.path.exists(val):
            os.makedirs(val)

        globalVar[key] = val.replace('\\', '/')

        log.info("[CHECK] {} : {}".format(key, val))

        # self 변수에 할당
        # setattr(self, key, val)

    return globalVar

# ================================================
# 4. 부 프로그램
# ================================================
class DtaProcess(object):
    # ================================================
    # 요구사항
    # ================================================
    # Python을 이용한 국가별로 탄소 모니터링 비율 계산

    # ================================================================================================
    # 환경변수 설정
    # ================================================================================================
    global env, contextPath, prjName, serviceName, log, globalVar

    # env = 'local'  # 로컬 : 원도우 환경, 작업환경 (현재 소스 코드 환경 시 .) 설정
    env = 'dev'  # 개발 : 원도우 환경, 작업환경 (사용자 환경 시 contextPath) 설정
    # env = 'oper'  # 운영 : 리눅스 환경, 작업환경 (사용자 환경 시 contextPath) 설정

    if (platform.system() == 'Windows'):
        contextPath = os.getcwd() if env in 'local' else 'E:/04. TalentPlatform/Github/TalentPlatform-Python'
    else:
        contextPath = os.getcwd() if env in 'local' else '/SYSTEMS/PROG/PYTHON/PyCharm'

    prjName = 'test'
    serviceName = 'LSH0456'

    # 4.1. 환경 변수 설정 (로그 설정)
    log = initLog(env, contextPath, prjName)

    # 4.2. 환경 변수 설정 (초기 변수)
    globalVar = initGlobalVar(env, contextPath, prjName)

    # ================================================================================================
    # 4.3. 초기 변수 (Argument, Option) 설정
    # ================================================================================================
    def __init__(self, inParams):

        log.info("[START] __init__ : {}".format("init"))

        try:
            # 초기 전달인자 설정 (파이썬 실행 시)
            # pyhton3 *.py argv1 argv2 argv3 ...
            initArgument(globalVar, inParams)

        except Exception as e:
            log.error("Exception : {}".format(e))
            raise e
        finally:
            log.info("[END] __init__ : {}".format("init"))

    # ================================================================================================
    # 4.4. 비즈니스 로직 수행
    # ================================================================================================
    def exec(self):

        log.info('[START] {}'.format("exec"))

        try:

            if platform.system() == 'Windows':
                pass
            else:
                globalVar['inpPath'] = '/DATA/INPUT'
                globalVar['outPath'] = '/DATA/OUTPUT'
                globalVar['figPath'] = '/DATA/FIG'
                globalVar['updPath'] = '/DATA/CSV'

            # 옵션 설정
            sysOpt = {
            }

            # *********************************************************************************
            # 파일 검색
            # *********************************************************************************
            sectorList = ['Coal', 'Oil', 'Gas']
            countryList = ['Japan', 'Russia', 'Australia', 'US', 'Mexico', 'Chile', 'Brazil', 'South Africa', 'UK', 'Germany', 'Italy', 'France', 'Spain', 'EU27 & UK', 'India', 'China']

            # inpFile = '{}/{}/{}'.format(globalVar['inpPath'], serviceName, 'carbon-monitor-Power-maingraphdatas.xlsx')
            inpFile = '{}/{}/{}'.format(globalVar['inpPath'], serviceName, 'energy_global_datas_2023-07-20.csv')
            fileList = sorted(glob.glob(inpFile))

            # data = pd.read_excel(fileList[0])
            data = pd.read_csv(fileList[0])
            dataL1 = data.dropna()

            dataL1['dtDate'] = pd.to_datetime(data['date'], format='%d/%m/%Y')

            dataL2 = dataL1[dataL1['sector'].isin(sectorList)].reset_index(drop=True)

            # statData = dataL2.groupby(['country', 'dtDate'])['GWh'].sum().reset_index().rename(columns={'GWh': 'sumGWh'})
            statData = dataL2.groupby(['country', 'dtDate'])['value'].sum().reset_index().rename(columns={'value': 'sumVal'})

            dataL3 = dataL2.merge(statData, left_on=['country', 'dtDate'], right_on=['country', 'dtDate'], how='left')
            # dataL3['rat'] = dataL3['GWh'] /  dataL3['sumGWh']
            dataL3['rat'] = dataL3['value'] /  dataL3['sumVal']

            # 정렬
            pivotData = dataL3.pivot_table(index='dtDate', columns=['sector', 'country'], values='rat')
            pivotDataL1 = pivotData.reindex(countryList, level=1, axis=1)
            pivotDataL2 = pivotDataL1.reindex(sectorList, level=0, axis=1)

            idx = pd.date_range('2019-01-01', '2023-05-31')
            pivotDataL3 = pivotDataL2.reindex(idx)

            saveFile = '{}/{}/{}.xlsx'.format(globalVar['outPath'], serviceName, '국가별로 탄소 모니터링 비율')
            os.makedirs(os.path.dirname(saveFile), exist_ok=True)
            pivotDataL3.to_excel(saveFile, index=True)
            log.info(f'[CHECK] saveFile : {saveFile}')

        except Exception as e:
            log.error("Exception : {}".format(e))
            raise e
        finally:
            log.info('[END] {}'.format("exec"))

# ================================================
# 3. 주 프로그램
# ================================================
if __name__ == '__main__':

    print('[START] {}'.format("main"))

    try:

        # 파이썬 실행 시 전달인자를 초기 환경변수 설정
        inParams = {}

        print("[CHECK] inParams : {}".format(inParams))

        # 부 프로그램 호출
        subDtaProcess = DtaProcess(inParams)

        subDtaProcess.exec()

    except Exception as e:
        print(traceback.format_exc())
        sys.exit(1)

    finally:
        print('[END] {}'.format("main"))


from math import radians, cos, sin, asin, sqrt
import os

def readFile(nama_file) :
    simpul = [] # Menyimpan list tuple dengan tuple (latitude, longitude, nama simpul)
    matrix = [] # Menyimpan adjacency matrix
    # Membaca file
    filepath = os.path.join('..\\test', nama_file)
    with open(filepath) as f:
        lines = f.readlines()

    lineNumber = 0
    nodeCount = 0
    for line in lines:
        # lineNumber == 0 membaca jumlah node
        if (lineNumber == 0) :
            nodeCount = int(line)
        else :
            # Kasus membaca simpul
            if (lineNumber < nodeCount + 1) :
                temp = line.split()
                temp[0] = float(temp[0])
                temp[1] = float(temp[1])
                simpul.append(temp)
            # Kasus membaca adjacency matrix
            else :
                temp = line.split()
                for i in range (len(temp)) :
                    temp[i] = int(temp[i])
                matrix.append(temp)
        lineNumber += 1
    return simpul,matrix,nodeCount

# Mencari indeks dari suatu nama tempat di array simpul
def searchPos(namaTempat) :
    found = False
    for i in range (len(simpul)) :
        if (simpul[i][2] == namaTempat) :
            return i
    if(not found) :
        return -1

# Mengubah adjacency matrix dari berisi boolean menjadi berisi weighted
def changeMatrix() :
    for i in range(nodeCount) :
        for j in range(i, nodeCount) :
            if(matrix[i][j] != 0) :
                temp = haversine(searchPos(simpul[i][2]), searchPos(simpul[j][2]))
                matrix[i][j] = temp
                matrix[j][i] = temp

# Menghitung jarak antara dua titik di bumi dengan
# menggunakan garis lintang dan garis bujur
def haversine(pos1, pos2):
    # Mengubah titik desimal menjadi radian
    lat1, lon1 = simpul[pos1][0], simpul[pos1][1]
    lat2, lon2 = simpul[pos2][0], simpul[pos2][1]
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # Rumus perhitungan haversine
    # r merupakan radius bumi dalam satuan kilometer
    r = 6371
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    h = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    x = asin(sqrt(h))
    result = 2 * x * r
    return result

def aStar(start, goal) :
    # Inisiasi
    stack = []  # Stack yang menyimpan jalur yang dilalui (jalur terpendek disimpan disini)
    visitedNodes = [] # Array boolean, menyimpan nodes yang sudah dilewati
    currNode = start    # Node saat ini
    stack.append(start)
    dFromStart = 0 # Jarak dari simpul asal
    found = False # Boolean yang mengecek apakah sudah mencapai simpul tujuan

    # Loop selama stack tidak kosong dan simpul tujuan belum ditemukan
    while(len(stack) > 0 and found == False) :
        # Inisialisasi nilai
        # nilai fungsi evaluasi paling minimal
        min = None
        minPos = None
        # boolean untuk mengecek apakah merupakann tetangga pertama yang ditemukan
        isFirst = True
        i = 0
        # boolean untuk mengecek apakah suatu node masih memiliki tetangga
        # yang belum dikunjungi
        neighbour = False

        # Loop selama jumlah iterasi tidak melebihi jumlah node
        while(i < nodeCount) :
            # Kasus ditemukan sisi yang nilainya tidak nol dan belum  pernah dikunjungi
            if ((matrix[searchPos(currNode)][i] != 0) and (simpul[i][2] not in visitedNodes)) :
                # Kasus sisi yang memenuhi syarat sebelumnya ditemukan pertama kalinya
                if (isFirst) :
                    isFirst = False
                    minPos = i
                    min = evalFunc(dFromStart, currNode, simpul[i][2], goal)
                # Kasus sisi ditemukannya sisi setelah sisi pertama
                else :
                    # Kasus ditemukannya fungsi evaluasi yang lebih minimal
                    if (min > evalFunc(dFromStart, currNode, simpul[i][2], goal)) :
                        minPos = i
                        min = evalFunc(dFromStart, currNode, simpul[i][2], goal)
                # Menandakan mempunyai tetangga yang belum pernah dikunjungi
                neighbour = True
            i+=1
        # Kasus sudah tidak mempunyai tetangga yang belum pernah dikunjungi
        if (neighbour == False) :
            # Memasukkan currNode ke boolean visitedNodes (menandakan sudah dikunjungi)
            if (currNode not in visitedNodes) :
                visitedNodes.append(currNode)
            # Melakukan backtrack
            temp = stack.pop()
            if (len(stack) > 0) :
                # Mengurangi jarak dari simpul asal yang dicatat (karena backtrack, jadi mundur ke simpul sebelumnya)
                dFromStart -= haversine(searchPos(temp), searchPos(stack[len(stack) - 1]))
                # Backtrack untuk currNode
                currNode = stack[len(stack) - 1]
        else :
            # Push simpul dengan evaluation function paling minimal
            stack.append(simpul[minPos][2])
            # Memasukkan currNode ke boolean visitedNodes (menandakan sudah dikunjungi)
            if (currNode not in visitedNodes) :
                visitedNodes.append(currNode)
            # Menambah jarak dari simpul asal
            dFromStart = gn(dFromStart, currNode, simpul[minPos][2])
            # Mengubah currNode ke simpul dengan evaluation function paling minimal
            currNode = simpul[minPos][2]
        # Kasus simpul tujuan ditemukan
        if (currNode == goal) :
            found = True
    # Kasus stack kosong, artinya tidak ditemukan jalur
    # antara simpul asal dan simpul tujuan
    if (len(stack) == 0) :
        # Set jarak dari simpul asal ke simpul tujuan menjadi 0
        dFromStart = 0
    return dFromStart, stack

# Menghitung fungsi evaluasi dengan rumus f(n) = g(n) + h(n)
def evalFunc (dFromStart, currNode, exploreNode, goal) :
    fn = gn (dFromStart, currNode, exploreNode) + hn(exploreNode, goal)
    return fn

# g(n) merupakan fungsi yang menghitung total
# jarak dari simpul awal menuju exploreNode
def gn (dFromStart, currNode, exploreNode) :
    result = dFromStart + matrix[searchPos(currNode)][searchPos(exploreNode)]
    return result

# h(n) merupakan fungsi yang menghitung jarak
# garis lurus dari exploreNode menuju simpul tujuan
def hn (exploreNode, goal) :
    return haversine (searchPos(exploreNode), searchPos(goal))

# Main Program
# Input file kasus uji
kasusUji = input("Masukkan nama file kasus uji: ")
# Mengolah input kasus uji
simpul, matrix, nodeCount = readFile(kasusUji)
# Mencetak semua simpul yang ada
print("List simpul: ")
no = 1
for node in simpul :
    print(no, end="")
    print(".", end="")
    print(node[2])
    no += 1
# Mengubah adjacency matrix yang berisi boolean menjadi
# berisi bobot sisi antar simpul
changeMatrix()
#Menerima input simpul asal dan simpul tujuan
startNode = int(input("No simpul asal: "))
goalNode = int(input("No simpul tujuan: "))

# Menjalankan algoritma A*
distance, shortestPath = aStar(simpul[startNode - 1][2], simpul[goalNode - 1][2])
# Kasus terdapat lintasan terpendek antara simpul asal dan tujuan
if (len(shortestPath) != 0) :
    print("Jarak lintasan terpendek antara " + simpul[startNode - 1][2] + " dan " + simpul[goalNode - 1][2]
            + " adalah " + str(distance) + " km")
# Kasus tidak terdapat lintasan antara simpul asal dan tujuan
else :
    print("Tidak terdapat lintasan antara " + simpul[startNode - 1][2] + " dan " + simpul[goalNode - 1][2])


"""
http客户端request的使用
"""

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132'
}
proxies = {
    'http': '176.235.99.13:9090'
}

def _get_():
    resp = requests.get('https://github.com/xiaokexiang', headers=headers, proxies=proxies)
    # 指定响应编码
    print('请求响应的编码： ', resp.encoding)
    with open('github.html', 'w', encoding=resp.encoding) as f:
        f.write(resp.text)

def _session_():
    session = requests.session()  # 某些共性接口使用同一个session，避免多次指定参数或header
    session.headers = headers
    session.proxies = proxies
    resp = session.get('https://github.com/xiaokexiang')
    print(resp.text)

_session_()


#!/usr/bin/env python

import re

import click
import pandas as pd

def extract_articleID_and_filename(record):
    record_items = record.split("\n")
    ref_id = "@" + re.search("{(.+?),", record_items[0]).group(1)
    item_file = [x for x in record_items if x.startswith("\tfile = {")]
    if len(item_file) > 0:
        item_file = item_file[0]
        notion_Name = re.search(
            r"\tfile = {(.+?).pdf:/Users", item_file, re.IGNORECASE
        ).group(1)
    else:
        notion_Name = None

    return ref_id, notion_Name

@click.command()
@click.option("--notion_draft", "-i", help="Notion exported markdown file")
@click.option("--bibtex", "-r", help="Zotero exported bibtex file")
@click.option("--manuscript", "-o", help="Output file in markdown format")
def main(notion_draft, bibtex, manuscript):
    with open(bibtex) as fh:
        ref = fh.read()
        items = [x for x in ref.split("\n@") if len(x) > 10]

    rst = []
    for record in items:
        ref_id, notion_Name = extract_articleID_and_filename(record)
        if notion_Name != None:
            rst += [[ref_id, notion_Name, record]]

    df = pd.DataFrame(rst, columns=["ref_id", "notion_Name", "bibtex_rec"])
    recs = df.to_dict(orient="records")

    # replace in draft
    with open(notion_draft) as fh:
        draft = fh.read()
        draft = re.sub(r"\(https://www.notion.so/[\w\"\'+-]*\)", "", draft)

    references = []
    for rec in recs:
        if rec["notion_Name"] in draft:
            draft = draft.replace(rec["notion_Name"], rec["ref_id"])
            references.append("@" + rec["bibtex_rec"])

    draft = re.sub(r"\],[\s]+\[@", "; @", draft)

    # Add header
    header = f"""---\ntitle: "Title"\noutput: word_document\nbibliography: {bibtex}\n---\n\n"""
    draft = header + draft + "\n\n# References\n"
    with open(manuscript, "w") as fh:
        fh.write(draft)

    with open(manuscript + ".bibtex", "w") as fh:
        fh.write("\n".join(references))

if __name__ == "__main__":
    main()


from typing import Generator, List, Optional
from datetime import datetime, timedelta
import tracemalloc

import pandas as pd
import numpy as np
from pandas.core.generic import json
import torch
from sklearn.preprocessing import StandardScaler

import sys

sys.path.append(".")
from common.custom_logger import CustomLogger  # noqa: E402
from common.config import GridSize, MinMaxScalingValue  # noqa: E402

logger = CustomLogger("utils_Logger")

def calc_u_v(df: pd.DataFrame, ob_point: str) -> list:
    """Calculate u, v wind from wind direction and wind speed of PPOTEKA `one_day_data`

    Args:
        df (pd.DataFrame): The row of the `one_day_data` at the given observation point.
        ob_point (str): The target opservation point name.

    Returns:
        list: [index, u wind, v wind] (u: X (East-West) v: Y(North-South))
    """
    wind_dir = float(df["WD1"])
    wind_speed = float(df["WS1"])

    rads = np.radians(float(wind_dir))
    wind_u, wind_v = -1 * wind_speed * np.cos(rads), -1 * wind_speed * np.sin(rads)
    # wind_u_v = wind_components(wind_speed * units("m/s"), wind_dir * units.deg)

    return [
        ob_point,
        round(wind_u, 5),
        round(wind_v, 5),
    ]  # (index, u wind, v wind) u: X (East-West) v: Y(North-South)

def get_mlflow_tag_from_input_parameters(input_parameters: list) -> str:
    """Generate mlflow tag from input parameters."""
    tag_str = ""
    for p in input_parameters:
        tag_str += p[0].upper() + p[0:]
    return tag_str

def split_input_parameters_str(input_parameters_str: str) -> list:
    """Split input parameters string (formatted like 'a/b/c') with slash"""
    return input_parameters_str.split("/")

def datetime_range(start: datetime, end: datetime, delta: timedelta) -> Generator[datetime, None, None]:
    """Create the list of datetime objects with a given step.
    Args:
        start (datetime): Starting datetime.
        end (datetime): End datatime.
        delta (timedelta): The time step.
    """
    current = start
    while current <= end:
        yield current
        current += delta

def convert_two_digit_date(x: str) -> str:
    """Format string of digit like dd."""
    if len(str(x)) == 2:
        return str(x)
    else:
        return "0" + str(x)

def timestep_csv_names(year: int = 2020, month: int = 1, date: int = 1, time_step_minutes: int = 10) -> List[str]:
    """Generate time step csv file names."""
    dts = [
        f"{dt.hour}-{dt.minute}.csv"
        for dt in datetime_range(
            datetime(year, month, date, 0), datetime(year, month, date, 23, 59), timedelta(minutes=time_step_minutes)
        )
    ]
    return dts

def format_bytes(size: int) -> str:
    power = 2**10
    n = 0
    power_labels = ["B", "KB", "MB", "GB", "TB"]
    while size > power and n <= len(power_labels):
        size /= power
        n += 1
    return f"current used memory: {size} {power_labels[n]}"

def log_memory() -> None:
    snapshot = tracemalloc.take_snapshot()
    size = sum([stat.size for stat in snapshot.statistics("filename")])
    print(format_bytes(size))

def min_max_scaler(min_value: float, max_value: float, arr: np.ndarray) -> np.ndarray:
    return (arr - min_value) / (max_value - min_value)

def rescale_tensor(min_value: float, max_value: float, tensor: torch.Tensor):
    return ((max_value - min_value) * tensor + min_value).to(dtype=torch.float)

def load_standard_scaled_data(path: str) -> np.ndarray:
    df = pd.read_csv(path, index_col=0, dtype=np.float32)
    scaler = StandardScaler()
    return scaler.fit_transform(df.values)

# return: ndarray
def load_scaled_data(path: str) -> np.ndarray:
    """Load the pd.DataFrame with a given file path and min-max scale it."""
    if path.endswith(".csv"):
        df = pd.read_csv(path, index_col=0, dtype=np.float32)
    elif path.endswith(".parquet.gzip"):
        df = pd.read_parquet(path)
    else:
        raise ValueError(f"Data file shoud be csv or parquet.gzip. (Given path is {path})")

    if "rain" in path:
        # df = df + 50
        # Scale [0, 100]
        return min_max_scaler(MinMaxScalingValue.RAIN_MIN, MinMaxScalingValue.RAIN_MAX, df.values)

    elif "temp" in path:
        # Scale [10, 45]
        return min_max_scaler(MinMaxScalingValue.TEMPERATURE_MIN, MinMaxScalingValue.TEMPERATURE_MAX, df.values)

    elif "abs_wind" in path:
        nd_arr = np.where(df > MinMaxScalingValue.ABS_WIND_MAX, MinMaxScalingValue.ABS_WIND_MAX, df)
        return min_max_scaler(MinMaxScalingValue.ABS_WIND_MIN, MinMaxScalingValue.ABS_WIND_MAX, nd_arr)

    elif "wind" in path:
        # Scale [-10, 10]
        return min_max_scaler(MinMaxScalingValue.WIND_MIN, MinMaxScalingValue.WIND_MAX, df.values)

    elif "humidity" in path:
        return min_max_scaler(MinMaxScalingValue.HUMIDITY_MIN, MinMaxScalingValue.HUMIDITY_MAX, df.values)

    elif "pressure" in path:
        return min_max_scaler(
            MinMaxScalingValue.SEALEVEL_PRESSURE_MIN, MinMaxScalingValue.SEALEVEL_PRESSURE_MAX, df.values
        )
    else:
        raise ValueError(f"Invalid data path: {path}")

def param_date_path(param_name: str, year, month, date) -> Optional[str]:
    """Generate the data folder path of a given parameter and datetime."""
    if "rain" in param_name:
        return f"data/rain_image/{year}/{month}/{date}"
    elif "abs_wind" in param_name:
        return f"data/abs_wind_image/{year}/{month}/{date}"
    elif "wind" in param_name:
        return f"data/wind_image/{year}/{month}/{date}"
    elif "temperature" in param_name:
        return f"data/temp_image/{year}/{month}/{date}"
    elif "humidity" in param_name:
        return f"data/humidity_image/{year}/{month}/{date}"
    elif "station_pressure" in param_name:
        return f"data/station_pressure_image/{year}/{month}/{date}"
    elif "seaLevel_pressure" in param_name:
        return f"data/seaLevel_pressure_image/{year}/{month}/{date}"
    else:
        raise ValueError(f"Invalid param name: {param_name}")

def create_time_list(year: int = 2020, month: int = 1, date: int = 1, delta: int = 10) -> List[datetime]:
    """Create time list of a given date and time step."""
    dts = [
        dt
        for dt in datetime_range(
            datetime(year, month, date, 0), datetime(year, month, date, 23, 59), timedelta(minutes=delta)
        )
    ]
    return dts

def get_ob_point_values_from_tensor(tensor: torch.Tensor, observation_point_file_path: str) -> torch.Tensor:
    """
    This function extract observation point values of a given tensor (gridded p-poteka data).

    Args:
        tensor(torch.Tensor): A gridded p-poteka data of one weather para,eter.
    Returns:
        (torch.Tensor): observation point values with the shape of (Number of observation point)
    """
    with open(observation_point_file_path, "r") as f:
        ob_point_data = json.load(f)
    ob_point_lons = [item["longitude"] for _, item in ob_point_data.items()]
    ob_point_lats = [item["latitude"] for _, item in ob_point_data.items()]

    grid_lons = np.linspace(120.90, 121.150, GridSize.WIDTH)
    grid_lats = np.linspace(14.350, 14.760, GridSize.HEIGHT)[
        ::-1
    ]  # Flip grid latitudes because the latitudes are in descending order.

    ob_point_values = torch.zeros((len(ob_point_lons)), dtype=torch.float)
    # Extract 9 data points in grid data near the each observation points.
    for ob_point_idx, (target_lon, target_lat) in enumerate(zip(ob_point_lons, ob_point_lats)):
        target_lon_idx, target_lat_idx = 0, 0
        for before_lon, next_lon in zip(grid_lons[:-1], grid_lons[1:]):
            target_lon_idx, target_lat_idx = 0, 0
            if before_lon < target_lon and target_lon < next_lon:
                target_lon_idx = np.where(grid_lons == before_lon)[0][0]
                break
        for next_lat, before_lat in zip(grid_lats[:-1], grid_lats[1:]):  # `grid_lats` is in descending order.
            if before_lat < target_lat and target_lat < next_lat:
                target_lat_idx = np.where(grid_lats == before_lat)[0][0]
                break
        if target_lon_idx == 0 or target_lon_idx == 0:
            raise ValueError(
                "longitude or latitude is too small for the "
                "area of longigude (120.90, 120,150) and latitude (14.350, 14.760)"
            )

        if target_lon_idx == len(grid_lons) - 1 or target_lon_idx == len(grid_lats) - 1:
            raise ValueError(
                "longitude or latitude is too big for the "
                "area of longigude (120.90, 120,150) and latitude (14.350, 14.760)"
            )
        # Extract values from gird data (tensor)
        ob_point_values[ob_point_idx] = (
            tensor[target_lat_idx - 1 : target_lat_idx + 2, target_lon_idx - 1 : target_lon_idx + 2].mean().item()
        )
    return ob_point_values

if __name__ == "__main__":
    tensor = torch.ones((50, 50))
    result = get_ob_point_values_from_tensor(tensor)
    print(result)


resp = 1
idados = [0,0]
gdados = [0,0]
empates = 0
grenais = 0
igol = 0
ggol = 0

while resp != 2 and resp == 1:
    gols = str(input()).split()
    igol = int(gols[0])
    ggol = int(gols[1])

    if igol > ggol:
        idados[0] += 1
        gdados[1] += 1
    elif igol < ggol:
        idados[1] += 1
        gdados[0] += 1
    else:
        empates += 1

    grenais += 1

    resp = int(input('Novo grenal (1-sim 2-nao)\n'))

print('{} grenais'.format(grenais))
print('Inter:{}'.format(idados[0]))
print('Gremio:{}'.format(gdados[0]))
print('Empates:{}'.format(empates))

if idados[0] > gdados[0]:
    print('Inter venceu mais')
elif idados[0] < gdados[0]:
    print('Gremio venceu mais')
else:
    print('Nao houve vencedor')


import numpy as np
from gym import spaces

from brains.ffnn import FeedForwardNumPy, FeedForwardPyTorch

class TestIBrain:
    low = -5.0
    high = 5.0
    one_dimensional_shape = (20,)
    rgb_shape = (3, 32, 32)
    multi_dimensional_shape = (30, 15)
    input_n = 50
    output_n = 10

    def test_parse_box_space(self, ffnn_config):
        input_space = spaces.Box(low=self.low, high=self.high, shape=self.one_dimensional_shape)
        output_space = spaces.Box(low=self.low, high=self.high, shape=self.multi_dimensional_shape)

        # First test the input space
        # Not used but needed to create a Brain
        dummy_individual = np.zeros((FeedForwardNumPy.get_individual_size(
            ffnn_config, input_space=input_space, output_space=output_space)))

        brain = FeedForwardPyTorch(input_space=input_space, output_space=output_space, individual=dummy_individual,
                                   config=ffnn_config)

        sample_input = np.ones(input_space.shape)
        assert input_space.contains(sample_input)
        parsed_input = brain.parse_brain_input(sample_input)

        # When input_space == spaces.Box the input is not transformed
        assert np.array_equal(sample_input, parsed_input)

        # Now test the output space
        brain_output = brain.step(sample_input)

        assert brain_output.shape == output_space.shape

    def test_parse_rgb_input(self, ffnn_config):
        # Environments with RGB observations usually use spaces.Box as their observation space, which means it is
        # the input space for the brains
        input_space = spaces.Box(low=self.low, high=self.high, shape=self.rgb_shape)
        output_space = spaces.Box(low=self.low, high=self.high, shape=self.one_dimensional_shape)

        # First test the input space
        # Not used but needed to create a Brain
        dummy_individual = np.zeros((FeedForwardNumPy.get_individual_size(
            ffnn_config, input_space=input_space, output_space=output_space)))

        brain = FeedForwardPyTorch(input_space=input_space, output_space=output_space, individual=dummy_individual,
                                   config=ffnn_config)

        sample_input = np.ones(input_space.shape)
        assert input_space.contains(sample_input)
        # Assume now we have RGB input space, in our flatten function this should return a multidimensional NumPy array
        parsed_input = brain.parse_brain_input(sample_input)

        # When input_space == spaces.Box the input is not transformed
        assert np.array_equal(sample_input, parsed_input)
        assert (isinstance(parsed_input, np.ndarray) and len(
            parsed_input.shape) == 3 and parsed_input.shape == sample_input.shape)

    def test_parse_discrete_space(self, ffnn_config):
        input_space = spaces.Discrete(n=self.input_n)
        output_space = spaces.Discrete(n=self.output_n)

        dummy_individual = np.zeros((FeedForwardNumPy.get_individual_size(
            ffnn_config, input_space=input_space, output_space=output_space)))

        brain = FeedForwardPyTorch(input_space=input_space, output_space=output_space, individual=dummy_individual,
                                   config=ffnn_config)

        # Test input space
        sample_input = 1
        assert input_space.contains(sample_input)
        parsed_input = brain.parse_brain_input(sample_input)

        # Parsed Input should be one-hot encoded
        assert len(parsed_input.shape) == 1
        assert len(parsed_input) == input_space.n
        assert all(x == 0 for x in parsed_input[:sample_input])
        assert parsed_input[sample_input] == 1
        assert all(x == 0 for x in parsed_input[sample_input + 1:])

        # Test output space
        brain_output = brain.step(sample_input)

        # This should be an Integer in [0, output_space.n - 1]
        assert isinstance(brain_output, np.integer)
        assert 0 <= brain_output < output_space.n

    def test_parse_tuple_space(self, ffnn_config):
        # Prepare some spaces to test the Tuple space
        one_dimensional_box = spaces.Box(low=self.low, high=self.high, shape=self.one_dimensional_shape)
        multi_dimensional_box = spaces.Box(low=self.low, high=self.high, shape=self.multi_dimensional_shape)
        first_discrete = spaces.Discrete(n=self.input_n)
        second_discrete = spaces.Discrete(n=self.output_n)

        input_space = spaces.Tuple([one_dimensional_box, first_discrete, multi_dimensional_box, second_discrete])
        output_space = spaces.Tuple([second_discrete, multi_dimensional_box, one_dimensional_box, first_discrete])

        dummy_individual = np.zeros((FeedForwardNumPy.get_individual_size(
            ffnn_config, input_space=input_space, output_space=output_space)))

        brain = FeedForwardPyTorch(input_space=input_space, output_space=output_space, individual=dummy_individual,
                                   config=ffnn_config)

        # Test input space
        sample_input = (np.ones(self.one_dimensional_shape), 1, np.ones(self.multi_dimensional_shape) * 2, 2)
        assert input_space.contains(sample_input)
        parsed_input = brain.parse_brain_input(sample_input)
        assert len(parsed_input.shape) == 1
        assert spaces.flatdim(input_space) == len(parsed_input)

        # Test output space
        brain_output = brain.step(sample_input)

        # 4 nested spaces inside the input space
        assert len(brain_output) == 4

        # First nested space is second_discrete
        nested_output = brain_output[0]
        assert isinstance(nested_output, np.integer)

        # Second nested space is multi_dimensional_box
        nested_output = brain_output[1]
        assert len(nested_output.shape) == len(self.multi_dimensional_shape)
        assert all([x == y for (x, y) in zip(nested_output.shape, self.multi_dimensional_shape)])

        # Third nested space is one_dimensional_box
        nested_output = brain_output[2]
        assert len(nested_output.shape) == len(self.one_dimensional_shape)
        assert all([x == y for (x, y) in zip(nested_output.shape, self.one_dimensional_shape)])

        # Fourth nested space is first_discrete
        nested_output = brain_output[3]
        assert isinstance(nested_output, np.integer)


import logging
from asyncio import Event
from socket import AF_INET, SOCK_STREAM, socket
from threading import Thread

from utils.utils_socket import get_socket

class ChatPeer:
    def __init__(self, type: str, name: str, id: str):
        self.type = type
        self.name = name
        self.id = id

        type = type.upper()
        if type in ['SERVER', 'CLIENT']:
            self.type = type
        else:
            raise NotImplementedError("Argument 'type' must be either 'SERVER' or 'CLIENT'.")

        self.identify_string = f"{ self.type } { self.name }({ self.id })"

class SendThread(Thread):
    def __init__(self, conn_socket: socket, msg_str: str, handler=None, fail_handler=None):
        super().__init__()

        self.conn_socket = conn_socket
        self.msg_str = msg_str
        self.handler = handler
        self.fail_handler = fail_handler

    def run(self):
        try:
            self.conn_socket.send(self.msg_str.encode('utf-8'))
            logging.info(f"Sent message to { self.conn_socket.getpeername() }")

            if self.handler is not None:
                self.handler(self.conn_socket)
        except Exception as ex:
            logging.error(f"Failed to send message. { ex }")
            if self.fail_handler is not None:
                self.fail_handler(None)


import pytest
from unittest import mock
from app.db.models import Model
from app.module.logic import Logic
from app.module.model_classes import MODEL_CLASSES

@mock.patch('app.db.database.sessionmaker')
def test_get_model_classes_not_empty(mock_sessionmaker: mock.MagicMock):
    logic = Logic(mock_sessionmaker)
    assert len(logic.get_model_classes()) > 0

@mock.patch('app.db.database.sessionmaker')
def test_fit_model_bad_model_type_raise_exception(mock_sessionmaker: mock.MagicMock):
    logic = Logic(mock_sessionmaker)
    with pytest.raises(FileNotFoundError):
        logic.fit_model('Bad model type', {}, [], [])

@mock.patch('app.db.database.sessionmaker')
def test_fit_model_add_new_model(mock_sessionmaker: mock.MagicMock):
    model_class = list(MODEL_CLASSES.keys())[0]
    model_class_object = list(MODEL_CLASSES.values())[0]
    mock_sessionmaker.execute.return_value.fetchall.return_value = []

    logic = Logic(mock_sessionmaker)
    new_model = logic.fit_model(model_class, {}, [[1, 2, 3], [2, 2, 3], [3, 2, 1]], [1, 2, 3])

    assert new_model['model_type'] == str(model_class)
    assert new_model['model_name'] == str(model_class_object())

@mock.patch('app.db.database.sessionmaker')
def test_fit_model_refit_exist_model(mock_sessionmaker: mock.MagicMock):
    model_class = list(MODEL_CLASSES.keys())[0]
    model_class_object = list(MODEL_CLASSES.values())[0]
    mock_exist_object = Model(id=1, model_type=str(model_class), model_name=str(model_class_object()), model_data=b'')
    mock_sessionmaker.execute.return_value.fetchall.return_value = [mock_exist_object]

    logic = Logic(mock_sessionmaker)
    new_model = logic.fit_model(model_class, {}, [[1, 2, 3], [2, 2, 3], [3, 2, 1]], [1, 2, 3])

    assert new_model['id'] == mock_exist_object.id
    assert new_model['model_type'] == mock_exist_object.model_type
    assert new_model['model_name'] == mock_exist_object.model_name


from collections import deque

# 로봇이 이동가능한 위치인지 확인
def can_move(board, visited, location1, location2, size):
    # 이동 위치가 지도 밖인 경우 통과
    if not (0 <= location1[1] < size and 0 <= location1[0] < size and 0 <= location2[1] < size and 0 <= location2[0] < size):
        return False
    # 이동 위치에 벽이 존재하는 경우 통과
    if board[location1[0]][location1[1]] == 1 or board[location2[0]][location2[1]] == 1:
        return False
    # 이동 위치가 이미 방문한 위치인 경우 통과
    if ((location1[0], location1[1]), (location2[0], location2[1])) in visited or ((location2[0], location2[1]), (location1[0], location1[1])) in visited:
        return False
    return True

# 방문할 위치에 추가
def push_queue(queue, visited, next_location1, next_location2, next_time):
    queue.append((next_location1, next_location2, next_time))  # 방문할 위치에 추가
    visited.append((next_location1, next_location2))  # 방문 처리

# 로봇 한 칸 이동
def move_robot(board, visited, queue, location1, location2, time, size):
    dx, dy = [1, 0, -1, 0], [0, 1, 0, -1]
    # 상, 하, 좌, 우로 이동
    for d in range(4):
        nx1, ny1 = location1[1] + dx[d], location1[0] + dy[d]
        nx2, ny2 = location2[1] + dx[d], location2[0] + dy[d]
        # 이동할 위치가 맞는지 확인 후 맞다면 이동할 위치 추가
        if can_move(board, visited, (ny1, nx1), (ny2, nx2), size):
            push_queue(queue, visited, (ny1, nx1), (ny2, nx2), time + 1)

# 로봇 회전
def rotate_robot(board, visited, queue, location1, location2, time, size):
    # 로봇이 가로로 배치된 경우
    if location1[0] == location2[0]:
        # location1을 축으로 시계방향으로 회전이 가능한 경우 회전
        if can_move(board, visited, (location1[0], location1[1]), (location1[0] + 1, location1[1]), size) and board[location2[0] + 1][location2[1]] == 0:
            push_queue(queue, visited, (location1[0], location1[1]), (location1[0] + 1, location1[1]), time + 1)
        # location1을 축으로 반시계방향으로 회전이 가능한 경우 회전
        if can_move(board, visited, (location1[0], location1[1]), (location1[0] - 1, location1[1]), size) and board[location2[0] - 1][location2[1]] == 0:
            push_queue(queue, visited, (location1[0], location1[1]), (location1[0] - 1, location1[1]), time + 1)
        # location2을 축으로 시계방향으로 회전이 가능한 경우 회전
        if can_move(board, visited, (location2[0] - 1, location2[1]), (location2[0], location2[1]), size) and board[location1[0] - 1][location1[1]] == 0:
            push_queue(queue, visited, (location2[0] - 1, location2[1]), (location2[0], location2[1]), time + 1)
        # location2을 축으로 반시계방향으로 회전이 가능한 경우 회전
        if can_move(board, visited, (location2[0] + 1, location2[1]), (location2[0], location2[1]), size) and board[location1[0] + 1][location1[1]] == 0:
            push_queue(queue, visited, (location2[0] + 1, location2[1]), (location2[0], location2[1]), time + 1)
    # 로봇이 세로로 배치된 경우
    else:
        # location1을 축으로 시계방향으로 회전이 가능한 경우 회전
        if can_move(board, visited, (location1[0], location1[1]), (location1[0], location1[1] - 1), size) and board[location2[0]][location2[1] - 1] == 0:
            push_queue(queue, visited, (location1[0], location1[1]), (location1[0], location1[1] - 1), time + 1)
        # location1을 축으로 반시계방향으로 회전이 가능한 경우 회전
        if can_move(board, visited, (location1[0], location1[1]), (location1[0], location1[1] + 1), size) and board[location2[0]][location2[1] + 1] == 0:
            push_queue(queue, visited, (location1[0], location1[1]), (location1[0], location1[1] + 1), time + 1)
        # location2을 축으로 시계방향으로 회전이 가능한 경우 회전
        if can_move(board, visited, (location2[0], location2[1] + 1), (location2[0], location2[1]), size) and board[location1[0]][location1[1] + 1] == 0:
            push_queue(queue, visited, (location2[0], location2[1] + 1), (location2[0], location2[1]), time + 1)
        # location2을 축으로 반시계방향으로 회전이 가능한 경우 회전
        if can_move(board, visited, (location2[0], location2[1] - 1), (location2[0], location2[1]), size) and board[location1[0]][location1[1] - 1] == 0:
            push_queue(queue, visited, (location2[0], location2[1] - 1), (location2[0], location2[1]), time + 1)

def solution(board):
    size = len(board)
    visited = []  # 방문한 위치인지 확인
    queue = deque()  # 이동 가능한 위치/시간 정보 저장: ((y1, x1), (y2, x2), time)
    queue.append(((0, 0), (0, 1), 0))  # 출발 위치와 시간 저장: (0, 0), (0, 1), 0

    while queue:
        location1, location2, time = queue.popleft()
        # (N, N) 위치에 로봇이 도착한 경우 최소 시간 반환
        if location1 == (size - 1, size - 1) or location2 == (size - 1, size - 1):
            return time
        move_robot(board, visited, queue, location1, location2, time, size)
        rotate_robot(board, visited, queue, location1, location2, time, size)

# print(solution([[0, 0, 0, 1, 1],[0, 0, 0, 1, 0],[0, 1, 0, 1, 1],[1, 1, 0, 0, 1],[0, 0, 0, 0, 0]]))
''' 입력 예시 1
[[0, 0, 0, 1, 1],[0, 0, 0, 1, 0],[0, 1, 0, 1, 1],[1, 1, 0, 0, 1],[0, 0, 0, 0, 0]]
'''
''' 출력 예시 1
7
'''

[이코테] 이것이 코딩 테스트다/Chap13 DFS와 BFS 문제/08 블록 이동하기.py

08 블록 이동하기.py


import sqlite3

MIN_CHOICE = 1
MAX_CHOICE = 5
CREATE = 1
READ = 2
UPDATE = 3
DELETE = 4
EXIT = 5

def main():
    choice = 0
    while choice != EXIT:
        display_menu()
        choice = get_menu_choice()

        if choice == CREATE:
            create()
        elif choice == READ:
            read()
        elif choice == UPDATE:
            update()
        elif choice == DELETE:
            delete()

# The display_menu function displays the main menu.
def display_menu():
    print('\n----- Inventory Menu -----')
    print('1. Create a new item')
    print('2. Read an item')
    print('3. Update an item')
    print('4. Delete an item')
    print('5. Exit the program')

# The get_menu_choice function gets the user's menu choice.
def get_menu_choice():
    # Get the user's choice.
    choice = int(input('Enter your choice: '))

    # Validate the input.
    while choice < MIN_CHOICE or choice > MAX_CHOICE:
        print(f'Valid choices are {MIN_CHOICE} through {MAX_CHOICE}.')
        choice = int(input('Enter your choice: '))

    return choice

# The create function creates a new item.
def create():
    print('Create New Item')
    name = input('Item Name: ')
    price = input('Price: ')
    insert_row(name, price)

# The read function reads an existing item.
def read():
    name = input('Enter an item name to search for: ')
    num_found = display_item(name)
    print(f'{num_found} row(s) found.')

# The update function updates an existing item's data.
def update():
    # First let the user search for the row.
    read()

    # Get the ID of the selected item.
    selected_id = int(input('Select an Item ID: '))

    # Get the new values for item name and price.
    name = input('Enter the new item name: ')
    price = input('Enter the new price: ')

    # Update the row.
    num_updated = update_row(selected_id, name, price)
    print(f'{num_updated} row(s) updated.')

# The delete function deletes an item.
def delete():
    # First let the user search for the row.
    read()

    # Get the ID of the selected item.
    selected_id = int(input('Select an Item ID to delete: '))

    # Confirm the deletion.
    sure = input('Are you sure you want to delete this item? (y/n) ')
    if sure.lower() == 'y':
        num_deleted = delete_row(selected_id)
        print(f'{num_deleted} row(s) deleted.')

# The insert_row function inserts a row into the Inventory table.
def insert_row(name, price):
    conn = None
    try:
        conn = sqlite3.connect('inventory.db')
        cur = conn.cursor()
        cur.execute('''INSERT INTO Inventory (ItemName, Price)
                       VALUES (?, ?)''',
                    (name, price))
        conn.commit()
    except sqlite3.Error as err:
        print('Database Error', err)
    finally:
        if conn != None:
            conn.close()

# The display_item function displays all items
# with a matching ItemName.
def display_item(name):
    conn = None
    results = []
    try:
        conn = sqlite3.connect('inventory.db')
        cur = conn.cursor()
        cur.execute('''SELECT * FROM Inventory
                       WHERE lower(ItemName) == ?''',
                    (name,))
        results = cur.fetchall()

        for row in results:
            print(f'ID: {row[0]:<3} Name: {row[1]:<15} '
                  f'Price: {row[2]:<6}')
    except sqlite3.Error as err:
        print('Database Error', err)
    finally:
        if conn != None:
            conn.close()
    # Return the number of matching rows.
    return len(results)

# The update_row function updates an existing row with a new
# ItemName and Price. The number of rows updated is returned.
def update_row(id, name, price):
    conn = None
    try:
        conn = sqlite3.connect('inventory.db')
        cur = conn.cursor()
        cur.execute('''UPDATE Inventory
                       SET ItemName = ?, Price = ?
                       WHERE ItemID == ?''',
                    (name, price, id))
        conn.commit()
        num_updated = cur.rowcount
    except sqlite3.Error as err:
        print('Database Error', err)
    finally:
        if conn != None:
            conn.close()

    return num_updated

# The delete_row function deletes an existing item.
# The number of rows deleted is returned.
def delete_row(id):
    conn = None
    try:
        conn = sqlite3.connect('inventory.db')
        cur = conn.cursor()
        cur.execute('''DELETE FROM Inventory
                       WHERE ItemID == ?''',
                    (id,))
        conn.commit()
        num_deleted = cur.rowcount
    except sqlite3.Error as err:
        print('Database Error', err)
    finally:
        if conn != None:
            conn.close()

    return num_deleted

# Execute the main function.
if __name__ == '__main__':
    main()


# Ç!/usr/bin/env python3
import cv2
import random
import numpy as np
import argparse
from DRL.evaluator import Evaluator
from utils.util import *
from utils.tensorboard import TensorBoard
import time

def train(agent, env, evaluate):
    train_times = args.train_times
    env_batch = args.env_batch
    validate_interval = args.validate_interval
    max_step = args.max_step
    debug = args.debug
    episode_train_times = args.episode_train_times
    resume = args.resume
    output = args.output
    time_stamp = time.time()
    step = episode = episode_steps = 0
    tot_reward = 0.
    observation = None
    noise_factor = args.noise_factor
    starttime = time.time()
    while step <= train_times:
        if step < args.warmup and step % 5 == 0:
            print("Step: {}, TrainTimes: {}".format(step, train_times))
        step += 1
        episode_steps += 1
        # reset if it is the start of episode
        if observation is None:
            observation = env.reset()
            agent.reset(observation, 0)
        if step <= args.warmup:
            action = agent.select_action(observation, noise_factor=noise_factor)
        else:
            action = agent.select_action(observation, noise_factor=0)
        observation, reward, done, _ = env.step(action)
        agent.observe(reward, observation, done, step)
        if episode_steps >= max_step and max_step:
            if step > args.warmup:
                # [optional] evaluate
                if episode > 0 and validate_interval > 0 and episode % validate_interval == 0:
                    reward, dist = evaluate(env, agent.select_action, debug=debug)
                    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
                          '{:10d} Step_{:07d}/TrainTimes_{:07d}: mean_reward:{:.6f} mean_dist:{:.6f} var_dist:{:.6f}'.format(
                              int(time.time() - starttime), step - 1, train_times, np.mean(reward), np.mean(dist),
                              np.var(dist)))
                    writer.add_scalar('validate/mean_reward', np.mean(reward), step)
                    writer.add_scalar('validate/mean_dist', np.mean(dist), step)
                    writer.add_scalar('validate/var_dist', np.var(dist), step)

            train_time_interval = time.time() - time_stamp
            time_stamp = time.time()
            if step > args.warmup:
                if step < 4000 * max_step:
                    #                    lr = (1e-4, 3e-4)
                    lr = (1e-4, 1e-4)
                elif step < 6000 * max_step:
                    #                    lr = (1e-4, 3e-4)
                    lr = (1e-4, 1e-4)
                else:
                    lr = (3e-5, 1e-4)
                for i in range(episode_train_times):
                    loss = agent.update_policy(lr)
                writer.add_scalar('train/actor_lr', lr[1], step)
            time_stamp = time.time()
            # reset
            observation = None
            episode_steps = 0
            episode += 1
        if step % 1000 == 0:
            agent.save_model(output, iter=step)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='FontRL')

    # hyper-parameter
    parser.add_argument('--warmup', default=500, type=int,
                        help='timestep without training but only filling the replay memory')
    parser.add_argument('--discount', default=0.95, type=float, help='discount factor')
    parser.add_argument('--batch_size', default=24, type=int, help='minibatch size')
    parser.add_argument('--rmsize', default=800, type=int, help='replay memory size')
    parser.add_argument('--env_batch', default=24, type=int, help='concurrent environment number')
    parser.add_argument('--tau', default=0.001, type=float, help='moving average for target network')
    parser.add_argument('--max_step', default=1, type=int, help='max length for episode')
    parser.add_argument('--noise_factor', default=0.5, type=float, help='noise level for parameter space noise')
    parser.add_argument('--validate_interval', default=50, type=int, help='how many episodes to perform a validation')
    parser.add_argument('--validate_episodes', default=50, type=int,
                        help='how many episode to perform during validation')
    parser.add_argument('--train_times', default=8000, type=int, help='total traintimes')
    parser.add_argument('--episode_train_times', default=10, type=int, help='train times for each episode')
    parser.add_argument('--resume', default=None, type=str, help='Resuming model path for testing')
    parser.add_argument('--output', default='./model', type=str, help='Resuming model path for testing')
    parser.add_argument('--debug', dest='debug', action='store_true', help='print some info')
    parser.add_argument('--seed', default=1234, type=int, help='random seed')
    parser.add_argument('--font', default='2', type=str, help='font name')
    parser.add_argument('--run_id', default='1', type=str)
    args = parser.parse_args()
    # args.output = get_output_folder(args.output, "Paint")
    args.output = "./model/{}/Paint-run{}".format(args.font, args.run_id)
    print("Saving model in {}".format(args.output))
    print("Using bs={}".format(args.batch_size))
    writer = TensorBoard(args.output)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    if torch.cuda.is_available(): torch.cuda.manual_seed_all(args.seed)
    random.seed(args.seed)
    torch.backends.cudnn.deterministic = False
    torch.backends.cudnn.benchmark = True
    from DRL.ddpg import DDPG
    from DRL.multi import fastenv

    fenv = fastenv(args.max_step, args.env_batch, writer, args.font)
    agent = DDPG(args.batch_size, args.env_batch, args.max_step, \
                 args.tau, args.discount, args.rmsize, \
                 writer, args.resume, args.output)
    evaluate = Evaluator(args, writer)
    train(agent, fenv, evaluate)


class Solution:
    def isValid(self, s: str) -> bool:
        a = []
        for i in range(len(s)):
            if i == 0:
                a.append(s[i])
            elif len(a)==0 and (s[i]==']' or s[i]==')' or s[i]=='}'):
                return False
            elif (s[i]==')' and a[-1]=='(') or (s[i]=='}' and a[-1]=='{') or (s[i]==']' and a[-1]=='['):
                a.pop()
            else:
                a.append(s[i])

        if len(a)==0:
            return True
        else:
            return False


# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 16:55:51 2021

@author: user

test2.py
입력된 자연수가 홀수인지 짝수인지 판별해
주는 함수를 람다식을 이용하여 작성해 보자.
"""
x = int(input("자연수를 입력하세요 : "))

if((lambda x : True if x % 2 == 1 else False)(x)):
    print(x,"숫자는 홀수 입니다")
else:
     print(x,"숫자는 짝수 입니다")


"""Controller program to manage the benchmark."""
import os
import random
import socket
import sys

from controller import Supervisor
try:
    from shapely.geometry import Point
    from shapely.geometry import LineString
except ImportError:
    sys.stderr.write("Error: 'shapely' module not found.\n")
    sys.exit(0)

VEHICLE_DEF_NAME = 'WEBOTS_VEHICLE0'
SUMO_PORTS_RANGE = [1024, 1998]
MAX_TIME = 60.0
sensorVisualizationNodes = []

try:
    sys.path.append(os.path.join(os.path.normpath(os.environ.get("WEBOTS_HOME")), 'projects', 'samples', 'robotbenchmark',
                                 'include'))
    from robotbenchmark import robotbenchmarkRecord
except ImportError:
    sys.stderr.write("Warning: 'robotbenchmark' module not found.\n")
    sys.exit(0)

def apply_spline_subdivision_to_path(path, subdivision):
    """Apply spline subdivision to the list of points."""
    spline = []
    points = list(path)
    pointsNumber = len(points)
    # extend the points array
    points.append((points[pointsNumber - 1][0] + (points[pointsNumber - 1][0] - points[pointsNumber - 2][0]),
                   points[pointsNumber - 1][1] + (points[pointsNumber - 1][1] - points[pointsNumber - 2][1])))
    points.append((points[pointsNumber][0] + (points[pointsNumber][0] - points[pointsNumber - 1][0]),
                   points[pointsNumber][1] + (points[pointsNumber][1] - points[pointsNumber - 1][1])))
    pointMinus1 = (points[0][0] + (points[0][0] - points[1][0]),
                   points[0][1] + (points[0][1] - points[1][1]))
    pointMinus2 = (pointMinus1[0] + (pointMinus1[0] - points[0][0]),
                   pointMinus1[1] + (pointMinus1[1] - points[0][1]))
    # adding to the end is equivalent to index -1 and -2
    points.append(pointMinus2)
    points.append(pointMinus1)

    # interpolation
    spline.append(points[0])  # first point
    for i in range(1, pointsNumber):
        # compute the third order coefficients
        coefficients = []
        for j in range(2):
            coefficients.append([
                (-points[i - 2][j] + 3 * points[i - 1][j] - 3 * points[i][j] + points[i + 1][j]) / 6.0,
                (3 * points[i - 2][j] - 6 * points[i - 1][j] + 3 * points[i][j]) / 6.0,
                (-3 * points[i - 2][j] + 3 * points[i][j]) / 6.0,
                (points[i - 2][j] + 4 * points[i - 1][j] + points[i][j]) / 6.0
            ])
        for j in range(subdivision):
            t = float(j + 1) / subdivision
            spline.append(((coefficients[0][2] + t * (coefficients[0][1] + t * coefficients[0][0])) * t + coefficients[0][3],
                           (coefficients[1][2] + t * (coefficients[1][1] + t * coefficients[1][0])) * t + coefficients[1][3]))
    return spline

def hide_sensors_visualization(supervisor):
    """Hide all the sensors visualization nodes to the camera."""
    vehicleNode = supervisor.getFromDef(VEHICLE_DEF_NAME)
    slotNames = [
        'sensorsSlotFront',
        'sensorsSlotRear',
        'sensorsSlotTop',
        'sensorsSlotCenter'
    ]
    renderingDevicesTypeName = [
        'Camera',
        'RangeFinder',
        'Lidar'
    ]
    renderingDevicesNodes = []
    # look for rendering devices nodes in slot fields
    for slotName in slotNames:
        field = vehicleNode.getField(slotName)
        for i in range(field.getCount()):
            node = field.getMFNode(i)
            if node.getBaseTypeName() in renderingDevicesTypeName:
                renderingDevicesNodes.append(node)
    # look for visualization nodes
    field = supervisor.getFromDef('SENSOR_VISUALIZATION').getField('children')
    for i in range(field.getCount()):
        node = field.getMFNode(i)
        if field.getMFNode(i).getTypeName() == 'DistanceSensorVisualization':
            sensorVisualizationNodes.append(node)
    # hide visualization nodes to rendering devices
    for renderingDevicesNode in renderingDevicesNodes:
        for sensorsVisualizationNode in sensorVisualizationNodes:
            sensorsVisualizationNode.setVisibility(renderingDevicesNode, False)

def enable_sensors_visualization(supervisor, enable):
    """Hide or show the sensors visualization nodes."""
    for node in sensorVisualizationNodes:
        node.setVisibility(supervisor.getFromDef('VIEWPOINT'), enable)

def add_sumo(supervisor):
    """Add the SUMO interface with a free port (in the range [1024;1998]) as argument."""
    freePortFound = False
    port = 8873
    while not freePortFound:
        port = random.randint(SUMO_PORTS_RANGE[0], SUMO_PORTS_RANGE[1])

        # check if this port is already used
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(3.0)
        try:
            s.connect(('localhost', port))
        except socket.error:
            freePortFound = True
        s.close()
    nodeString = 'SumoInterface {'
    nodeString += '  gui FALSE'
    nodeString += '  radius 200'
    nodeString += '  laneChangeDelay 4'
    nodeString += '  enableWheelsRotation TRUE'
    nodeString += '  port %d' % port
    nodeString += '  seed 0'  # equivalent to 'random' for SUMO
    nodeString += '}'
    supervisor.getRoot().getField('children').importMFNodeFromString(-1, nodeString)

supervisor = Supervisor()
hide_sensors_visualization(supervisor)
add_sumo(supervisor)

timestep = int(supervisor.getBasicTimeStep())

# get main vehicle node and position
vehicleNode = supervisor.getFromDef(VEHICLE_DEF_NAME)
initialPosition = vehicleNode.getPosition()
initialPoint = Point((initialPosition[0], initialPosition[1]))

# get first SUMO vehicle node and position
sumoFirstVehicle = supervisor.getFromDef("SUMO_VEHICLE0")
sumoFirstVehicleInitialPosition = sumoFirstVehicle.getPosition()
sumoInitializationChecked = False

# parse the road node to extract road path
roadNode = supervisor.getFromDef("ROAD")
coordinates = []
splineSubdivision = roadNode.getField("splineSubdivision").getSFInt32()
waypoints = roadNode.getField("wayPoints")
laneNumber = roadNode.getField("numberOfLanes").getSFInt32()
width = roadNode.getField("width").getSFFloat()
laneWidth = width / laneNumber
for i in range(waypoints.getCount()):
    point = waypoints.getMFVec3f(i)
    coordinates.append((point[1], point[0]))
subdividedCoordinates = coordinates
if splineSubdivision > 0:
    subdividedCoordinates = apply_spline_subdivision_to_path(coordinates, splineSubdivision)
roadPath = LineString(subdividedCoordinates)
emergencyLanePath = roadPath.parallel_offset(1.5 * laneWidth, 'right')
initialDistance = roadPath.project(initialPoint)

# main loop
inEmergencyLane = False
collided = False
sumoFailure = False
time = 0.0
while time < MAX_TIME and not inEmergencyLane and not collided and not sumoFailure and supervisor.step(timestep) != -1:
    # check that SUMO is running
    if time >= 10.0 and not sumoInitializationChecked:
        sumoInitializationChecked = True
        position = sumoFirstVehicle.getPosition()
        # check if first sumo vehicle has moved
        if (position[0] == sumoFirstVehicleInitialPosition[0] and
                position[1] == sumoFirstVehicleInitialPosition[1] and
                position[2] == sumoFirstVehicleInitialPosition[2]):
            sumoFailure = True
    # check if robot is inside the emergency lane
    position = vehicleNode.getPosition()
    positionPoint = Point((position[0], position[1]))
    if emergencyLanePath.distance(positionPoint) < 0.5 * laneWidth:
        inEmergencyLane = True
    # check for collision
    contactPoints = vehicleNode.getContactPoints()
    if len(contactPoints) > 0:
        collided = True
    time = supervisor.getTime()
    distance = roadPath.project(positionPoint) - initialDistance
    supervisor.wwiSendText("update: " + str(time) + " {0:.3f}".format(distance))
    # check if sensors visualization should be enabled/disabled
    message = supervisor.wwiReceiveText()
    while message:
        if message.startswith("sensors visualization:"):
            if message.endswith("false"):
                enable_sensors_visualization(supervisor, False)
            elif message.endswith("true"):
                enable_sensors_visualization(supervisor, True)
        message = supervisor.wwiReceiveText()

supervisor.wwiSendText("stop")

if inEmergencyLane:
    supervisor.setLabel(0, "The vehicle should not enter in the emergency lane.",
                        0.01, 0.85, 0.09, 0xFF0000, 0, "Lucida Console")
elif collided:
    supervisor.setLabel(0, "The vehicle should not collide.",
                        0.01, 0.85, 0.09, 0xFF0000, 0, "Lucida Console")
elif sumoFailure:
    supervisor.setLabel(0, "Problem with traffic generation using SUMO, we can't take this performance into account.",
                        0.01, 0.85, 0.09, 0xFF0000, 0, "Lucida Console")

position = vehicleNode.getPosition()
distance = round(roadPath.project(Point((position[0], position[1]))) - initialDistance, 3)

while supervisor.step(timestep) != -1:
    # wait for record message
    message = supervisor.wwiReceiveText()
    while message:
        if message.startswith("record:"):
            record = robotbenchmarkRecord(message, "highway_driving", distance)
            supervisor.wwiSendText(record)
            break
        elif message == "exit":
            break
        message = supervisor.wwiReceiveText()

supervisor.simulationSetMode(Supervisor.SIMULATION_MODE_PAUSE)


import torch.nn as nn
import torch.nn.functional as F
from transformers import ViTModel
from transformers import ViTFeatureExtractor

class ViTForImageClassification(nn.Module):
    def __init__(self, num_labels=3):
        super(ViTForImageClassification, self).__init__()
        self.vit = ViTModel.from_pretrained('google/vit-base-patch16-224-in21k')
        self.dropout = nn.Dropout(0.1)
        self.classifier = nn.Linear(self.vit.config.hidden_size, num_labels)
        self.num_labels = num_labels

    def forward(self, pixel_values, labels):
        outputs = self.vit(pixel_values=pixel_values)
        output = self.dropout(outputs.last_hidden_state[:,0])
        logits = self.classifier(output)

        loss = None
        if labels is not None:
            loss_fct = nn.CrossEntropyLoss()
            loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
        if loss is not None:
            return logits, loss.item()
        else:
            return logits, None


import requests

url = 'http://127.0.0.1:1080'  # localhost and the defined port + endpoint
body = {"rest_name": "강남역점 홍콩반점0410", "rest_category": "밀집도"}
response = requests.post(url, data=body)
response.json()

'''
import requests
import json

r = requests.post("http://127.0.0.1:5000/predict", json = {"rest_name": "강남역점 홍콩반점0410",
"rest_category": "밀집도"})
print(r.json())

with open('C:\\Users\\user\\Documents\\rest_data.json', 'rt', encoding='utf-8-sig') as f:
    json_data = json.load(f)

try:
  r = requests.get(BASE, json = json.dumps(json_data, ensure_ascii = False, indent="\t"), verify=False, timeout=5)
  print(r.json())
except requests.exceptions.ConnectionError as e:
    r = "No response"
#except:
  #time.sleep(6)
  #r = requests.get(BASE, json = json.dumps(json_data, ensure_ascii = False, indent="\t"), verify=False)
'''
#try:

'''
try:
  r = requests.get(BASE, json=  {
    "FIELD1": 2159,
    "rest_name": "강남역점 홍콩반점0410",
    "rest_category": "중국식",
    "rest_number": "02  553 9295",
    "rest_address": "서울특별시 강남구 역삼동 827-4번지 ",
    "rest_location": "[37.4966545, 127.0304097]",
    "rest_rating": 84.59,
    "rest_density": 52.29,
    "rest_recommend": 61.97999999999999
  })
except:
  time.sleep(2)
  requests.get(BASE, json=  {
    "FIELD1": 2159,
    "rest_name": "강남역점 홍콩반점0410",
    "rest_category": "중국식",
    "rest_number": "02  553 9295",
    "rest_address": "서울특별시 강남구 역삼동 827-4번지 ",
    "rest_location": "[37.4966545, 127.0304097]",
    "rest_rating": 84.59,
    "rest_density": 52.29,
    "rest_recommend": 61.97999999999999
  })

#for i in range(len())

data = [{"likes": 78, "name": "Tim", "views": 100000},
        {"likes": 10000, "name": "Tim", "views": 80000},
        {"likes": 35, "name": "Tim", "views": 2000}]

for i in range(len(data)):
  response = requests.put(BASE + "video/" + str(i), data[i])
  print(response.json())

input()
response = requests.get(BASE + "video/6")
print(response.json())

'''