# ArchivistBot.py
# Version 0.1
# Purpose:
# For the indexing and querying of text

import discord
import asyncio
import pickle
import random
import secrets
import re
import time
import threading
from Objs.DiscordSwitchboard.DiscordSwitchboard import DiscordSwitchboard, PriorityLevel
from Objs.CardsAgainstGovernance.CardsAgainstGovernance import CardsAgainstGovernance
from Objs.Deck.Deck import Card
from Configs.CardList import QuestionsList, AnswersList

ADMIN_ID = "192729741395099648"
CHANNEL = "484621382810992661"

HELP_MESSAGE = """```
Welcome to Cards Bot
```"""

class Cardsbot:
    def __init__(self):
        # For now we assume only one game at a time. We can try doing more in the future as necessary.
        self.game_started = False
        self.game = None
        self.game_lock = threading.Lock()

    @staticmethod
    def MakeCards():
        questions_list = []
        # Make cards
        for card_param in QuestionsList:
            for _ in range(card_param[1]):
                questions_list.append(Card(card_param[0], card_param[2]))
        answers_list = []
        for card_param in AnswersList:
            for _ in range(card_param[1]):
                answers_list.append(Card(card_param[0], card_param[2]))
        return questions_list, answers_list

    def main(self):
        client = discord.Client()

        @client.event
        async def on_ready():
            self.switchboard = DiscordSwitchboard()
            self.switchboard.MustHave(channel_id=CHANNEL, is_private=True, any=True)   # We're not using it for any other channel right now, so let's just ahead and do this.

        @client.event
        async def on_message(message):
            this_message = message.content.lower()
            if this_message == "!help cardbot":
                await client.send_message(message.channel, HELP_MESSAGE)
                return
            if this_message == '!cardshutdown' and message.author.id == ADMIN_ID:
                await client.logout()
                return
            # We do this explicitly here for clarity but in the future the class can take care of it.
            if this_message == '!cardpreparegame' and message.channel.id == CHANNEL and not self.game_started:
                with self.game_lock:
                    self.game = CardsAgainstGovernance(self.switchboard, message.channel, client, self.MakeCards())
                    self.game_started = True
                return
            await self.switchboard.on_message(message)

        # Blocking. Must be last.
        client.run(secrets.BOT_TOKEN)

if __name__ == '__main__':
    bot = Cardsbot()
    bot.main()


from datetime import datetime
from time import perf_counter

from geopy import distance

from pyspark.sql.window import Window
import pyspark.sql.functions as F
from pyspark.sql.types import FloatType, ArrayType, StructType, StructField, StringType

# Increment this version number when there is a new release:
__author__  = 'Christopher Morris'
__email__   = 'christopher.morris@jacobs.com'
__version__ = '0.1.0'

class VelocityCalculations:
    def __init__(self, single_partition_length=100):
        self.single_partition_length = single_partition_length

    def compute_velocities(self, df, ):
        # Select the columns relevant for computation
        df = df.select('imo', 'basedatetime', 'lat', 'lon')

        # Pull lat and lon together into a tuple structure
        df = df.withColumn('latlon', F.struct('lat', 'lon'))

        # Create the Spark Window that allows the data to be ordered within each IMO
        w = Window.orderBy('basedatetime').partitionBy('imo')

        # These index columns help create groupings of latlons within an individual IMO
        df = df.withColumn('index', F.row_number().over(w))
        df = df.withColumn('index_previous', F.lag(df['index']).over(w))

        # Create lagged pairs of lat-lon and basedatetime
        df = df.withColumn('latlon_previous', F.lag(df['latlon']).over(w))
        df = df.withColumn('basedatetime_previous', F.lag(df['basedatetime']).over(w))

        df = df.withColumn('latlon_pair', F.struct(df['latlon_previous'], df['latlon']))
        df = df.withColumn('basedatetime_pair', F.struct(df['basedatetime_previous'], df['basedatetime']))

        # print(df.count())
        df = df.filter(df['latlon_previous'].isNotNull())
        # print(df.count())
        # should be a drop of 22 for this test table, which has 22 distinct vessels

        # Find the total volume for each IMO
        # dfg = df.groupBy('imo').agg(F.max('index_previous').alias('total_rows'))

        # Collect lists of these records, to make the PySpark UDF more efficient, as
        # these UDFs operate more quickly the more data that can be pushed into a single instance
        df = df.withColumn('group_id', F.floor(df['index_previous'] / self.single_partition_length))

        # Create lists for faster operation in the UDF
        df = df.groupBy('imo', 'group_id').agg(F.collect_list(F.col('latlon_pair')).alias('latlon_pair'),
                                               F.collect_list(F.col('basedatetime_pair')).alias('basedatetime_pair'))
        num_partitions = df.count()
        df = df.repartition(num_partitions)
        # df.show()

        def dist_time_vel(latlon_previous, latlon, basedatetime_previous, basedatetime):
            """From lat-lon pairs at two timestamps, calculate the distnace,
            time, and average velocity traveled.
            """

            error = "No error"
            try:
                dist = distance.distance(latlon_previous, latlon).km
            except Exception as e:
                error = str(e)
                dist = float('NaN')

            try:
                t0 = datetime.fromisoformat(basedatetime_previous)
                t1 = datetime.fromisoformat(basedatetime)
                delta_hrs = (t1 - t0).total_seconds() / 60 / 60
            except Exception as e:
                error = str(e)
                delta_hrs = float('NaN')

            try:
                velocity = dist / delta_hrs
            except Exception as e:
                error = str(e)
                velocity = float('NaN')

            return (dist, delta_hrs, velocity, error)

        def dist_time_vel_list(latlon_pair_list, basedatetime_pair_list):
            """This function is set up as a PySpark UDF that operates
            over lists. This increases the function of the UDF, by purposefully
            bringing more data locally for each Spark executor.
            """
            start = perf_counter()

            dist_list, delta_hrs_list, velocity_list, error_list = [], [], [], []
            for i, _ in enumerate(latlon_pair_list):
                latlon_previous = latlon_pair_list[i][0]
                latlon = latlon_pair_list[i][1]
                basedatetime_previous = basedatetime_pair_list[i][0]
                basedatetime = basedatetime_pair_list[i][1]

                dist, delta_hrs, velocity, error = dist_time_vel(latlon_previous,
                                                                                latlon,
                                                                                basedatetime_previous,
                                                                                basedatetime)

                dist_list.append(dist)
                delta_hrs_list.append(delta_hrs)
                velocity_list.append(velocity)
                error_list.append(error)

            end = perf_counter()
            execution_time = (end - start)

            return (dist_list, delta_hrs_list, velocity_list, error_list, execution_time)

        # Register the UDF and its schema
        schema = StructType([
                    StructField("distance_km", ArrayType(FloatType()), True),
                    StructField("delta_hrs", ArrayType(FloatType()), True),
                    StructField("velocities_kph", ArrayType(FloatType()), True),
                    StructField("error", ArrayType(StringType()), True),
                    StructField("execution_time", FloatType(), True),
                ])

        dist_time_vel_udf = F.udf(dist_time_vel_list, schema)

        # Compute the UDF value for each
        df = df.withColumn('combined_output', dist_time_vel_udf(
                                                                'latlon_pair',
                                                                'basedatetime_pair',
                                                            ))

        # Extract the desired columns, and undo the list creation from
        # earlier that allowed for more efficient PySpark calculation
        extract_cols = ['distance_km', 'delta_hrs', 'velocities_kph', 'error']
        for column in extract_cols + ['execution_time']:
            df = df.withColumn(column, df['combined_output'].getItem(column))

        df = df.drop('lat','lon','combined_output')

        zipcols = extract_cols + ['latlon_pair', 'basedatetime_pair']
        df = df.withColumn('tmp', F.arrays_zip(*zipcols))
        df = df.withColumn('tmp', F.explode('tmp'))
        df = df.drop(*zipcols)

        for output_column in zipcols:
            df = df.withColumn(output_column, F.col('tmp').getItem(output_column))

        df = df.drop('tmp')

        df = df.withColumn('latlon_previous', df['latlon_pair'].getItem('latlon_previous'))
        df = df.withColumn('latlon', df['latlon_pair'].getItem('latlon'))
        df = df.withColumn('basedatetime_previous', df['basedatetime_pair'].getItem('basedatetime_previous'))
        df = df.withColumn('basedatetime', df['basedatetime_pair'].getItem('basedatetime'))

        df = df.withColumnRenamed('basedatetime_previous','t_start')
        df = df.withColumnRenamed('basedatetime','t_end')

        df = df.withColumn('lat_start', df['latlon_previous'].getItem('lat'))
        df = df.withColumn('lon_start', df['latlon_previous'].getItem('lon'))

        df = df.withColumn('lat_end', df['latlon'].getItem('lat'))
        df = df.withColumn('lon_end', df['latlon'].getItem('lon'))

        df = df.select(
                    'imo',
                    't_start',
                    't_end',
                    'lat_start',
                    'lon_start',
                    'lat_end',
                    'lon_end',
                    'distance_km',
                    'delta_hrs',
                    'velocities_kph',
                    'error',
                    'execution_time'
                    )

        return df


from flask import Flask, render_template, request
from subprocess import Popen, PIPE
from time import sleep
from os import path
global p

app = Flask(__name__, static_folder='static', template_folder='../templates')

def LastNlines(file, N):
    """
    Utillity function to read last n lines of logfile
    :param file:
    :param N:
    :return:
    """
    str = '

Previous result:'
    for line in (file.readlines() [-N:]):
        str+='
'
        str+=line
    return str

# Index page
@app.route('/')
def index():
    global p

    if request.args.get("start") == '1':
        print('Starting process')
        p = startProcess()

    if path.exists("../log/output.log"):
        prev_result =LastNlines(open ("../log/output.log", "r"), 1)
    else:
        prev_result = ''

    try:
        if p.poll() is None:
            # Process exists and is running
            logdata = ''
            with open ("../log/output.log", "r") as myfile:
                for last_line in myfile:
                    logdata=last_line.split('|')[-1]
            return render_template('index.html', data={'status':'running', 'logdata':logdata,'prev_result':prev_result})
        else:
            # Process object exists, but is not running
            return render_template('index.html', data={'status':'not running','prev_result':prev_result})

    except NameError as e:
        # Process object does not exist
        print(e)
        return render_template('index.html', data={'status':'not running','prev_result':prev_result})

