import os
import sys
import shutil
import plistlib
import toml
import subprocess
import json
from urllib.request import urlopen, urlretrieve

class AppBundle:
    frameworks_url = 'https://api.github.com/repos/3-manifolds/frameworks/releases/latest'
    python_link = '../Frameworks/Python.framework/Versions/Current/bin/python3'

    def __init__(self):
        with open("info.toml") as info_toml:
            self.info = info = toml.load(info_toml)
        self.app_name = info['CFBundleDisplayName']
        self.bundle = self.app_name + '.app'
        self.icon_file = info['CFBundleIconFile']
        self.sdef_file = info['OSAScriptingDefinition']
        self.python_version = f'{sys.version_info.major}.{sys.version_info.minor}'

    def create_bundle_structure(self):
        """Construct a macOS Application bundle.

        The info.toml file provides configuration information.
        This assumes that the current working directory contains:
            A configuration file info.toml.
            A directory main_ex containing the main executable;
            An icon file named as specified in info.toml;
            An sdef file named as specified in info.toml;
            A python script named main.py which runs the app;
            A tarball (or a symlink to one) named Frameworks.tgz.
        """
        # Raises an exception if the bundle exists.
        os.mkdir(self.bundle)
        # Build the main executable (if necessary).
        os.chdir('main_ex')
        subprocess.run(['make'])
        os.chdir(os.path.pardir)
        # Download the frameworks (if necessary).
        tarball_base = f'Frameworks-{self.python_version}'
        tarball = tarball_base + '.tgz'
        if not os.path.exists(tarball):
            with urlopen(self.frameworks_url) as json_data:
                release_info = json.load(json_data)
            for asset in release_info['assets']:
                filename = asset['name']
                base, ext = os.path.splitext(filename)
                if base != tarball_base:
                    continue
                urlretrieve(asset['browser_download_url'], filename)
                if filename.endswith('.sha1'):
                    hash_file = filename
                elif filename.endswith('.tgz'):
                    tar_file = filename
            result = subprocess.run(['shasum', '-c', hash_file],
                        capture_output=True)
            if result.returncode:
                print('Framework download failed')
                sys.exit(1)
            os.unlink(hash_file)
        contents = os.path.join(self.bundle, 'Contents')
        macos = os.path.join(contents, 'MacOS')
        resources = os.path.join(contents, 'Resources')
        for subdir in (contents, macos, resources):
            os.makedirs(subdir, exist_ok=True)
        shutil.copy(self.icon_file, resources)
        shutil.copy(self.sdef_file, resources)
        main_ex_path = os.path.join(macos, self.app_name)
        shutil.copy('main_ex/AppMain', main_ex_path)
        plist_path = os.path.join(contents, 'Info.plist')
        with open(plist_path, "wb") as info_plist:
            plistlib.dump(self.info, info_plist)
        symlink_path = os.path.join(macos, 'Python')
        os.symlink(self.python_link, symlink_path)
        shutil.copy('main.py', resources)
        subprocess.run(['tar', 'xz', '-C', contents, '-f', tarball])

    def add_packages(self):
        if not os.path.exists('requirements.txt'):
            print('The requirements.txt file was not found.')
            sys.exit(1)
        bundle_name = self.app_name + '.app'
        if not os.path.exists(bundle_name):
            print(bundle_name, 'was not found')
            sys.exit(1)
        lib_dir = os.path.join(bundle_name, 'Contents', 'Frameworks',
            'Python.framework', 'Versions', 'Current', 'lib')
        package_dir = None
        for file in os.listdir(lib_dir):
            package_dir = os.path.join(lib_dir, file, 'site-packages')
            if os.path.exists(package_dir):
                break
        subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-r',
            'requirements.txt', '--no-user', '--target', package_dir])


from ctypes import windll
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import random

colors = ["Red", "Blue", "Green", "Yellow"]
guess = []
tries = 0
to_guess = []

# Generate a code with 4 random colors :
def generate_code(colors_table):
    code_table = []
    for _ in range(4):
        color = random.choice(colors_table)
        code_table.append(color)
    print(code_table)
    return code_table

to_guess = generate_code(colors)

def place_peg(color):
    peg = tk.Label(master=combination_frm, text=color,
                   background=color, width=3)
    if len(guess) < 4:
        guess.append(peg["text"])
        peg.pack(side=tk.LEFT, padx=5)
    else:
        messagebox.showinfo(
            "4 colors", "4 pegs only!")

def place_red_peg():
    place_peg("Red")

def place_blue_peg():
    place_peg("Blue")

def place_green_peg():
    place_peg("Green")

def place_yellow_peg():
    place_peg("Yellow")

def clear_combination():
    global guess
    guess = []
    for widget in combination_frm.winfo_children():
        widget.destroy()

def validate():
    # Updating the number of tries
    global tries
    tries += 1

    # Clearing the submit field and pushing the combination lower in the window
    number_ok = 0
    number_misplaced = 0
    to_guess_copy = to_guess.copy()
    pegs_frm = tk.Label(master=tries_frm)
    for color in guess:
        peg = tk.Label(master=pegs_frm, text=color, background=color, width=3)
        peg.pack(side=tk.LEFT, padx=5)
        for widget in combination_frm.winfo_children():
            widget.destroy()
    pegs_frm.grid(column=0)

    check_table = check_code(to_guess_copy, guess, number_misplaced, number_ok)

    # print(f"ok: {check_table[0]}, misplaced: {check_table[1]}, turn: {tries}")

    # Prints the number of pegs OK or misplaced :
    check_pegs = tk.Label(
        master=tries_frm, text=f"Colors ok: {check_table[0]} \n Colors misplaced: {check_table[1]}")
    check_pegs.grid(column=1)

    # Resets the "guess" list to zero
    clear_combination()

    # Check if win or lose
    win_or_lose(check_table[0])

def check_code(table1, table2, numOK, num_mis):
    # Checking the color combination
    for x in range(len(table1)):
        if table2[x] == table1[x]:
            numOK += 1
            table2[x] = "#"
            table1[x] = "*"
    for y in range(len(table1)):
        if table2[y] in table1:
            table1[table1.index(table2[y])] = "*"
            num_mis += 1
    return [numOK, num_mis]

def win_or_lose(combination):
    if combination == 4:
        messagebox.showinfo(
            "You win!", "Congratulations, you found the code!")
        for color in to_guess:
            peg = tk.Label(master=reveal_frm, text=color,
                           background=color, width=3)
            reveal_code.pack()
            peg.pack(side=tk.LEFT, padx=5)
    elif tries == 12:
        messagebox.showinfo(
            "You lose", "You haven't found the right combination. Check it on the board!")
        for color in to_guess:
            peg = tk.Label(master=reveal_frm, text=color,
                           background=color, width=3)
            reveal_code.pack()
            peg.pack(side=tk.LEFT, padx=5)

# Create main window
window = tk.Tk()
window.title("Mastermind")

# Fixing the blur on text
windll.shcore.SetProcessDpiAwareness(1)

# Create rules frame and content
main_frm = ttk.Frame(window, width=400).pack()
rules_frm = ttk.Label(master=main_frm).pack()
rules_lbl = ttk.Label(master=rules_frm, relief=tk.RIDGE, borderwidth=4,
                      padding=15, text="Guess a 4 color combination").pack()

# Creating peg buttons and packing them in a grid
peg_list_frm = ttk.Frame(window, padding=15)

red_peg_btn = tk.Button(master=peg_list_frm, text="Red", height=1, width=6,
                        background="red", command=place_red_peg)
blue_peg_btn = tk.Button(master=peg_list_frm, text="Blue", height=1, width=6,
                         background="blue", command=place_blue_peg)
green_peg_btn = tk.Button(
    master=peg_list_frm, text="Green", height=1, width=6, bg="green", command=place_green_peg)
yellow_peg_btn = tk.Button(
    master=peg_list_frm, text="Yellow", height=1, width=6, bg="yellow", command=place_yellow_peg)

pegs_list = [red_peg_btn, blue_peg_btn, green_peg_btn, yellow_peg_btn]

for index, peg in enumerate(pegs_list):
    peg.grid(row=0, column=index)

peg_list_frm.pack()

# Create a selected combination frame
select_frm = ttk.Frame(window, padding=15)
combination_frm = tk.Frame(master=select_frm)
buttons_frm = tk.Frame(master=select_frm)

validate_btn = tk.Button(
    master=buttons_frm, text="Submit combination", command=validate).pack()
clear_btn = tk.Button(master=buttons_frm,
                      text="Clear combination", command=clear_combination).pack()

buttons_frm.grid(row=0, column=1)
combination_frm.grid(row=0, column=0, ipadx=10)
select_frm.pack()

# Create a table for played combinations
tries_frm = ttk.Frame(window, padding=15)
tries_frm.pack()

# Create a frame for reveal
reveal_frm = ttk.Frame(window, padding=15).pack()
reveal_code = ttk.Label(master=reveal_frm, text="The code was:")

window.mainloop()


import socket,sys
import multiprocessing as mp
import subprocess as sp
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sstr=''

print('pncat starting.')
print('by deepcloud,ver 0.3')
if len(sys.argv)<3:
    print('use: python3 pncat.py [ip] [port] [-l] [-s]')
    print('    -l:open the listen mode(if not open this mode,the mode will be connect mode.)')
    print('    -s:open the shell mode(run the command)')
    sys.exit()

#start socket!!
try:
    if '-l' in sys.argv:
        s.bind((sys.argv[1],int(sys.argv[2])))
        print('listen on %s:%s' %(sys.argv[1],sys.argv[2]))
        s.listen()
        conn,ht=s.accept()
        print('accecp at %s:%s'%(ht[0],ht[1]))
    else:
        s.connect((sys.argv[1],int(sys.argv[2])))
        conn=s
        print('connect done at %s:%s' %(sys.argv[1],sys.argv[2]))
        ht=(sys.argv[1],sys.argv(2))
    while True:
        if '-s' not in sys.argv:
            sstr=str(input(ht[0] + '>'))+'\r\n'
            #raise KeyboardInterrupt
            conn.send(sstr.encode('utf-8'))
            sstr=conn.recv(102400).decode('utf-8').replace('\r\n','').replace('\r','')
            print(sstr)
        else:
            sstr=conn.recv(1024).decode('utf-8').replace('\r\n','').replace('\r','')
            sstr=sp.getoutput(sstr.split()).encode('utf-8')
            conn.send(sstr)

except ConnectionRefusedError:
    print('connect to %s:%s failed.' % (sys.argv[1],sys.argv[2]))
except KeyboardInterrupt:
    pass
except BrokenPipeError:
    print('broken pipe.')
finally:
    s.close()


#!python

from jaraco.nxt import *
from jaraco.nxt.messages import *

import time
import sdl2
import math

sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
joystick = sdl2.SDL_JoystickOpen(0)

# open the connection. Get this string from preferences>bluetooth>NXT>edit serial ports
conn = Connection('/dev/tty.Addy-DevB')  # antons NXT

def clamp(n, minn, maxn):
    return max(min(maxn, n), minn)

