#!/usr/bin/env python3
import datetime
import statistics
import tempfile

# prompt user to select from mailroom menu: send a thank you, create a report, or quit
# send a thank you: allows user to select a name, adds donor if not in donor list, otherwise ask for donation
# and thanks donor
# create a report summarizes the donors and their donations in a table
# quit ends the program

# donors exists in global namespace
donors = {
      "Jerry Seinfeld": [
          324.33
      ],
      "John Stewart": [
          5000000.00
      ],
      "Larry David": [
          1800.18,
          36036.36
      ],
      "Gene Wilder": [
          7272.72,
          1818.18,
          545454.54
      ],
      "Jerry Lewis": [
          0.00
      ],
      "Gilda Radner": [
          324.32
      ],
      "Rodney Dangerfield": [
          363363.63,
          18181.81,
          545454.54,
          727.72,
          9090.90,
          108.18,
          126.12,
          7272.72,
          54.54,
          18.00,
          0.18
      ]
}
now = datetime.datetime.now()

def main():
    main_prompt = ("\nPlease enter an option from the following menu\n"
                   "1 - Send a Thank You to a single donor\n"
                   "2 - Create a Report\n"
                   "3 - Send letters to all donors\n"
                   "4 - Quit\n>> ")
    dispatch = {"1": send_thank_you, "2": create_report, "3": send_thank_you_all_donors, "4": quit_mailroom}
    menu_selection(main_prompt, **dispatch)

def menu_selection(prompt, **dispatch_dict):
    """
    prompts user for input and calls function object in dispatch_dict
    :param prompt: user input prompt
    :param dispatch_dict: dict of dispatch functions
    :return:
    """
    while True:
        try:
            response = get_user_input(f"{prompt}")
        except (TypeError, ValueError) as menu_err:
            print(f"Invalid option {response}\n")
            raise menu_err
        except (KeyboardInterrupt, EOFError):
            return None
        if dispatch_dict[response]() == 4:
            break

def quit_mailroom():
    """
    quit the mailroom
    :return: 4 (quit option)
    """
    return 4

def send_thank_you():
    """
    prompt user for a donor name; if name exists, prompts for donation, otherwise add name to donors
    'list' displays a list of donors
    print thank you to donor
    :return: None
    """
    donor_name = get_user_input("Please enter the name of a donor: ")
    if donor_name == 'list':
        print(f"List of donors: {', '.join(list_donors(**donors))}")
    else:
        while True:
            try:
                donation = float(get_user_input("Please enter the donation amount: ").strip('$'))
                if bool(donation) is True:
                    break
                else:
                    print(f"Invalid donation, please enter a valid donation.\n")
            except ValueError as donation_err:
                raise donation_err
                continue
        donor_info = (donor_name, donation)
        update_donor(donor_info)
        print(f"{format_thank_you(donor_info)}")

def list_donors(**donors):
    """
    :param donors: dict of key:donor and value:list of donations
    :return: list of donors
    """
    if not donors:
        raise TypeError("donors cannot be empty")
    else:
        try:
            return list(donors.keys())
        except KeyError as key_error:
            print(f"{key_error}")

def update_donor(donor_info=None):
    """
    add donor if donor does not exist, otherwise update donor's list of donations
    :param donor_info: tuple of donor name and donation amount
    :return:
    """
    if not donor_info[0]:
        raise TypeError("donor_name cannot be empty")
    else:
        if donor_info[0] in donors:
            try:
                donors.setdefault(donor_info[0], []).append(donor_info[1])
            except IndexError as donor_info_error:
                print(f"{donor_info_error}")
        else:
            donors.setdefault(donor_info[0], []).append(donor_info[1])
            print(f"Sorry, the name you entered is not in our donor list.  Adding donor to list...")

def send_thank_you_all_donors():
    """
    generate a thank you letter for all donors, write each letter to disk as .txt in tempdir
    :return: None
    """
    try:
        with tempfile.TemporaryDirectory(suffix='mailroom2', prefix='tys_all_donors', dir='.') as tempdir:
            for donor in donors:
                donor_info = (donor, format(donors.get(donor)[-1], '.2f'))
                with open(f"{(donor_info[0]).replace(' ','_')}_{str(now.date()).replace('-','_')}.txt", 'w') as f:
                    f.write(format_thank_you(donor_info))
    except (IOError,  PermissionError, NotADirectoryError, FileExistsError, FileNotFoundError) as report_err:
        print(f"{report_err}")
        raise report_err

def format_thank_you(donor_info=None):
    """
    create thank you letter
    :param donor_info: tuple of donor name and donation amount
    :return:
    """
    if not donor_info[0]:
        raise ValueError("donor name and donation cannot be empty")
    elif not donor_info[1]:
        raise ValueError("donation amount cannot be empty")
    else:
        thank_you = (
            f"\n\n{now.date()}\n\n"
            f""
            f"Dear {donor_info[0]},\n\n"
            f""
            f"On behalf of all of us at the ADL office we'd like to recognize and thank you for your generous\n"
            f"donation of ${donor_info[1]}.  "
            f"These funds will be used to further our mission in fighting hate\n"
            f"through leadership programs and education.  \n\n"
            f"We look forward to seeing you at this year's banquet.\n"
            f"\n"
            f"Sincerely, "
            f"\n"
            f"ADL")
    return str(thank_you)

def display_report(donor_summary=None):
    """
    prints formatted donor report
    :param donor_summary:
    :return:
    """
    print(f"Donor Name{'':<20} | Total Given{'':>0} | Num Gifts{'':>0} | Average Gift{'':>0}")
    print(f"-" * 72)
    for name, total, num_gift, avg_gift in donor_summary:
        print(f"{name:<32}${total:>11.2f}{num_gift:>12}  ${avg_gift:>13.2f}")

def get_report(donors=None):
    """
    data logic function for reports
    :param donors:
    :return: donor summary list
    """
    donor_summary = []
    if not donors:
        raise ValueError("donors list cannot be empty")
    else:
        for donor in donors:
            try:
                donor_summary.append([donor, sum(donors.get(donor)), len(donors.get(donor)),
                                     statistics.mean(donors.get(donor))])
            except (KeyError, IndexError) as donor_summary_err:
                raise donor_summary_err
    donor_summary.sort(key=lambda x: float(x[1]), reverse=True)
    return donor_summary

def create_report():
    """
    dispatch function for creating and displaying donor report
    :return:
    """
    display_report(get_report(donors))

def get_user_input(prompt):
    """
    :param prompt: prompt for user to respond to
    :return: response to question/prompt
    """
    return input(prompt).strip()

if __name__ == "__main__":
    print("Running", __file__)
    main()
else:
    print("Running as imported module", __file__)


# Module: addon
# Author: Tomas "tomplast" Gustavsson
# Created on: 30.12.2022
# License: GPL v.3 https://www.gnu.org/copyleft/gpl.html
"""
Premier One video plugin
"""
import xbmcgui
import xbmcplugin
import requests
import uuid
import routing

plugin = routing.Plugin()
DEVICE_ID = str(uuid.uuid4())

@plugin.route("/list_search/<term>/<page>")
def list_search(term, page):
    search_term = term

    if term == "_":
        search_term = xbmcgui.Dialog().input("Поиск")

    search_result = requests.get(
        f"https://premier.one/app/v1.2/search?query={search_term}&page={page}&picture_type=card_group&system=hwi_vod_id%2Chwi_world&is_active=1&device=web",
        headers={"x-device-type": "browser", "x-device-id": DEVICE_ID},
    ).json()

    for card in search_result["results"]:
        list_item = xbmcgui.ListItem(
            label=f'[B]{card["type"]["title"]}[/B] - {card["name"]}'
        )
        list_item.setArt({"thumb": card["picture"]})

        list_item.setInfo(
            "video",
            {
                "title": card["name"],
                "genre": ", ".join([x["name"] for x in card["genres"]]),
                "mediatype": "video",
            },
        )

        url = plugin.url_for(list_seasons, program=card["slug"])

        if card["type"]["name"] == "movie":
            list_item.setProperty("IsPlayable", "true")
            url = plugin.url_for(play_video, media_id=f'p:{card["slug"]}')

        xbmcplugin.addDirectoryItem(
            plugin.handle, url, list_item, not list_item.getProperty("IsPlayable")
        )

    if search_result["has_next"]:
        xbmcplugin.addDirectoryItem(
            plugin.handle,
            plugin.url_for(list_search, term=search_term, page=int(page) + 1),
            xbmcgui.ListItem(label="следующий"),
            True,
        )

    xbmcplugin.endOfDirectory(plugin.handle)

@plugin.route("/list_seasons/<program>")
def list_seasons(program):
    result = requests.get(
        f"https://premier.one/uma-api/metainfo/tv/{program}/season/?picture_type=banner"
    ).json()

    for season in result:
        list_item = xbmcgui.ListItem(label=f'сезон {season["number"]}')
        list_item.setArt({"thumb": season["picture"]})

        url = plugin.url_for(
            list_videos, program=program, season=int(season["number"]), page=1
        )
        xbmcplugin.addDirectoryItem(plugin.handle, url, list_item, True)

    xbmcplugin.endOfDirectory(plugin.handle)

@plugin.route("/")
def list_main_menu():
    xbmcplugin.addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_free, page=1),
        xbmcgui.ListItem(label="Бесплатно"),
        True,
    )

    xbmcplugin.addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_search, term='_', page=1),
        xbmcgui.ListItem(label="Поиск (Может работать)"),
        True,
    )

    xbmcplugin.endOfDirectory(plugin.handle)

@plugin.route("/list_programs")
def list_programs(page=1):
    card_group = requests.get(
        f"https://premier.one/uma-api/feeds/cardgroup/202?alias=all_premier&style=portrait&link=https%3A%2F%2Ftnt-premier.ru&title=&bg_url=https%3A%2F%2Ftnt-premier.ru%2Fimg%2Fdevices-4.1168fded.png&picture_type=card_group&quantity=6&sort=publication_d&origin__type=hwi,rtb&is_active=1&system=hwi_vod_id,hwi_world&page={page}"
    ).json()

    xbmcplugin.addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_search),
        xbmcgui.ListItem(label="Поиск"),
        True,
    )

    for card in card_group["results"]:
        list_item = xbmcgui.ListItem(
            label=f'[B]{card["type"]["title"]}[/B] - {card["object"]["name"]}'
        )
        list_item.setArt({"thumb": card["object"]["picture"]})

        list_item.setInfo(
            "video",
            {
                "title": card["object"]["name"],
                "genre": ", ".join([x["name"] for x in card["object"]["genres"]]),
                "mediatype": "video",
            },
        )

        url = plugin.url_for(list_seasons, program=card["object"]["slug"])

        if card["type"]["name"] == "movie":
            list_item.setProperty("IsPlayable", "true")
            url = plugin.url_for(play_video, media_id=f'p:{card["object"]["slug"]}')

        xbmcplugin.addDirectoryItem(
            plugin.handle, url, list_item, not list_item.getProperty("IsPlayable")
        )

    if card_group["has_next"]:
        xbmcplugin.addDirectoryItem(
            plugin.handle,
            plugin.url_for(list_programs, page=int(page) + 1),
            xbmcgui.ListItem(label="следующий"),
            True,
        )

    xbmcplugin.endOfDirectory(plugin.handle)