def startProcess():
    """
    Starts async process that optimizes portfolio
    :return: Process object
    """
    # Getting arguments
    parameters = []
    if request.args.get('tickers','') != '':
        parameters.extend(['--tickers='+request.args.get('tickers','').replace(" ","")])

    if request.args.get('iterations','') != '':
        parameters.extend(['--iterations='+request.args.get('iterations','')])

    if request.args.get('risk_free_interest','') != '':
        parameters.extend(['--risk_free_interest='+request.args.get('risk_free_interest','')])

    if request.args.get('end_date','') != '':
        parameters.extend(['--end_date='+request.args.get('end_date','')])

    if request.args.get('start_date','') != '':
            parameters.extend(['--start_date='+request.args.get('start_date','')])

    if request.args.get('number_of_processes','') != '':
                parameters.extend(['--number_of_processes='+request.args.get('number_of_processes',1)])

    if request.args.get('number_of_chunks','') != '':
                parameters.extend(['--number_of_chunks='+request.args.get('number_of_chunks',1)])

    # Defining log
    log = open('../log/output.log', "w")
    command = ['python','-u', './PortfolioOptimizer.py','--verbose=1']
    command.extend(parameters)

    p = Popen(command, stdout=log)
    return p

if __name__ == '__main__':
    print('Ready to serve...')
    app.run(port=5000, debug=True, use_reloader=False, host='0.0.0.0')


import requests
# import pycurl
import json
import time
import os

import asyncio
import websockets

BENCHMARK_TIME = 10
servers = {
    'http': 8000,
    'turbogears2': 8003,
    'bottle': 8007
}
WEBSOCKET_PORT = 8010
RESULTS_FILE = '/benchmarks/results.json'

def requests_benchmark(port: int):
    start = time.time()
    counter = 0

    while time.time() - start < BENCHMARK_TIME:
        r = requests.get(f"http://localhost:{port}")
        if r.status_code != 200:
            print("GET Error: status code is", r.status_code)
            exit()
        counter += 1

    return counter

async def websocket_request(results):
    ws_url = f"ws://localhost:{WEBSOCKET_PORT}"
    async with websockets.connect(ws_url) as websocket:
        start = time.time()
        counter = 0
        while time.time() - start < BENCHMARK_TIME:
            await websocket.send('')
            await websocket.recv()
            print('Received response')
            counter += 1
        results['websocket'] = counter
        with open(RESULTS_FILE, 'w') as file:
            json.dump(results, file)

if __name__ == "__main__":
    print("Requests client started.")

    results = {}
    for server in servers:
        requests_counter = requests_benchmark(servers[server])

        if os.path.exists(""):
            with open(RESULTS_FILE, 'r') as file:
                results = json.load(file)

        results['requests_' + server] = requests_counter
        with open(RESULTS_FILE, 'w') as file:
            json.dump(results, file)

    asyncio.run(websocket_request(results))


import openpyxl

# 1) 엑셀 만들기
wb = openpyxl.Workbook()

# 2) 엑셀 워크시트 만들기

ws = wb.create_sheet('학생 정보')

# 3) 데이터 추가하기

ws['A1'] = '학번'
ws['B1'] = '이름'

ws['A2'] = 2020123456
ws['B2'] = '백준호'

# 4) 엑셀 저장하기

wb.save(r'학생정보.xlsx')


import numpy as np
from numpy import *
import torch

# input
# hamdis是距离矩阵 还没有排序
# train_label test_label是array
def cal_mAP(train_label,test_label,hamdis):
    numtest, numtrain = size(hamdis,0),size(hamdis,1)
    apall = torch.zeros(1,numtest)
    for i in range(numtest):
        if i%100 == 0:
            print(i," ap has been processed")
        y = torch.Tensor(hamdis[i]).int()  # y是一个1*60000的矩阵，表示test中的数据点i到数据集中其他点之间的距离
        y.resize_((1,len(y)))
        x = 0
        p = 0
        temp_test_label = test_label[i].reshape(1,len(test_label[i]))
        new_label = ((temp_test_label.mm(train_label.T))>0).int()
        # new_label = (test_label[i].resize_(1,len(test_label[i]))).mm((train_label).T).float()
        topK = numtrain  # 所有的样本数量
        IX = np.lexsort(np.array(y))
        # y new_label
        # print("begin")
        # print(temp_y[0,10:20])
        # print(temp_label[0,10:20])
        # print(compose[:,:10])
        # temp_0 = compose[0,:]  # 距离
        # temp_0 = temp_0.reshape(1,numtrain)
        # print(temp_0[0,10:20])
        # temp_1 = compose[1,:]  # 相似性
        # temp_1 = temp_1.reshape((1,numtrain))
        # print(temp_1[0,10:20])
        # print(compose[:,:30])
        for j in range(topK):
            # if compose[1][j] == 1:
            if new_label[0,IX[j]] == 1:
                x = x+1
                p = p+x/(j+1)  # x/j是第j个位置上的Precision
                # if x in topR:
                #     x_pre.append(x/(j+1))
                #     x_re.append(x/1000)
        # print(x_pre)
        # print(x_re)
        # preall.append(x_pre)
        # reall.append(x_re)
        if p == 0:
            apall[0][i] = 0
        else:
            apall[0][i] = p/x

    # print("total_good_pairs: ",total_good_pairs)
    # mpre = np.mean(preall,axis=0)
    # mre = np.mean(reall,axis=0)
    temp= np.array(apall[0])
    # print(temp)
    map = mean(temp)
    return map

def cal_precision_recall(train_label,test_label,hamdis):
    numtest, numtrain = size(hamdis, 0), size(hamdis, 1)
    topR = [1, 1000, 2000, 3000, 4000, 5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000]
    new_label = ((test_label.mm(train_label.T))>0).int()
    preall = []
    reall = []
    for i in range(numtest):
        y = torch.Tensor(hamdis[i]).int()  # y是一个1*60000的矩阵，表示test中的数据点i到数据集中其他点之间的距离
        y.resize_((1, len(y)))
        IX = np.lexsort(np.array(y))
        # y new_label
        temp_y = y.T[IX].T
        temp_label = new_label[i].T[IX].T
        hamdis[i] = temp_y
        new_label[i] = temp_label

    total_good_pairs = sum(sum(np.array(new_label))).item()

    for i in range(len(topR)):
        if i%100 == 0:
            print(i," pre and re has been processed")
        g = topR[i]
        retrieved_good_pairs = sum(np.sum(np.array(new_label[:,:g]),axis=0)).item()
        # print(retrieved_good_pairs)
        temp = new_label[:,:g]
        row, col = temp.size()
        total_pairs = row * col
        reall.append(retrieved_good_pairs/total_good_pairs)
        preall.append(retrieved_good_pairs/total_pairs)
    preall = np.array(preall)
    reall = np.array(reall)
    return preall,reall


from pydantic import BaseSettings

class DevConfig(BaseSettings):

    # secret used for signing JWT tokens
    JWT_SECRET: str

    # hash of payload with pow_token must start with {POW_DIFFICULTY} 0 bits
    POW_DIFFICULTY: int

    # db uri like postgres://user:password@host:port/db-name
    DATABASE_URI: str

    # display name of this service instance
    SERVICE_NAME: str

    class Config:
        case_sensitive = True
        env_file = ".env"
        env_file_encoding = "utf-8"

settings = DevConfig()


import curses
import sudoku
import numpy as np
import textwrap

BOARD_WIDTH = 9*3 + 2  # 9 cells (+2 spaces) + 2 separators + newline
BOARD_HEIGHT = 9 + 3  # 9 cells + separators

def infowrite(win, text):
    win.clear()
    for n, line in enumerate(textwrap.wrap(text, width=BOARD_WIDTH)):
        win.addstr(n, 1, line)
    win.refresh()

def query(infowin, question, options):
    options_str = [f"{i}. {opt}"
                   for i, opt in enumerate(options.keys(), start=1)]
    infowin.clear()
    infowin.addstr(0, 1, question)
    for n, optstr in enumerate(options_str, start=1):
        infowin.addstr(n, 1, optstr)
    infowin.refresh()
    while True:
        key = infowin.getkey()
        if key == 'q':
            return None
        if not key.isdigit():
            continue
        key = int(key)
        if key > 0 and key <= len(options):
            return [optval
                    for i, optval in enumerate(options.values(), start=1)
                    if i == key][0]

def intchar(int):
    return chr(ord('0') + int)

def draw_board(board, screen, cur_pos):
    screen.move(0, 0)
    for i, row in enumerate(board):
        if max(1, i) % 3 == 0:
            screen.addstr("+".join(["-"*9]*3))
        rowstr = np.vectorize(lambda x: f" {x if x != 0 else '.'} ")(row)
        if i == cur_pos[0]:
            rowstr[cur_pos[1]] = f">{rowstr[cur_pos[1]][1]}<"
        rowstr = ''.join(np.insert(rowstr,
                                   range(3, len(rowstr), 3),
                                   '|'))
        screen.addstr(rowstr)

def loop(boardwin, infowin, board):
    cur_pos = [0, 0]
    infowrite(infowin, "Welcome! Hit [N]ew to generate a sudoku board.")
    while True:
        draw_board(board, boardwin, cur_pos)
        if sudoku.complete(board):
            infowrite(infowin, "Puzzle solved!")
        boardwin.refresh()
        key = boardwin.getkey()
        infowin.clear()
        infowin.refresh()
        if key == 'q':
            break
        if key == 'S':
            try:
                board = sudoku.solve(board)
            except Exception as err:
                infowrite(infowin, str(err))
        if key == 'N':
            difficulty = query(infowin, "Select difficulty", {"Easy": 25, "Medium": 40, "Hard": 60})
            if difficulty:
                board = sudoku.generate(difficulty)
            infowin.clear()
            infowin.refresh()
        if key == 'h':
            cur_pos[1] = max(0, cur_pos[1] - 1)
        if key == 't':
            cur_pos[0] = min(8, cur_pos[0] + 1)
        if key == 'n':
            cur_pos[0] = max(0, cur_pos[0] - 1)
        if key == 's':
            cur_pos[1] = min(8, cur_pos[1] + 1)
        if key.isdigit():
            board[tuple(cur_pos)] = key