while True:
    sdl2.SDL_PumpEvents()

    # read joystick input and normalise it to a range of -100 to 100
    joy_x = (sdl2.SDL_JoystickGetAxis(joystick, 0) - 17268) / 172.68
    joy_y = (sdl2.SDL_JoystickGetAxis(joystick, 1) - 17268) / 172.68

    # use shoulder buttons on the game pad to make the omnibot rotate around it's axis.
    turnpower = 0
    if sdl2.SDL_JoystickGetButton(joystick, 5):turnpower = 75
    if sdl2.SDL_JoystickGetButton(joystick, 4):turnpower = -75

    # convert joystick x and y to a direction and power (deviation from the centre)
    joy_direction = math.atan2(joy_y, joy_x)  # in radians
    joy_power = (joy_x ** 2 + joy_y ** 2) ** 0.5  # pythagoras

    # building a list of three motor commands to send over
    cmds = []
    for i in range(3):
        # for each motor the angle has a different offset (0, 120 and 240 degrees)
        angle = i * 2 * 3.1415 / 3 + joy_direction

        # motor power calculation. A simple sin.
        motorpower = math.sin(angle) * joy_power + turnpower

        motorpower = round(clamp(motorpower, -100, 100))

        cmds.append(SetOutputState(
                                          i,
                                          motor_on=True,
                                          set_power=motorpower,
                                          run_state=RunState.running,
                                          use_regulation=True,
                                          regulation_mode=RegulationMode.motor_speed
                                          )
                    )

    map(conn.send, cmds)

    # wait a bit before sending more commands. If we don't the BT buffer overflows.
    time.sleep(0.05)

    # end the fun if button 1 is pressed.
    if sdl2.SDL_JoystickGetButton(joystick, 0) : break

# clean up
conn.close()


import math
import os
import random
import re
import sys

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

def dynamicArray(n, queries):
    # print("n", n, "queries", queries)

    arr = []
    for _ in range(n):
        arr.append([])

    lastAnswer = 0
    out = []

    for type, x, y in queries:
        idx = (x ^ lastAnswer) % n

        if type == 1:
            arr[idx].append(y)

        if type == 2:
            lastAnswer = arr[idx][y % len(arr[idx])]
            out.append(lastAnswer)

    return out

if __name__ == "__main__":

    def process(s):
        inp = s.strip().split("\n")

        first_multiple_input = inp[0].rstrip().split()

        n = int(first_multiple_input[0])

        q = int(first_multiple_input[1])

        queries = []

        for _ in range(q):
            queries.append(list(map(int, inp[_ + 1].rstrip().split())))

        result = dynamicArray(n, queries)

        print("-----")
        print(s)
        print()
        print("res:")
        print(result)

    process(
        """2 5
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1
            """
    )


def solution(distance, rocks, n):
    answer = 0
    rocks.sort()
    all_rocks = rocks.copy()
    all_rocks.append(0)
    all_rocks.append(distance)
    tmp_dist = []

    for t in rocks:
        tmp = list(map(lambda x:abs(x - t), all_rocks))
        tmp.remove(0)
        tmp_dist.append(min(tmp))
    return max(tmp_dist)


import logging
import argparse
from mdpalgo import constants

from mdpalgo.interface.simulator import Simulator

# Logging
logging.basicConfig(level=logging.INFO)

# parse the arguments
parser = argparse.ArgumentParser()
parser.add_argument("--hl", help="run in headless mode", action="store_true")
parser.add_argument("--cen", help="center pathing on obstacle",
                    action="store_true")
parser.add_argument("--testwifi", help="use test wifi server on PC instead of real rpi",
                    action="store_true")

def main():
    constants.HEADLESS = False
    args = parser.parse_args()
    if args.hl:
        constants.HEADLESS = True
        print("Running in headless mode")
    if args.testwifi:
        constants.WIFI_IP = constants.TEST_IP
        print("Use local IP address for integration testing without RPi")

    x = Simulator()
    x.run()

if __name__ == '__main__':
    main()


from flask import Flask, render_template, Response, request
from picamera import PiCamera
from flask import jsonify,json
import numpy as np
from camera_pi import Camera

import sys
import wave
import contextlib
import time
import cv2
import pygame
import RPi.GPIO as GPIO

app = Flask(__name__)
cam = Camera()

@app.route('/', methods=['GET','POST'])
def index():
    """Video streaming home page."""

    return render_template('index.html')

@app.route('/button', methods=['GET','POST'])
def button():
    print("Coucou")
    return jsonify({})

def gen(camera):
    """Video streaming generator function."""
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/png\r\n\r\n' + frame + b'\r\n')

@app.route('/video_feed')
def video_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(cam),
                   mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/pic', methods=['GET','POST'])
def pic():
    print("Pic taken")
    cam.save_frame()
    num_pic = cam.nbPic
    return jsonify({'num_pic' : str(num_pic)+ " pictures"})
#This application allows to play a sound
@app.route('/sound', methods=['GET','POST'])
def sound():
    pygame.init()
    pygame.mixer.music.load("output.wav")
    pygame.mixer.music.play()
    length=pygame.mixer.Sound('output.wav').get_length()
    time.sleep(length+10)
    return jsonify({})

#This application allows to choose a time where laser is turned on
@app.route('/switch', methods=['GET','POST'])
def switch():
    out1 = 40
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(out1,GPIO.OUT)
    val_switch = request.args.get('val_switch',0 , type = int)
    GPIO.output(out1,GPIO.HIGH)
    time.sleep(val_switch)
    value = GPIO.input(out1)
    print(value)
    GPIO.output(out1,GPIO.LOW)
    print(GPIO.input(out1))
    GPIO.cleanup()
    return jsonify({})

#This application allows to make a full turn of the servo of the ball launcher
@app.route('/shoot', methods=['GET','POST'])
def shoot():
    GPIO.cleanup()
    x =10
    print('shot')
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(36, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(36,50)
    pwm.start(x)
    time.sleep(0.4)
    GPIO.cleanup()
    return jsonify({})

#This application is useless but allows you tu use buttons to control a servo
@app.route('/servo', methods=['GET','POST'])
def servo():
    if request.method == 'POST':
        angle = request.form['angle']
    print(angle)

#This application allows to control the servo for the laser :set the right GPIO of RPi
@app.route('/servo_las', methods=['GET','POST'])
def servo_las():
    GPIO.cleanup()
    angle_las = request.args.get('angle_las',0 , type = int)
    print(angle_las)
    x = (-float(angle_las)+135)*12/180
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(38, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(38,50)
    pwm.start(0)
    time.sleep(1)
    pwm.ChangeDutyCycle(x)
    time.sleep(0.5)
    GPIO.cleanup()
    return jsonify({})

#This application allows to control the servo to move the ball launcher. Set the right pin
@app.route('/servo_ball', methods=['GET','POST'])
def servo_ball():
    GPIO.cleanup()
    angle_ball = request.args.get('angle_ball',0 , type = int)
    print(angle_ball)

    x =( int(angle_ball) +77)/18
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(32, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(32,50)
    pwm.start(x)
    time.sleep(0.5)
    GPIO.cleanup()
    return jsonify({})

# This application allows to control the stepper motor of the station . Set the right pin
@app.route('/step', methods=['GET','POST'])
def step():
    angle = request.args.get('angle',0 , type=int)
    print(angle)

    t = 0.02
    step_out1=37
    step_out2=35
    step_out3=33
    step_out4=31

    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(step_out1,GPIO.OUT)
    GPIO.setup(step_out2,GPIO.OUT)
    GPIO.setup(step_out3,GPIO.OUT)
    GPIO.setup(step_out4,GPIO.OUT)

    GPIO.output(step_out1,GPIO.LOW)
    GPIO.output(step_out2,GPIO.LOW)
    GPIO.output(step_out3,GPIO.LOW)
    GPIO.output(step_out4,GPIO.LOW)

    y=angle*25/180
    if y>0 and angle <= 360 :

         for i in range(0,int(y)):

            GPIO.output(step_out1,GPIO.HIGH)
            GPIO.output(step_out2,GPIO.LOW)
            GPIO.output(step_out3,GPIO.LOW)
            GPIO.output(step_out4,GPIO.LOW)
            time.sleep(t)

            GPIO.output(step_out1,GPIO.LOW)
            GPIO.output(step_out2,GPIO.LOW)
            GPIO.output(step_out3,GPIO.HIGH)
            GPIO.output(step_out4,GPIO.LOW)
            time.sleep(t)

            GPIO.output(step_out1,GPIO.LOW)
            GPIO.output(step_out2,GPIO.HIGH)
            GPIO.output(step_out3,GPIO.LOW)
            GPIO.output(step_out4,GPIO.LOW)
            time.sleep(t)

            GPIO.output(step_out1,GPIO.LOW)
            GPIO.output(step_out2,GPIO.LOW)
            GPIO.output(step_out3,GPIO.LOW)
            GPIO.output(step_out4,GPIO.HIGH)
            time.sleep(t)

    if y<0 and abs(angle) <= 360:
        for i in range(0,-int(y)):

            GPIO.output(step_out1,GPIO.LOW)
            GPIO.output(step_out2,GPIO.LOW)
            GPIO.output(step_out3,GPIO.LOW)
            GPIO.output(step_out4,GPIO.HIGH)
            time.sleep(t)

            GPIO.output(step_out1,GPIO.LOW)
            GPIO.output(step_out2,GPIO.HIGH)
            GPIO.output(step_out3,GPIO.LOW)
            GPIO.output(step_out4,GPIO.LOW)
            time.sleep(t)

            GPIO.output(step_out1,GPIO.LOW)
            GPIO.output(step_out2,GPIO.LOW)
            GPIO.output(step_out3,GPIO.HIGH)
            GPIO.output(step_out4,GPIO.LOW)
            time.sleep(t)

            GPIO.output(step_out1,GPIO.HIGH)
            GPIO.output(step_out2,GPIO.LOW)
            GPIO.output(step_out3,GPIO.LOW)
            GPIO.output(step_out4,GPIO.LOW)
            time.sleep(t)

    return jsonify({})

#@app.route('/5')
def move5():
    GPIO.cleanup()
    angle = 5
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/10')
def move10():
    GPIO.cleanup()
    angle = 10
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/15')
def move15():
    GPIO.cleanup()
    angle = 15
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/20')
def move20():
    GPIO.cleanup()
    angle = 20
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/25')
def move25():
    GPIO.cleanup()
    angle = 25
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/30')
def move30():
    GPIO.cleanup()
    angle = 30
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/35')
def move35():
    GPIO.cleanup()
    angle = 35
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/40')
def move40():
    GPIO.cleanup()
    angle = 40
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/45')
def move45():
    GPIO.cleanup()
    angle = 45
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/l5')
def movel5():
    GPIO.cleanup()
    angle = -5
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/l10')
def movel10():
    GPIO.cleanup()
    angle = -10
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/l15')
def movel15():
    GPIO.cleanup()
    angle = -15
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/l20')
def movel20():
    GPIO.cleanup()
    angle = -20
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/l25')
def movel25():
    GPIO.cleanup()
    angle = -25
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/l30')
def movel30():
    GPIO.cleanup()
    angle = -30
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/l35')
def movel35():
    GPIO.cleanup()
    angle = -35
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/l40')
def movel40():
    GPIO.cleanup()
    angle = -40
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/l45')
def movel45():
    GPIO.cleanup()
    angle = -45
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})
@app.route('/l0')
def movel0():
    GPIO.cleanup()
    angle = -0
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

@app.route('/0')
def move0():
    GPIO.cleanup()
    angle = 0
    x = (int(angle) +72)/18
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(26, GPIO.OUT)
    GPIO.setwarnings(False)
    pwm=GPIO.PWM(26,50)
    pwm.start(x)
    time.sleep(1)
    return jsonify({})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port =80, debug=True, threaded=True)