@plugin.route("/list_videos/<program>/<season>/<page>")
def list_videos(program, season, page):
    videos = requests.get(
        f"https://premier.one/uma-api/metainfo/tv/{program}/video/?show_all=1&season={season}&type=6%2C9&limit=18&origin__type=hwi%2Crtb&page={page}"
    ).json()

    for video in videos["results"]:
        list_item = xbmcgui.ListItem(label=f"{video['title']}")
        list_item.setArt({"thumb": video["thumbnail_url"]})
        list_item.setInfo(
            "video",
            {
                "title": video["title"],
                "plot": video["description"],
                "season": season,
                "episode": video["episode"],
                "mediatype": "video",
                "picture": video["thumbnail_url"],
            },
        )
        list_item.setProperty("IsPlayable", "true")

        url = plugin.url_for(play_video, media_id=video["id"])

        xbmcplugin.addDirectoryItem(plugin.handle, url, list_item, False)

    if videos["has_next"]:
        xbmcplugin.addDirectoryItem(
            plugin.handle,
            plugin.url_for(
                list_videos, season=season, program=program, page=int(page) + 1
            ),
            xbmcgui.ListItem(label="следующий"),
            True,
        )

    xbmcplugin.endOfDirectory(plugin.handle)

@plugin.route("/list_free/<page>")
def list_free(page):
    card_group = requests.get(
        f"https://premier.one/uma-api/feeds/cardgroup/250?alias=all_premier&style=portrait&link=https%3A%2F%2Ftnt-premier.ru&title=&bg_url=https%3A%2F%2Ftnt-premier.ru%2Fimg%2Fdevices-4.1168fded.png&picture_type=card_group&quantity=6&sort=publication_d&origin__type=hwi,rtb&is_active=1&system=hwi_vod_id,hwi_world&page={page}"
    ).json()

    for card in card_group["results"]:
        list_item = xbmcgui.ListItem(
            label=f'[B]{card["object"]["type"]["title"]}[/B] - {card["object"]["name"]}'
        )

        list_item.setArt({"thumb": card["object"]["picture"]})

        list_item.setInfo(
            "video",
            {
                "title": card["object"]["name"],
                "genre": ", ".join([x["name"] for x in card["object"]["genres"]]),
                "mediatype": "video",
            },
        )

        url = plugin.url_for(list_seasons, program=card["object"]["slug"])

        if card["object"]["type"]["name"] == "movie":
            list_item.setProperty("IsPlayable", "true")
            url = plugin.url_for(play_video, media_id=f'p:{card["object"]["slug"]}')

        xbmcplugin.addDirectoryItem(
            plugin.handle, url, list_item, not list_item.getProperty("IsPlayable")
        )

    if card_group["has_next"]:
        xbmcplugin.addDirectoryItem(
            plugin.handle,
            plugin.url_for(list_free, page=int(page) + 1),
            xbmcgui.ListItem(label="следующий"),
            True,
        )

    xbmcplugin.endOfDirectory(plugin.handle)

@plugin.route("/play_video/<media_id>")
def play_video(media_id):
    if media_id.startswith("p:"):
        _, program = media_id.split("p:")
        video = requests.get(
            f"https://premier.one/uma-api/metainfo/tv/{program}/video/?show_all=1&season=0&type=6%2C9&limit=18&origin__type=hwi%2Crtb&page=1"
        ).json()

        media_id = video["results"][0]["id"]

    response = requests.get(
        f"https://premier.one/api/play/options/{media_id}/?format=json&no_404=true&referer=https://premier.one/show/istoriya-na-noch/season/1/episode/18?fullscreen=true"
    )

    json_response = response.json()

    if response.status_code != 200:
        error_message = next(
            x["title"]
            for x in json_response["detail"]["languages"]
            if x["lang"] == "rus"
        )
        xbmcgui.Dialog().ok("Ошибка", error_message)
        return

    play_item = xbmcgui.ListItem(path=json_response["video_balancer"]["default"])

    xbmcplugin.setResolvedUrl(plugin.handle, True, listitem=play_item)

if __name__ == "__main__":
    xbmcplugin.setPluginCategory(plugin.handle, "")
    plugin.run()


import base64

from src.models.api_client import ApiClientModel

def get_api_client_from_form_data(event):
    form = event['body']
    client_id = form['client_id']
    client_secret = form['client_secret']
    client = ApiClientModel.get_by_client_data(client_id, client_secret)
    return client

def get_api_client_from_headers(event):
    headers = event['headers']

    if 'Authorization' not in headers:
        return False

    authorization = headers['Authorization']

    b64_token = authorization.split(' ')[-1]

    # decode the base64 encoded header value
    client_id, client_secret = base64.b64decode(b64_token).decode("ascii").split(':')

    # check if the given api key actually exists
    client = ApiClientModel.get_by_client_data(client_id, client_secret)

    return client


# -*- coding: utf-8 -*-
""" Calculations provided by aiida_turborvb turborvb main executable.
"""

from aiida.common import datastructures
from aiida.engine import CalcJob
from aiida.orm import SinglefileData, Dict, Str, StructureData

class TurboRVBConvertfort10molCalculationWRP(CalcJob):
    """
    AiiDA calculation plugin for TurboRVB.

    Serves as a calculation job provider for TurboRVB main executable,
    for execution of quantum monte carlo calculations
    """

    @classmethod
    def define(cls, spec):
        """Define inputs and outputs of the calculation."""
        # yapf: disable
        super().define(spec)

        # set default values for AiiDA options
        spec.inputs['metadata']['options']['resources'].default = {
            'num_machines': 1,
            'num_mpiprocs_per_machine': 1,
        }
        spec.input('fort10', valid_type=SinglefileData, help='')
        spec.input('pseudo', valid_type=SinglefileData, required=False, help='')
        spec.input('parameters', valid_type=Dict, help='')

        spec.output('fort10', valid_type=SinglefileData, help='')

        spec.inputs['metadata']['options']['parser_name'].default = 'turborvb.convertfort10molwrp'
        spec.inputs['metadata']['options']['input_filename'].default = 'execute.sh'
        spec.inputs['metadata']['options']['output_filename'].default = 'execute.out'

        spec.exit_code(300, 'ERROR_MISSING_OUTPUT_FILES', message='Calculation did not produce all expected output files.')

    def prepare_for_submission(self, folder):
        """
        Create input files.

        :param folder: an `aiida.common.folders.Folder` where the plugin should temporarily place all files
            needed by the calculation.
        :return: `aiida.common.datastructures.CalcInfo` instance
        """

        parameters = self.inputs.parameters.get_dict()

        with folder.open("fort.10_in", "w") as fhandle_out, \
             self.inputs.fort10.open() as fhandle_in:
            fhandle_out.write(fhandle_in.read())

        if "pseudo" in self.inputs:
            with folder.open("pseudo.dat", "w") as fhandle_out, \
                 self.inputs.pseudo.open() as fhandle_in:
                fhandle_out.write(fhandle_in.read())

        with folder.open(self.options.input_filename, "w") as fhandle:
            content = []
            content.append('turbo-genius.sh -j convertfort10mol -g')
            if "namelist_update" in parameters:
                content.append("cp convertfort10mol.input source")
                for key, value in parameters["namelist_update"].items():
                    content.append("sed 's/\s*!\?"+key+"\s*=.*$/"+key+"="+f"{value}"+"/g' source > dest")
                    content.append("cp dest source")
                content.append("cp dest convertfort10mol.input")
            content.append('convertfort10mol.x < convertfort10mol.input > convertfort10mol.output')

            fhandle.write("\n".join(content))

        codeinfo = datastructures.CodeInfo()
        codeinfo.code_uuid = self.inputs.code.uuid
        codeinfo.cmdline_params = []
        codeinfo.stdin_name = f"{self.inputs.metadata.options.input_filename}"
        codeinfo.stdout_name = f"{self.inputs.metadata.options.output_filename}"

        calcinfo = datastructures.CalcInfo()
        calcinfo.codes_info = [codeinfo]

        calcinfo.retrieve_list = ["fort.10_new",
                                  self.options.output_filename]

        return calcinfo


import logging

from sqlalchemy.exc import SQLAlchemyError

from database.manager import DatabaseManager
from database.models import User

logger = logging.getLogger(__name__)
SessionLocal = DatabaseManager.get_session_local

def insert_user(user_data: dict) -> User:
    """
    Insert a new user in the database
    :param user_data: dict, data of the user to insert
    :return: User, the inserted user
    """
    with SessionLocal() as db:
        user: User = User(**user_data)
        try:
            db.add(user)
            db.commit()
            db.refresh(user)
            logger.info(f'User {user.username} inserted successfully in the database.')
        except SQLAlchemyError:
            db.rollback()
            raise
    return user

def get_user(**kwargs) -> User:
    """
    Retrieve a user from the database based on the given filters
    :param kwargs: Keyword arguments, accepts either discord_id or username
    :return: User, the user
    """
    with SessionLocal() as db:
        filters: list = []
        if 'discord_id' in kwargs:
            filters.append(User.discord_id == kwargs['discord_id'])
        if 'username' in kwargs:
            filters.append(User.username == kwargs['username'])

        if not filters:
            raise ValueError('No valid filter given')

        user: User = db.query(User).filter(*filters).first()
        logger.debug(f'User retrieved from the database: {user}')

    return user

def get_all_users() -> list[User]:
    """
    Retrieve all users from the database
    :return: list[User], all users
    """
    with SessionLocal() as db:
        users = db.query(User).all()
        logger.debug(f'All users retrieved from the database: {len(users)}')
    return users

def update_user(user: User, user_data: dict) -> User:
    """
    Update a user in the database.
    :param user: User, the user to update
    :param user_data: dict, data to update
    :return: User, the updated user
    """
    with SessionLocal() as db:
        try:
            db_user = db.query(User).filter(User.discord_id == user.discord_id).first()
            if not db_user:
                raise ValueError('User not found')

            for key, value in user_data.items():
                setattr(db_user, key, value)

            db.commit()
            db.refresh(db_user)
            logger.info(f'User {db_user.username} updated successfully in the database.')
        except SQLAlchemyError:
            db.rollback()
            raise
    return db_user


import networkx as nx
import random
import pandas as pd
import time
#from Graph_gen import *
from fast_graph_gen import *
from VNS import vns
from LP_solver import solver
from greedy import *

def func1(arg):
    return solver(arg)

def func2(arg):
    return vns(arg,100,3)

def func3(arg):
    return objective_function(ghmwdds(arg), arg)

def benchmark_function(func, args_list):
    runtimes = []
    results = []

    for arg in args_list:
        if func == func2:
            temp_runtimes = []
            temp_results = []

            for _ in range(10):
                start_time = time.time()
                result = func(arg)
                end_time = time.time()

                temp_runtimes.append(end_time - start_time)
                temp_results.append(result)

            runtimes.append(temp_runtimes)
            results.append(temp_results)

        else:
            start_time = time.time()
            result = func(arg)
            end_time = time.time()

            runtimes.append(end_time - start_time)
            results.append(result)

    return runtimes, results

def main():
    args_list = create_list_of_random_graphs()

    functions = [func1, func2, func3]  # Solveri

    all_runtimes = []
    all_results = []

    for func in functions:
        runtimes, results = benchmark_function(func, args_list)
        all_runtimes.append(runtimes)
        all_results.append(results)

    data = {
        'Arguments': list(range(len(args_list))),
        'Func1_Runtime': all_runtimes[0],
        'Func1_Result': all_results[0]
    }

    for i in range(10):
        data[f"Func2_Runtime_{i + 1}"] = [runtimes[i] for runtimes in all_runtimes[1]]
        data[f"Func2_Result_{i + 1}"] = [result[i] for result in all_results[1]]

    data['Func3_Runtime'] = all_runtimes[2]
    data['Func3_Result'] = all_results[2]

    df = pd.DataFrame(data)
    csv_filename = "benchmark_results.csv"
    df.to_csv(csv_filename, index=False)