def init(stdscr):
    stdscr.clear()
    sudokuwin = curses.newwin(BOARD_HEIGHT, BOARD_WIDTH,
                              (curses.LINES - BOARD_HEIGHT)//2,
                              (curses.COLS - BOARD_WIDTH)//2)
    # sudokuwin.border()
    infowin = curses.newwin(BOARD_HEIGHT, BOARD_WIDTH,
                            (curses.LINES - BOARD_HEIGHT)//2 + BOARD_HEIGHT,
                            (curses.COLS - BOARD_WIDTH)//2)
    curses.curs_set(0)  # hide cursor
    curses.use_default_colors()
    curses.init_pair(1, curses.COLOR_RED, -1)
    curses.init_pair(2, curses.COLOR_BLUE, -1)
    stdscr.addstr("Sudoku ~ "
                  "Move: [h,t,n,s]  "
                  "Select number: [1-9]  "
                  "Clear: [0]  "
                  "Solve: [S]  "
                  "New: [N]  "
                  "Quit: [q]", curses.color_pair(2))
    stdscr.refresh()
    sudokuwin.refresh()
    return sudokuwin, infowin

def main(stdscr):
    empty_board = np.zeros((9, 9), dtype=int)
    boardwin, infowin = init(stdscr)
    loop(boardwin, infowin, empty_board)

curses.wrapper(main)


from types import MappingProxyType
from typing import List, Tuple

import pandas as pd

import mundi
from mundi import Region
from pydemic import models
from pydemic.diseases import covid19
from pydemic.utils import pc
from pydemic_ui import components as ui
from pydemic_ui import info
from pydemic_ui import st
from pydemic_ui.i18n import _

TARGETS = list(range(90, 10, -10))
TARGETS_DEFAULT = [TARGETS[2], TARGETS[4], TARGETS[6]]

COLUMNS = [
    # Infectious model
    "susceptible",
    "exposed",
    "asymptomatic",
    "infectious",
    "recovered",
    "cases",
    "infected",
    "R0",
    # Clinical outcomes
    "severe",
    "critical",
    "deaths",
    "natural_deaths",
    # Parameters
    "icu_capacity",
    "hospital_capacity",
    "icu_surge_capacity",
    "hospital_surge_capacity",
]
COLUMNS_DEFAULT = ["critical", "severe"]
COL_NAMES = {
    "critical": _("ICU"),
    "severe": _("Clinical"),
    "cases": _("Cases"),
    "infected": _("Infected"),
    "deaths": _("Deaths"),
}

DAYS = [1, 5, 7, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 75, 90]
DAYS_DEFAULT = [7, 15, 30, 60]

REGIONS_TYPES = {
    "BR": {
        _("State"): {"type": "state", "country_code": "BR"},
        _("Macro-region"): {
            "type": "region",
            "subtype": "macro-region",
            "country_code": "BR",
        },
        # _("SUS macro-region"): {
        #     "type": "region",
        #     "subtype": "healthcare region",
        #     "country_code": "BR",
        # },
    }
}

def get_column(
    models: dict,
    regions: List[Region],
    isolation: float,
    col: str,
    days: Tuple[int, int],
    duration: int,
):
    data = {}
    day, prev_day = days
    for r in regions:
        model = models[r, isolation]
        try:
            values = model[col]
        except KeyError:
            value = getattr(model, col)
        else:
            initial = -(duration - prev_day)
            final = -(duration - day)
            value = values.iloc[initial:final].max()
        data[r.id] = value

    data = pd.Series(data)
    data.name = col
    data.index.name = "region"
    return data

@info.ttl_cache(key="app.projections_br", force_streamlit=True)
def process_region(region, targets, duration):
    data = info.get_seair_curves_for_region(region, use_deaths=True)
    m = models.SEAIR(region=region, disease=covid19)
    m.set_data(data)
    m.initial_cases = info.get_cases_for_region(region)["cases"].iloc[0]

    out = {}
    for level in targets:
        new = m.copy(name=_("Isolation {}").format(pc(level / 100)))
        new.R0 *= 1 - level / 100
        new.run(duration)
        out[level] = new.clinical.overflow_model()

    return MappingProxyType(out)

@info.ttl_cache(key="app.projections_br", force_streamlit=True)
def get_models(regions, targets, duration) -> dict:
    models = {}
    for region in regions:
        with st.spinner(_("Processing {name}").format(name=region.name)):
            result = process_region(region, targets, duration)
            models.update({(region, k): v for k, v in result.items()})
    return models

@info.ttl_cache(key="app.projections_br", force_streamlit=True)
def get_dataframe(regions, days, targets, columns, duration):
    models = get_models(regions, targets, duration)
    frames = []

    prev_day = 0
    for day in days:
        delta = (day, prev_day)
        for target in targets:
            frame = pd.DataFrame(
                {
                    col: get_column(models, regions, target, col, delta, duration)
                    for col in columns
                }
            ).astype(int)

            names = ("days", "isolation", "data")
            prepend = (
                _("{n} days").format(n=day),
                _("isolation {pc}").format(pc=pc(target / 100)),
            )
            cols = ((*prepend, c) for c in frame.columns)

            frame.columns = pd.MultiIndex.from_tuples(cols, names=names)
            frames.append(frame)
        prev_day = day

    df = pd.concat(frames, axis=1)
    extra = df.mundi["numeric_code", "short_code", "name"]
    extra = extra.astype(str)  # streamlit bug?
    extra.columns = pd.MultiIndex.from_tuples(("info", x, "") for x in extra.columns)
    df = pd.concat([extra, df], axis=1)
    return df.sort_values(df.columns[0])

@st.cache
def get_regions(**query):
    """
    Get all children in region that have the same values of the parameters passed
    as keyword arguments.
    """
    return [mundi.region(id_) for id_ in mundi.regions(**query).index]

def collect_inputs(parent_region="BR", where=st.sidebar):
    """
    Collect input parameters for the app to run.

    Returns:
        Dictionary with the following keys:
            parent_region, regions, columns, targets, days
    """
    st = where
    kind = st.selectbox(_("Select scenario"), list(REGIONS_TYPES[parent_region]))
    query = REGIONS_TYPES[parent_region][kind]

    regions = get_regions(**query)

    msg = _("Columns")
    columns = st.multiselect(msg, COLUMNS, default=COLUMNS_DEFAULT)

    msg = _("Isolation scores")
    kwargs = {"default": TARGETS_DEFAULT, "format_func": lambda x: f"{x}%"}
    targets = st.multiselect(msg, TARGETS, **kwargs)

    msg = _("Show values for the given days")
    days = st.multiselect(msg, DAYS, default=DAYS_DEFAULT)

    return {
        "parent_region": parent_region,
        "regions": regions,
        "columns": columns,
        "targets": targets,
        "days": days,
    }

def show_results(parent_region, regions, columns, targets, days, disease=covid19):
    """
    Show results from user input.
    """

    parent_region = mundi.region(parent_region)
    ax = parent_region.plot.cases_and_deaths(disease=disease, logy=True, grid=True)
    st.pyplot(ax.get_figure())
    if days and targets and columns:
        df = get_dataframe(regions, tuple(days), tuple(targets), tuple(columns), 61)

        st.subheader(_("Download results"))
        st.dataframe_download(df, name="report-brazil.{ext}")

def main(embed=False, disease=covid19):
    """
    Main function for application.
    """

    if not embed:
        ui.css()

    if not embed:
        ui.logo(where=st.sidebar)

    st.title(_("Scenarios for COVID-19 evolution in Brazil"))
    inputs = collect_inputs(where=st if embed else st.sidebar)
    show_results(disease=disease, **inputs)

if __name__ == "__main__":
    main()


from PyQt5.QtWidgets import QComboBox, QLineEdit, QListWidget, QCheckBox, QListWidgetItem

class ComboCheckBox(QComboBox):
    def loadItems(self, items):
        self.items = items
        self.items.insert(0, '全部')
        self.row_num = len(self.items)
        self.Selectedrow_num = 0
        self.qCheckBox = []
        self.qLineEdit = QLineEdit()
        self.qLineEdit.setReadOnly(True)
        self.qListWidget = QListWidget()
        self.addQCheckBox(0)
        self.qCheckBox[0].stateChanged.connect(self.All)
        for i in range(0, self.row_num):
            self.addQCheckBox(i)
            self.qCheckBox[i].stateChanged.connect(self.showMessage)
        self.setModel(self.qListWidget.model())
        self.setView(self.qListWidget)
        self.setLineEdit(self.qLineEdit)

    def showPopup(self):
        select_list = self.Selectlist()
        self.loadItems(items=self.items[1:])
        for select in select_list:
            index = self.items[:].index(select)
            self.qCheckBox[index].setChecked(True)
        return QComboBox.showPopup(self)
    def printResults(self):
        list = self.Selectlist()
        print(list)
    def addQCheckBox(self, i):
        self.qCheckBox.append(QCheckBox())
        qItem = QListWidgetItem(self.qListWidget)
        self.qCheckBox[i].setText(self.items[i])
        self.qListWidget.setItemWidget(qItem, self.qCheckBox[i])
    def selQCheckBoxByName(self, name):
        try: index = self.items[:].index(name)
        except: return
        self.qCheckBox[index].setChecked(True)
    def Selectlist(self):
        Outputlist = []
        for i in range(1, self.row_num):
            if self.qCheckBox[i].isChecked() == True:
                Outputlist.append(self.qCheckBox[i].text())
        self.Selectedrow_num = len(Outputlist)
        return Outputlist
    def showMessage(self):
        Outputlist = self.Selectlist()
        self.qLineEdit.setReadOnly(False)
        self.qLineEdit.clear()
        show = ';'.join(Outputlist)

        if self.Selectedrow_num == 0:
            self.qCheckBox[0].setCheckState(0)
        elif self.Selectedrow_num == self.row_num - 1:
            self.qCheckBox[0].setCheckState(2)
        else:
            self.qCheckBox[0].setCheckState(1)
        self.qLineEdit.setText(show)
        self.qLineEdit.setReadOnly(True)
    def All(self, zhuangtai):
        if zhuangtai == 2:
            for i in range(1, self.row_num):
                self.qCheckBox[i].setChecked(True)
        elif zhuangtai == 1:
            if self.Selectedrow_num == 0:
                self.qCheckBox[0].setCheckState(2)
        elif zhuangtai == 0:
            self.clear()
    def clear(self):
        for i in range(self.row_num):
            self.qCheckBox[i].setChecked(False)
    def currentText(self):
        return QComboBox.currentText(self).split(';')


# 物体検出スクリプトをテストするための画像を作る
# アノテーションファイルも作る
import cv2
import numpy as np
import random

w = 640
h = 480
N = 1000
tsize = 40
classesN = 0

fout = open("annotation.txt", "w") # txtファイルを書き込みモードで作成

for i in range(N):
    img = np.ones((h,w,3), np.uint8)
    img = img * 255

    for c in range(100):
        hr = random.randint(0, h)
        wr = random.randint(0, w)
        radr = random.randint(0, 100)
        rr = random.randint(0, 255)
        gr = random.randint(0, 255)
        br = random.randint(0, 255)
        img = cv2.circle(img,(wr,hr), radr, (rr,gr,br), -1)

    hr = random.randint(0, h-tsize)
    wr = random.randint(0, w-tsize)

    pts = np.array([[wr+tsize/2,hr],[wr,hr+tsize],[wr+tsize,hr+tsize]], np.int32)
    pts = pts.reshape((-1,1,2))
    #img = cv2.polylines(img,[pts],True,(0,0,0))
    img = cv2.fillConvexPoly(img, pts, (0,0,0))

    #画像を保存
    imname = 'JPG/' + 'img' + str(i) + '.jpg'
    cv2.imwrite(imname, img)
    #アノテーションファイルに記録
    annostr = 'model_data/' + imname + ' ' + str(wr) + ','  + str(hr) + ','  + str(wr+tsize) + ',' + str(hr+tsize) + ',' + str(classesN)
    fout.writelines(annostr + "\n")

fout.close()


#!/usr/bin/env python3
# -*- coding: ascii -*-
"""The xonsh installer."""
# Note: Do not embed any non-ASCII characters in this file until pip has been
# fixed. See https://github.com/xonsh/xonsh/issues/487.
import os
import sys
import json
import subprocess

from setuptools import setup, find_packages
from setuptools.command.sdist import sdist
from setuptools.command.install import install
from setuptools.command.develop import develop
from setuptools.command.build_py import build_py
from setuptools.command.install_scripts import install_scripts

TABLES = [
    "xonsh2/lexer_table.py",
    "xonsh2/parser_table.py",
    "xonsh2/__amalgam__.py",
    "xonsh2/completers/__amalgam__.py",
    "xonsh2/history/__amalgam__.py",
    "xonsh2/prompt/__amalgam__.py",
    "xonsh2/procs/__amalgam__.py",
]

def clean_tables():
    """Remove the lexer/parser modules that are dynamically created."""
    for f in TABLES:
        if os.path.isfile(f):
            os.remove(f)
            print("Removed " + f)

os.environ["XONSH_DEBUG"] = "1"
from xonsh2 import __version__ as XONSH_VERSION

def amalgamate_source():
    """Amalgamates source files."""
    sys.path.insert(0, os.path.dirname(__file__))
    try:
        import amalgamate
    except ImportError:
        print("Could not import amalgamate, skipping.", file=sys.stderr)
        return
    amalgamate.main(
        [
            "amalgamate",
            "--debug=XONSH_DEBUG",
            "xonsh2",
            "xonsh2.completers",
            "xonsh2.history",
            "xonsh2.prompt",
            "xonsh2.procs",
        ]
    )
    sys.path.pop(0)

def build_tables():
    """Build the lexer/parser modules."""
    print("Building lexer and parser tables.")
    sys.path.insert(0, os.path.dirname(__file__))
    from xonsh2.parser import Parser

    Parser(
        lexer_table="lexer_table",
        yacc_table="parser_table",
        outputdir="xonsh2",
        yacc_debug=True,
    )
    sys.path.pop(0)

def dirty_version():
    """
    If install/sdist is run from a git directory (not a conda install), add
    a devN suffix to reported version number and write a gitignored file
    that holds the git hash of the current state of the repo to be queried
    by ``xonfig``
    """
    try:
        _version = subprocess.check_output(["git", "describe", "--tags"])
    except Exception:
        print("failed to find git tags", file=sys.stderr)
        return False
    _version = _version.decode("ascii")
    try:
        _, N, sha = _version.strip().split("-")
    except ValueError:  # tag name may contain "-"
        print("failed to parse git version", file=sys.stderr)
        return False
    sha = sha.strip("g")
    replace_version(N)
    _cmd = ["git", "show", "-s", "--format=%cd", "--date=local", sha]
    try:
        _date = subprocess.check_output(_cmd)
        _date = _date.decode("ascii")
        # remove weekday name for a shorter string
        _date = " ".join(_date.split()[1:])
    except:
        _date = ""
        print("failed to get commit date", file=sys.stderr)
    with open("xonsh2/dev.githash", "w") as f:
        f.write("{}|{}".format(sha, _date))
    print("wrote git version: " + sha, file=sys.stderr)
    return True

ORIGINAL_VERSION_LINE = None

def replace_version(N):
    """Replace version in `__init__.py` with devN suffix"""
    global ORIGINAL_VERSION_LINE
    with open("xonsh2/__init__.py", "r") as f:
        raw = f.read()
    lines = raw.splitlines()
    msg_assert = "__version__ must be the first line of the __init__.py"
    assert "__version__" in lines[0], msg_assert
    ORIGINAL_VERSION_LINE = lines[0]
    lines[0] = lines[0].rstrip(' "') + '.dev{}"'.format(N)
    upd = "\n".join(lines) + "\n"
    with open("xonsh2/__init__.py", "w") as f:
        f.write(upd)

def restore_version():
    """If we touch the version in __init__.py discard changes after install."""
    if ORIGINAL_VERSION_LINE is None:
        return
    with open("xonsh2/__init__.py", "r") as f:
        raw = f.read()
    lines = raw.splitlines()
    lines[0] = ORIGINAL_VERSION_LINE
    upd = "\n".join(lines) + "\n"
    with open("xonsh2/__init__.py", "w") as f:
        f.write(upd)

class xbuild_py(build_py):
    """Xonsh specialization of setuptools build_py class."""

    def run(self):
        clean_tables()
        build_tables()
        amalgamate_source()
        # add dirty version number
        dirty = dirty_version()
        super().run()
        if dirty:
            restore_version()

class xinstall(install):
    """Xonsh specialization of setuptools install class.
    For production, let setuptools generate the
    startup script, e.g: `pip installl .' rather than
    relying on 'python setup.py install'."""

    def run(self):
        clean_tables()
        build_tables()
        amalgamate_source()
        # add dirty version number
        dirty = dirty_version()

        super().run()
        if dirty:
            restore_version()

class xsdist(sdist):
    """Xonsh specialization of setuptools sdist class."""

    def make_release_tree(self, basedir, files):
        clean_tables()
        build_tables()
        amalgamate_source()
        dirty = dirty_version()
        files.extend(TABLES)
        super().make_release_tree(basedir, files)
        if dirty:
            restore_version()

# Hack to overcome pip/setuptools problem on Win 10.  See:
#   https://github.com/tomduck/pandoc-eqnos/issues/6
#   https://github.com/pypa/pip/issues/2783

# Custom install_scripts command class for setup()
class install_scripts_quoted_shebang(install_scripts):
    """Ensure there are quotes around shebang paths with spaces."""

    def write_script(self, script_name, contents, mode="t", *ignored):
        shebang = str(contents.splitlines()[0])
        if (
            shebang.startswith("#!")
            and " " in shebang[2:].strip()
            and '"' not in shebang
        ):
            quoted_shebang = '#!"%s"' % shebang[2:].strip()
            contents = contents.replace(shebang, quoted_shebang)
        super().write_script(script_name, contents, mode, *ignored)

class install_scripts_rewrite(install_scripts):
    """Change default python3 to the concrete python binary used to install/develop inside xon.sh script"""

    def run(self):
        super().run()
        if not self.dry_run:
            for file in self.get_outputs():
                if file.endswith("xon.sh"):
                    # this is the value distutils use on its shebang translation
                    bs_cmd = self.get_finalized_command("build_scripts")
                    exec_param = getattr(bs_cmd, "executable", None)

                    with open(file, "r") as f:
                        content = f.read()

                    processed = content.replace(
                        " python3 ", ' "{}" '.format(exec_param)
                    )

                    with open(file, "w") as f:
                        f.write(processed)

# The custom install needs to be used on Windows machines
cmdclass = {
    "install": xinstall,
    "sdist": xsdist,
    "build_py": xbuild_py,
}
if os.name == "nt":
    cmdclass["install_scripts"] = install_scripts_quoted_shebang
else:
    cmdclass["install_scripts"] = install_scripts_rewrite

class xdevelop(develop):
    """Xonsh specialization of setuptools develop class."""

    def run(self):
        clean_tables()
        build_tables()
        dirty = dirty_version()
        develop.run(self)
        if dirty:
            restore_version()

    def install_script(self, dist, script_name, script_text, dev_path=None):
        if script_name == "xon.sh":
            # change default python3 to the concrete python binary used to install/develop inside xon.sh script
            script_text = script_text.replace(
                " python3 ", ' "{}" '.format(sys.executable)
            )
        super().install_script(dist, script_name, script_text, dev_path)

def main():
    """The main entry point."""
    try:
        if "--name" not in sys.argv:
            logo_fname = os.path.join(os.path.dirname(__file__), "logo.txt")
            with open(logo_fname, "rb") as f:
                logo = f.read().decode("utf-8")
            print(logo)
    except UnicodeEncodeError:
        pass
    with open(os.path.join(os.path.dirname(__file__), "README.rst"), "r") as f:
        readme = f.read()
    scripts = ["scripts/xon.sh"]
    skw = dict(
        name="xonsh2",
        description="Python-powered, cross-platform, Unix-gazing shell",
        long_description=readme,
        license="BSD",
        version=XONSH_VERSION,
        author="Anthony Scopatz",
        maintainer="Anthony Scopatz",
        author_email="scopatz@gmail.com",
        url="https://github.com/xonsh/xonsh",
        platforms="Cross Platform",
        classifiers=["Programming Language :: Python :: 3"],
        packages=[
            "xonsh2",
            "xonsh2.ply.ply",
            "xonsh2.ptk_shell",
            "xonsh2.ptk2",
            "xonsh2.procs",
            "xonsh2.parsers",
            "xonsh2.xoreutils",
            "xontrib2",
            "xonsh2.completers",
            "xonsh2.history",
            "xonsh2.prompt",
            "xonsh2.lib",
            "xonsh2.webconfig",
        ],
        package_dir={
            "xonsh2": "xonsh2",
            "xontrib2": "xontrib2",
            "xonsh2.lib": "xonsh2/lib",
            "xonsh2.webconfig": "xonsh2/webconfig",
        },
        package_data={
            "xonsh2": ["*.json", "*.githash"],
            "xonsh2.vended_ptk": ["LICENSE-prompt-toolkit", "LICENSE-wcwidth"],
            "xontrib2": ["*.xsh"],
            "xonsh2.lib": ["*.xsh"],
            "xonsh2.webconfig": [
                "*.html",
                "js/app.min.js",
                "js/bootstrap.min.css",
                "js/LICENSE-bootstrap",
            ],
        },
        cmdclass=cmdclass,
        scripts=scripts,
    )
    skw["packages"].extend(
        ["xonsh2.vended_ptk." + pkg for pkg in find_packages(where="xonsh2/vended_ptk")]
    )
    # We used to avoid setuptools 'console_scripts' due to startup performance
    # concerns which have since been resolved, so long as install is done
    # via `pip install .` and not `python setup.py install`.
    skw["entry_points"] = {
        "pygments.lexers": [
            "xonsh2 = xonsh2.pyghooks:XonshLexer",
            "xonshcon = xonsh2.pyghooks:XonshConsoleLexer",
        ],
        "pytest11": ["xonsh2 = xonsh2.pytest_plugin"],
        "console_scripts": [
            "xonsh2 = xonsh2.main:main",
            "xonsh-cat = xonsh2.xoreutils.cat:cat_main",
        ],
    }
    skw["cmdclass"]["develop"] = xdevelop
    skw["extras_require"] = {
        "ptk": ["prompt-toolkit>=3.0"],
        "pygments": ["pygments>=2.2"],
        "mac": ["gnureadline"],
        "linux": ["distro"],
        "proctitle": ["setproctitle"],
        "zipapp": ['importlib_resources; python_version < "3.7"'],
        "full": ["ptk", "pygments", "distro"],
    }
    skw["python_requires"] = ">=3.6"
    setup(**skw)

if __name__ == "__main__":
    main()


import pygame,sys       #import modules

screen_w = 500
screen_h = 600

colors = {              #definition of basics colors
    "black":(0,0,0),
    "white":(255,255,255),
    "red":(255,0,0),
    "blue":(0,255,0),
    "green":(0,0,255),
    }

pygame.init()
window = pygame.display.set_mode((screen_h,screen_w)) #window creation
game = True

grass = pygame.image.load("grass.png")

snake = pygame.image.load("snake.png")

position_snake = snake.get_rect()
window.blit(snake, (100, 100))

try:
    while game:

        if pygame.key.get_pressed()[pygame.K_UP]:
            position_snake = position_snake.move(0,-1)
        if pygame.key.get_pressed()[pygame.K_DOWN]:
            position_snake = position_snake.move(0,1)
        if pygame.key.get_pressed()[pygame.K_LEFT]:
            position_snake = position_snake.move(-1,0)
        if pygame.key.get_pressed()[pygame.K_RIGHT]:
            position_snake = position_snake.move(1,0)

        for event in pygame.event.get():
            if event.type == pygame.QUIT or pygame.key.get_pressed()[pygame.K_ESCAPE]:  #Escape or exit  is pressed
                game = False #end of the game

        window.fill(colors["black"])
        for i in range (0,50):
            for j in range (0, 32):
                window.blit(grass, (i*16,j*16))

        window.blit(snake, position_snake)
        pygame.display.flip()

except:
    print("Exit error")

finally:
    pygame.quit()
    sys.exit()


"""
计算两幅图的梯度图的Bce_loss
"""
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F

def show_tensor(image):
    gt = image["gt"]
    gt_sobel = image["gt_sobel"]
    pred_sobel = image["pred_sobel"]
    plt.subplot(1, 3, 1).imshow(gt[0, 0, :, :].detach().cpu().numpy())
    plt.subplot(1, 3, 2).imshow(gt_sobel[0, 0, :, :].detach().cpu().numpy())
    plt.subplot(1, 3, 3).imshow(pred_sobel[0, 0, :, :].detach().cpu().numpy())
    plt.show()

def compute_loss_and_metrics(images):
    """
    This part compute loss and metrics for the generator
    """
    grad_loss = F.l1_loss(images['gt_sobel'], images['pred_sobel'])
    # 取总体差的平方，适用于两组图不对应的情况
    # grad_loss = (torch.mean(images['gt_sobel']) - torch.mean(images['pred_sobel'])) ** 2
    return grad_loss

class SobelOperator(nn.Module):
    def __init__(self, epsilon):
        super().__init__()
        self.epsilon = epsilon

        x_kernel = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]]) / 4
        self.conv_x = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1, bias=False)
        self.conv_x.weight.data = torch.tensor(x_kernel).unsqueeze(0).unsqueeze(0).float().cuda()
        self.conv_x.weight.requires_grad = False

        y_kernel = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) / 4
        self.conv_y = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1, bias=False)
        self.conv_y.weight.data = torch.tensor(y_kernel).unsqueeze(0).unsqueeze(0).float().cuda()
        self.conv_y.weight.requires_grad = False

    def forward(self, x):
        b, c, h, w = x.shape
        if c > 1:
            x = x.view(b * c, 1, h, w)

        x = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)

        grad_x = self.conv_x(x)
        grad_y = self.conv_y(x)

        x = torch.sqrt(grad_x ** 2 + grad_y ** 2 + self.epsilon)
        x = x.view(b, c, h, w)

        return x