##################################################
#                                                #
# File by 0Stormy                                #
# Github: https://github.com/Kinda-Stormy/tfm    #
#                                                #
##################################################

# Packages
import os
import platform
import keyboard
import time
import cursor
import subprocess
from multiprocessing import Process
from colorama import Fore, Back, Style

# Functions \/

# Draw the topbar
def drawTopBar():
    dirStringLen = len(currentDirectory + ' | Press H For help')
    print(f'{Back.CYAN}{currentDirectory} | Press H For help' + ' ' * (terminalX - dirStringLen) + Style.RESET_ALL)

# Create tempfile
def createTempfile():

    try:
        with open('tfm', 'w') as f:
            f.write(os.path.expanduser("~"))
    except:
        print("Can't open tempfile")
# Read tempfile
def readTempfile():
    try:
        with open('tfm', 'r') as f:
            global currentDirectory
            currentDirectory = f.read()
    except:
        print("Can't open tempfile")

# Clear the screen
def clearScreen():
    if platform.system() == 'Windows':
        os.system('cls')
    else:
        os.system('clear')

# Draw contents
def drawContents():
    folderContents = os.listdir(currentDirectory)
    listLength = len(folderContents)
    terminalX = os.get_terminal_size().columns
    int(terminalX)

    for i in range(listLength):
        if os.path.isfile(f'{currentDirectory}/{folderContents[i]}') == False:
            print(Fore.YELLOW, folderContents[i], Style.RESET_ALL)
        else:
            print(Fore.LIGHTBLUE_EX, folderContents[i], Style.RESET_ALL)

        if i == (terminalY - 4):
            break

# Main loop
def mainLoop():
    while True:
        if keyboard.is_pressed("d"):
            global haultLoop
            haultLoop = True
            subprocess.run(['python', 'cd.py'])
            haultLoop = False

            if haultLoop == True:
                while haultLoop == True:
                    time.sleep(0.1)
        clearScreen()
        readTempfile()
        cursor.hide()
        global terminalX
        global terminalY
        terminalY = os.get_terminal_size().lines
        terminalX = os.get_terminal_size().columns
        int(terminalX)
        int(terminalY)
        drawTopBar()
        drawContents()
        time.sleep(0.2)

# -------------------- #

createTempfile()

mainLoop()


from typing import Optional

import numpy as np
import matplotlib.pyplot as plt
import cv2

from sklearn.manifold import TSNE

import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.nn.functional as F

def tsne_display_tensorboard(embeddings, c_vector: Optional = None, title: Optional[str] = None) -> np.ndarray:
    fig = plt.figure()

    if title is not None:
        plt.title(title)

    if c_vector is not None:
        plt.scatter(embeddings[:, 0], embeddings[:, 1], c=c_vector)
    else:
        plt.scatter(embeddings[:, 0], embeddings[:, 1])
    plt.colorbar()
    fig.canvas.draw()

    img_plot = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
    img_plot = img_plot.reshape(fig.canvas.get_width_height()[::-1] + (3,)) / 255
    img_plot = cv2.flip(img_plot, 0)
    img_plot = cv2.rotate(img_plot, cv2.ROTATE_90_CLOCKWISE)
    img_plot = np.swapaxes(img_plot, 0, 2)

    return img_plot

def run_tsne(model: nn.Module, loader: DataLoader, device):

    model.eval()
    h_vector = []
    z_vector = []
    c_vector = []

    for img, c in loader:
        img = img.to(device)

        with torch.no_grad():
            h, z = model(img)
            h = F.normalize(h, dim=1)
            z = F.normalize(z, dim=1)

        h_vector.extend(h.cpu().detach().numpy())
        z_vector.extend(z.cpu().detach().numpy())
        c_vector.extend(c.cpu().detach().numpy())

    model.train()

    h_vector = np.array(h_vector)
    z_vector = np.array(z_vector)
    c_vector = np.array(c_vector)
    embeddings_h = TSNE(n_components=2).fit_transform(h_vector)
    embeddings_z = TSNE(n_components=2).fit_transform(z_vector)

    return tsne_display_tensorboard(embeddings_h, c_vector), \
        tsne_display_tensorboard(embeddings_z, c_vector)


from moviepy.editor import *

def createVideo():
    # clip = VideoClip(make_frame = None, duration=4)  # for custom animations (see below)
    # clip = VideoFileClip("my_video_file.mp4")  # or .avi, .webm, .gif ...
    # clip = ImageSequenceClip(['0 State.png', "1 State.png", "2 State.png"], fps=24)
    # clip = ImageClip(".png")  # or .jpeg, .tiff, ...
    # clip = TextClip("Hello !", font="Amiri-Bold", fontsize=70, color="black")
    # clip = ColorClip(size=(460, 380))

    img = ['0 State.png', '1 State.png', '2 State.png']

    clips = [ImageClip(m).set_duration(3)
             for m in img]

    concat_clip = concatenate_videoclips(clips, method="compose")
    concat_clip.write_videofile("test.mp4", fps=24)

createVideo()


from data.SongClassifierModel import SongClassifierModel
from data.SongClassifierModel2 import SongClassifierModel2
from data.CSVDataSet import CSVDataSet
from torch.utils.data import DataLoader
from torch.utils.data import random_split
import torch

dataset = CSVDataSet('./data/data.csv')
savepath = './models/weights/weights2'

print(len(dataset))

train, test = random_split(dataset, [round(len(dataset)/2), len(dataset) - round(len(dataset)/2)])
train_dl = DataLoader(train, batch_size = 32, shuffle = True)
test_dl = DataLoader(test, batch_size = 1, shuffle = False)
full_dl = DataLoader(dataset, batch_size = len(dataset), shuffle = True)
input_size = 9

def getmaxitem(items):
    index = 0
    maxitem = items[0]
    for i in range(len(items)):
        if items[i].item() > maxitem.item():
            index = i
            maxitem = items[i]
    return index, maxitem

def run_test(test_dl = test_dl, savepath = savepath, print_values = True, modeltype = SongClassifierModel, input_size = input_size):
    model = modeltype(9)
    #print('loading weights...')
    model.load_state_dict(torch.load(savepath))
    #print('successfully loaded weights')
    criterion = torch.nn.MSELoss()

    total_loss = 0
    for  i,(inputs, targets) in enumerate(test_dl):
        yhat = model(inputs.float())
        target = targets
        #print(i, yhat)
        test = 'Correct'
        maxyhat = getmaxitem(yhat[0])
        maxtarget = getmaxitem(targets[0])
        #checks if index of the maximum values are the same indicating a correct match.
        if maxyhat[0] != maxtarget[0]:
            total_loss += 1
            test = 'Incorrect'
        if print_values:
            print(test, ' predicted: ', round(yhat.item(), 3), ' actual: ', target.item())
        #print(loss.item())

    return total_loss/len(test_dl)

if __name__ == '__main__':
    print('loss: ', run_test())


def run(t):
  N = int(raw_input())
  mem = [N+1] * (N + 1)
  mem[1] = 1
  for i in range(2, N + 1):
    reverse = int(str(i)[::-1])
    if i % 10 == 0 or reverse >= i:
      reverse = i-1
    mem[i] = min(mem[i-1], mem[reverse]) + 1

  print('Case #{}: {}'.format(t, mem[N]))

T = int(raw_input())
for t in xrange(1, T + 1):
  run(t)


#! /usr/bin/env python3

import argparse
import re

parser = argparse.ArgumentParser()
parser.add_argument('filename', help='The input file')
parser.add_argument('-D', '--debug', action='store_true')

args = parser.parse_args()

PART_1 = True

with open(args.filename) as file:
    lines = file.readlines()
    lines = [line.rstrip() for line in lines]

target_regex = re.compile(r'target area: x=(-?\d+)..(-?\d+), y=(-?\d+)..(-?\d+)')
match = target_regex.match(lines[0])

x_min = int(match[1])
x_max = int(match[2])
y_min = int(match[3])
y_max = int(match[4])

# The fastest possible horizontal speed is `x_max`, as otherwise the probe would
# overshoot the target area right away.
max_horizontal_speed = x_max

# The fastest possible vertical speed is `y_min`, as otherwise the probe would
# go deeper than the target area right away.
max_positive_vertical_speed = abs(y_min)
max_negative_vertical_speed = y_min

def probe_trajectory(initial_x, initial_y):
    step = 0
    x_speed = initial_x
    x_pos = 0
    y_speed = initial_y
    y_pos = 0

    while x_pos <= x_max and y_pos >= y_min:
        step += 1

        x_pos += x_speed
        if x_speed > 0:
            x_speed -= 1
        elif x_speed < 0:
            x_speed += 1

        y_pos += y_speed
        y_speed -= 1

        if x_min <= x_pos and x_pos <= x_max and y_min <= y_pos and y_pos <= y_max:
            # This probe is within the target area
            return True

    # Once we go past the target area, there's no hope
    return False

valid_speeds = []

for horiz_speed in range(1, max_horizontal_speed + 1):
    for vert_speed in range(max_negative_vertical_speed, max_positive_vertical_speed + 1):
        velocity = (horiz_speed, vert_speed)
        result = probe_trajectory(horiz_speed, vert_speed)
        if result:
            if args.debug:
                print(f"  Success: {velocity}")
            valid_speeds.append(velocity)

print(f"There are {len(valid_speeds)} trajectories that reach the target zone")


# OandaAPIによるドル円取得からのデータ構造の扱い

# ライブラリインポート
import os
import oandapyV20
from oandapyV20.endpoints.instruments import InstrumentsCandles
from pprint import pprint   # 追加

# アカウント情報
accountID = os.environ.get('OANDA_ID')
access_token = os.environ.get('OANDA_TOKEN')

# APIに接続
api = oandapyV20.API(access_token=access_token, environment="practice")

# 取得したいデータ情報
r = InstrumentsCandles(instrument="USD_JPY", params={"granularity": "H1",
                                                     "count": 3  # 追加
                                                     })

# APIへデータ要求
api.request(r)

# 「data」変数に取得データを格納
data = r.response

high_price = data["candles"][0]["mid"]["h"] #追加
# データ出力
# print(data)
#pprint(data)  # 追加
print(high_price) #変更


import logging
from io import BytesIO
from typing import List

from aiogram import types
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher import FSMContext
from aiogram.utils.callback_data import CallbackData
from aiogram.utils.exceptions import MessageNotModified