if __name__ == "__main__":
    main()


# Quality-Adjusted Life-Year

from functools import reduce

N = int(input())

qaly = 0
for i in range(N):
    q, y = map(float, input().split())
    qaly += q*y
print('{:.3f}'.format(qaly))


import pandas as pd
import seaborn as sns
import db
from sklearn import preprocessing # 머신러닝 전처리 => 데이터 정규화
import matplotlib.pyplot as plt

# 분석 끝나서 동적으로 쓸때 데이터프레임 db로 부터 받아올 필요있음.
# 전처리전 db 연결해서 데이터 뽑아옴
conn=db.get_connection()
anal_list_table=db.get_anal_list(conn)

# matplotlib 한글 폰트 처리
import platform
from matplotlib import font_manager, rc
plt.rcParams['axes.unicode_minus']=False

if platform.system()=='Windows':
    path = 'c:/Windows/Fonts/malgun.ttf'
    font_name=font_manager.FontProperties(fname=path).get_name()
    rc('font',family=font_name)

ac_anal=pd.read_excel('dynamic/data/ac_anal.xls',encoding='euc-kr')
pop_seoul=pd.read_excel('dynamic/data/Pop_seoul_real.xls',encoding='euc-kr')
ac_anal=pd.merge(ac_anal,pop_seoul,on='자치구')
ac_anal.set_index('자치구',inplace=True)

ac_anal['미성년자']=ac_anal['5~9세']+ac_anal['10~14세']+ac_anal['15~19세']
del ac_anal['10~14세']
del ac_anal['5~9세']
del ac_anal['15~19세']

# 상관관계 및 정규화 대상 칼럼 지정
col1 = ['무단횡단 사고',
        '중국인',
        '유흥업소']

col2 = ['무단횡단 사고',
        '유기동물보호현황',
        '인구밀도',
        '통근,통학',
        '총인구합계']

col3 = ['무단횡단 사고',
        '도로 총 계',
        '광로(40m이상)', '대로(25~40)', '중로(12~25)', '소로(12m미만)']

col4 = ['무단횡단 사고', '횡단보도수', '신호등O', '신호등X']

col5 = ['무단횡단 사고',
        '기초생활수급자',
        '미성년자', '노인인구합계']

col_list = [col1, col2, col3, col4, col5]

# 정규화 모듈

def Normalize(column_list):
    x = ac_anal[column_list].values
    min_max_scaler = preprocessing.MinMaxScaler()  # 전처리 모듈
    x_scaled = min_max_scaler.fit_transform(x.astype(float))

    ac_anal_norm = pd.DataFrame(x_scaled, columns=column_list, index=ac_anal.index)  # 정규화 DataFrame 생성

    return ac_anal_norm
# col1 ~ col5에 대한 정규화 테이블 생성

ac_anal_norm1=Normalize(col1) # 무단횡단 / 중국인 / 유흥업소
ac_anal_norm2=Normalize(col2) # '무단횡단 사고','유기동물보호현황','인구밀도','통근,통학'
ac_anal_norm3=Normalize(col3) # '무단횡단 사고','도로 총 계','광로(40m이상)','대로(25~40)','중로(12~25)','소로(12m미만)','도로연장당 횡단보도 수'
ac_anal_norm4=Normalize(col4) # '무단횡단 사고','횡단보도수','신호등O','신호등X'
ac_anal_norm5=Normalize(col5) # '무단횡단 사고','기초생활수급자','5~9세','10~14세','15~19세','노년부양비','노령화지수'

# 사진 저장 경로 수정해야함
# 그래프 사진 저장
# 영등포구 >> 무단횡단사고/중국인/유흥업소 수 히트맵
plt.figure(figsize = (15, 16))
Y_plot1=sns.heatmap(data = ac_anal_norm1, annot = True, fmt = '.2f', cmap = 'Reds')
fig1=Y_plot1.get_figure()
#fig1.savefig('C:\Multicampus_kssj\Anal_image\Yongdeungpo1_hitmap.png')
fig1.savefig('C:\Last_kssj_project\static')
# 영등포구 >> 무단횡단사고/중국인/유흥업소 상관계수 히트맵
plt.figure(figsize = (10, 10))
Y_plot2=sns.heatmap(data = ac_anal_norm1.corr(), annot = True, fmt = '.2f', cmap = 'Reds')
fig2=Y_plot2.get_figure()
fig2.savefig('C:\Multicampus_kssj\Anal_image\Yondeungpo2_corr_hitmap.png')

# 영등포구 >> 무단횡단사고/중국인/유흥업소 상관관계 pairplot
Y_plot3=sns.pairplot(ac_anal_norm1,x_vars=['중국인','유흥업소'],y_vars=['무단횡단 사고'],kind='reg',size=5)
Y_plot3.savefig('C:\Multicampus_kssj\Anal_image\Yondeungpo3_corr_pairplot.png')

# ***********************************************

# 2.관악구
plt.figure(figsize = (15, 15))
G_plot1=sns.heatmap(data = ac_anal_norm2, annot = True, fmt = '.2f', cmap = 'Blues')
fig1=G_plot1.get_figure()
fig1.savefig('C:\Multicampus_kssj\Anal_image\Gwanak1_hitmap.png')

plt.figure(figsize = (10, 10))
G_plot2=sns.heatmap(data = ac_anal_norm2.corr(), annot = True, fmt = '.2f', cmap = 'Blues')
fig2=G_plot2.get_figure()
fig2.savefig('C:\Multicampus_kssj\Anal_image\Gwanak2_corr_hitmap.png')

G_plot3=sns.pairplot(ac_anal_norm2,vars=['무단횡단 사고','인구밀도','통근,통학'],kind='reg',size=3)
G_plot3.savefig('C:\Multicampus_kssj\Anal_image\Gwanak3_corr_pairplot.png')

# 3.종로구
plt.figure(figsize = (15, 15))
J_plot1=sns.heatmap(data = ac_anal_norm5, annot = True, fmt = '.2f', cmap = 'Blues')
fig1=J_plot1.get_figure()
fig1.savefig('C:\Multicampus_kssj\Anal_image\Jongro1_hitmap.png')

plt.figure(figsize = (10, 10))
J_plot2=sns.heatmap(data = ac_anal_norm5.corr(), annot = True, fmt = '.2f', cmap = 'Blues')
fig2=J_plot2.get_figure()
fig2.savefig('C:\Multicampus_kssj\Anal_image\Jongro2_corr_hitmap.png')

J_plot3=sns.pairplot(ac_anal_norm3,x_vars=['광로(40m이상)','대로(25~40)','중로(12~25)','소로(12m미만)'],y_vars=['무단횡단 사고'],kind='reg',size=5)
J_plot3.savefig('C:\Multicampus_kssj\Anal_image\Jongro3_corr_pairplot.png')


from collections import Counter
import sys

def read_dictionary():
    #ソートしてある辞書を読み込む
    f = open('score_sort_dictionary.txt', 'r')
    data = f.read()
    f.close()

    list = data.split() #\nを除いて配列にする

    new = []

    for i in range(len(list)):#文字の出現回数と元の言葉をペアにする
        count_array = []
        l = list[i].split(',')
        for j in range(26):#文字の出現回数を数値の配列にする
            count_array.append(int(l[j]))
        new.append((count_array, l[26]))#l[26]は元の言葉
    return new

def read_textfile(fileName):
    #アナグラムを探すテキストファイル読み込み
    f = open(fileName, 'r')
    data = f.read()
    f.close()

    list = data.split() #\nを除いて配列にする

    return list

def count_word(word):
    #出てきた文字の回数を数値の配列にする
    #catなら、'abcdefghijklmnopqrstuvwsyz'->[1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]

    #単語に出てくるアルファベットの数を調べる
    count_num = sorted(list(Counter(word).items()))

    alphabet = 'abcdefghijklmnopqrstuvwxyz'#26個
    count_array = [0]*26
    for i in range(len(count_num)):
        index = alphabet.find(count_num[i][0])
        count_array[index] += count_num[i][1]
    return count_array

def linear_search(dictionary, count_array, word):
    #上から辞書を見ていって、アナグラムを見つけたら返す
    for i in range(len(dictionary)):
        flag = 1
        for j in range(len(count_array)):
            if dictionary[i][0][j]>count_array[j]:
                flag = 0
                break
        if flag:
            if(dictionary[i][1]!=word):
                return dictionary[i][1]
    return ""

if __name__=='__main__':
    dictionary = read_dictionary()
    text = read_textfile(sys.argv[1])

    ans_arr = []

    for i in range(len(text)):
        print(i)
        counting = count_word(text[i])
        ans = linear_search(dictionary, counting, text[i])
        print(ans)
        print()

        ans_arr.append(ans)

    #ファイル書き込み
    f = open(sys.argv[2], 'w')
    f.write('\n'.join(ans_arr))
    f.close()


import os
from flask import Flask
from api.config.database import db
from api.routes.user import user as user_blueprint

def create_app():
    app = Flask(__name__)

    app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', 'sqlite:///database.db')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db.init_app(app)

    app.register_blueprint(user_blueprint)

    with app.app_context():
        db.create_all()

    return app

if __name__ == "__main__":
    app = create_app()
    app.run(debug=True)


from repository.tariff_db_manager.tariff_db_manager import TariffDbManager
from models.tariff_model.tariff_model import TarifModelForView, InnerModelForTarif, PersonalTarifForCreating
from service.tariff_service_manager.tariff_service_interface import TarifServiceInterface

language_dict = {
            "ru": 0,
            "en": 1,
            "hy": 2
        }

class TariffServiceManager(TarifServiceInterface):

    @staticmethod
    async def get_tarifes_for_view(language)->list[TarifModelForView] | None:
        try:
            # _tariff = RedisClient.get_pydantic_redis(TarifModelForView)
            # print(_tariff)
            # if _tariff:
            #     return _tariff
            temp_ = await TariffDbManager.get_tarifes_for_view()
            lan_ = language_dict[language]
            if temp_ is not None:
                _info = [
                    TarifModelForView(
                        tarif_id=i['tarif_id'],
                        tarif_names=i['tarif_names'][lan_],
                        tarif_month_prices=i['tarif_month_prices'],
                        inner_content=InnerModelForTarif(
                            cassa_names=i['cassa_names'][lan_],
                            cassa_counts=i['cassa_counts'],
                            cassa_prices=i['c_per_price'],
                            cassa_inf_prices=i['c_inf_price'],
                            manager_names=i['manager_names'][lan_],
                            manager_counts=i['manager_counts'],
                            manager_prices=i['m_per_price'],
                            manager_inf_prices=i['m_inf_price'],
                            web_names=i['web_names'][lan_],
                            web_counts=i['web_counts'],
                            web_prices=i['w_m_per_price'],
                            web_inf_prices=i['w_m_inf_price'],
                            mobile_cassa_names=i['mobile_cassa_names'][lan_],
                            mobile_cassa_counts=i['mobile_cassa_counts'],
                            mobile_prices=i['m_c_per_price'],
                            mobile_inf_prices=i['m_c_inf_price'],
                            tarifes_others=i['tarifes_others'], )
                    )
                    for i in temp_
                ]
                return _info
            else:
                return None
        except Exception as e:
            print(e)
            return

    @staticmethod
    async def get_tariff_details(tariff_id):
        try:
            _tariff_details = await TariffDbManager.get_tariff_details(tariff_id)
            if not _tariff_details:
                return None
            return _tariff_details
        except Exception as e:
            print(e)
            return

    @staticmethod
    async def check_summ_and_return(item):
        try:
            summ_ = item.mobile_cass_price * item.mobile_cass_count + \
                    item.cass_stantion_count * item.cass_stantion_price + \
                    item.mobile_cass_count * item.mobile_cass_price + \
                    item.web_manager_price * item.web_manager_count
            return summ_
        except Exception as e:
            print(e)
            return