class SobelComputer:
    def __init__(self):
        self.sobel = SobelOperator(1e-4)

    def compute_edges(self, images):
        images['gt_sobel'] = self.sobel(images['gt'])
        images['pred_sobel'] = self.sobel(images['pred'])


import bpy
from .select import FocusObject

def DuplicateObject(target):
    """
    Duplicates the given object.
    WARNING - Will also apply the transformation for that object in order to preserve the scale.  </3
    """

    #### Select and make target active
    bpy.ops.object.select_all(action='DESELECT')
    bpy.context.view_layer.objects.active = bpy.data.objects[target.name]
    bpy.ops.object.select_pattern(pattern=target.name)

    # Duplicate the object
    bpy.ops.object.duplicate_move()

    # Now switch the active object to the duplicate
    duplicate = bpy.context.active_object

    # Now set the transform details
    duplicate.rotation_euler = target.rotation_euler
    duplicate.rotation_axis_angle = target.rotation_axis_angle

    # To preserve the scale, it has to be applied.  Sorreh!
    bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)

def DuplicateObjects(targets):
    """
    Duplicates the given objects.
    WARNING - Will also apply the transformation for the objects in order to preserve the scale.  </3
    """

    #### Select and make target active
    bpy.ops.object.select_all(action='DESELECT')

    for target in targets:
        bpy.context.view_layer.objects.active = bpy.data.objects[target.name]
        bpy.ops.object.select_pattern(pattern=target.name)

    # Duplicate the object
    bpy.ops.object.duplicate_move()

    # Now switch the active object to the duplicate
    duplicate = bpy.context.active_object

    # Now set the transform details
    duplicate.rotation_euler = target.rotation_euler
    duplicate.rotation_axis_angle = target.rotation_axis_angle

    # To preserve the scale, it has to be applied.  Sorreh!
    bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)