import settings

from bot.bot import dp, bot
from frames.actions import ActionABC, get_action, actions
from frames.image import PilImage

file_id_action_callback_data = CallbackData("i", "file_id", "action_code")

class NotInStorageException(Exception):
    pass

class InMemoryStorage():
    def __init__(self):
        self._storage = {}

    def save(self, data):
        key = data[-32:]
        self._storage[key] = data
        return key

    def get(self, key):
        if key in self._storage:
            return self._storage.get(key)
        else:
            raise Exception(f"{key} not in storage")

    def get(self, key):
        if key in self._storage:
            return self._storage.get(key)
        else:
            raise Exception(f"{key} not in storage")

storage = InMemoryStorage()

def _get_keyboard(file_id, actions: List[ActionABC]):

    return InlineKeyboardMarkup().row(*(
        InlineKeyboardButton(text=a.name, callback_data=file_id_action_callback_data.new(file_id, a.code))
        for a in actions
    )
    )

@dp.message_handler(content_types=['photo', 'document'], state="*")
async def image_action_handler(message: types.Message):
    logging.warning(f'Recieved a image from {message.from_user}')
    if message.photo:
        file_id = message.photo[-1].file_id
    if message.document:
        file_id = message.document.file_id
    short_file_id = storage.save(file_id)

    await message.reply("Received image. Which action to perform?", reply_markup=_get_keyboard(short_file_id, actions))
    return

@dp.callback_query_handler(file_id_action_callback_data.filter())
async def perform_action(callback: types.CallbackQuery, callback_data):

    file_id = storage.get(callback_data['file_id'])
    action_code = callback_data['action_code']
    action: ActionABC = get_action(action_code)

    try:
        await bot.edit_message_text(
            f'Received image. Performing {action.name}',
            callback.from_user.id,
            callback.message.message_id,
            reply_markup=None,
        )
    except MessageNotModified:
        # message already answered
        return

    file = await bot.get_file(file_id)
    origin_image = await bot.download_file(file.file_path)
    origin_image.seek(0)

    image = PilImage.open(origin_image)
    processor = action.processor(image)
    modified_image = processor.modified_image()
    response = BytesIO()
    response.name = "result.jpg"
    modified_image.save(response)
    response.seek(0)

    await callback.message.answer_document(types.InputFile(response))

    for supervisor in settings.TG_SUPERVISORS_LIST:
        await bot.send_message(
            chat_id=supervisor,
            text=f"User @{callback.from_user['username']} created image.",
        )

        response = BytesIO()
        response.name = "result.jpg"
        modified_image.save(response)
        response.seek(0)
        await bot.send_document(
            chat_id=supervisor,
            document=types.InputFile(response),
        )

    file_id = storage.get(callback_data['file_id'])
    await callback.answer()
    return

@dp.message_handler(state='*', commands='cancel')
@dp.message_handler(Text(equals='cancel', ignore_case=True), state='*')
async def cancel_handler(message: types.Message, state: FSMContext):
    """
    Allow user to cancel any action
    """

    current_state = await state.get_state()
    if current_state is None:
        return

    logging.info('Cancelling state %r', current_state)
    # Cancel state and inform user about it

    await state.finish()
    # And remove keyboard (just in case)

    await message.reply('Cancelled.', reply_markup=types.ReplyKeyboardRemove())


#!/usr/bin/env python
from vtkmodules.vtkCommonExecutionModel import vtkCompositeDataPipeline
from vtkmodules.vtkIOEnSight import vtkGenericEnSightReader
from vtkmodules.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Make sure all algorithms use the composite data pipeline
cdp = vtkCompositeDataPipeline()

reader = vtkGenericEnSightReader()
reader.SetDefaultExecutivePrototype(cdp)
reader.SetCaseFileName(VTK_DATA_ROOT + "/Data/EnSight/particles/particles.case")
reader.ReadAllVariablesOn()
reader.UpdateTimeStep(0.000375)
reader.UpdateTimeStep(9.9803)
reader.UpdateTimeStep(0.000375)
reader.UpdateTimeStep(9.9803)

# Leaks without this line
reader.SetDefaultExecutivePrototype(None)


from typing import Optional, Callable, List, Union, NamedTuple
import re
from enum import Enum

class Predicate(Enum):
    isA = 0
    consistsOf = 1
    hasA = 2
    can = 3

class ExtractionGroup(NamedTuple):
    subject: Optional[int]
    predicate: Optional[int]
    object: Optional[int]

class GroupProcessing(NamedTuple):
    subject: Callable[[str], str]
    predicate: Callable[[str], Union[Predicate, str]]
    object: Callable[[str], List[str]]

class ExtractionSpecification(NamedTuple):
    extraction_regex: re.Pattern
    expected_groups: int
    extraction_ordering: ExtractionGroup
    processing_functions: GroupProcessing

class TripleExtraction:
    def __init__(self, extraction_specification: ExtractionSpecification):
        self.extraction_specification = extraction_specification

    def extract_triples(self, output: str, prompt: str) -> List[List[str]]:
        """
        return structured triples from extracted patterns of the model output in the shape of [ [<s: str>, <p: str>, <o: str>], ... ]
        """
        clean_output = self.__clean_output(output, prompt)
        extraction_regex = self.extraction_specification["extraction_regex"]

        triples = []
        for match in re.finditer(extraction_regex, clean_output, re.DOTALL):
            triples.extend(self.__process_match(match))

        return triples

    def __clean_output(self, output: str, prompt: str) -> str:
        """
        remove original prompt from the output
        """
        return output.replace(prompt, "").strip()

    def __process_match(self, match: re.Match) -> List[str]:
        """
        process a regex match in the output into structured triples according to the extraction_specification
        """
        triples = []
        if len(match.groups()) == self.extraction_specification["expected_groups"]:
            subject = self.__process_group(match, "subject")
            predicate = self.__process_group(match, "predicate")
            objects = self.__process_group(match, "object")

            for object in objects:
                triple = {
                    "subject": subject,
                    "predicate": predicate,
                    "object": object,
                    "source_id": 1
                }
                triples.append(triple)
        return triples

    def __process_group(self, match: re.Match, key: str) -> None:
        """
        apply post processing to transform the extracted sequence to the atomic triple element(s)
        """
        group_index = self.extraction_specification["extraction_groups"][key]
        process_function = self.extraction_specification["processing_functions"][key]

        group = match.group(group_index)
        return process_function(group)


"""
定义自增加_id的计数器
"""
import pymongo

# 连接指定IP地址的数据库
client = pymongo.MongoClient("127.0.0.1", 27017)
# 获取数据库
db = client.get_database("data_status")
# 获取集合
ctn = db.get_collection("counters")
ctn.drop()  # 先删除集合，再插入
# 批量插入documents,插入一个数组
input_tuple = [{"_id": "U01", "no": 0}, {"_id": "U02", "no": 0},
               {"_id": "U03", "no": 0}, {"_id": "U04", "no": 0},
               {"_id": "U05", "no": 0}, {"_id": "U06", "no": 0},
               {"_id": "U07", "no": 0}, {"_id": "U08", "no": 0}
               ]
ctn.insert(input_tuple)


from functools import lru_cache
import logging

from dynaconf.base import Settings
from google.cloud.storage import Client
import google.auth

from project.config import load_config

@lru_cache
def client() -> Client:
    """Return initialized Storage."""
    config = load_config()
    return make_client(config)

def make_client(config: Settings) -> Client:
    """Return a new initialized Storage client for a config."""
    credentials, _ = google.auth.default(scopes=config.storage.scopes)
    gcs = Client(
        project=config.gcp.project,
        credentials=credentials,
    )
    LOGGER.debug('Initialized Storage client on %s with scopes %s.',
                 config.gcp.project,
                 ', '.join([s.split('/')[-1] for s in config.storage.scopes]))
    return gcs

LOGGER = logging.getLogger(__name__)


'''
LEGO SPIKE Prime Microbit Backpack
LPF2forMicrobit class allows communication between LEGO SPIKE Prime and Microbit Backpacks
Version Date: 01/08/2020

Tufts Center for Engineering Education and Outreach
Updated on: 01/08/2020
'''
import utime
import gc
from machine import UART,Pin
import machine

txpin=1
rxpin=3

uart=UART(0)

class LPF2:
     def __init__(self):
          self.connected = False
          self.tx = machine.Pin(txpin, machine.Pin.OUT)
          self.rx = machine.Pin(rxpin, machine.Pin.IN)

     def send_value(self, data):
          value = (data & 0xFF)
          payload = bytes([0xC0, value, 0xFF ^ 0xC0 ^ value])
          size = uart.write(payload)
          if not size:
               self.connected = False

     def initialize(self):

          self.tx.value(0)
          utime.sleep_ms(500)
          self.tx.value(1)
          uart.init(baudrate=2400, bits=8, parity=None, stop=1)
          uart.write(b'\x00')
          #uart.write(b'\x40\x23\x9C')  #CMD_TYPE (x40)  Type   checksum
          uart.write(b'\x40\x3e\x81')  #CMD_TYPE (x40)  Type   checksum
          uart.write(b'\x49\x00\x00\xB6')  #CMD_MODE (x49)  # Modes  # Views   checksum
          uart.write(b'\x52\x00\xC2\x01\x00\x6E')  #CMD_SPEED (x52)  baud (LSB first)   checksum
          uart.write(b'\x5F\x00\x00\x00\x02\x00\x00\x00\x02\xA0')  #CMD_VERSION (x5F)  Hardware_V  Software_V   checksum
          uart.write(b'\xA0\x00\x4C\x50\x46\x32\x2D\x44\x45\x54\x45\x43\x54\x00\x00\x00\x00\x00\x1D')  #CMD_INFO|bytes|mode  0 name 0   checksum
          uart.write(b'\x98\x01\x00\x00\x00\x00\x00\x00\x20\x41\x07')  #CMD_INFO|3|mode  1 (raw) raw_min  raw_max   checksum
          uart.write(b'\x98\x02\x00\x00\x00\x00\x00\x00\xC8\x42\xEF')  #CMD_INFO|3|mode  2 (pct) pct_min  pct_max   checksum
          uart.write(b'\x98\x03\x00\x00\x00\x00\x00\x00\x20\x41\x05')  #CMD_INFO|3|mode  3 (SI) si_min  si_max   checksum
          uart.write(b'\x80\x04\x00\x7B')  #CMD_INFO|size|mode  0,4,symbol   checksum
          uart.write(b'\x88\x05\x10\x00\x62')  #CMD_INFO|1|mode  5 (FM) Function Map-In   -out   checksum
          uart.write(b'\x90\x80\x01\x00\x03\x00\xED')  #CMD_INFO|2|mode  x80 sample_size   Data_type   Figures   Decimals   checksum
          utime.sleep_ms(5)
          uart.write(b'\x04')
          #display.show(4)
          starttime = utime.ticks_ms()
          currenttime = starttime
          while (currenttime-starttime) < 2000:
               utime.sleep_ms(5)
               data = uart.read(uart.any())
               if data.find(b'\x04') >= 0:
                    self.connected = True
                    #display.show(5)
                    currenttime = starttime+3000
               else:
                    self.connected = True
                    currenttime = utime.ticks_ms()
          self.tx.value(0)
          utime.sleep_ms(10)
          uart.init(baudrate=115200, bits=8, parity=None, stop=1)
          self.send_value(2)# Write your code here :-)