import csv

def esc(code):
    return f'\u001b[{code}m'

def array_init(array_in, st):
    for i in range(10):
        for j in range(10):
            if j == 0:
                array_in[i][j] = st * (8 - i) + st
            if i == 9:
                array_in[i][j] = j
    return array_in

def array_fill(array_fi, res, st):
    for i in range(9):
        for j in range(10):
            if abs(array_fi[i][0] - res[9 - j]) < st:
                for k in range(9):
                    if 8 - k == j:
                        array_fi[i][k + 1] = 1
    return array_fi

def draw_plot(array_pl):
    for i in range(9):
        line = ''
        for j in range(10):
            if j == 0:
                line += WHITE + '\t' + str(int(array_pl[i][j])) + '\t'
            if array_pl[i][j] == 0:
                line += '  '
            if array_pl[i][j] == 1:
                line += RED + '  ' + WHITE
        line += END
        print(line)
    print(WHITE + '\t0\t1 2 3 4 5 6 7 8 9 ' + END)

RED = esc(41)
BLUE = esc(44)
WHITE = esc(47)
BLACK = esc(40)
END = esc(0)

array_plot = [[0 for x in range(10)] for y in range(10)]
result = [0 for i in range(10)]

for i in range(10):
    result[i] = i ** 2
step = round(abs(result[0] - result[9]) / 9, 1)
print("Шаг: " + str(step) + "; Функция: y = x^2")

array_init(array_plot, step)
array_fill(array_plot, result, step)

draw_plot(array_plot)

def flag_fr():
    for i in range(6):
        print(f'{BLUE}{"  " * 4}{WHITE}{"  " * 4}{RED}{"  " * 4}{END}')

def design(kol=1):
    for i in range(3):
        line = ''
        for ii in range(kol):
            if i % 2 == 0:
                if ii % 2 == 0:
                    line += f'{BLACK}{"  "}{WHITE}{"  "}{BLACK}{"  "}{END}'
                else:
                    line += f'{WHITE}{"  "}{BLACK}{"  "}{WHITE}{"  "}{END}'
            else:
                if ii % 2 == 0:
                    line += f'{WHITE}{"  "}{BLACK}{"  "}{WHITE}{"  "}{END}'
                else:
                    line += f'{BLACK}{"  "}{WHITE}{"  "}{BLACK}{"  "}{END}'
        print(line)

def design2(kol=1):
    for i in range(3):
        line = ''
        for ii in range(kol):
            if i % 2 == 0:
                line += f'{BLACK}{"  "}{WHITE}{"  "}{BLACK}{"  "}{END}'
            else:
                line += f'{WHITE}{"  "}{BLACK}{"  "}{WHITE}{"  "}{END}'
        print(line)

def get_books_info():
    with open('books.csv', 'r') as csvfile:
        table = csv.reader(csvfile, delimiter=';')
        next(table)
        before = 0
        after = 0

        for row in table:
            if int((row[6].split(' ')[0]).split("-")[0]) <= 2014:
                before += 1
            else:
                after += 1
        before_percent = before / (after+before)
        before_str = str(before_percent * 100).split(".")[0] + "%) "
        after_str = str(100 - int(str(before_percent * 100).split(".")[0])) + "%) "

    total_symbols = 50
    before_symbols = round(total_symbols * before_percent)
    after_symbols = total_symbols - before_symbols

    chart = f'{RED}{" " * before_symbols}{BLUE}{" " * after_symbols}{END}'

    print("Процентное соотношение книг до 2014 года и после: \n")
    print(chart)
    print(" ")
    print(f'{RED}{" "}{END}{" - Книги до 2014 года (включительно) (" + str(before_str)}{BLUE}{" "}{END}'
          f'{" - Книги после 2014 года (" + after_str}{END}')

    with open('books-en.csv', 'r') as csvfile:
        table = csv.reader(csvfile, delimiter=';')
        next(table)
        before = 0
        after = 0

        for row in table:
            if int(row[3]) <= 1980:
                before += 1
            else:
                after += 1
        before_percent = before / (after+before)
        before_str = str(before_percent * 100).split(".")[0] + "%) "
        after_str = str(100 - int(str(before_percent * 100).split(".")[0])) + "%) "

    total_symbols = 50
    before_symbols = round(total_symbols * before_percent)
    after_symbols = total_symbols - before_symbols

    chart = f'{RED}{" " * before_symbols}{BLUE}{" " * after_symbols}{END}'
    print(" ")
    print("Процентное соотношение книг до 1980 года и после: \n")
    print(chart)
    print(" ")
    print(f'{RED}{" "}{END}{" - Книги до 1980 года (включительно) (" + str(before_str)}{BLUE}{" "}{END}'
          f'{" - Книги после 1980 года (" + after_str}{END}')

print(" ")
print("Флаг Франции: ")
flag_fr()
print(" ")
print("Узор вариант 1: ")
design(1)
print(" ")
print("Узор вариант 2: ")
design2(1)
print(" ")
get_books_info()


import numpy as np
from numpy.core.fromnumeric import mean
from scipy.spatial import cKDTree
import sys
from collections import defaultdict
from os import listdir, mkdir, path
from os.path import join
from bearing import calculate_bearing, next_point, haversine, angledist, printProgressBar
import numpy as np
from queue import PriorityQueue
from time import time

def process_input(input_folder):
    files = list(listdir(input_folder))

    trajs = defaultdict(list)  # {trip_name: [trip_info]}
    data = []  # [trip_info,...]

    for fi in files:
        with open(join(input_folder, fi)) as f:
            for i, line in enumerate(f):
                # format: id, lat, lng, timestamp
                id_, lat, lng, ts = line.strip().split(',')
                lat = lat[:7]
                lng = lng[:7]
                lat, lng, ts = float(lat), float(lng), int(float(ts))
                if i:
                    # compute angle
                    a = calculate_bearing((trajs[fi][-1][1],
                                           trajs[fi][-1][0]), (lat, lng))
                    trajs[fi].append((lng, lat, ts, a))
                    data.append((lng, lat, ts, a))
                else:
                    trajs[fi].append((lng, lat, ts, 0))
                    data.append((lng, lat, ts, 0))
            if len(trajs[fi]) > 1:
                trajs[fi][0] = (trajs[fi][0][0], trajs[fi][0][1], trajs[fi][0][2],
                                trajs[fi][1][3])

    return trajs, data

def impute_trajectories(trajs):
    visited = set([])
    totalTrajs = len(list(trajs.values()))
    currentTraj = 0
    for k, traj in list(trajs.items()):
        # consider angle of first point is same as second one.
        # For each consecutive pair of points in the trajectory:
        trimpute_traj = []
        printProgressBar(currentTraj, totalTrajs, 'Progress', 'Completed')
        if len(traj) and path.getsize(input_folder + '/' + k) > 0:
            inside_traj = False
            start_time = time()
            for i, (a, b) in enumerate(zip(traj, traj[1:])):
                inside_traj = True

                s = (a[0], a[1], a[2], a[3])
                d = (b[0], b[1], b[2], b[3])

                seg_dist = haversine(s[0], s[1], d[0], d[1])
                cid = centroids.index((s[0], s[1]))
                nns = c_nns[cid]
                angles = [data[_][3] for _ in nns]

                hist, bins = np.histogram(angles, bins=[_*ANGLE_BIN for _ in
                                                        range(int(360/ANGLE_BIN)+1)], density=True)

                relevant_directions = []
                FOUND = False
                dense_segment = []
                for bearing, pr in zip(bins[:-1], hist):
                    if pr*ANGLE_BIN > CROWD_THRESHOLD\
                            and angledist(bearing, a[3]) < ANGLE_THRESHOLD:
                        # filter bins and find the average angle inside each bin

                        bin_angles = list(
                            filter(lambda ang: bearing <= ang < bearing + ANGLE_BIN, angles))
                        bin_average = sum(bin_angles)/len(bin_angles)
                        relevant_directions.append((bin_average, pr*ANGLE_BIN))

                paths = PriorityQueue()
                visited.add(s)
                for rd in relevant_directions:
                    new_pt = next_point(s[1], s[0], DISTANCE_THRESHOLD, rd[0])
                    new_pt = (round(new_pt[0], 4), round(
                        new_pt[1], 4))  # epsilon = 10m
                    new_pt_angle = calculate_bearing((s[1], s[0]),
                                                     (new_pt[1], new_pt[0]))

                    new_pt = (new_pt[0], new_pt[1], a[2], new_pt_angle)
                    remaining_dist = haversine(
                        new_pt[0], new_pt[1], d[0], d[1])

                    if remaining_dist > RADIUS_METER\
                            and new_pt not in visited:
                        paths.put((haversine(s[0], s[1], new_pt[0], new_pt[1]) +
                                   remaining_dist, (DISTANCE_THRESHOLD, [s, new_pt])))
                        visited.add(new_pt)

                    elif new_pt not in visited:
                        FOUND = True
                        dense_segment = [s, new_pt]
                        break

                while not paths.empty() and not FOUND:
                    path_weight, (leng, curr_path) = paths.get()

                    if leng >= LENGTH_FACTOR * seg_dist:
                        continue

                    curr_pt = curr_path[-1]
                    curr_angle = calculate_bearing((curr_path[-2][1], curr_path[-2][0]),
                                                   (curr_pt[1], curr_pt[0]))
                    nns = idx.query_ball_point(
                        x=(curr_pt[0], curr_pt[1]), r=RADIUS_DEGREE, p=2)

                    # Discard points that have no neighbors
                    if len(nns) < MIN_NNS:
                        continue

                    angles = [data[_][3] for _ in nns]
                    hist, bins = np.histogram(angles, bins=[_*ANGLE_BIN for _ in
                                                            range(int(360/ANGLE_BIN)+1)], density=True)
                    relevant_directions = []
                    # Angle condition:
                    for bearing, pr in zip(bins[:-1], hist):
                        if pr*ANGLE_BIN > CROWD_THRESHOLD\
                                and angledist(bearing, curr_angle) < ANGLE_THRESHOLD:
                            # filter bins and find the average angle inside each bin

                            bin_angles = list(
                                filter(lambda ang: bearing <= ang < bearing + ANGLE_BIN, angles))
                            bin_average = sum(bin_angles)/len(bin_angles)
                            relevant_directions.append(
                                (bin_average, pr*ANGLE_BIN))

                    for rd in relevant_directions:
                        new_pt = next_point(
                            curr_pt[1], curr_pt[0], DISTANCE_THRESHOLD, rd[0])
                        new_pt = (round(new_pt[0], 4), round(new_pt[1], 4))
                        new_pt_angle = calculate_bearing((curr_pt[1], curr_pt[0]),
                                                         (new_pt[1], new_pt[0]))

                        new_pt = (new_pt[0], new_pt[1],
                                  curr_pt[2], new_pt_angle)
                        dist = haversine(new_pt[0], new_pt[1], d[0], d[1])

                        # Candidate point, consider rest of the path
                        if dist > RADIUS_METER and new_pt not in visited:
                            paths.put((leng+DISTANCE_THRESHOLD + dist, (leng + haversine(curr_pt[0], curr_pt[1],
                                                                                new_pt[0], new_pt[1]), curr_path + [new_pt])))
                            visited.add(new_pt)

                        # We found the last point of the imputation
                        elif new_pt not in visited:
                            FOUND = True
                            dense_segment = curr_path + [new_pt]
                            break
                # No imputation
                if len(dense_segment) == 0:
                    dense_segment.append(a)
                    trimpute_traj += dense_segment
                if FOUND:
                    # append dense segment points to the densified trajectory
                    time_diff = d[2] - s[2]
                    delta_time = int(
                        time_diff/max(1, (len(dense_segment) - 1)))
                    ts = s[2]
                    dense_seg_temporal = [dense_segment[0]]
                    for j, _ in enumerate(dense_segment[1:]):
                        dense_seg_temporal.append((_[0], _[1], ts + (j+1) *
                                                   delta_time, _[3]))
                    trimpute_traj += dense_seg_temporal

            # Write the densified trimpute_traj to the output file
            with open(output_folder+'/%s' % k, 'w') as g:
                for pt in trimpute_traj:
                    g.write('%s,%s,%s,%s\n' % pt)
                # Add the last point in the sparse trajectory
                if inside_traj:
                    g.write('%s,%s,%s,%s\n' % (d[0], d[1], d[2], d[3]))
            timeTaken = time() - start_time
            with open(output_folder+'/results.csv', 'a') as h:
                h.write("%s,%s,%s,%s\n" % (k, len(traj), len(trimpute_traj), timeTaken))
            currentTraj += 1