def DeleteObject(target):
    """
    Deletes the given object and removes it from memory.
    """

    # This needs proper data deletion, and all delete operations need to use this
    FocusObject(target)
    bpy.ops.object.delete()

    # Currently removing just in case...
    DeleteObjectByMemory(target)

def DeleteObjectByMemory(target):

    try:
        ob = bpy.data.objects[target.name]

    except:
        ob = None

    if ob != None:
        ob.user_clear()
        bpy.data.objects.remove(ob)

    return

def SwitchObjectMode(newMode, target):
    """
    Forces an object mode switch to the one given, if it isn't already in that mode.
    """

    bpy.context.view_layer.objects.active = bpy.data.objects[target.name]
    prevMode = target.mode
    if target.mode != newMode:
        bpy.context.view_layer.objects.active = bpy.data.objects[target.name]
        bpy.ops.object.mode_set(mode=newMode)
        return prevMode

def FindObjectsWithName(context, object_name):
    """
    Attempts to find an object with the given name in the scene of the given context.
    """

    objects_found = []

    for object in context.scene.objects:
        if object.name.find(object_name) != -1:
            objects_found.append(object)

    return objects_found


from flask import Flask, render_template, url_for, redirect, request, jsonify
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
import marisa_trie

app = Flask(__name__)

# hack to store vocabulary in MARISA Trie
class _MarisaVocabularyMixin(object):

    def fit_transform(self, raw_documents, y=None):
        super(_MarisaVocabularyMixin, self).fit_transform(raw_documents)
        self._freeze_vocabulary()
        return super(_MarisaVocabularyMixin, self).fit_transform(raw_documents, y)

    def _freeze_vocabulary(self):
        if not self.fixed_vocabulary_:
            self.vocabulary_ = marisa_trie.Trie(self.vocabulary_.keys())
            self.fixed_vocabulary_ = True
            del self.stop_words_

class MarisaTfidfVectorizer(_MarisaVocabularyMixin, TfidfVectorizer):
    def fit(self, raw_documents, y=None):
        super(MarisaTfidfVectorizer, self).fit(raw_documents)
        self._freeze_vocabulary()
        return super(MarisaTfidfVectorizer, self).fit(raw_documents, y)