#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
                        print_function)
import six

__license__   = 'GPL v3'
__copyright__ = '2011, Grant Drake <grant.drake@gmail.com>'
__docformat__ = 'restructuredtext en'

import os, traceback
from collections import OrderedDict
try:
    from PyQt5.Qt import Qt, QVBoxLayout, QDialogButtonBox, QGroupBox, QGridLayout, QCheckBox
except ImportError:
    from PyQt4.Qt import Qt, QVBoxLayout, QDialogButtonBox, QGroupBox, QGridLayout, QCheckBox

from calibre.gui2 import warning_dialog

from calibre_plugins.edit_columns.common_utils import (SizePersistedDialog, ImageTitleLayout, debug_print)

DIALOG_NAME = 'Edit Columns'

class UpdateCustomColsDialog(SizePersistedDialog):

    def __init__(self, parent, plugin_action):
        SizePersistedDialog.__init__(self, parent, 'edit columns plugin:update custom columns dialog')
        self.plugin_action = plugin_action
        self.help_anchor   = "UpdateCustomCols"

        self.custom_cols = self.get_custom_columns ()
        self.db = self.plugin_action.gui.library_view.model().db

        self.initialize_controls()
        self.restart = False

    def initialize_controls(self):
        self.setWindowTitle(DIALOG_NAME)
        layout = QVBoxLayout(self)
        self.setLayout(layout)
        title_layout = ImageTitleLayout(self, 'images/icon.png', 'Update custom columns in Library')
        layout.addLayout(title_layout)

        column_group = QGroupBox(_("Columns to update"), self)
        layout.addWidget(column_group)
        column_layout = QGridLayout()
        column_group.setLayout(column_layout)

        pos = 0
        self.checkbox = {}
        for key in sorted (self.custom_cols):
            value = self.custom_cols[key]
            self.checkbox[key] = self.createCheckbox (value)
            column_layout.addWidget(self.checkbox[key], int ((pos / 2)), int ((pos % 2)* 2 + 1), 1, 1)
            pos = pos + 1

        layout.addStretch(1)

        # Dialog buttons
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.ok_clicked)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)

    def ok_clicked(self):

        #debug_print ("Columns: ", self.custom_cols)

        for key, checkbox in six.iteritems(self.checkbox):
            col = self.custom_cols[key]
            #aux = checkbox.checkState == Qt.Checked
            aux = checkbox.isChecked ()

            debug_print (key, "[", col['datatype'], "]: ", checkbox.isChecked())

            if (aux != col['is_editable']):
                debug_print ("Modificando ", col['name'])
                self.db.set_custom_column_metadata (col['colnum'], is_editable=aux)
                self.restart = True
            else:
                debug_print (col['name'], ": ", aux)

        self.accept()

    def get_custom_columns(self):
        column_types = ['composite', '*composite']
        custom_columns = self.plugin_action.gui.library_view.model().custom_columns
        available_columns = {}
        for key, column in six.iteritems(custom_columns):
            typ = column['datatype']
            if typ not in column_types:
                available_columns[key] = column

            # Include type, name (header, long name), is_multiple, display, is_editable
            #'label':record[0],
            #        'name':record[1],
            #        'datatype':record[2],
            #        'editable':bool(record[3]),
            #        'display':json.loads(record[4]),
            #        'normalized':bool(record[5]),
            #        'colnum':record[6],
            #        'is_multiple':bool(record[7]),

            # Modificar: set_custom_column_data
        return available_columns

    def createCheckbox (self, column):
        checkbox = QCheckBox(column['name'], self)
        checkbox.setChecked(column['is_editable'])

        return checkbox


def solve(B, M):
    p = 1
    i = 0
    while True:
        if i + 2 > B:
            return ('IMPOSSIBLE', None, None)
        if p >= M:
            break
        p *= 2
        i += 1
    r = p - M
    j = 0
    cut_indicies = []
    while r != 0:
        if r & 1 == 1:
            cut_indicies.append(B - 2 - j)
        r >>= 1
        j += 1
    return ('POSSIBLE', cut_indicies, B - 2 - i)

def solve2(B, M, t):
    answer, cut_indicies, start_index = solve(B, M)
    print('Case #{}: {}'.format(t + 1, answer))
    if answer != 'POSSIBLE':
        return
    table = [[0 for _ in range(B)] for _ in range(B)]
    if start_index != 0:
        table[0][start_index] = 1
    for i in range(start_index, B):
        if i in cut_indicies:
            continue
        for j in range(i + 1, B):
            if j in cut_indicies:
                continue
            table[i][j] = 1
    for line in table:
        print(''.join(map(str, line)))

T = int(input())
for t in range(T):
    B, M = map(int, input().split())
    solve2(B, M, t)


#!/usr/bin/python

import argparse
import logging
import os
import sys
import threading
import time

from subsystems.emobdh import emObdh
from subsystems.emvirtual import emVirtual

def eekMexLogging():

    # ------------------------------------------------------------
    # Base Logging Setup
    # ------------------------------------------------------------

    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(name)-2s %(module)-10s %(levelname)-4s %(message)s',
                        filename='output/eekmexmain.log',
                        filemode='a')

    # ------------------------------------------------------------
    # Logging Handlers
    # ------------------------------------------------------------

    loggerConsole = logging.StreamHandler()
    loggerConsole.setLevel(logging.INFO)

    loggerFile = logging.FileHandler('output/eekmexbackup.log', 'a')
    loggerFile.setLevel(logging.INFO)

    loggerFileGoogleEarth = logging.FileHandler('output/eekmexprekml.log', 'a')
    loggerFileGoogleEarth.setLevel(logging.WARNING)

    # ------------------------------------------------------------
    # Logging Formatters
    # ------------------------------------------------------------

    loggerConsoleFormatter = logging.Formatter('%(name)-2s: %(module)-10s %(levelname)-4s %(message)s')
    loggerConsole.setFormatter(loggerConsoleFormatter)

    loggerFileFormatter = logging.Formatter('%(asctime)s %(name)-2s %(module)-10s %(levelname)-4s %(message)s')
    loggerFile.setFormatter(loggerFileFormatter)

    loggerFileGoogleEarthFormatter = logging.Formatter('%(process)d %(asctime)s %(message)s', datefmt="%d %m %Y %H %M %S ")
    loggerFileGoogleEarth.setFormatter(loggerFileGoogleEarthFormatter)

    # ------------------------------------------------------------
    # Logging Handlers
    # ------------------------------------------------------------

    logging.getLogger('').addHandler(loggerConsole)
    logging.getLogger('').addHandler(loggerFile)
    logging.getLogger('').addHandler(loggerFileGoogleEarth)

if __name__=='__main__':

    eekMexLogging()

    description = 'EekMex, Aerospace Learning Platform'
    logging.info(description)

    parser = argparse.ArgumentParser(description)
    parser.add_argument('-c', '--clean', help='Mode Clean Up')
    parser.add_argument('-p', '--project', help='Mode Project')
    parser.add_argument('-v', '--virtual', help='Mode Virtual')
    args = parser.parse_args()

    if args.clean == 'files':

        logging.info('Mode Clean Up, Remove Files')

        os.remove('output/eekmexmain.log')
        os.remove('output/eekmexbackup.log')
        os.remove('output/eekmexprekml.log')

    if args.virtual:

        logging.info('Mode Virtual')

        emvirtual = emVirtual()
        while True:
            try:
                pass
            except KeyboardInterrupt:
                logging.info('Mode Virtual ... Exiting')
                sys.exit(0)

    if args.project:

        logging.info('Mode Project')

# End of File


import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.by import By

#############################
# Curso:    Selenium Testing Framework con Python ¡De novato a experto! - Udemy
# Tema:     Capturas de pantalla con Selenium
# Autor:    M.M.
# Fecha:    15/06/2020
#
# Descripción: Uso de la función get_screenshot_as_file para capturar la
# pantalla de prueba
#
###############################
# Log:
# 15/06/2020    MMM - Se crea el archivo
################################

horaGlobal = time.strftime("%H%M%S")