if __name__ == '__main__':

    try:
        input_folder = "./datasets/input/%s" % (sys.argv[1])
        output_folder = "./datasets/output/%s" % (sys.argv[2])
    except Exception as e:
        print("Not enough arguments!")
        exit()

    try:
        mkdir(output_folder)
    except Exception as e:
        print(e)
        exit()

    start_time = time()
    print('started')

    # Main parameters
    CANDIDATE_POINTS = 6  # N
    CROWD_THRESHOLD = 0.005  # alpha
    ANGLE_THRESHOLD = 120  # delta
    DISTANCE_THRESHOLD = 50  # d

    # Global values
    RADIUS_METER = DISTANCE_THRESHOLD
    ANGLE_BIN = 360/CANDIDATE_POINTS
    RADIUS_DEGREE = RADIUS_METER * 10e-6
    LENGTH_FACTOR = 3  # path should not exceed 3 times the birdfly distance.
    MIN_NNS = 1  # at least one neighbor

    trajs, data = process_input(input_folder)

    print('Indexing points')

    points = [(_[0], _[1]) for _ in data]
    idx = cKDTree(list(points))
    centroids = list(set(points))

    # store the neighbors within RADIUS meters for every centorid
    c_nns = idx.query_ball_point(x=list(centroids), r=RADIUS_DEGREE, p=2)

    print('Imputation started')

    impute_trajectories(trajs)

    print("--- %s seconds ---" % (time() - start_time))


"""
If we write out the digits of "60" as English words we get "sixzero"; the number
of letters in "sixzero" is seven. The number of letters in "seven" is five. The
number of letters in "five" is four. The number of letters in "four" is four:
we have reached a stable equilibrium.

Note: for integers larger than 9, write out the names of each digit in a single
word (instead of the proper name of the number in English). For example, write
12 as "onetwo" (instead of twelve), and 999 as "nineninenine" (instead of nine
hundred and ninety-nine).

For any integer between 0 and 999, return an array showing the path from that
integer to a stable equilibrium:

Examples
numbersOfLetters(60) --> ["sixzero", "seven", "five", "four"]
numbersOfLetters(1) --> ["one", "three", "five", "four"]

"""

# my solution

def numbers_of_letters(n):
    # arr for number string values
    num_words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
                 'eight', 'nine']
    # split original number into arr of numbers
    num_arr = [int(x) for x in str(n)]
    # create word array to store words for each loop
    word_arr = []
    # establish string value of first number
    word = ''.join([num_words[num] for num in num_arr])

    # while the word != 'four', continue to create new string value based on word
    # length
    while word != 'four':
        word_arr.append(word)
        word_len = len(word)
        num_arr = [int(x) for x in str(word_len)]
        word = ''.join([num_words[num] for num in num_arr])
    # add 'four' to the list and return
    word_arr.append('four')

    return word_arr

# other solutions

NUM = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
       "nine"]

def numbers_of_letters(n):
    s = ''.join(NUM[i] for i in map(int, str(n)))
    return [s] + (numbers_of_letters(len(s)) if len(s) != n else [])

collection = {
    0 : 'zero',
    1 : 'one',
    2 : 'two',
    3 : 'three',
    4 : 'four',
    5 : 'five',
    6 : 'six',
    7 : 'seven',
    8 : 'eight',
    9 : 'nine',
}

def numbers_of_letters(n):
    res = []
    while 'four' not in res:
        ns = ''.join( [ collection[int(i)] for i in str(n if len(res) < 1 else
        len(ns)) ] )
        res.append(ns)
    return res


#!/usr/bin/env python
# -*- coding: utf-8 -*-

# lda.pyで求めた文書トピック分布を用いてsvm-multi classiferを実装，およびmatplotlibでの図示

from sklearn.datasets import load_digits
from sklearn.cross_validation import train_test_split
from sklearn.svm import LinearSVC
from sklearn.metrics import accuracy_score

# データとラベルを受け取ってsvmを実行
def svm(data, label, train_size):
	# トレーニングデータとテストデータに分割
	data_train, data_test, label_train, label_test = train_test_split(data, label, train_size=train_size)
	# 分類器にパラメータを与える
	estimator = LinearSVC(C=1.0)
	# トレーニングデータで学習する
	estimator.fit(data_train, label_train)
	# テストデータの予測をする
	label_predict = estimator.predict(data_test)

	return label_predict, label_test

# 図示用
def plot_graph(all_error, rates):
	import matplotlib.pylot as plt

	# 各aによってerror rateが変わるかを図示
	plt.plot(rates, all_error[0],'ro',label = "alpha=0.1")
	plt.plot(rates, all_error[1],'b',label = "alpha=1.0")
	plt.plot(rates, all_error[2],label = "alpha=3.0")
	plt.plot(rates, all_error[3],label = "alpha=10.0")

	plt.legend() # 凡例を表示
	plt.xticks(rates,("","0.02","0.05","0.1","0.2"))
	# plt.title("Graph Title")
	plt.xlabel("Training Size")
	plt.ylabel("Error Rate")
	plt.show()
	# トピック次元によって

def main():
	rates = [0.01, 0.02, 0.05, 0.1, 0.2]
	files = ["1",
	"2",
	"3"]
	all_error = []
	# 各データについてsvmを実施する
	for f in files:
		# shelveでオープン
		dic = shelve.open(f)
		data = dic['thetas']
		label = dic['categories']
		error_rates = []
		for r in rates:
			# svmを実行
			label_predict, label_test = svm(data, label, r)
			# Error Rateを求める
			error_rates.append(1.0 - accuracy_score(label_predict, label_test))
		all_error.append(error_rates)
		dic.close()

	# 図示
	result = shelve.open('result')
	result['all_error'] = all_error
	result.close()
	plot_graph(all_error, rates)

def make_graph():
	# 不安だったらここで確認
	result = shelve.open('result')
	all_error = result['all_error']
	result.close()

if __name__ == "__main__":
    # test()
    main()
    make_graph()


from gfl.core.manager.node import GflNode
from gfl.core.lfs.lfs import save_topology_manager
from gfl.core import TopologyConfig
from gfl.core import JobManager, DatasetManager
from gfl.gfl.generator import DatasetGenerator, JobGenerator

import tests.gfl_test.model as fl_model
from tests import gfl_test as fl_dataset
from gfl.topology import CentralizedTopologyManager

def generate_dataset():
    generator = DatasetGenerator(fl_dataset)
    generator.metadata.content = "mnist dataset"
    generator.dataset_config.with_dataset(fl_dataset.mnist_dataset)
    generator.dataset_config.with_val_rate(0.2)
    dataset = generator.generate()
    DatasetManager.submit_dataset(dataset)
    print(dataset.dataset_id)
    return dataset

def generate_job():
    generator = JobGenerator(fl_model)
    generator.metadata.content = "mnist CNN"
    generator.job_config.with_trainer(TrainerStrategy.SUPERVISED)
    # generator.job_config.with_trainer("SupervisedTrainer")
    generator.job_config.with_aggregator(AggregatorStrategy.FED_AVG)
    # generator.job_config.with_aggregator("FedAvgAggregator")
    generator.train_config.with_model(fl_model.model)
    generator.train_config.with_optimizer(fl_model.MnistOptimizer, lr=0.2)
    generator.train_config.with_loss(fl_model.CrossEntropyLoss)
    generator.train_config.with_epoch(1)
    generator.aggregate_config.with_round(2)
    generator.aggregate_config.with_loss(fl_model.CrossEntropyLoss)
    job = generator.generate()
    JobManager.init_job_sqlite(job.job_id)
    JobManager.submit_job(job)
    print(job.job_id)
    return job

def generate_topology(job_id):
    # 生成3个node。1个是聚合方，2个是训练方
    node1 = GflNode.standalone_nodes[0]
    node2 = GflNode.standalone_nodes[1]
    node3 = GflNode.standalone_nodes[2]
    # 拓扑结构
    topology_config = TopologyConfig()
    topology_config.with_train_node_num(2)
    topology_config.with_server_nodes([node1.address])
    topology_config.with_client_nodes([node2.address, node3.address])
    topology_config.with_index2node([node1.address, node2.address, node3.address])
    tpmgr = CentralizedTopologyManager(topology_config)
    # tpmgr.add_server(server_node=node1, add_into_topology=True)
    # 加到拓扑结构当中
    # tpmgr.add_node_into_topology(node2)
    # tpmgr.add_node_into_topology(node3)
    # 生成中心化的拓扑结构
    tpmgr.generate_topology()
    save_topology_manager(job_id=job_id, topology_manager=tpmgr)
    return tpmgr

def generate_nodes():
    GflNode.init_node()
    GflNode.add_standalone_node()
    GflNode.add_standalone_node()
    GflNode.add_standalone_node()

if __name__ == "__main__":
    # generate_dataset()
    generate_nodes()
    job = generate_job()
    generate_topology(job.job_id)


import os
import sys
from glob import glob
from jupyter_packaging import get_data_files
from setuptools import setup, find_packages

long_desc = "{{description}}"

here = os.path.abspath(os.path.dirname(__file__))

setup_args = dict(
    name="{{package-name}}",
    version="{{version}}",
    url="https://github.com/elyra-ai/elyra",
    description="Elyra provides AI Centric extensions to JupyterLab",
    long_description=long_desc,
    author="Elyra Maintainers",
    license="Apache License Version 2.0",
    data_files=get_data_files([{{data - files}}]),
    packages=find_packages(),
    install_requires=[{{install - requires}}],
    include_package_data=True,
    classifiers=(
        "License :: OSI Approved :: Apache Software License",
        "Operating System :: OS Independent",
        "Topic :: Scientific/Engineering",
        "Topic :: Scientific/Engineering :: Artificial Intelligence",
        "Topic :: Software Development",
        "Topic :: Software Development :: Libraries",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
    ),
    entry_points={},
)