# load the model from disk
loaded_model = pickle.load(open('finalized_model.sav', 'rb'))

data = pickle.load(open('dataframe.sav','rb'))

id_to_category = pickle.load(open('idcategory.sav','rb'))

tfidf = MarisaTfidfVectorizer(sublinear_tf=True, min_df=5, norm='l2', encoding='latin-1', ngram_range=(1, 2), stop_words='english')
features = tfidf.fit_transform(data.text).toarray()

@app.route('/tickets', methods=['POST'])
def json_example():
    texts = []
    request_data = request.get_json()
    texts.append(request.form.get('ticket', ''))
    if(texts[0]==''):
        data_response = {'status':'400'}
        return jsonify(data_response)
    else:
        text_features = tfidf.transform(texts)
        predictions = loaded_model.predict(text_features)
        for text, predicted in zip(texts, predictions):
            print('"{}"'.format(text))
            print("  - Predicted as: '{}'".format(id_to_category[predicted]))
            print("")
            response = id_to_category[predicted]

        data_response = {'status':'200','category':response}

        return jsonify(data_response)

if __name__ == '__main__':
    app.run(host="localhost", debug=True)


# coding: utf-8

import networkx as nx
from collections import Counter
import random
import math
import matplotlib.pyplot as plt

#Add single edge
def insert_edge(G, n1, n2):
    if n1 == n2:
        raise AssertionError("Cannot add self-loop")
    if n1 < n2:
        G.add_edge(n1, n2)
    else:
        G.add_edge(n2, n1)
    return G

#Add edges
def insert_edges(G, edges):
    for edge in edges:
        G = insert_edge(G, edge[0], edge[1])
    return G

#Check if the core values given are actually realizable
def is_realizable(cores):
    cores = sorted(cores, reverse=True)
    num_max_core_val = max(idx for idx, val in enumerate(cores) if val == cores[0])
    if num_max_core_val < cores[0]:
        return False
    return True

#Add lower core value nodes
def add_lower_nodes(cores, indices, G, k):
    K = cores[0]
    higher_nodes = [node for i in range(k+1, K+1) for node in indices[i]]
    G.add_nodes_from(indices[k])
    for node in indices[k]:
        rands = random.sample(higher_nodes, k)
        G = insert_edges(G, [(r, node) for r in rands])
    if k == 0:
        return G
    return add_lower_nodes(cores, indices, G, k-1)

#Build up single core graph
def generate_k_graph(C, N, G):
    if not C%2 == N%2:
        G.add_nodes_from(range(N))
        G = insert_edges(G, [(i, i+1) for i in range(N-1)])
        G = insert_edge(G, 0, N-1)
        z = math.ceil((N-C+1)/2)
        print(z)
        for i in range(N):
            print(i)
            start = (i+z+1)%(N)
            stop = (i-z)%(N)
            print(start)
            print(stop)
            print()
            if stop >= start:
                edges = set([r for r in range(list(range(N))[(start)],  list(range(N))[(stop)])])
            else:
                edges = set([r for l in [range(list(range(N))[start], N), range(0, list(range(N))[stop])] for r in l])
            G = insert_edges(G, [(i, e) for e in edges])
    else:
        G = generate_k_graph(C, N-1, G)
        G.add_node(N-1)
        rands = random.sample(range(N-1), C)
        G = insert_edges(G, [(N-1, r) for r in rands])
    return G

#Main function: give a list of core values
def generate_graph(cores):
    cores = sorted(cores, reverse=True)
    if not is_realizable(cores):
        return False
    K = cores[0]
    nums = Counter(cores)
    indices = {i : [idx for idx, val in enumerate(cores) if val == i] for i in range(0, K+1)}
    G = nx.Graph()
    if K == 0:
        G.add_nodes_from(indices[0])
        return G
    if K == 1:
        G.add_nodes_from(indices[1])
        for i in range(nums[1]-1):
            G = insert_edge(G, i, i+1)
        G.add_nodes_from(indices[0])
        return G
    if K == 2:
        G.add_nodes_from(indices[2])
        for i in range(nums[2]-1):
            G = insert_edge(G, i, i+1)
        G = insert_edge(G, 0, nums[2]-1)
        return add_lower_nodes(cores, indices, G, 1)
    else:
        G = generate_k_graph(K, nums[K], G)
        G = add_lower_nodes(cores, indices, G, K-1)
        return G


from marrow.package.loader import load
from sqlalchemy.orm.exc import NoResultFound
from ..app.djrq.model.lastplay import DJs
from webob.exc import HTTPFound, HTTPError, HTTPNotFound

class DJExtension:
    needs = {'selective'}

    def __init__(self, config=None):
        self.whatsnewdays = config['whatsnew_days']
        self.lastplay_count = config['lastplay_count']

    def prepare(self, context):
        """ Setup basic stuff needed for all pages """

        context.__dict__['whatsnewdays'] = self.whatsnewdays
        context.__dict__['lastplay_count'] = self.lastplay_count
        try:
            djrow = context.db.lastplay.query(DJs).filter(DJs.dj == context.djname).one()
        except NoResultFound:
            raise HTTPNotFound('Host Not Found')

        context.__dict__['djname'] = djrow.dj

        package = 'web.app.djrq.model.'+djrow.databasetype

        context.__dict__['databasetype'] = djrow.databasetype
        context.__dict__['queries'] = load(package+'.queries:Queries')(db=context.db.default)
        Listeners = load(package + '.listeners:Listeners')
        context.__dict__['Users'] = load(package+'.users:Users')

        try:
            album = load(package + '.album:Album', default='Album')
        except ImportError:
            album = 'Album'
        try:
            artist = load(package + '.artist:Artist', default='Artist')
        except ImportError:
            artist = 'Artist'

        context.__dict__['artist'] = artist
        context.__dict__['album'] = album
        context.__dict__['requestlist'] = load(package + '.requestlist:RequestList')
        context.__dict__['mistags'] = load(package + '.mistags:Mistags')
        context.__dict__['suggestions'] = load(package + '.suggestions:Suggestions')
        if context.queries.db is None:
            raise HTTPError("Queries is None!")
        context.__dict__['dbstats'] = context.queries.get_song_stats()
        context.__dict__['requests_info'] = context.queries.get_requests_info()
        context.__dict__['new_counts'] = context.queries.get_new_counts(days=context.whatsnewdays)

        try:
            context.__dict__['listeners'] = context.db.default.query(Listeners).one()
        except NoResultFound:
            context.__dict__['listeners'] = None
        context.__dict__['alldjs'] = context.db.lastplay.query(DJs).filter(DJs.hide_from_menu == 0).order_by(DJs.dj)
        context.siteoptions = context.queries.get_siteoptions()
        context.suggestions_count = context.queries.get_suggestions_count().suggestions_count
        context.mistags_count = context.queries.get_mistags_count().mistags_count


import hashlib
import os
from collections import OrderedDict

import click

from platformio import fs
from platformio.compat import IS_WINDOWS, hashlib_encode_data

class ConfigOption:  # pylint: disable=too-many-instance-attributes
    def __init__(
        self,
        scope,
        group,
        name,
        description,
        type=str,
        multiple=False,
        sysenvvar=None,
        buildenvvar=None,
        oldnames=None,
        default=None,
        validate=None,
    ):
        self.scope = scope
        self.group = group
        self.name = name
        self.description = description
        self.type = type
        self.multiple = multiple
        self.sysenvvar = sysenvvar
        self.buildenvvar = buildenvvar
        self.oldnames = oldnames
        self.default = default
        self.validate = validate

    def as_dict(self):
        result = dict(
            scope=self.scope,
            group=self.group,
            name=self.name,
            description=self.description,
            type="string",
            multiple=self.multiple,
            sysenvvar=self.sysenvvar,
            default=self.default() if callable(self.default) else self.default,
        )
        if isinstance(self.type, click.ParamType):
            result["type"] = self.type.name
        if isinstance(self.type, (click.IntRange, click.FloatRange)):
            result["min"] = self.type.min
            result["max"] = self.type.max
        if isinstance(self.type, click.Choice):
            result["choices"] = self.type.choices
        return result

def ConfigPlatformioOption(*args, **kwargs):
    return ConfigOption("platformio", *args, **kwargs)

def ConfigEnvOption(*args, **kwargs):
    return ConfigOption("env", *args, **kwargs)

def calculate_path_hash(path):
    return "%s-%s" % (
        os.path.basename(path),
        hashlib.sha1(hashlib_encode_data(path)).hexdigest()[:10],
    )

def expand_dir_templates(path):
    project_dir = os.getcwd()
    tpls = {
        "$PROJECT_DIR": lambda: project_dir,
        "$PROJECT_HASH": lambda: calculate_path_hash(project_dir),
    }
    done = False
    while not done:
        done = True
        for tpl, cb in tpls.items():
            if tpl not in path:
                continue
            path = path.replace(tpl, cb())
            done = False
    return path

def validate_dir(path):
    if not path:
        return path
    # if not all values expanded, ignore validation
    if "${" in path and "}" in path:
        return path
    if path.startswith("~"):
        path = fs.expanduser(path)
    if "$" in path:
        path = expand_dir_templates(path)
    return os.path.abspath(path)

def get_default_core_dir():
    path = os.path.join(fs.expanduser("~"), ".platformio")
    if IS_WINDOWS:
        win_core_dir = os.path.splitdrive(path)[0] + "\\.platformio"
        if os.path.isdir(win_core_dir):
            return win_core_dir
    return path