class Test_015(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(15)
        self.driver.maximize_window()

        # -------------------- INGRESO A LA APP --------------------
        self.driver.get("https://www.amazon.com.mx/")

    def test_015(self):
        localizador = self.driver.find_element(By.XPATH,
                                               "/html[1]/body[1]/div[1]/div[5]/div[1]/div[1]/div[1]/ul[1]/li[2]/a[1]")
        self.driver.execute_script("arguments[0].click();", localizador)
        time.sleep(5)

        title = "Amazon.com.mx Mensaje"
        assert title == self.driver.title, "No son iguales"

        self.driver.get_screenshot_as_file(f"../data/capturas/{title}-{horaGlobal}.png")

    def tearDown(self):
        self.driver.close()

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


import math
import time

# from graphTree import TreeGraph
from collections import defaultdict

import numpy as np

from Gui import Gui
from model import *
from naive_player import NaivePlayer
from reward import Reward
from rewardBasedPlayer import RewardBasedPlayer, get_max_difference, randomMax

FIRST_SEARCH = 5
FOE_SEARCH = 3
SEARCH_TIME = 0.1
GAMMA = 0.9
MAX = 10000
USING_GUI =True

class MI_PlayerSimuSave(RewardBasedPlayer):
    def __init__(self, _id):
        super().__init__(_id)
        self.search_agent = Mcts_search(_id, False, self)
        #self.using_reward = 'RewardPro'

    def SelectMove(self, moves, game_state):
        player_order = self.get_player_order(game_state)
        moves = self.filtering_moves(game_state.players[self.id], moves)
        move = self.search_agent.search(moves, game_state, player_order)
        return move

class Mcts_search:
    def __init__(self, _id, log, agent):
        self.id = _id
        self.log = log
        self.agent = agent

    def search(self, moves, game_state, player_order):
        self.tree = []
        self.init_game_state = game_state
        self.init_moves = moves
        self.player_order = player_order

        state = self.init_game_state
        parent = None
        f_move = None
        act_id = self.id
        root_node = Node(state, parent, f_move, act_id, self.tree)
        self.root_node = root_node

        self.time_monitor = defaultdict(float)

        start = time.time()
        n = 0
        # while n<= 4:
        # while True:
        nodes_len = (2**(len(moves)**(1/2)))

        while time.time()-start<len(moves)*SEARCH_TIME:
        #while n<nodes_len:
        #while time.time() - start < 0.2474:
            #a = input('input')
            n += 1
            self.one_search(root_node)
        print('searched times', n)
        print('nodes:', len(self.tree))
        print('{} finished'.format(str(self.agent.__class__)))
        print('seach duration', time.time() - start)
        print('distribute', self.time_monitor)
        print()

        dict = {}
        for m, (c, p) in root_node.moves.items():
            Q = get_max_difference(c.value, self.id) if c is not None else -1000
            dict[m] = Q
        move = randomMax(dict)
        track = self.get_predict_track(root_node, move)
        if USING_GUI:
            Gui(self.tree, 'mcts save')
        return move

    def get_predict_track(self, root_node, move):
        track = [move]
        node = root_node.moves[move][0]
        while True:
            node.mark = True
            id = node.act_id
            children = [c for m, (c,p) in node.moves.items() if c is not None] if node.moves is not None else []
            if len(children) == 0:
                break
            node = max(children, key=lambda x:get_max_difference(x.value, id))

            track.append((node.from_move[1], str(node.from_move[2]), str(id), node, node.value))

        return track

    def one_search(self, root_node):
        start = time.time()
        select_node, move = self.select(root_node)
        self.time_monitor['select']+=(time.time()-start)

        if self.log:
            print('select')
            print(select_node, move)

        start = time.time()
        node = self.expand(select_node, move)
        self.time_monitor['expand'] += (time.time() - start)

        if self.log:
            print('expand')
            print(node)

        start = time.time()
        node, result = self.simulate(node)
        self.time_monitor['simulate'] += (time.time() - start)

        if self.log:
            print(result)

        start = time.time()
        self.backup(node, result)
        self.time_monitor['back'] += (time.time() - start)

    def select(self, root_node):
        node = root_node
        while not node.is_end():
            if node.moves is None:
                moves = self.get_pre_prob(node.state,
                                          node.state.players[node.act_id].GetAvailableMoves(node.state),
                                          node.act_id, self.player_order)
                node.give_moves(moves)
            if not node.is_fully_expanded():
                return node, node.get_unexpanded_move()
            else:
                node = self.best_child(node)
        return node, None

    def best_child(self, p_node):
        if self.log:
            print('jump')
            print(p_node)
        node_v_para = 2 * math.log(p_node.visited)
        uct_dict = {}
        for m, (c, p) in p_node.moves.items():
            Q = get_max_difference(c.value, self.id) / max(c.value) if max(c.value) != 0 else 0
            #N = 1 / c.visited if c.visited != 0 else MAX
            N = ((node_v_para/c.visited)**(1/2)) if c.visited!=0 else MAX
            uct_value = Q + p + N
            uct_dict[c] = uct_value
        node = randomMax(uct_dict)
        return node

    def expand(self, p_node, move):
        if move is None:
            return p_node
        state = copy.deepcopy((p_node.state))
        state.ExecuteMove(p_node.act_id, move)
        parent = p_node
        f_move = move
        act_id = p_node.act_id + 1 if p_node.act_id < len(self.player_order) - 1 else 0
        return Node(state, parent, f_move, act_id, self.tree)

    def simulate(self, s_node):

        player_count = len(self.player_order)
        players = [Simu_Player(i, self.agent.using_reward) for i in range(player_count)]
        act_id = s_node.act_id

        node = s_node
        moves = self.get_pre_prob(node.state,
                                  node.state.players[node.act_id].GetAvailableMoves(node.state),
                                  node.act_id, self.player_order)
        node.give_moves(moves)
        while node.state.TilesRemaining():

            state = copy.deepcopy(node.state)
            #print(state)
            move = players[act_id].SelectMove(node.moves, state)
            #print(move)
            #print(move[1],str(move[2]))

            state.ExecuteMove(act_id, move)
            act_id = act_id + 1 if act_id + 1 < player_count else 0
            new_node = Node(state, node, move, act_id, self.tree)

            moves = self.get_pre_prob(new_node.state,
                                      new_node.state.players[new_node.act_id].GetAvailableMoves(new_node.state),
                                      new_node.act_id, self.player_order)
            new_node.give_moves(moves)

            node =  new_node

            if self.log:
                print(act_id)
                print('id', act_id)
                print('before')
                print(state.detail_str())

        state = copy.deepcopy(node.state)
        if self.log:
            print('simulate over')
        state.ExecuteEndOfRound()
        reward = [0] * player_count
        for i, plr in enumerate(state.players):
            reward[i] = state.players[i].score
        # print(state.detail_str())
        # print(reward)
        game_continuing = True
        for i in range(player_count):
            plr_state = state.players[i]
            completed_rows = plr_state.GetCompletedRows()
            if completed_rows > 0:
                game_continuing = False
                break
        if not game_continuing:
            for i in range(player_count):
                state.players[i].EndOfGameScore()
                reward[i] = state.players[i].score
        else:
            for i, plr in enumerate(state.players):
                expect_score = eval(self.agent.using_reward)(state, i, self.player_order).get_round_expection()
                reward[i] = state.players[i].score + expect_score
        # print(reward)
        return node, reward

    def backup(self, node, result):
        update_node = node
        update_node.update(self.id, result)

        while True:
            update_node = update_node.parent
            if update_node is None:break
            update_node.update(self.id)

    def get_pre_prob(self, game_state, moves, act_id, player_order):
        threshold_most = FOE_SEARCH if act_id!= self.id else FIRST_SEARCH
        #threshold_impo = 4

        ft_moves = self.agent.filtering_moves(game_state.players[act_id], moves)
        move_dict = {}
        for move in ft_moves:
            reward, score_list = self.agent.get_place_reward(game_state, move, act_id, player_order)
            move_dict[move] = reward, score_list

        move_tuple = sorted(move_dict.items(), key=lambda x: x[1][0], reverse=True)[:threshold_most] if len(
            move_dict) > threshold_most else move_dict.items()

        move_prob_dict = {}
        sum_reward = sum([math.e**m[1][0] for m in move_tuple])
        for i, m in enumerate(move_tuple):
            move_prob_dict[m[0]] = None, (math.e**m[1][0])/sum_reward
        return move_prob_dict

class Node:
    def __init__(self, game_state, parent, from_move, act_id, tree):
        self.state = game_state
        self.parent = parent
        self.from_move = from_move
        if self.parent is not None:
            #print( self.parent.moves[from_move])
            self.parent.moves[from_move] = (self, self.parent.moves[from_move][1])
            peers = [c for m, (c, p) in self.parent.moves.items()]
            assert self in peers
        self.act_id = act_id
        self.value = [0] * len(game_state.players)
        tree.append(self)
        self.visited = 0
        self.name = 'n'+str(len(tree))
        self.mark = False
        self.moves = None

    def is_fully_expanded(self):
        for m, (c, p) in self.moves.items():
            if c is None:
                return False
        return True

    def give_moves(self, moves):
        self.moves = moves

    def get_unexpanded_move(self):
        unexp_dict = {}
        for m, (c, p) in self.moves.items():
            if c is None:
                unexp_dict[m] = p
        unexp_prob = sum(unexp_dict.values())
        assert len(unexp_dict) > 0
        # print(unexp_dict.values())
        for m, p in unexp_dict.items():
            unexp_dict[m] = p/unexp_prob
        # print(sum(unexp_dict.values()))
        unexp_m_list = [(k, v) for k, v in unexp_dict.items()]
        p = np.array([v for k, v in unexp_m_list])
        # print(p)
        index = np.random.choice([i for i in range(len(p))], p=p.ravel())
        m, _ = unexp_m_list[index]
        return m

    def is_end(self):
        return not self.state.TilesRemaining()

    def update(self, agent_id, result=None):
        self.visited += 1
        if result is not None:
            for i in range(len(self.value)):
                self.value[i] = (self.value[i]*(self.visited-1)+result[i])/self.visited
            return

        value_list = []
        for m, (c, p) in self.moves.items():
            if c is None or c.visited == 0:
                continue
            value = c.value.copy()
            value_list.append(value)
        value_list = sorted(value_list, key=lambda x: get_max_difference(x, self.act_id), reverse=True)
        self.value = value_list[0]

    def get_children(self):
        return [c for m, (c, p) in self.moves.items()]

    def info(self):
        info = '{:2},{}\nr:{}\np:{}\nv:{}\n{} {}\n{}'.format(
            self.from_move[1], self.from_move[2], ' ', ' ', self.visited,
            str(round(self.value[0], 2)), str(round(self.value[1], 2)),
            self.act_id) if self.from_move is not None else ''
        return info

class Simu_Player(RewardBasedPlayer):
    def __init__(self, _id, using_reward):
        super().__init__(_id)
        self.using_reward = using_reward

    def SelectMove(self, moves, game_state):
        move= max(moves.items(), key=lambda x:x[1][1])[0]
        return move


import numpy as np

def view(x,y):
    if all([i > y for i in x]):
        return 1
    elif any([i >= y for i in x]):
        cnt = 0
        for ii in x:
            if ii < y:
                cnt += 1
            else:
                cnt += 1
                break
        return cnt
    else:
        return len(x)

def solve_p1(input):
    x = len(input[0])
    y = len(input)
    i = [int(i) for s in input for i in s]
    arr = np.array(i).reshape(x,y)
    rarr = np.zeros((x,y))

    for xx in range(x):
        for yy in range(y):

          val = arr[xx,yy]

          if xx in [0,x-1] or yy in [0,y-1]:
            rarr[xx,yy] = 1
          elif any([
                all([e < val for e in list(arr[0:xx,yy])]),
                all([e < val for e in list(arr[(xx+1):x,yy])]),
                all([e < val for e in list(arr[xx,0:yy])]),
                all([e < val for e in list(arr[xx,(yy+1):y])])
            ]):
            rarr[xx,yy] = 1

    return rarr.sum()

def solve_p2(input):
    x = len(input[0])
    y = len(input)
    i = [int(i) for s in input for i in s]
    arr = np.array(i).reshape(x,y)
    rarr = np.zeros((x,y))

    for xx in range(x):
        for yy in range(y):
            val = arr[xx,yy]
            if xx not in [0,x-1] and yy not in [0,y-1]:
                rarr[xx,yy] = 1
            if rarr[xx,yy] == 1:
                tmp = list(arr[0:(xx),yy])
                tmp.reverse()
                rarr[xx,yy] *= view(tmp,val)
                tmp = list(arr[(xx+1):x,yy])
                rarr[xx,yy] *= view(tmp,val)
                tmp = list(arr[xx,0:yy])
                tmp.reverse()
                rarr[xx,yy] *= view(tmp,val)
                tmp = list(arr[xx,(yy+1):y])
                rarr[xx,yy] *= view(tmp,val)

    return rarr.max()

with open("data/d08.txt") as f:
    input = f.read().split("\n")

# Part 1 Answer
print(solve_p1(input))

# Part 2 Answer
print(solve_p2(input))


import os

class Y1A1shifter(object):

    def __init__(self, run, balrog):
        self.jobroot = '/Valarauko-job/jobroot'
        self.outroot = '/Valarauko-job/outroot'
        self.slrroot = '/Valarauko-job/slrroot'
        self.catroot = '/Valarauko-job/catroot'
        self.posroot = '/Valarauko-job/posroot'
        self.homeroot = '/home/user/site'

        gitdir = '/software/Valarauko'
        self.thisdir = os.path.join(gitdir, 'source-code')
        site = os.path.join(gitdir, 'site-setups', 'shifter', 'y1a1')
        #balrog['pyconfig'] = os.path.join(site, 'balrog-config.py')
        balrog['pyconfig'] = os.path.join(gitdir, 'pyconfig', 'y1a1.py')

        astroconfig = os.path.join(site, 'astro_config')
        run['swarp-config'] = os.path.join(astroconfig, '20150806_default.swarp')
        balrog['sexnnw'] = os.path.join(astroconfig, '20150806_sex.nnw')
        balrog['sexconv'] = os.path.join(astroconfig, '20150806_sex.conv')
        balrog['sexparam'] = os.path.join(astroconfig, '20150806_sex.param_diskonly')
        balrog['nosimsexparam'] = os.path.join(astroconfig, '20150806_sex.param_diskonly')
        balrog['sexconfig'] = os.path.join(astroconfig, '20150806_sex.config')

        other = os.path.join(site, 'other')
        run['release'] = 'y1a1_coadd'
        run['db-columns'] = os.path.join(other, 'y1a1_coadd_objects-columns.fits')

def GetShifter(run, balrog):
    if run['shifter']=='esuchyta/balrog-docker:v1':
        return Y1A1shifter(run, balrog)
    elif run['shifter'].endswith('y1a1'):
        return Y1A1shifter(run, balrog)


from setuptools import setup
from glob import glob

package_name    = 'atlas_basic'

setup(
    name=package_name,
    version='0.0.0',
    packages=[package_name],
    data_files=[
        ('share/ament_index/resource_index/packages',
            ['resource/' + package_name]),
        ('share/' + package_name, ['package.xml'],),
        ('share/' + package_name, glob('launch/*.launch.py'))
    ],
    install_requires=['setuptools'],
    zip_safe=True,
    maintainer='atlas',
    maintainer_email='lorenzo@caltech.edu',
    description='Basic nodes to run Atlas: wheel control, encoder counting, command, etc.',
    license='Apache License 2.0',
    tests_require=['pytest'],
    entry_points={
        'console_scripts': [
            'wheel_control  = atlas_basic.wheel_control.wheel_control:main',
            'odometry       = atlas_basic.odometry.odometry:main',
            'teleop         = atlas_basic.odometry.teleop:main',
            'planner        = atlas_basic.planner.planner:main',
        ],
    },
)


import logging
import os
import re
from typing import Any, Dict, List, Union

import requests
from bs4 import BeautifulSoup
from linebot.models import FlexSendMessage, TextSendMessage

from utils import sqlite
from utils.flex import skill_list, specific_flex
from utils.language import Language
from utils.pikalytics import Pikalytics
from utils.poke_crawler import (
    arrange_text,
    find_pokemon_image,
    pokemon_wiki,
)

logger = logging.getLogger(__file__)

def find_specific_pokemon_all_status(pokemon_name: str = "Roaring Moon") -> List[Dict[str, Any]]:
    series_search_name: str = pokemon_name
    # Force to change name to %20 (e.g. Roaring Moon)
    if re.findall("\w+\s+\w+", pokemon_name):
        poke_split: List[str] = series_search_name.split(' ')
        series_search_name = f'{poke_split[0]}%20{poke_split[1]}'.lower()
    series: str = os.getenv('SERIES')
    url: str = f"https://www.pikalytics.com/pokedex/{series}/{series_search_name}"
    logger.debug('Pokemon series web crawler query: ' + url)

    rs: requests.Response = requests.get(url=url)
    specific_soup: BeautifulSoup = BeautifulSoup(rs.text, "html.parser")
    details: List[BeautifulSoup] = specific_soup.select(
        '.pokedex-category-wrapper')
    logger.debug(pokemon_name+' record start...')

    if len(details) == 0:
        logger.info(pokemon_name+' is not in this series.')
        return [{
            "type": "bubble",
            "body": {
                "type": "box",
                "layout": "vertical",
                "contents": [
                    {
                        "type": "text",
                        "text": f"賽季 {series} 沒有 {pokemon_name} 出場紀錄..",
                        "weight": "bold",
                        "size": "md",
                        "wrap": True
                    }
                ]
            }
        }]
    else:
        contents: List[Dict[str, Any]] = []
        # 或許可以把對應 API 都放在 mapping 裏面
        for index in range(1, len(details)):
            s: List[BeautifulSoup] = details[index].select(
                '.pokedex-move-entry-new')
            item: str = ''
            items: List[str] = []
            # 整理爬蟲下來各個清單對應的陣列
            for entry_idx in range(0, len(s)):
                if index == 5 and entry_idx == 5:
                    break

                item = arrange_text(s[entry_idx].text)
                if item[0] == 'Other':
                    break
                items.append(item)

            pika: Pikalytics = Pikalytics(index=index, url=url)
            pika.poke_mapping(items)

            logger.debug('Pokemon all body status: ' + str(pika.template))

            # 輸出成 Flex，若 API 有圖片可能需要另外處理
            contents.append(skill_list(
                name=pika.template['name'],
                abilities=pika.template['abilities'],
                url=url))
        logger.debug('Ready to generate FlexMessage...')
        return contents

def search_specific_pokemon_by_wiki(pokemon_name: str = '快龍') -> Union[FlexSendMessage, TextSendMessage]:
    # If found, return SQL data.
    # If not, return None.

    language = Language(pokemon_name)
    name_location, _ = language.match()
    pokemon_row_list: List[Dict[str, str]] = pokemon_wiki(
        pokemon_name=pokemon_name, language=name_location)

    if pokemon_row_list and len(pokemon_row_list) > 0:
        eng_name, poke_img = find_pokemon_image(pokemon_row_list)
        logger.debug(f'Pokemon image url" {poke_img}')
        try:
            with sqlite.connect() as con:
                poke_query: Dict[str, str] = sqlite.exec_one(
                    con,
                    f"SELECT idx, name_zh FROM t_pokemon WHERE name_en = '{eng_name}'")
                logger.info(
                    f"Specific Pokemon query from sqlite: {poke_query}")
                poke_detail: Dict[str, Union[int, str]] = sqlite.exec_one(
                    con,
                    f"SELECT * FROM t_pokemon_detail_base_stat WHERE idx = '{poke_query.get('idx')}'"
                )
                logger.info(f"The Pokemon status is: {poke_detail}")

            # zh_name, _ = find_pokemon_name(eng_name)
            response_flex: Dict[str, Any] = specific_flex(
                image=poke_img, name=[pokemon_name, eng_name], body=poke_detail)
            return FlexSendMessage(alt_text=eng_name, contents=response_flex)
        except:
            logger.info(f'{pokemon_name} not in SQL')
            return None
    else:
        logger.info(f"Keyword {pokemon_name} not found.")
        return None


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import struct

import compas
from compas import _iotools
from compas.geometry import Translation
from compas.utilities import geometric_key

class STL(object):
    """Class for working with STL files.

    Parameters
    ----------
    filepath : path string | file-like object | URL string
        A path, a file-like object or a URL pointing to a file.
    precision : str, optional
        A COMPAS precision specification.

    Attributes
    ----------
    reader : :class:`STLReader`
        A STL file reader.
    parser : :class:`STLParser`
        A STL file parser.

    """

    def __init__(self, filepath, precision=None):
        self.filepath = filepath
        self.precision = precision
        self._is_parsed = False
        self._reader = None
        self._parser = None
        self._writer = None

    @property
    def reader(self):
        if not self._is_parsed:
            self.read()
        return self._reader

    @property
    def parser(self):
        if not self._is_parsed:
            self.read()
        return self._parser

    def read(self):
        """Read and parse the contents of the file.

        Returns
        -------
        None

        """
        self._reader = STLReader(self.filepath)
        self._parser = STLParser(self._reader, precision=self.precision)
        self._is_parsed = True

    def write(self, mesh, **kwargs):
        """Write a mesh to the file.

        Parameters
        ----------
        mesh : :class:`~compas.datastructures.Mesh`
            The mesh.
        binary : bool, optional
            Flag indicating that the file should be written in binary format.
        solid_name : str, optional
            The name of the solid.
            Defaults to the name of the mesh.
        precision : str, optional
            COMPAS precision specification for parsing geometric data.

        Returns
        -------
        None

        """
        self._writer = STLWriter(self.filepath, mesh, **kwargs)
        self._writer.write()

class STLReader(object):
    """Class for reading raw geometric data from STL files.

    Parameters
    ----------
    filepath : path string | file-like object | URL string
        A path, a file-like object or a URL pointing to a file.

    References
    ----------
    * http://paulbourke.net/dataformats/stl/

    """

    def __init__(self, filepath):
        self.filepath = filepath
        self.file = None
        self.header = None
        self.facets = []
        self.read()

    def read(self):
        """Read the data.

        Returns
        -------
        None

        """
        is_binary = False
        with _iotools.open_file(self.filepath, "rb") as file:
            line = file.readline().strip()
            if b"solid" in line:
                is_binary = False
            else:
                is_binary = True
        try:
            if not is_binary:
                self._read_ascii()
            else:
                self._read_binary()
        except Exception:
            # raise if it was already detected as binary, but failed anyway
            if is_binary:
                raise
            # else, ascii parsing failed, try binary
            is_binary = True
            self._read_binary()

    # ==========================================================================
    # ascii
    #
    # @see: https://en.wikipedia.org/wiki/STL_(file_format)
    #
    # solid name
    # facet normal ni nj nk
    #     outer loop
    #         vertex v1x v1y v1z
    #         vertex v2x v2y v2z
    #         vertex v3x v3y v3z
    #     endloop
    # endfacet
    # endsolid name
    #
    # ==========================================================================

    def _read_ascii(self):
        with _iotools.open_file(self.filepath, "r") as file:
            self.file = file
            self.file.seek(0)
            self.facets = self._read_solids_ascii()

    def _read_solids_ascii(self):
        solids = {}
        facets = []

        while True:
            line = self.file.readline().strip()

            if not line:
                break

            parts = line.split()

            if parts[0] == "solid":
                if len(parts) == 2:
                    name = parts[1]
                else:
                    name = "solid"
                solids[name] = []

            elif parts[0] == "endsolid":
                name = None

            elif parts[0] == "facet":
                facet = {"normal": None, "vertices": None}
                if parts[1] == "normal":
                    facet["normal"] = [float(parts[i]) for i in range(2, 5)]

            elif parts[0] == "outer" and parts[1] == "loop":
                vertices = []

            elif parts[0] == "vertex":
                xyz = [float(parts[i]) for i in range(1, 4)]
                vertices.append(xyz)

            elif parts[0] == "endloop":
                facet["vertices"] = vertices

            elif parts[0] == "endfacet":
                solids[name].append(facet)
                facets.append(facet)

            # no known line start matches, maybe not ascii
            elif not parts[0].isalnum():
                raise RuntimeError("File is not ASCII")

        return facets

    # ==========================================================================
    # binary
    #
    # @see: https://en.wikipedia.org/wiki/STL_(file_format)
    #
    # UINT8[80] - Header
    # UINT32 - Number of triangles
    #
    # foreach triangle
    # REAL32[3] - Normal vector
    # REAL32[3] - Vertex 1
    # REAL32[3] - Vertex 2
    # REAL32[3] - Vertex 3
    # UINT16 - Attribute byte count
    # end
    #
    # ==========================================================================

    def _read_uint16(self):
        bytes_ = self.file.read(2)
        return struct.unpack("<H", bytes_)[0]

    def _read_uint32(self):
        bytes_ = self.file.read(4)
        return struct.unpack("<I", bytes_)[0]

    def _read_binary(self):
        with _iotools.open_file(self.filepath, "rb") as file:
            self.file = file
            self.file.seek(0)
            self.header = self._read_header_binary()
            self.facets = self._read_facets_binary()

    def _read_header_binary(self):
        bytes_ = self.file.read(80)
        return struct.unpack("80s", bytes_)[0]

    def _read_number_of_facets_binary(self):
        return self._read_uint32()

    def _read_facet_binary(self):
        # Read full facet at once
        # 4 bytes per float * 3 floats per vector/vertex * 4 items (1 vector + 3 vertices)
        bytes_ = self.file.read(48)
        floats_ = struct.unpack("<12f", bytes_)

        normal = floats_[0:3]
        vertices = (floats_[3:6], floats_[6:9], floats_[9:12])
        keys = (bytes_[12:24], bytes_[24:36], bytes_[36:48])

        # Skip two-byte attributes, it's not used anywhere (by anyone - on this planet)
        self.file.seek(2, 1)

        return {"normal": normal, "vertices": vertices, "keys": keys}

    def _read_facets_binary(self):
        facets = []
        n = self._read_number_of_facets_binary()
        for i in range(n):
            facets.append(self._read_facet_binary())
        return facets

class STLParser(object):
    """Class for parsing data from a STL file.

    The parser converts the raw geometric data of the file
    into corresponding COMPAS geometry objects and data structures.

    Parameters
    ----------
    reader : :class:`STLReader`
        A STL file reader.
    precision : str, optional
        COMPAS precision specification for parsing geometric data.

    Attributes
    ----------
    vertices : list[list[float]]
        The vertex coordinates.
    faces : list[list[int]]
        The faces as lists of vertex indices.

    """

    def __init__(self, reader, precision=None):
        self.precision = precision
        self.reader = reader
        self.vertices = None
        self.faces = None
        self.parse()

    def parse(self):
        """Parse the the data found by the reader.

        Returns
        -------
        None

        """
        gkey_index = {}
        vertices = []
        faces = []
        for facet in self.reader.facets:
            face = []
            facet_vertices = facet["vertices"]
            for i in range(3):
                xyz = facet_vertices[i]
                if "keys" in facet:
                    gkey = facet["keys"][i]
                else:
                    gkey = geometric_key(xyz, self.precision)
                if gkey not in gkey_index:
                    gkey_index[gkey] = len(vertices)
                    vertices.append(xyz)
                face.append(gkey_index[gkey])
            faces.append(face)
        self.vertices = vertices
        self.faces = faces

class STLWriter(object):
    """Class for writing geometric data to a PLY file.

    Parameters
    ----------
    filepath : path string | file-like object | URL string
        A path, a file-like object or a URL pointing to a file.
    mesh : :class:`~compas.datastructures.Mesh`
        The mesh.
    binary : bool, optional
        Flag indicating that the file should be written in binary format.
    solid_name : str, optional
        The name of the solid.
        Defaults to the name of the mesh.
    precision : str, optional
        COMPAS precision specification for parsing geometric data.

    """

    def __init__(self, filepath, mesh, binary=False, solid_name=None, precision=None):
        self.filepath = filepath
        self.mesh = mesh
        self.solid_name = solid_name or mesh.name
        self.precision = precision or compas.PRECISION
        self.file = None
        self.binary = binary

    @property
    def _vertex_xyz(self):
        bbox = self.mesh.bounding_box()
        xmin, ymin, zmin = bbox[0]
        if not self.binary and (xmin < 0 or ymin < 0 or zmin < 0):
            T = Translation.from_vector([-xmin, -ymin, -zmin])
            mesh = self.mesh.transformed(T)
        else:
            mesh = self.mesh
        return {vertex: mesh.vertex_attributes(vertex, "xyz") for vertex in mesh.vertices()}

    def write(self):
        """Write the data to a file.

        Returns
        -------
        None

        """
        if not self.mesh.is_trimesh():
            raise ValueError("Mesh must be triangular to be encoded in STL.")
        if not self.binary:
            with _iotools.open_file(self.filepath, "w") as self.file:
                self._write_header()
                self._write_faces()
                self._write_footer()
        else:
            with _iotools.open_file(self.filepath, "wb") as self.file:
                self.file.seek(0)
                self._write_binary_header()
                self._write_binary_num_faces()
                self._write_binary_faces()

    def _write_header(self):
        self.file.write("solid {}\n".format(self.solid_name))

    def _write_footer(self):
        self.file.write("endsolid {}\n".format(self.solid_name))

    def _write_faces(self):
        vertex_xyz = self._vertex_xyz
        for face in self.mesh.faces():
            normal = list(self.mesh.face_normal(face))
            self.file.write("facet normal {0} {1} {2}\n".format(*normal))
            self.file.write("    outer loop\n")
            for vertex in self.mesh.face_vertices(face):
                self.file.write("        vertex {0} {1} {2}\n".format(*vertex_xyz[vertex]))
            self.file.write("    endloop\n")
            self.file.write("endfacet\n")

    def _write_binary_header(self):
        self.file.write(b"\0" * 80)

    def _write_binary_num_faces(self):
        try:
            self.file.write(struct.pack("<L", self.mesh.number_of_faces()))
        except struct.error:
            raise ValueError("Mesh must have fewer than 4294967295 faces to be written to binary STL.")

    def _write_binary_faces(self):
        vertex_xyz = self._vertex_xyz
        for face in self.mesh.faces():
            normal = list(self.mesh.face_normal(face))
            self.file.write(struct.pack("<3f", *normal))
            for vertex in self.mesh.face_vertices(face):
                self.file.write(struct.pack("<3f", *vertex_xyz[vertex]))
            self.file.write(b"\0\0")


def count_n_dig(num):
	# "12345678"
	s_num = str(num)
	dig_num = len(s_num)
	bottom_half = int(s_num[dig_num/2:])
	top_half = int(s_num[:dig_num/2][::-1])
	if top_half == 1:
		return bottom_half
	return top_half + bottom_half

def count(num):
	if num < 10:
		return num
	if num % 10 == 0:
		return count(num-1) + 1
	ret = 10
	p = 10
	while p*10 <= num:
		ret += count_n_dig(p*10 - 1) + 1
		p *= 10
	ret += count_n_dig(num)
	return ret

def parse(filename):
	output = open("output.txt", "w")
	with open(filename, "rb") as f:
		T = int(f.readline())
		for i in xrange(T):
			num = int(f.readline())
			res = count(num)
			output.write("Case #%d: %d\n" % (i+1, res))

parse("input.txt")


import logging
import os
from mq_http_sdk.mq_exception import MQExceptionBase
from mq_http_sdk.mq_producer import *
from mq_http_sdk.mq_client import *

def initialize(context):
    global msg_producer,topic
    access_key_id = context.credentials.access_key_id
    access_key_secret = context.credentials.access_key_secret
    security_token = context.credentials.security_token
    endpoint = os.getenv('ROCKETMQ_ENDPOINT')
    instanceID = os.getenv('INSTANCEID')
    topic = os.getenv('TOPIC')
    mq_client = MQClient(endpoint, access_key_id, access_key_secret, security_token)
    msg_producer = mq_client.get_producer(instanceID, topic)

def handler(environ, start_response):
    logger = logging.getLogger()
    logger.info("Publishi Message To Topic {}".format(topic))
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]

    try:
        msg = TopicMessage(
            "hello rocketmq",
            "tag greeting"
        )
        msg.put_property("a", 1)
        msg.set_message_key("MessageKey")
        re_msg = msg_producer.publish_message(msg)
        start_response(status, response_headers)
        return "Publish Message Succeed. MessageID:%s , BodyMD5 : %s" % (re_msg.message_id, re_msg.message_body_md5)
    except MQExceptionBase as e:
        if e.type == "TopicNotExist":
            logger.info("Topic Not Exist")
        raise RuntimeError(e)