if __name__ == "__main__":
    setup(**setup_args)


import subprocess
from multiprocessing import Process
from threading import Thread

import paho.mqtt.client as mqtt
import random as rand
import time
import sys

from datetime import datetime

class ChiengDeGarde(Process):
    def __init__(self, ip='127.0.0.255', port=1883):
        super().__init__()
        self.client = mqtt.Client(client_id="ChiengDeGarde")
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.connect(ip, port=port)

        self.port = port
        self.ip = ip

        self.lastPings = [datetime.now(), datetime.now(), datetime.now()]

        self.isAlive = False

    def start(self):
        self.client.connect(self.ip, port=self.port)
        self.client.subscribe("/cdg/kill")
        self.client.subscribe("/server0/state")
        self.client.subscribe("/server1/state")
        self.client.subscribe("/server2/state")
        self.client.loop_start()

        self.isAlive = True

    # Action lorsque le capteur c'est bien connecté au réseau MQTT
    def on_connect(self, client, userdata, flag, rc):
        print("C'est mon chien connecte !")

    def on_message(self, client, userdata, msg):
        if msg.topic == "/cdg/kill":
            self.isAlive = False
            return

        elif msg.topic == "/server0/state":
            self.lastPings[0] = datetime.now()
        elif msg.topic == "/server1/state":
            self.lastPings[1] = datetime.now()
        elif msg.topic == "/server2/state":
            self.lastPings[2] = datetime.now()

        return

    def run(self):
        # Envoie d'un nombre aléatoire chaque seconde
        while self.isAlive:
            self.stalker()
            time.sleep(1)

    def stalker(self):
        t = datetime.now()
        d = [t - self.lastPings[0],
             t - self.lastPings[1],
             t - self.lastPings[2]]

        for i in range(len(d)):
            if d[i].total_seconds() >= 3:
                print(f"Wouf, le server {i} est dead")

                thread = Thread(target=lambda: subprocess.run(f"python server.py {i} restart"), daemon=True)
                thread.start()

        pass

if __name__ == "__main__":
    cdg = ChiengDeGarde()
    cdg.start()
    cdg.run()

    sys.exit()


import requests
import json
import jsonpath

def test_st_add_new():
    global id
    ADD_url = 'http://thetestingworldapi.com/api/studentsDetails'
    f = open("C:\\python-t\\API-testing\\utilities\\studendata.json", 'r')

    request_json = json.loads(f.read())
    reponse = requests.post(ADD_url, request_json)

    id = jsonpath.jsonpath(reponse.json(), 'id')
    print(id[0])

def test_st_info():
    final_details = 'http://thetestingworldapi.com/api/studentsDetails/' + str(id[0])
    response = requests.get(final_details)
    print(response.text)
    assert response.status_code == 450


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

conditions_numb_list = []    # empty list for numbers that match the conditions

# selection of numbers by conditions in the range [2476, 7857]:
# 1) number multiple of 2, but not multiple of 8
# 2) the second digit from the end of the number doesn't exceed 7
for iter in range(2476, 7858):    # go through the range by iter
    if ((iter % 2 == 0) and (iter % 8 != 0)) and (int(iter % 100 / 10) <= 7):    # check conditions
        conditions_numb_list.append(iter)    # add element for list

# print length of list
print('Number of elements that match the conditions: {};'.format(len(conditions_numb_list)))
# print arithmetic mean of max and min elements (only the whole part)
print('Arithmetic mean of max and min elements: {}'.format(int((max(conditions_numb_list) + min(conditions_numb_list)) / 2)))


#!/usr/bin/python3

""" Function to find perimiter of an island """

def island_perimeter(grid):
    """
    Input: List of Lists
    Returns: Perimeter of the island
    """
    count = 0
    row = len(grid)
    col = len(grid[0]) if row else 0

    for i in range(len(grid)):
        for j in range(len(grid[i])):

            neighbors = [(i - 1, j), (i, j - 1), (i, j + 1), (i + 1, j)]
            is_valid_neighbor = [1 if k[0] in range(row) and k[1] in range(col) else 0
                               for k in neighbors]

            if grid[i][j]:
                count += sum([1 if not is_neighbor or not grid[k[0]][k[1]] else 0
                              for is_neighbor, k in zip(is_valid_neighbor, neighbors)])

    return count


#User function Template for python3
class Solution:
    def leastPrimeFactor (self, n):
        ans=[i for i in range(n+1)]
        for i in range(3,n+1):
            if(i%2==0):ans[i]=2
            elif(ans[i]==i):
                for j in range(i,n+1,i):
                    if(ans[j]==j):ans[j]=i
        return ans

#{
 # Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
	T=int(input())
	for i in range(T):
		n = int(input())
		ob = Solution();
		ans = ob.leastPrimeFactor(n)
		for i in range(1, n+1):
			print(ans[i], end = " ")
		print()

# } Driver Code Ends

Least Prime Factor - GFG/least-prime-factor.py


from argparse import RawDescriptionHelpFormatter
import argparse
import filecmp
import json
import os
import subprocess

# Start of our unit test
# -- main() -------------------------------------------------------------------
#
# The entry point to this script.
#
# Note: It is called at the end of this script so that the other functions
#       and classes have been defined and the syntax validated
def main():
  # -- Configure the argument parser
  parser = argparse.ArgumentParser(formatter_class=RawDescriptionHelpFormatter, description='description:\n  Unit test wrapper for the SmartNic section')
  parser.add_argument('--resource-dir', nargs='?', default=".", help='directory containing data to be used by this unit test')
  args = parser.parse_args()

  # Validate that the resource directory is valid
  if not os.path.exists(args.resource_dir):
      raise Exception("Error: The resource-dir '" + args.resource_dir +"' does not exist")

  if not os.path.isdir(args.resource_dir):
      raise Exception("Error: The resource-dir '" + args.resource_dir +"' is not a directory")

  # Prepare for testing
  xclbinutil = "xclbinutil"

  # Start the tests
  print ("Starting test")

  # ---------------------------------------------------------------------------
  step = "1) Read in a validate JSON file and validate it against the schema"

  inputJSON = os.path.join(args.resource_dir, "smartnic_full_validate_syntax.json")

  cmd = [xclbinutil, "--add-section", "SMARTNIC:JSON:" + inputJSON]
  execCmd(step, cmd)

  # ---------------------------------------------------------------------------
  step = "2) Read in a byte file and validate it was transformed correctly"

  inputJSON = os.path.join(args.resource_dir, "simple_bytefiles.json")
  outputJSON = "simple_bytefiles_output.json"
  expectedJSON = os.path.join(args.resource_dir,"simple_bytefiles_expected.json")

  cmd = [xclbinutil, "--add-section", "SMARTNIC:JSON:" + inputJSON, "--dump-section", "SMARTNIC:JSON:" + outputJSON, "--force"]
  execCmd(step, cmd)

  # Validate that the output file matches expectation
  jsonFileCompare(expectedJSON, outputJSON)

  # ---------------------------------------------------------------------------
  step = "3a) Merging Validation : Adding v++ linker contents to the xclbin"

  vppLinkerJSON = os.path.join(args.resource_dir, "vpp_linker.json")
  vppLinkerXclbin = "vpp_linker.xclbin"

  cmd = [xclbinutil, "--add-merge-section", "SMARTNIC:JSON:" + vppLinkerJSON, "--output", vppLinkerXclbin, "--force"]
  execCmd(step, cmd)

  # ...........................................................................
  step = "3b) Merging Validation : Merging Extension Metadata"

  extensionJSON = os.path.join(args.resource_dir, "extension.json")
  vppPackerXclbin1 = "vpp_packager1.xclbin"

  cmd = [xclbinutil, "--input", vppLinkerXclbin, "--add-merge-section", "SMARTNIC:JSON:" + extensionJSON, "--output", vppPackerXclbin1, "--force"]
  execCmd(step, cmd)

  # ...........................................................................
  step = "3c) Merging Validation : Merging Softhub metadata"

  softhubJSON = os.path.join(args.resource_dir, "softhub.json")
  vppPackerXclbin2 = "vpp_packager2.xclbin"

  cmd = [xclbinutil, "--input", vppPackerXclbin1, "--add-merge-section", "SMARTNIC:JSON:" + softhubJSON, "--output", vppPackerXclbin2, "--force"]
  execCmd(step, cmd)

  # ...........................................................................
  step = "3d) Merging Validation : Merging eBPF"

  ebpfJSON = os.path.join(args.resource_dir, "eBPF.json")
  expectedJSON = os.path.join(args.resource_dir,"vitis_merged_expected.json")
  vppPackerXclbin3 = "vpp_packager3.xclbin"
  outputJSON = "vitis_merged_output.json"

  cmd = [xclbinutil, "--input", vppPackerXclbin2, "--add-merge-section", "SMARTNIC:JSON:" + ebpfJSON, "--dump-section", "SMARTNIC:JSON:" + outputJSON, "--output", vppPackerXclbin3, "--force"]
  execCmd(step, cmd)

  # Validate that the output file matches expectation
  jsonFileCompare(expectedJSON, outputJSON)

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

  # If the code gets this far, all is good.
  return False

def testDivider():
  print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

def jsonFileCompare(file1, file2):
  if not os.path.isfile(file1):
    raise Exception("Error: The following json file does not exist: '" + file1 +"'")

  with open(file1) as f:
    data1 = json.dumps(json.load(f), indent=2)

  if not os.path.isfile(file2):
    raise Exception("Error: The following json file does not exist: '" + file2 +"'")

  with open(file2) as f:
    data2 = json.dumps(json.load(f), indent=2)

  if data1 != data2:
      # Print out the contents of file 1
      print ("\nFile1 : "+ file1)
      print ("vvvvv")
      print (data1)
      print ("^^^^^")

      # Print out the contents of file 1
      print ("\nFile2 : "+ file2)
      print ("vvvvv")
      print (data2)
      print ("^^^^^")

      raise Exception("Error: The two files are not the same")

def execCmd(pretty_name, cmd):
  testDivider()
  print(pretty_name)
  testDivider()
  cmdLine = ' '.join(cmd)
  print(cmdLine)
  proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  o, e = proc.communicate()
  print(o.decode('ascii'))
  print(e.decode('ascii'))
  errorCode = proc.returncode

  if errorCode != 0:
    raise Exception("Operation failed with the return code: " + str(errorCode))

# -- Start executing the script functions
if __name__ == '__main__':
  try:
    if main() == True:
      print ("\nError(s) occurred.")
      print("Test Status: FAILED")
      exit(1)
  except Exception as error:
    print(repr(error))
    print("Test Status: FAILED")
    exit(1)

# If the code get this far then no errors occured
print("Test Status: PASSED")
exit(0)


#! /usr/bin/env python
# -*- coding: utf-8 -*-

a = 1

name = 'tom'

def func():
    a = 2
    global name
    name = 'jerry'
#    print(f"a = {a}")
    print(f"func {name}")
#print(a)

print(name)
func()
print('调用函数之后的name')
print(name)


from tkinter import Tk, messagebox, scrolledtext, Menu, Toplevel, Label, StringVar, NW, NE, CENTER, END, DISABLED
from tkinter.ttk import Entry, Button, Radiobutton
from os.path import abspath
from os import execl
from sys import executable, argv
from requests import get as rget
from requests import ConnectionError
from threading import Thread
from wiktionaryparser import WiktionaryParser
from localStoragePy import localStoragePy
import json

localStorage = localStoragePy("me.jkelol111.tkdictionary", "text")