ProjectOptions = OrderedDict(
    [
        ("%s.%s" % (option.scope, option.name), option)
        for option in [
            #
            # [platformio]
            #
            ConfigPlatformioOption(
                group="generic",
                name="name",
                description="A project name",
            ),
            ConfigPlatformioOption(
                group="generic",
                name="description",
                description="Describe a project with a short information",
            ),
            ConfigPlatformioOption(
                group="generic",
                name="default_envs",
                description=(
                    "Configure a list with environments which PlatformIO should "
                    "process by default"
                ),
                oldnames=["env_default"],
                multiple=True,
                sysenvvar="PLATFORMIO_DEFAULT_ENVS",
            ),
            ConfigPlatformioOption(
                group="generic",
                name="extra_configs",
                description=(
                    "Extend main configuration with the extra configuration files"
                ),
                multiple=True,
            ),
            # Dirs
            ConfigPlatformioOption(
                group="directory",
                name="core_dir",
                description=(
                    "PlatformIO Core location where it keeps installed development "
                    "platforms, packages, global libraries, "
                    "and other internal information"
                ),
                oldnames=["home_dir"],
                sysenvvar="PLATFORMIO_CORE_DIR",
                default=get_default_core_dir,
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="globallib_dir",
                description=(
                    "A library folder/storage where PlatformIO Library Dependency "
                    "Finder (LDF) looks for global libraries"
                ),
                sysenvvar="PLATFORMIO_GLOBALLIB_DIR",
                default=os.path.join("${platformio.core_dir}", "lib"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="platforms_dir",
                description=(
                    "A location where PlatformIO Core keeps installed development "
                    "platforms"
                ),
                sysenvvar="PLATFORMIO_PLATFORMS_DIR",
                default=os.path.join("${platformio.core_dir}", "platforms"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="packages_dir",
                description=(
                    "A location where PlatformIO Core keeps installed packages"
                ),
                sysenvvar="PLATFORMIO_PACKAGES_DIR",
                default=os.path.join("${platformio.core_dir}", "packages"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="cache_dir",
                description=(
                    "A location where PlatformIO Core stores caching information "
                    "(requests to PlatformIO Registry, downloaded packages and "
                    "other service information)"
                ),
                sysenvvar="PLATFORMIO_CACHE_DIR",
                default=os.path.join("${platformio.core_dir}", ".cache"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="build_cache_dir",
                description=(
                    "A location where PlatformIO Core keeps derived files from a "
                    "build system (objects, firmwares, ELFs) and caches them between "
                    "build environments"
                ),
                sysenvvar="PLATFORMIO_BUILD_CACHE_DIR",
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="workspace_dir",
                description=(
                    "A path to a project workspace directory where PlatformIO keeps "
                    "by default compiled objects, static libraries, firmwares, and "
                    "external library dependencies"
                ),
                sysenvvar="PLATFORMIO_WORKSPACE_DIR",
                default=os.path.join("$PROJECT_DIR", ".pio"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="build_dir",
                description=(
                    "PlatformIO Build System uses this folder for project environments"
                    " to store compiled object files, static libraries, firmwares, "
                    "and other cached information"
                ),
                sysenvvar="PLATFORMIO_BUILD_DIR",
                default=os.path.join("${platformio.workspace_dir}", "build"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="libdeps_dir",
                description=(
                    "Internal storage where Library Manager will install project "
                    "dependencies declared via `lib_deps` option"
                ),
                sysenvvar="PLATFORMIO_LIBDEPS_DIR",
                default=os.path.join("${platformio.workspace_dir}", "libdeps"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="include_dir",
                description=(
                    "A default location for project header files. PlatformIO Build "
                    "System automatically adds this path to CPPPATH scope"
                ),
                sysenvvar="PLATFORMIO_INCLUDE_DIR",
                default=os.path.join("$PROJECT_DIR", "include"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="src_dir",
                description=(
                    "A default location where PlatformIO Build System looks for the "
                    "project C/C++ source files"
                ),
                sysenvvar="PLATFORMIO_SRC_DIR",
                default=os.path.join("$PROJECT_DIR", "src"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="lib_dir",
                description="A storage for the custom/private project libraries",
                sysenvvar="PLATFORMIO_LIB_DIR",
                default=os.path.join("$PROJECT_DIR", "lib"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="data_dir",
                description=(
                    "A data directory to store contents which can be uploaded to "
                    "file system (SPIFFS, etc.)"
                ),
                sysenvvar="PLATFORMIO_DATA_DIR",
                default=os.path.join("$PROJECT_DIR", "data"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="test_dir",
                description=(
                    "A location where PlatformIO Unit Testing engine looks for "
                    "test source files"
                ),
                sysenvvar="PLATFORMIO_TEST_DIR",
                default=os.path.join("$PROJECT_DIR", "test"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="boards_dir",
                description="A storage for custom board manifests",
                sysenvvar="PLATFORMIO_BOARDS_DIR",
                default=os.path.join("$PROJECT_DIR", "boards"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="monitor_dir",
                description="A storage for custom monitor filters",
                sysenvvar="PLATFORMIO_MONITOR_DIR",
                default=os.path.join("$PROJECT_DIR", "monitor"),
                validate=validate_dir,
            ),
            ConfigPlatformioOption(
                group="directory",
                name="shared_dir",
                description=(
                    "A location which PlatformIO Remote Development service uses to "
                    "synchronize extra files between remote machines"
                ),
                sysenvvar="PLATFORMIO_SHARED_DIR",
                default=os.path.join("$PROJECT_DIR", "shared"),
                validate=validate_dir,
            ),
            #
            # [env]
            #
            # Platform
            ConfigEnvOption(
                group="platform",
                name="platform",
                description="A name or specification of development platform",
                buildenvvar="PIOPLATFORM",
            ),
            ConfigEnvOption(
                group="platform",
                name="platform_packages",
                description="Custom packages and specifications",
                multiple=True,
            ),
            # Board
            ConfigEnvOption(
                group="platform",
                name="board",
                description="A board ID",
                buildenvvar="BOARD",
            ),
            ConfigEnvOption(
                group="platform",
                name="framework",
                description="A list of project dependent frameworks",
                multiple=True,
                buildenvvar="PIOFRAMEWORK",
            ),
            ConfigEnvOption(
                group="platform",
                name="board_build.mcu",
                description="A custom board MCU",
                oldnames=["board_mcu"],
                buildenvvar="BOARD_MCU",
            ),
            ConfigEnvOption(
                group="platform",
                name="board_build.f_cpu",
                description="A custom MCU frequency",
                oldnames=["board_f_cpu"],
                buildenvvar="BOARD_F_CPU",
            ),
            ConfigEnvOption(
                group="platform",
                name="board_build.f_flash",
                description="A custom flash frequency",
                oldnames=["board_f_flash"],
                buildenvvar="BOARD_F_FLASH",
            ),
            ConfigEnvOption(
                group="platform",
                name="board_build.flash_mode",
                description="A custom flash mode",
                oldnames=["board_flash_mode"],
                buildenvvar="BOARD_FLASH_MODE",
            ),
            # Build
            ConfigEnvOption(
                group="build",
                name="build_type",
                description="Project build configuration",
                type=click.Choice(["release", "test", "debug"]),
                default="release",
            ),
            ConfigEnvOption(
                group="build",
                name="build_flags",
                description=(
                    "Custom build flags/options for preprocessing, compilation, "
                    "assembly, and linking processes"
                ),
                multiple=True,
                sysenvvar="PLATFORMIO_BUILD_FLAGS",
                buildenvvar="BUILD_FLAGS",
            ),
            ConfigEnvOption(
                group="build",
                name="build_src_flags",
                oldnames=["src_build_flags"],
                description=(
                    "The same as `build_flags` but configures flags the only for "
                    "project source files in the `src` folder"
                ),
                multiple=True,
                sysenvvar="PLATFORMIO_BUILD_SRC_FLAGS",
                buildenvvar="SRC_BUILD_FLAGS",
            ),
            ConfigEnvOption(
                group="build",
                name="build_unflags",
                description="A list with flags/option which should be removed",
                multiple=True,
                sysenvvar="PLATFORMIO_BUILD_UNFLAGS",
                buildenvvar="BUILD_UNFLAGS",
            ),
            ConfigEnvOption(
                group="build",
                name="build_src_filter",
                oldnames=["src_filter"],
                description=(
                    "Control which source files from the `src` folder should "
                    "be included/excluded from a build process"
                ),
                multiple=True,
                sysenvvar="PLATFORMIO_BUILD_SRC_FILTER",
                buildenvvar="SRC_FILTER",
                default="+<*> -<.git/> -<.svn/>",
            ),
            ConfigEnvOption(
                group="build",
                name="targets",
                description="A custom list of targets for PlatformIO Build System",
                multiple=True,
            ),
            # Upload
            ConfigEnvOption(
                group="upload",
                name="upload_port",
                description=(
                    "An upload port which `uploader` tool uses for a firmware flashing"
                ),
                sysenvvar="PLATFORMIO_UPLOAD_PORT",
                buildenvvar="UPLOAD_PORT",
            ),
            ConfigEnvOption(
                group="upload",
                name="upload_protocol",
                description="A protocol that `uploader` tool uses to talk to a board",
                buildenvvar="UPLOAD_PROTOCOL",
            ),
            ConfigEnvOption(
                group="upload",
                name="upload_speed",
                description=(
                    "A connection speed (baud rate) which `uploader` tool uses when "
                    "sending firmware to a board"
                ),
                type=click.INT,
                buildenvvar="UPLOAD_SPEED",
            ),
            ConfigEnvOption(
                group="upload",
                name="upload_flags",
                description="An extra flags for `uploader` tool",
                multiple=True,
                sysenvvar="PLATFORMIO_UPLOAD_FLAGS",
                buildenvvar="UPLOAD_FLAGS",
            ),
            ConfigEnvOption(
                group="upload",
                name="upload_resetmethod",
                description="A custom reset method",
                buildenvvar="UPLOAD_RESETMETHOD",
            ),
            ConfigEnvOption(
                group="upload",
                name="upload_command",
                description=(
                    "A custom upload command which overwrites a default from "
                    "development platform"
                ),
                buildenvvar="UPLOADCMD",
            ),
            # Monitor
            ConfigEnvOption(
                group="monitor",
                name="monitor_port",
                description="A port, a number or a device name",
            ),
            ConfigEnvOption(
                group="monitor",
                name="monitor_speed",
                description="A monitor speed (baud rate)",
                type=click.INT,
                oldnames=["monitor_baud"],
                default=9600,
            ),
            ConfigEnvOption(
                group="monitor",
                name="monitor_parity",
                description="A monitor parity checking",
                type=click.Choice(["N", "E", "O", "S", "M"]),
                default="N",
            ),
            ConfigEnvOption(
                group="monitor",
                name="monitor_filters",
                description=(
                    "Apply the filters and text transformations to monitor output"
                ),
                multiple=True,
            ),
            ConfigEnvOption(
                group="monitor",
                name="monitor_rts",
                description="A monitor initial RTS line state",
                type=click.IntRange(0, 1),
            ),
            ConfigEnvOption(
                group="monitor",
                name="monitor_dtr",
                description="A monitor initial DTR line state",
                type=click.IntRange(0, 1),
            ),
            ConfigEnvOption(
                group="monitor",
                name="monitor_eol",
                description="A monitor end of line mode",
                type=click.Choice(["CR", "LF", "CRLF"]),
                default="CRLF",
            ),
            ConfigEnvOption(
                group="monitor",
                name="monitor_raw",
                description="Disable encodings/transformations of device output",
                type=click.BOOL,
                default=False,
            ),
            ConfigEnvOption(
                group="monitor",
                name="monitor_echo",
                description="Enable a monitor local echo",
                type=click.BOOL,
                default=False,
            ),
            ConfigEnvOption(
                group="monitor",
                name="monitor_encoding",
                description="Custom encoding (e.g. hexlify, Latin1, UTF-8)",
                default="UTF-8",
            ),
            # Library
            ConfigEnvOption(
                group="library",
                name="lib_deps",
                description=(
                    "A list of project library dependencies which should be installed "
                    "automatically before a build process"
                ),
                oldnames=["lib_use", "lib_force", "lib_install"],
                multiple=True,
            ),
            ConfigEnvOption(
                group="library",
                name="lib_ignore",
                description=(
                    "A list of library names which should be ignored by "
                    "Library Dependency Finder (LDF)"
                ),
                multiple=True,
            ),
            ConfigEnvOption(
                group="library",
                name="lib_extra_dirs",
                description=(
                    "A list of extra directories/storages where Library Dependency "
                    "Finder (LDF) will look for dependencies"
                ),
                multiple=True,
                sysenvvar="PLATFORMIO_LIB_EXTRA_DIRS",
            ),
            ConfigEnvOption(
                group="library",
                name="lib_ldf_mode",
                description=(
                    "Control how Library Dependency Finder (LDF) should analyze "
                    "dependencies (`#include` directives)"
                ),
                type=click.Choice(["off", "chain", "deep", "chain+", "deep+"]),
                default="chain",
            ),
            ConfigEnvOption(
                group="library",
                name="lib_compat_mode",
                description=(
                    "Configure a strictness (compatibility mode by frameworks, "
                    "development platforms) of Library Dependency Finder (LDF)"
                ),
                type=click.Choice(["off", "soft", "strict"]),
                default="soft",
            ),
            ConfigEnvOption(
                group="library",
                name="lib_archive",
                description=(
                    "Create an archive (`*.a`, static library) from the object files "
                    "and link it into a firmware (program)"
                ),
                type=click.BOOL,
                default=True,
            ),
            # Check
            ConfigEnvOption(
                group="check",
                name="check_tool",
                description="A list of check tools used for analysis",
                type=click.Choice(["cppcheck", "clangtidy", "pvs-studio"]),
                multiple=True,
                default=["cppcheck"],
            ),
            ConfigEnvOption(
                group="check",
                name="check_src_filters",
                oldnames=["check_patterns"],
                description=(
                    "Configure a list of target files or directories for checking"
                ),
                multiple=True,
            ),
            ConfigEnvOption(
                group="check",
                name="check_flags",
                description="An extra flags to be passed to a check tool",
                multiple=True,
            ),
            ConfigEnvOption(
                group="check",
                name="check_severity",
                description="List of defect severity types for analysis",
                multiple=True,
                type=click.Choice(["low", "medium", "high"]),
                default=["low", "medium", "high"],
            ),
            ConfigEnvOption(
                group="check",
                name="check_skip_packages",
                description="Skip checking includes from packages directory",
                type=click.BOOL,
                default=False,
            ),
            # Test
            ConfigEnvOption(
                group="test",
                name="test_framework",
                description="A unit testing framework",
                type=click.Choice(["doctest", "googletest", "unity", "custom"]),
                default="unity",
            ),
            ConfigEnvOption(
                group="test",
                name="test_filter",
                description="Process tests where the name matches specified patterns",
                multiple=True,
            ),
            ConfigEnvOption(
                group="test",
                name="test_ignore",
                description="Ignore tests where the name matches specified patterns",
                multiple=True,
            ),
            ConfigEnvOption(
                group="test",
                name="test_port",
                description="A serial port to communicate with a target device",
            ),
            ConfigEnvOption(
                group="test",
                name="test_speed",
                description="A connection speed (baud rate) to communicate with "
                "a target device",
                type=click.INT,
                default=115200,
            ),
            ConfigEnvOption(
                group="test",
                name="test_build_src",
                oldnames=["test_build_project_src"],
                description="Build main source code in pair with a test code",
                type=click.BOOL,
                default=False,
            ),
            ConfigEnvOption(
                group="test",
                name="test_testing_command",
                multiple=True,
                description=(
                    "A custom testing command that runs test cases "
                    "and returns results to the standard output"
                ),
            ),
            # Debug
            ConfigEnvOption(
                group="debug",
                name="debug_tool",
                description="A name of debugging tool",
            ),
            ConfigEnvOption(
                group="debug",
                name="debug_build_flags",
                description=(
                    "Custom debug flags/options for preprocessing, compilation, "
                    "assembly, and linking processes"
                ),
                multiple=True,
                default=["-Og", "-g2", "-ggdb2"],
            ),
            ConfigEnvOption(
                group="debug",
                name="debug_init_break",
                description=(
                    "An initial breakpoint that makes program stop whenever a "
                    "certain point in the program is reached"
                ),
                default="tbreak main",
            ),
            ConfigEnvOption(
                group="debug",
                name="debug_init_cmds",
                description="Initial commands to be passed to a back-end debugger",
                multiple=True,
            ),
            ConfigEnvOption(
                group="debug",
                name="debug_extra_cmds",
                description="An extra commands to be passed to a back-end debugger",
                multiple=True,
            ),
            ConfigEnvOption(
                group="debug",
                name="debug_load_cmds",
                description=(
                    "A list of commands to be used to load program/firmware "
                    "to a target device"
                ),
                oldnames=["debug_load_cmd"],
                multiple=True,
                default=["load"],
            ),
            ConfigEnvOption(
                group="debug",
                name="debug_load_mode",
                description=(
                    "Allows one to control when PlatformIO should load debugging "
                    "firmware to the end target"
                ),
                type=click.Choice(["always", "modified", "manual"]),
                default="always",
            ),
            ConfigEnvOption(
                group="debug",
                name="debug_server",
                description="Allows one to setup a custom debugging server",
                multiple=True,
            ),
            ConfigEnvOption(
                group="debug",
                name="debug_port",
                description=(
                    "A debugging port of a remote target (a serial device or "
                    "network address)"
                ),
            ),
            ConfigEnvOption(
                group="debug",
                name="debug_speed",
                description="A debug adapter speed (JTAG speed)",
            ),
            ConfigEnvOption(
                group="debug",
                name="debug_svd_path",
                description=(
                    "A custom path to SVD file which contains information about "
                    "device peripherals"
                ),
                type=click.Path(exists=True, file_okay=True, dir_okay=False),
            ),
            ConfigEnvOption(
                group="debug",
                name="debug_server_ready_pattern",
                description=(
                    "A pattern to determine when debugging server is ready "
                    "for an incoming connection"
                ),
            ),
            ConfigEnvOption(
                group="debug",
                name="debug_test",
                description=("A name of a unit test to be debugged"),
            ),
            # Advanced
            ConfigEnvOption(
                group="advanced",
                name="extends",
                description=(
                    "Inherit configuration from other sections or build environments"
                ),
                multiple=True,
            ),
            ConfigEnvOption(
                group="advanced",
                name="extra_scripts",
                description="A list of PRE and POST extra scripts",
                oldnames=["extra_script"],
                multiple=True,
                sysenvvar="PLATFORMIO_EXTRA_SCRIPTS",
            ),
        ]
    ]
)

def get_config_options_schema():
    return [opt.as_dict() for opt in ProjectOptions.values()]


"""
Provides functions for testing functions
"""

import json

def ratio(success_count, attempt_count):
    """ Pretty-print a success rate """
    success_ratio = success_count / (attempt_count or 1)
    return "%d/%d=%d%%"%(success_count, attempt_count, int(success_ratio*100))

def test(func, get_parts=None):
    """
    Test a function on specific parts using the training data

    Parameters
    ----------
    func
        The function to test
    get_parts
        A function to split each case into sub-cases to independently test

        Default: just test each whole test case without splitting
    """
    with open("data/training/isl.json") as f:
        data = json.load(f)
    failures = []
    failure_count = 0
    success_count = 0
    case_success_count = 0
    case_total_count = len(data)
    for case in data:
        successful = True
        content = case["content"]
        try:
            if get_parts is None:
                parts = [content]
            else:
                print(get_parts)
                print(get_parts("abc $def$ hi"))
                parts = get_parts(content)
        except:
            print("failed on parts")
            successful = False
            parts = []
        for expr in parts:
            try:
                func(expr)
                success_count += 1
            except:
                if successful:
                    print("Failed on part ", expr)
                successful = False
                failure_count += 1
                failures.append(expr)
        if successful:
            case_success_count += 1
    total_count = success_count + failure_count
    print("Failed expressions:\n", "\n".join(failures))
    print("Successful parts: %s"%ratio(success_count, total_count))
    if get_parts is not None:
        print("Successful cases: %s"%ratio(case_success_count, case_total_count))


import requests

import conf
import util

def link_moodle_course(course_id: str, moodle_short_name: str, sync_students: bool, sync_grades: bool, force: bool):
    body = {
        "moodle_props": {
            "moodle_short_name": moodle_short_name,
            "sync_students": sync_students,
            "sync_grades": sync_grades
        },
        "force": force
    }

    resp = requests.put(conf.EMS_BASE_URL + '/courses/' + course_id + '/moodle', json=body, headers=util.get_token_header())
    print(resp.status_code)