import socket

localIP     = "127.0.0.1"
localPort   = 20001
bufferSize  = 1024

msgFromServer       = "Hello UDP Client"
bytesToSend         = str.encode(msgFromServer)

# Create a datagram socket
UDPServerSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM, socket.IPPROTO_UDP)

UDPServerSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

# Bind to address and ip
UDPServerSocket.bind(("", localPort))

print("UDP server up and listening")

# Listen for incoming datagrams
def write_esp(x):

    #bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
    #message = bytesAddressPair[0]
    #address = bytesAddressPair[1]
    #clientMsg = "Message from Client:{}".format(message)
    #clientIP  = "Client IP Address:{}".format(address)
    #print(clientMsg)
    #print(clientIP)
    # Sending a reply to client
    UDPServerSocket.sendto(bytes(x, "utf-8"), ("<broadcast>", 4210))


from typing import Callable
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from app.config.settings import Settings
from .models import Base

class DatabaseManager:
    def __init__(self) -> None:
        self.SQLALCHEMY_DATABASE_URI = None
        self.engine = None
        self.session_factory = None

    def initialize(self, settings: Settings) -> None:
        self.settings = settings
        self.engine = create_async_engine(
            self.settings.SQLALCHEMY_DATABASE_URI, echo=True, pool_pre_ping=True)
        self.session_factory = scoped_session(sessionmaker(
            self.engine, class_=AsyncSession, expire_on_commit=False))

    async def get_db_session(self) -> Callable[..., AsyncSession]:
        session: AsyncSession = self.session_factory()
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()

    async def init_models(self) -> None:
        async with self.engine.begin() as conn:
            await conn.run_sync(Base.metadata.create_all)


import uuid
from sqlalchemy import create_engine
from shared.database_service import DatabaseService
from shared.table_one import TableOne
from application import DB_URL

def create_entries(number_of_seeds):
    entries_to_write = []
    for i in range(0, number_of_seeds):
        entry = TableOne()
        entry.property_one = str(uuid.uuid4())
        entry.property_two = str(uuid.uuid4())
        entry.property_three = str(uuid.uuid4())
        entry.property_four = str(uuid.uuid4())
        entry.property_five = str(uuid.uuid4())
        entry.property_six = str(uuid.uuid4())
        entry.property_seven = str(uuid.uuid4())
        entry.property_eight = str(uuid.uuid4())
        entries_to_write.append(entry)
    return entries_to_write

def persist_entries(session, entries_to_write):
    for entry in entries_to_write:
        session.add(entry)
    session.commit()

def query_entries(session):
    entries = session.query(TableOne).all()
    print(len(entries))
    print(type(entries[0]))

@profile
def start():
    database_service = DatabaseService()
    database_service.init(create_engine(DB_URL))

    with database_service.scoped_session() as session:
        session.query(TableOne).delete()
        entries = create_entries(100000)
        persist_entries(session, entries)
        query_entries(session)

if __name__ == '__main__':
    start()