def start_thread(function):
    t = Thread(target=function)
    t.start()

def print_to_textbox(message):
    dictionaryTextView.insert(END, message + "\n")
def clear_textbox():
    dictionaryTextView.delete('1.0', END)

def checkNetwork():
    turl='http://www.google.com/'
    tout=5
    try:
        testGoogle = rget(url=turl, timeout=tout)
        messagebox.showinfo("", "The network is available.\nTkDictionary should work.")
    except ConnectionError:
        messagebox.showerror("", "The network is unavailable.\nTkDictionary will not work.")

def about():
    aboutWindow = Toplevel()
    aboutWindow.wm_resizable(False, False)
    aboutWindow.focus_set()
    aboutWindow.grab_set()
    appName_label = Label(aboutWindow, text="TkDictionary v.0.8")
    appName_label.pack()
    aboutMessage = "A dictionary application written in Python that uses\nWiki or Urban Dictionary.\n\n(C) Nguyen Thanh Nam (jkelol111) 2018\nLicensed under the MIT license."
    aboutMessage_label = Label(aboutWindow, text=aboutMessage)
    aboutMessage_label.pack()
    ok_button = Button(aboutWindow, text="OK", command=lambda: aboutWindow.destroy())
    ok_button.pack()
    mainWindow.update_idletasks()
    aboutWindow.update_idletasks()
    w = aboutWindow.winfo_width()
    h = aboutWindow.winfo_height()
    x = mainWindow.winfo_width()/2 + mainWindow.winfo_x()-180
    y = mainWindow.winfo_height()/2 + mainWindow.winfo_y()-80
    aboutWindow.geometry("%dx%d+%d+%d" % (w, h, x, y))
    aboutWindow.mainloop()

def settings():
    dictChoice = StringVar()
    langChoice = StringVar()
    langChoice.set(lang)
    themeChoice = StringVar()
    def restartAppToApplyChanges():
        restart = messagebox.askyesno("", "The app will restart for the changes to take effect.\nDo you want to restart the app now?")
        if restart == True:
            execl(executable, abspath(__file__), *argv)
        elif restart == False:
            messagebox.showwarning("", "Please save your work and restart the app as soon as possible for changes to take effect.")
    def resetSettings():
        settingsWindow.grab_release()
        resetY = messagebox.askyesno("", "This will reset TkDictionary to defaults. Do you want to continue?")
        if resetY == True:
            settingsWindow.destroy()
            config_contents = dict(language='english', source='urbandictionary', theme="light")
            localStorage.setItem("config.json", json.dumps(config_contents))
            restartAppToApplyChanges()
        elif resetY == False:
            settingsWindow.focus_set()
            settingsWindow.grab_set()
    def saveSettings():
        settingsWindow.destroy()
        config_contents = dict(language=langChoice.get(), source=dictChoice.get(), theme=themeChoice.get())
        localStorage.setItem("config.json", json.dumps(config_contents))
        restartAppToApplyChanges()
    settingsWindow = Toplevel()
    settingsWindow.wm_resizable(False, False)
    settingsWindow.focus_set()
    settingsWindow.grab_set()
    sourceLabel = Label(settingsWindow, text="Dictionary source:")
    sourceLabel.pack(anchor=NW)
    wikiRadioButton = Radiobutton(settingsWindow, text="Wiktionary", variable=dictChoice, value="wiktionary")
    wikiRadioButton.pack(anchor=NW, padx=10)
    urbanRadioButton = Radiobutton(settingsWindow, text="Urban Dictionary", variable=dictChoice, value="urbandictionary")
    urbanRadioButton.pack(anchor=NW, padx=10)
    if src == "wiktionary":
        wikiRadioButton.invoke()
    elif src == "urbandictionary":
        urbanRadioButton.invoke()
    else:
        pass
    disclaimerLabel = Label(settingsWindow, text="All content belongs to their respective owners. Please agree to their respective terms and conditions before use.")
    disclaimerLabel.pack(anchor=NW)
    langLabel = Label(settingsWindow, text="Dictionary language:")
    langLabel.pack(anchor=NW)
    langInput = Entry(settingsWindow, textvariable=langChoice)
    langInput.pack(anchor=NW, padx=10)
    langInstructLabel1 = Label(settingsWindow, text="This option only works with Wiktionary. Not all languages available.")
    langInstructLabel1.pack(anchor=NW)
    langInstructLabel2 = Label(settingsWindow, text="Example: English = english, Italian = italian, French = french, etc.")
    langInstructLabel2.pack(anchor=NW)
    themeLabel = Label(settingsWindow, text="App theme (not working):")
    themeLabel.pack(anchor=NW)
    lightRadioButton = Radiobutton(settingsWindow, text="Light", variable=themeChoice, value="light")
    lightRadioButton.pack(anchor=NW, padx=10)
    darkRadioButton = Radiobutton(settingsWindow, text="Dark", variable=themeChoice, value="dark")
    darkRadioButton.pack(anchor=NW, padx=10)
    if theme == "light":
        lightRadioButton.invoke()
    elif theme == "dark":
        darkRadioButton.invoke()
    else:
        pass
    saveSettingsButton = Button(settingsWindow, text="Save settings", command=saveSettings)
    saveSettingsButton.pack()
    resetSettingsButton = Button(settingsWindow, text="Reset settings", command=resetSettings)
    resetSettingsButton.pack()
    mainWindow.update_idletasks()
    settingsWindow.update_idletasks()
    w = settingsWindow.winfo_width()
    h = settingsWindow.winfo_height()
    x = mainWindow.winfo_width()/2 + mainWindow.winfo_x()-218
    y = mainWindow.winfo_height()/2 + mainWindow.winfo_y()-130
    settingsWindow.geometry("%dx%d+%d+%d" % (w, h, x, y))
    settingsWindow.mainloop()

def searchWord():
    word = wordEntry.get()
    clear_textbox()
    print_to_textbox("Loading, please wait...")
    if src == "wiktionary":
        parser = WiktionaryParser()
        result = parser.fetch(word, language=lang)
        clear_textbox()
        from pprint import pprint
        pprint(result)
        print_to_textbox(word)
        print_to_textbox("\nMeanings:")
        for n in result[0]["definitions"]:
            print(len(n))
            for i in result[0]["definitions"][len(n)]["text"]:
                print_to_textbox(i)
    elif src == "urbandictionary":
        parameters2 = {"term": word}
        result2 = rget("http://api.urbandictionary.com/v0/define", params=parameters2).json()
        clear_textbox()
        print_to_textbox(result2["list"][0]["word"])
        print_to_textbox("\nMost-voted definition:\n"+result2["list"][0]["definition"])
        print_to_textbox("\nExamples:\n"+result2["list"][0]["example"])
        print_to_textbox("\nBy user: "+result2["list"][0]["author"]+"        "+"Votes: UP: "+str(result2["list"][0]["thumbs_up"])+" DOWN: "+str(result2["list"][0]["thumbs_down"]))
    else:
        clear_textbox()
        errmessage = "Dictionary with name null not found. Check your settings in 'Actions & others' above!"
        print_to_textbox(errmessage)
        messagebox.showerror("TkDictionary Error", errmessage)

if not localStorage.getItem("config.json"):
    createConfig = messagebox.askquestion("TkDictionary Error", "We couldn't find your configuration file. Do you want to create one?")
    if createConfig == "yes":
        try:
            localStorage.setItem("config.json", json.dumps(dict(language='en', source='urbandictionary', theme="light")))
        except:
            messagebox.showerror("TkDictionary error", "Could not make config file. The app will now quit.")
            exit()
        execl(executable, abspath(__file__), *argv)
    else:
        messagebox.showerror("TkDictionary error", "We couldn't find your configuration file. The app will now exit.")
        exit()
else:
    try:
        config_contents = json.loads(localStorage.getItem("config.json"))
        lang = config_contents["language"]
        src = config_contents["source"]
        theme = config_contents["theme"]
    except Exception as e:
        print(str(e))

mainWindow = Tk()
mainWindow.title("TkDictionary")
mainWindow.wm_resizable(False, False)
mainWindow.focus_get()

menubar = Menu(mainWindow)
actionMenu = Menu(menubar, tearoff=0)
actionMenu.add_command(label="Test network activity...", command=checkNetwork)
actionMenu.add_separator()
actionMenu.add_command(label="Settings...", command=settings)
menubar.add_cascade(label="Actions & others", menu=actionMenu)
aboutMenu = Menu(menubar, tearoff=0)
aboutMenu.add_command(label="About TkDictionary...", command=about)
menubar.add_cascade(label="About & help", menu=aboutMenu)

wordEntry = Entry(mainWindow, justify=CENTER, width=mainWindow.winfo_reqwidth()-160)
wordEntry.focus_set()
wordEntry.pack()

if src == "wiktionary":
    searchButton_text = "Search Wiktionary..."
elif src == "urbandictionary":
    searchButton_text = "Search Urban Dictionary..."
else:
    searchButton_text = "Config Error! Check settings!"
searchButton = Button(mainWindow, text=searchButton_text, command=lambda: start_thread(searchWord))
searchButton.pack()

dictionaryTextView = scrolledtext.ScrolledText(mainWindow)
dictionaryTextView.pack()

mainWindow.config(menu=menubar)

mainWindow.update_idletasks()
w = mainWindow.winfo_reqwidth()
h = mainWindow.winfo_reqheight()
x = (mainWindow.winfo_screenwidth() - w) / 2
y = (mainWindow.winfo_screenheight() - h) / 2
mainWindow.geometry("%dx%d+%d+%d" % (w, h, x, y))

mainWindow.mainloop()


"""This module contains the definition for a pylint HoudiniPackageRunner."""

# =============================================================================
# IMPORTS
# =============================================================================

# Future
from __future__ import annotations

# Standard Library
import pathlib
import sys
from io import StringIO
from typing import TYPE_CHECKING, List

# Third Party
from pylint import lint
from pylint.reporters.text import ColorizedTextReporter

# Houdini Package Runner
import houdini_package_runner.config
import houdini_package_runner.parser
import houdini_package_runner.runners.utils
import houdini_package_runner.utils
from houdini_package_runner.discoverers import package
from houdini_package_runner.runners.base import HoudiniPackageRunner

# Imports for type checking.
if TYPE_CHECKING:
    import argparse

    from houdini_package_runner.config import BaseRunnerConfig
    from houdini_package_runner.discoverers.base import BaseItemDiscoverer
    from houdini_package_runner.items.base import BaseItem

# =============================================================================
# CLASSES
# =============================================================================

class PyLintRunner(HoudiniPackageRunner):
    """Implementation for a pylint package runner.

    :param discoverer: The item discoverer used by the runner.
    :param runner_config: Optional BaseRunnerConfig object.

    """

    def __init__(
        self, discoverer: BaseItemDiscoverer, runner_config: BaseRunnerConfig = None
    ) -> None:
        super().__init__(discoverer, runner_config=runner_config)

        self._disabled: List[str] = []

    # -------------------------------------------------------------------------
    # PROPERTIES
    # -------------------------------------------------------------------------

    @property
    def name(self) -> str:
        """The runner name used for identification."""
        return "pylint"

    # -------------------------------------------------------------------------
    # METHODS
    # -------------------------------------------------------------------------

    @staticmethod
    def build_parser(parser: argparse.ArgumentParser = None) -> argparse.ArgumentParser:
        """Build a parser for the runner.

        :param parser: Optional parser to add arguments to, otherwise a new one will be created.
        :return: The common parser for the runner.

        """
        if parser is None:
            parser = houdini_package_runner.parser.build_common_parser(
                description="""Run pylint on Houdini package items.

Any unknown args will be passed along to the pylint command.
"""
            )

        parser.add_argument(
            "--rcfile",
            action="store",
            help="Specify a configuration file",
        )

        parser.add_argument("--disable", action="store", help="Tests to disable.")

        return parser

    def init_args_options(self, namespace: argparse.Namespace, extra_args: List[str]):
        """Initialize any extra options from parser data.

        :param namespace: Argument parser namespace.
        :param extra_args: Optional list of extra_args to pass to isort.

        """
        super().init_args_options(namespace, extra_args)

        if namespace.rcfile:
            extra_args.insert(0, f"--rcfile={namespace.rcfile}")

        if namespace.disable:
            self._disabled = namespace.disable.split(",")

        if extra_args:
            self._extra_args.extend(extra_args)

    def process_path(self, file_path: pathlib.Path, item: BaseItem) -> int:
        """Process a file path.

        :param file_path: The path to lint.
        :param item: The item to lint.
        :return: The process return code.

        """
        flags = []

        flags.extend(self.extra_args)

        to_disable = []

        if self._disabled:
            to_disable.extend(self._disabled)

        to_disable.extend(self.config.get_config_data("to_disable", item, file_path))

        flags.extend(self.config.get_config_data("command", item, file_path))

        known_builtins: List[str] = item.ignored_builtins

        known_builtins.extend(
            self.config.get_config_data("known_builtins", item, file_path)
        )

        if known_builtins:
            houdini_package_runner.utils.add_or_append_to_flags(
                flags, "--additional-builtins", known_builtins
            )

        if to_disable:
            flags.append(f"--disable={','.join(to_disable)}")

        command = flags + [str(file_path)]

        if self.verbose:
            houdini_package_runner.runners.utils.print_runner_command(
                item, command, extra="pylint --output-format=colorized "
            )

        buf = StringIO()

        result = lint.Run(command, reporter=ColorizedTextReporter(buf), exit=False)

        output = buf.getvalue()

        if output:
            sys.stdout.write(output)

        return result.linter.msg_status

# =============================================================================
# FUNCTIONS
# =============================================================================

def main() -> int:
    """Run 'pylint' on package files."""
    parser = PyLintRunner.build_parser()
    parsed_args, unknown = parser.parse_known_args()

    discoverer = package.init_standard_package_discoverer(parsed_args)

    run_tool = PyLintRunner(discoverer)
    run_tool.init_args_options(parsed_args, unknown)

    result = run_tool.run()
    return result


import numpy as np
from scipy.io import loadmat

def load_data(subject=1):
    filename = 'data/meg_data_%da.mat' % subject
    data = loadmat(filename)

    triggers = data['triggers']
    planardat = data['planardat']

    t1 = triggers['t1'][0, 0].squeeze()
    t2 = triggers['t2'][0, 0].squeeze()
    t3 = triggers['t3'][0, 0].squeeze()
    t4 = triggers['t4'][0, 0].squeeze()
    t5 = triggers['t5'][0, 0].squeeze()
    t6 = triggers['t6'][0, 0].squeeze()
    test = triggers['test'][0, 0].squeeze()
    behav = triggers['behav'][0, 0].squeeze()
    return t1, t2, t3, t4, t5, t6, test, behav, planardat

def create_train_test_sets(subject=1, window_size=125, t_offset=0,
                           normalize=True):
    t1, t2, t3, t4, t5, t6, test, behav, planardat = load_data(subject)
    t_all = np.concatenate([t1, t2, t3, t4, t5, t6])
    labels_all = np.concatenate([np.ones(t1.size), np.ones(t2.size) * 2,
                                 np.ones(t3.size) * 3, np.ones(t4.size) * 4,
                                 np.ones(t3.size) * 5, np.ones(t4.size) * 6])
    idx = np.argsort(t_all)
    if normalize:
        # This is a global normalization, not per-trial:
        planardat = np.nan_to_num((planardat.T - planardat.mean(1))
                                  / planardat.std(1)).T

    # Ntrials x Nchannels X Nsamples:
    X_train = np.array([planardat[:, t+t_offset: t+t_offset+window_size]
                        for t in t_all[idx]])
    y_train = labels_all[idx].astype(np.int)
    X_test = np.array([planardat[:, t+t_offset: t+t_offset+window_size]
                       for t in test])
    return X_train, y_train, X_test

if __name__ == '__main__':

    subject = 1
    t1, t2, t3, t4, t5, t6, test, behav, planardat = load_data(subject)

    import matplotlib.pyplot as plt
    plt.interactive(True)
    plt.figure()
    plt.plot(planardat[0, :], 'r-')
    plt.plot(t4, np.zeros(t4.size), 'b*')
    plt.plot(test, np.zeros(test.size), 'kx')
    plt.plot(behav, np.zeros(behav.size), 'go')

    X_train, y_train, X_test = create_train_test_sets(subject)

    plt.figure()
    plt.plot(X_train[0, 0, :], 'r-')


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

"""Ensembles of AdK transitions.

https://figshare.com/articles/Simulated_trajectory_ensembles_for_the_closed-to-open_transition_of_adenylate_kinase_from_DIMS_MD_and_FRODA/7165306
"""

from os.path import dirname, exists, join
from os import makedirs, remove
import tarfile
import glob

import logging

from .base import get_data_home
from .base import _fetch_remote, _read_description
from .base import RemoteFileMetadata
from .base import Bunch

METADATA = {
    'DIMS': {
        'NAME': "adk_transitions_DIMS",
        'DESCRIPTION': "adk_transitions_DIMS.rst",
        'ARCHIVE': {
            'tarfile': RemoteFileMetadata(
                filename='DIMS.tar.gz',
                url='https://ndownloader.figshare.com/files/13182490',
                checksum='81dfd247da7084bc7f47889c098069978b61f8f8b4f7706841266d284bfd3b55',
            ),
        },
        'CONTENTS': {
            'topology': "DIMS/topologies/adk4ake.psf",
            'trajectories': "DIMS/trajectories/dims*_fit-core.dcd",
            'N_trajectories': 200,
        },
    },
    'FRODA': {
        'NAME': "adk_transitions_FRODA",
        'DESCRIPTION': "adk_transitions_FRODA.rst",
        'ARCHIVE': {
            'tarfile': RemoteFileMetadata(
                filename='FRODA.tar.gz',
                url='https://ndownloader.figshare.com/files/13182493',
                checksum='fc2c90b9819fd07720e7effada033d4045663919ba7d2c8bd84f548dfbeee73c',
            ),
        },
        'CONTENTS': {
            'topology': "FRODA/topologies/1ake.pdb",
            'trajectories': "FRODA/trajectories/pathway*_fit-core.dcd",
            'N_trajectories': 200,
        },
    },
}

logger = logging.getLogger(__name__)

def fetch_adk_transitions_DIMS(data_home=None, download_if_missing=True):
    """Load the AdK DIMS transititions dataset

    Parameters
    ----------
    data_home : optional, default: None
        Specify another download and cache folder for the datasets. By default
        all MDAnalysisData data is stored in '~/MDAnalysis_data' subfolders.
        This dataset is stored in ``<data_home>/adk_transitions_DIMS``.
    download_if_missing : optional, default=True
        If ``False``, raise a :exc:`IOError` if the data is not locally available
        instead of trying to download the data from the source site.

    Returns
    -------
    dataset : dict-like object with the following attributes:
    dataset.topology : filename
        Filename of the topology file
    dataset.trajectories : list
        list with filenames of the trajectory ensemble
    dataset.N_trajectories : int
        number of trajectories in the ensemble
    dataset.DESCR : string
        Description of the ensemble

    See :ref:`adk-transitions-DIMS-dataset` for description.
    """
    return _fetch_adk_transitions(METADATA['DIMS'],
                                  data_home=data_home,
                                  download_if_missing=download_if_missing)

def fetch_adk_transitions_FRODA(data_home=None, download_if_missing=True):
    """Load the AdK FRODA transititions dataset

    Parameters
    ----------
    data_home : optional, default: None
        Specify another download and cache folder for the datasets. By default
        all MDAnalysisData data is stored in '~/MDAnalysis_data' subfolders.
        This dataset is stored in ``<data_home>/adk_transitions_FRODA``.
    download_if_missing : optional, default=True
        If ``False``, raise a :exc:`IOError` if the data is not locally available
        instead of trying to download the data from the source site.

    Returns
    -------
    dataset : dict-like object with the following attributes:
    dataset.topology : filename
        Filename of the topology file
    dataset.trajectories : list
        list with filenames of the trajectory ensemble
    dataset.N_trajectories : int
        number of trajectories in the ensemble
    dataset.DESCR : string
        Description of the ensemble

    See :ref:`adk-transitions-FRODA-dataset` for description.
    """
    return _fetch_adk_transitions(METADATA['FRODA'],
                                  data_home=data_home,
                                  download_if_missing=download_if_missing)

def _fetch_adk_transitions(metadata, data_home=None, download_if_missing=True):
    """Generic function to load the AdK transititions datasets

    Parameters
    ----------
    metdata : dict
        dictionary with `NAME`, `DESCRIPTION` and `ARCHIVE` that contains
        a tar.gz file with directories topologies and trajectories
    data_home : optional, default: None
        Specify another download and cache folder for the datasets. By default
        all MDAnalysisData data is stored in '~/MDAnalysis_data' subfolders.
    download_if_missing : optional, default=True
        If ``False``, raise a :exc:`IOError` if the data is not locally available
        instead of trying to download the data from the source site.

    Returns
    -------
    dataset : dict-like object with the following attributes:
    dataset.topology : filename
        Filename of the topology file
    dataset.trajectories : list
        list with filenames of the trajectory ensemble
    dataset.DESCR : string
        Description of the ensemble

    Note
    ----
    Assumptions that are built in:
    - download a single tar.gz file
    - trajectories are given with a glob pattern

    """
    name = metadata['NAME']
    data_location = join(get_data_home(data_home=data_home),
                         name)
    if not exists(data_location):
        makedirs(data_location)

    records = Bunch()

    meta = metadata['ARCHIVE']['tarfile']
    local_path = join(data_location, meta.filename)

    if not exists(local_path):
        if not download_if_missing:
            raise IOError("Data {0}={1} not found and `download_if_missing` is "
                          "False".format(file_type, local_path))
        logger.info("Downloading {0}: {1} -> {2}...".format(
            "tarfile", meta.url, local_path))
        archive_path = _fetch_remote(meta, dirname=data_location)

        logger.info("Unpacking {}...".format(archive_path))
        with tarfile.open(archive_path, 'r') as tar:
            tar.extractall(path=data_location)

    records.topology = join(data_location, metadata['CONTENTS']['topology'])
    if not exists(records.topology):
        # should not happen...
        raise RuntimeError("topology file {} is missing".format(records.topology))

    trajectory_pattern = join(data_location, metadata['CONTENTS']['trajectories'])
    records.trajectories = glob.glob(trajectory_pattern)
    records.N_trajectories = metadata['CONTENTS']['N_trajectories']
    if len(records.trajectories) != records.N_trajectories:
        # should not happen...
        raise RuntimeError("trajectory files in {0} are incomplete: only {1} "
                           "but should be {2}.".format(
                               trajectory_pattern, len(records.trajectories),
                               records.N_trajectories))

    records.DESCR = _read_description(metadata['DESCRIPTION'])

    return records