#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import os

#points (1 for Rock, 2 for Paper, and 3 for Scissors)
#points (0 if you lost, 3 if the round was a draw, and 6 if you won)

#1st column opponent, 2nd column me
#A, X for Rock, 1 point
#B, Y for Paper, 2 points
#C, Z Scissors, 3 points

def read_input(path, header=None, delim_whitespace= True):

    input = pd.read_csv(path, header=header, delim_whitespace=delim_whitespace)

    return input

def strategy_guide(row,points_dict):
    total_points = 0
    opponent_value = row['opponent']
    print('opponent value {}'.format(opponent_value))
    my_value = row['me']
    print('my value {}'.format(my_value))

    my_value_points = points_dict[my_value]
    opponent_value_points = points_dict[opponent_value]

    #to cover draw
    if my_value_points == opponent_value_points:
        print("it's a draw, 3 points")
        result = 'Draw'
        total_points += 3
    elif my_value == 'X':
        print('I have Rock')
        if opponent_value == 'B':
            print('opponent has Paper, i lose, 0 points')
            total_points += 0
            result = 'Lose'
        elif opponent_value == 'C':
            print('opponent has Scissors, i win, 6 points')
            total_points += 6
            result = 'Win'
    elif my_value == 'Y':
        print('I have Paper')
        if opponent_value == 'A':
            print('opponent has Rock, i win, 6 points')
            total_points += 6
            result = 'Win'
        elif opponent_value == 'C':
            print('opponent has Scissors, i lose, 0 points')
            total_points += 0
            result = 'Lose'
    elif my_value == 'Z':
        print('I have Scissors')
        if opponent_value == 'A':
            print('opponent has Rock, i lose, 0 points')
            total_points += 0
            result = 'Lose'
        elif opponent_value == 'B':
            print('opponent has Paper, i win, 6 points')
            total_points += 6
            result = 'Win'

    extra_points = points_dict[my_value]
    print(extra_points)
    print('extra points {}'.format(extra_points))
    total_points += extra_points
    print('total points {}'.format(total_points))
    final_points = total_points

    # result = result
    return final_points

def strategy_guide2(row,points_dict):
    total_points = 0
    opponent_value = row['opponent']
    print('opponent value {}'.format(opponent_value))
    my_result = row['me']
    print('my result {}'.format(my_result))

    if my_result == 'X':
        print('I need to lose')
        total_points += 0
        if opponent_value == 'A':
            print('Opponent has Rock, I need Scissors')
            my_value = 'Z'
        elif opponent_value == 'B':
            print('Opponent has Paper, I need Rock')
            my_value = 'X'
        elif opponent_value == 'C':
            print('Opponent has Scissors, I need paper')
            my_value = 'Y'
    elif my_result == 'Y':
        print('I need a draw')
        total_points +=3
        if opponent_value == 'A':
            print('Opponent has Rock, I need Rock')
            my_value = 'X'
        elif opponent_value == 'B':
            print('Opponent has Paper, I need Paper')
            my_value = 'Y'
        elif opponent_value == 'C':
            print('Opponent has Scissors, I need Scissors')
            my_value = 'Z'
    elif my_result == 'Z':
        print('I need to win')
        total_points += 6
        if opponent_value == 'A':
            print('Opponent has Rock, I need Paper')
            my_value = 'Y'
        elif opponent_value == 'B':
            print('Opponent has Paper, I need Scissors')
            my_value = 'Z'
        elif opponent_value == 'C':
            print('Opponent has Scissors, I need Rock')
            my_value = 'X'

    extra_points = points_dict[my_value]
    print(extra_points)
    print('extra points {}'.format(extra_points))
    total_points += extra_points
    print('total points {}'.format(total_points))
    final_points = total_points

    # result = result
    return final_points

def main():
    """ Main program """
    # Code goes over here.
    dir_path = os.path.dirname(os.path.realpath(__file__))
    input_path = dir_path +"/input.csv"
    #print(input_path)

    input_df = read_input(input_path,0)
    print(input_df)
    print(input_df.columns)

    points ={
        'A':1,
        'B':2,
        'C':3,
        'X':1,
        'Y':2,
        'Z':3
    }

    input_df['points'] = input_df.apply(lambda row: strategy_guide(row,points), axis=1)

    #print(input_df)
    print('part 1')
    print(input_df['points'].sum())

    #part2
    #X you need to loose
    #Y you need draw
    #Z you need to win
    print('part 2')
    input_df['points2'] = input_df.apply(lambda row: strategy_guide2(row,points), axis=1)
    print(input_df['points2'].sum())

    return 0

if __name__ == "__main__":
    main()


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

import yaml

from bag.core import BagProject

from analog_ec.layout.dac.rladder.core import ResLadderDAC

if __name__ == '__main__':
    with open('specs_test/analog_ec/rdac/unit.yaml', 'r') as f:
        block_specs = yaml.load(f)

    local_dict = locals()
    if 'bprj' not in local_dict:
        print('creating BAG project')
        bprj = BagProject()

    else:
        print('loading BAG project')
        bprj = local_dict['bprj']

    bprj.generate_cell(block_specs, ResLadderDAC, debug=True)
    # bprj.generate_cell(block_specs, ResLadderDAC, gen_sch=True, run_lvs=True, debug=True)


from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse

from app1.models import Board
from app1.forms import ChessForm

def home(request):

    if(Board.objects.all().count() == 0):
        reset(request)
    if(request.method == 'GET' and 'Reset' in request.GET):
        reset(request)
    column_labels = ['0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
    page_data = {"rows": [], "chess_form": ChessForm}
    if(request.method == 'POST'):
        chess_form = ChessForm(request.POST)
        if(chess_form.is_valid()):
            Source = chess_form.cleaned_data["Source"]
            pieces = Board.objects.filter(Source=Source).values()[0]
            Destination = chess_form.cleaned_data["Destination"]
            Board(Source=Source, Destination="&nbsp").save()
            Board(Source=Destination, Destination=pieces['Destination']).save()
        else:
            page_data["chess_form"] = chess_form
    for row in range(1,9):
        row_data = {}
        for col in range(1,10):#2,10
            id="{}{}".format(column_labels[col-1],9-row)
            try:
                record = Board.objects.get(Source=id)
                row_data[id] = record.Destination
            except Board.DoesNotExist:
                    row_data[id] = "&nbsp"
        page_data.get("rows").append(row_data)

    return render(request, 'app1/home.html', page_data)

def reset(request):
    page_data= {
    "rows": [
        {"08":8, "a8":"&#9820", "b8":"&#9822", "c8":"&#9821", "d8":"&#9819", "e8":"&#9818", "f8":"&#9821", "g8":"&#9822", "h8":"&#9820"},
        {"07":7, "a7":"&#9823", "b7":"&#9823", "c7":"&#9823", "d7":"&#9823", "e7":"&#9823", "f7":"&#9823", "g7":"&#9823", "h7":"&#9823"},
        {"06":6, "a6":"", "b6":"", "c6":"", "d6":"", "e6":"", "f6":"", "g6":"", "h6":""},
        {"05":5, "a5":"", "b5":"", "c5":"", "d5":"", "e5":"", "f5":"", "g5":"", "h5":""},
        {"04":4, "a4":"", "b4":"", "c4":"", "d4":"", "e4":"", "f4":"", "g4":"", "h4":""},
        {"03":3, "a3":"", "b3":"", "c3":"", "d3":"", "e3":"", "f3":"", "g3":"", "h3":""},
        {"02":2, "a2":"&#9817", "b2":"&#9817", "c2":"&#9817", "d2":"&#9817", "e2":"&#9817", "f2":"&#9817", "g2":"&#9817", "h2":"&#9817"},
        {"01":1, "a1":"&#9814", "b1":"&#9816", "c1":"&#9815", "d1":"&#9813", "e1":"&#9812", "f1":"&#9815", "g1":"&#9816", "h1":"&#9814"},
    ]
    }
    Board.objects.all().delete()
    for row in page_data.get("rows"):
        for Source, Destination in row.items():
            Board(Source=Source, Destination=Destination).save()

def history(request):
    return render(request, 'app1/history.html')

def rules(request):
    return render(request, 'app1/rules.html')

def about(request):
    return render(request, 'app1/about.html')


import sys
sys.stdin = open("GNS_test_input.txt")

T = int(input())

for tc in range(1, T + 1):
    tcn, ml = list(map(str, input().split()))
    arr = input().split()
    arrlist = ''
    search = ["ZRO", "ONE", "TWO", "THR", "FOR", "FIV", "SIX", "SVN", "EGT", "NIN"]
    ans = []

    for i in range(len(search)):
        for j in range(len(arr)):
            if search[i] == arr[j]:
                ans.append(arr[j])
    print(f'#{tc}')
    print(*ans)

    # for word in arr:
    #     arrlist += word
    # print(arrlist)


from ..player import BasePlayer
from ..utils import count_min

class Agachao(BasePlayer):
    '''
    This player doesn't want to pass,
    so if there is a number that appears in only one piece,
    this piece will not be used until there's no other choice.
    '''
    def __init__(self, name):
         super().__init__(f"Agachao::{name}")

    def filter(self, valids=None):
        valids = super().filter(valids)

        heads = []
        first_move = True
        amount_played = {}

        for e, *d in self.history:
            if e.name == 'MOVE':
                player, piece, head = d
                if player == self.me:
                    amount_played[piece[0]] = amount_played.get(piece[0], 0) + 1
                    if piece[0] != piece[1]:
                        amount_played[piece[1]] = amount_played.get(piece[1], 0) + 1
                if first_move:
                    heads = list(piece)
                    first_move = False
                else:
                    heads[head] = piece[piece[0] == heads[head]]

        best, data = (-1, -1), []
        for piece, head in valids:
            mn, i = count_min(self, piece)
            value = (mn, amount_played.get(piece[i], 0))
            if value > best:
                best = value
                data.clear()
            if value == best:
                data.append((piece, head))

        return data


import re

from docx import Document

from Helpers import to_float, without_whitespace, to_float_or, without_lines

class ParseMachines:
    def __init__(self, model):
        self.model = model
        self.last_id = None
        pass

    def run(self, doc: Document, collection_id: int, id_prefix: str, collection_type: int):
        self.doc = doc
        self.collection_id = collection_id
        self.id_prefix = id_prefix
        self.collection_type = collection_type
        for table in doc.tables:
            self.parse_caption(table)

    def parse_caption(self, table):
        rows = table.rows
        continue_n = 0
        for row in range(0, len(rows)):
            if continue_n > 0:
                continue_n -= 1
                continue
            try:
                cells = rows[row].cells
            except Exception as e:
                continue
            self.model.commit()
            for cell in range(0, len(cells)):
                cells = rows[row].cells
                text = cells[cell].text
                text_all = ' '
                for i in cells:
                    text_all += i.text
                text_all = re.sub(r'\n', '', text_all)
                text_all = re.sub(r'\t', '', text_all)
                if self.check_kniga(text_all):
                    self.last_kniga_id = self.model.insert_caption(self.collection_id, None, text)
                    break
                elif self.check_razdel(text_all):
                    self.last_razdel_id = self.model.insert_caption(self.collection_id, self.last_kniga_id, text)
                    break
                elif self.check_gruppa(text_all):
                    if cells[cell].text:
                        self.last_table_id = self.model.insert_caption(self.collection_id, self.last_razdel_id, cells[cell].text)
                    else:
                        self.last_table_id = self.model.insert_caption(self.collection_id, self.last_razdel_id,
                                                                       cells[cell + 1].text)
                    continue_n = row - self.parse_costs(table, row + 1)

                    cells = rows[row].cells
                    break
                else:
                    break

    def parse_costs(self, table, row_i):
        addon_string = ''
        rows = table.rows
        continue_n = 0
        codes = None
        for row in range(row_i, len(rows)):
            if continue_n > 0:
                continue_n -= 1
                continue
            cells = rows[row].cells
            for cell in range(0, len(cells)):
                cell_text = rows[row].cells[cell].text
                if self.check_kniga(cell_text):
                    return row - 1
                if self.check_razdel(cell_text):
                    return row - 1
                if self.check_gruppa(cell_text):
                    return row - 1

            if len(rows[row].cells) == 5:
                if cells[1].text == cells[2].text:
                    addon_string = without_lines(cells[1].text)
                    continue
                id = without_lines(without_whitespace(cells[0].text))
                name = addon_string + ' ' + without_lines(cells[1].text)
                unit = without_lines(without_whitespace(cells[2].text))
                price = to_float(cells[3].text)
                price_driver = to_float(cells[4].text)

                self.model.insert_machine(id, name, unit, price, price_driver, self.last_table_id)

                continue
            if len(rows[row].cells) > 6:
                print('sghafolksfjlhlgaf;gdsjhfj               {}'.format(len(rows[row].cells)))
                pass
        return row

    def check_kniga(self, row_str: str):
        row_str = re.sub(r'\n', '', row_str)
        row_str = re.sub(r'\t', '', row_str)
        result = re.search(r'(Книга(.*?)$)', row_str, re.IGNORECASE)
        if result:
            return result.group(1)
        return None

    def check_razdel(self, row_str: str):
        result = re.search(r'(Раздел(.*?)$)', row_str, re.IGNORECASE)
        if result:
            return result.group(1)
        return None

    def check_gruppa(self, row_str: str):
        result = re.search(r'((Группа(.*?))$)', row_str, re.IGNORECASE)
        if result:
            return result.group(1)
        return None


from odoo import fields, models, api, _

class ProjectInherit(models.Model):
    _inherit = 'project.project'

    cost_sheet_id = fields.Many2one('cost.sheet', string='Cost Sheet',
                                    related='sale_order_id.cost_sheet_id')
    estimated_hours = fields.Float(related='cost_sheet_id.total_hours',
                                   string='Budgeted Hours', store=True)
    amount_untaxed = fields.Monetary(related='sale_order_id.amount_untaxed',
                                     string='Amount', store=True)
    amount_tax = fields.Monetary(related='sale_order_id.amount_tax',
                                 string='Vat Amount', store=True)
    amount_total = fields.Monetary(related='sale_order_id.amount_total',
                                   string='Total Amount', store=True)
    invoice_type = fields.Selection(
        selection=[('combine', 'Combined'), ('individual', 'Separate')],
        string='Invoice Type', default='combine')
    sequence = fields.Char(string="Project Number", readonly=True,
                           required=True,
                           copy=False, default='New')
    name = fields.Char("Name", index='trigram', required=True, tracking=True,
                       translate=True, default_export_compatible=True,
                       help="Name of your project. It can be anything you want e.g. the name of a customer or a service.")
    task_assignees_ids = fields.Many2many('res.users', 'task_assignees_rel', string="Task Assignees",
                                          compute='_compute_task_assignees_ids')

    def action_view_tasks_main(self):
        action = self.env['ir.actions.act_window'].with_context(
            {'active_id': self.id})._for_xml_id(
            'project.act_project_project_2_project_task_all')
        return action

    @api.model
    def create(self, vals_list):
        vals_list['sequence'] = self.env['ir.sequence'].next_by_code(
            'project.crowe.sequence') or _('New')
        customer_name = self.env['res.partner'].browse(
            vals_list['partner_id']).name
        vals_list['name'] = vals_list['sequence'] + customer_name
        return super(ProjectInherit, self).create(vals_list)

    @api.depends('task_ids')
    def _compute_task_assignees_ids(self):
        for rec in self:
            for id in rec._origin.task_ids.mapped('user_ids.id'):
                rec.write({
                    'task_assignees_ids': [(4, id)]
                })


import torch
import torch.nn as nn
import numpy as np
import os
import matplotlib.pyplot as plt

def get_inds(problem_type, length, num_kept_samples):
    """
    Given a number of samples to keep and a problem type, returns indices to keep from a list.

    Args:
        problem_type: What type of inpainting problem we are dealing with.
                      String in {"random", "equal", "forecast", "full", "log", "sqrt"}.
        length: The original length of the signal.
                Int.
        num_kept_samples: The number (or proportion) of samples to keep.
                          Int <= length OR float <= 1.0.

    Returns:
        kept_inds: Array with (sorted, increasing) indices of samples to keep from the original signal.
                   Numpy array of Ints.
        missing_inds: Array with  (sorted, increasing) indices of discarded sampled from the original signal.
                      Numpy array of Ints.
    """
    if isinstance(num_kept_samples, float) and num_kept_samples <= 1.0:
        num_kept_samples = int(length * num_kept_samples)
        num_kept_samples = max(num_kept_samples, 1)

    if problem_type=="random":
        kept_inds = np.random.choice(length, num_kept_samples, replace=False)
    elif problem_type=="equal":
        kept_inds = np.linspace(0, length-1, num=num_kept_samples, dtype=int)
    elif problem_type=="forecast":
        kept_inds = np.arange(0, num_kept_samples)
    elif problem_type=="full":
        kept_inds = np.arange(0, length)
    elif problem_type=="log":
        kept_inds = np.geomspace(1, length, num=num_kept_samples, dtype=int) #geomspace can't take 0 as start index
        kept_inds = kept_inds - 1
        kept_inds = np.sort(kept_inds) #making the list unique
        for i in range(1, len(kept_inds)):
            if kept_inds[i] <= kept_inds[i-1]:
                kept_inds[i] = kept_inds[i-1] + 1
    elif problem_type=="sqrt":
        r = (length - 1.) / ((num_kept_samples - 1.)**2) #base quadratic factor
        kept_inds = [round(r * (s**2)) for s in range(num_kept_samples - 1)]
        kept_inds.append(length-1)
        kept_inds = np.array(kept_inds)
        kept_inds = np.sort(kept_inds) #making the list unique
        for i in range(1, len(kept_inds)):
            if kept_inds[i] <= kept_inds[i-1]:
                kept_inds[i] = kept_inds[i-1] + 1
    else:
        raise NotImplementedError("THIS PROBLEM TYPE IS UNSUPPORTED")

    missing_inds = np.array([t for t in range(length) if t not in kept_inds])

    return np.sort(kept_inds), np.sort(missing_inds)

def get_network_from_file(root_pth, chip_num):
    """
    Grabs an SK-RF Network and its associated metadata from a given root path
        and chip number.
    Different from grab_chip_data since this function returns the raw Network object
        and not np arrays.

    Args:
        root_pth: Root of the folder containing chip info.
        chip_num: Chip number.

    Returns:
        out_dict: Dictionary with relevant entries.
                  Entries:
                    network: The ground truth network.
                             Scikit-RF Network object.
                    fmin: Minimum frequency sampled.
                          Float.
                    fmax: Max frequency sampled.
                          Float.
                    length: The length of the channels.
                            String.
                    sweep: The spacing between sampled points.
                           String.
                    port_pairs: The paied ports on the chip.
                                Array of tuples.
    """
    from skrf import Network

    #Grab the correct folder
    chip_num = str(chip_num) if chip_num > 9 else "0" + str(chip_num)
    fname = os.path.join(root_pth, "case"+chip_num)

    net_str = str(chip_num) + ".s"
    desc_str = "description.txt"

    #grab the correct file we want
    children = os.listdir(fname)

    net_fpth = [f for f in children if net_str in f][0]
    net_fpth = os.path.join(fname, net_fpth)

    desc_fpth = [f for f in children if desc_str in f][0]
    desc_fpth = os.path.join(fname, desc_fpth)

    #grab the network and metadata
    out_network = Network(net_fpth)

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

    fmin = None
    fmax = None
    length = None
    sweep = None
    port_pairs = []

    for line in lines:
        if "fmin" in line:
            fmin = float(line.split(" ")[-1])
        elif "fmax" in line:
            fmax = float(line.split(" ")[-1])
        elif "length" in line:
            length = line.split(" ")[-1]
        elif "sweep" in line:
            sweep = line.split(" ")[-1]
        elif "port_pair" in line:
            port1 = int(line.split(" ")[-2])
            port2 = int(line.split(" ")[-1])
            port_pairs.append((port1, port2))

    out_dict = {"network": out_network,
                "fmin": fmin,
                "fmax": fmax,
                "length": length,
                "sweep": sweep,
                "port_pairs": port_pairs}

    return out_dict

def network_to_sparams(network):
    """
    Converts a given Sk-RF network object into a [1, 2*N_-sparams, N_freqs] torch tensor.

    Args:
        network: sk-rf network object.

    Returns:
        [1, 2*N_sparams, N_freqs] torch tensor. Channel dimenson has reals
            on the even indices and their respective imag's on the odd indices.
    """
    re_mat = network.s.real
    im_mat = network.s.imag
    out_mat = np.stack((re_mat, im_mat), axis=-1)

    out_mat = out_mat.reshape((out_mat.shape[0], -1, out_mat.shape[-1])) #[FREQ, N_PORT^2, RE/IM]
    out_mat = out_mat.reshape((out_mat.shape[0], -1)).transpose() #[Re/im Sparams, FREQ]

    return torch.from_numpy(out_mat).unsqueeze(0).type(torch.float32)

def matrix_to_network(data_matrix, data_freqs, name, resample_freqs=None):
    """
    Takes a raw 4D sparam matrix and returns a Scikit-RF Network object.

    Args:
        data_matrix: Raw 4D sparam matrix.
                     (4D torch tensor) - Axes are [Freq, In_port, Out_port, Re/Im].
        data_freqs: Sampled frequencies. Must be same length as first axis of data_matrix.
                    (1D numpy array).
        name: The name of the network.
              (String)
        resample_freqs: Frequencies to resample the data to. Default is None.
                        (1D numpy array).

    Returns:
        net: A scikit-RF Network object.
    """
    from skrf import Network, Frequency

    #Convert the data properly to complex
    temp_data = data_matrix.detach().cpu().numpy().astype('float64')

    net_data = np.empty(temp_data.shape[:-1], dtype=np.complex128)
    net_data.real = temp_data[..., 0]
    net_data.imag = temp_data[..., 1]

    #Make the network
    net_freqs = Frequency.from_f(data_freqs, unit="hz")

    net = Network(frequency=net_freqs, s=net_data, name=name)

    #Check if we need to re-sample
    if resample_freqs is not None:
        new_freqs = Frequency.from_f(resample_freqs)
        net.resample(new_freqs)

    return net

def sparams_to_mag(sparams, get_phase=False, in_db=False):
    """
    Computes the magnitude, and optionally the phase, of a given complex signal.

    Args:
        sparams: Signal with real and imaginary components.
                 Torch tensor [1, 2*num_unique_sparams, F].
                 We expect the real and imaginary components for each s-parameter to be adjacent
                    channels in the second axis.
        get_phase: If True, returns the phase of the signal as well.
        in_db: If True, will return the magnitude in Decibels.

    Returns:
        mag: Magnitude of the given signal. If in_db is True, will be in Decibels.
             Torch tensor [1, num_unique_sparams, F].
        phase (optional): Phase of the given signal in radians. Only returned if get_phase is true.
                          Torch tensor [1, num_unique_sparams, F].
    """

    x_complex = torch.complex(sparams[:, ::2, :], sparams[:, 1::2, :]) #evens are real, odds are imaginary

    x_mag = torch.abs(x_complex)
    if in_db:
        x_mag = 20 * torch.log10(x_mag) #multiply here by 20 instead of 10 because abs is a square root term

    if get_phase:
        x_phase = torch.angle(x_complex)
        return x_mag, x_phase
    else:
        return x_mag

def plot_mags(sparams_list, freqs=None, chip_labels=None, not_reciprocal=False, plot_subset_list=None, ylims=False):
    mag_list = [sparams_to_mag(sparam) for sparam in sparams_list]

    num_ports = (-1 + np.sqrt(8*mag_list[0].shape[1] + 1)) // 2
    num_ports = int(num_ports)
    if not_reciprocal:
        num_ports = int(np.sqrt(mag_list[0].shape[1]))

    x = freqs if freqs is not None else [np.arange(mag_list[0].shape[-1])]*len(mag_list)
    labels = chip_labels if chip_labels is not None else np.arange(len(mag_list))

    if not_reciprocal:
        sparam_str_list = [str(s_idx//num_ports) + str(s_idx%num_ports) for s_idx in range(mag_list[0].shape[1])]
    else:
        sparam_str_list = []
        for i in range(num_ports):
            for j in range(i+1):
                sparam_str_list.append(str(i) + str(j))

    plot_chips = plot_subset_list if plot_subset_list is not None else np.arange(len(mag_list))

    fig, axs = plt.subplots((mag_list[0].shape[1] + 1) // 2, 2, figsize=(20,15))

    for s_idx in range(mag_list[0].shape[1]):
        if s_idx >= mag_list[0].shape[1]:
            break
        for chip_idx in plot_chips:
            axs[s_idx//2, s_idx%2].plot(x[chip_idx], mag_list[chip_idx][0, s_idx], label=str(labels[chip_idx]))
        axs[s_idx//2, s_idx%2].set_title(sparam_str_list[s_idx])
        axs[s_idx//2, s_idx%2].legend()
        if ylims:
            axs[s_idx//2, s_idx%2].set_ylim(0, 1)

    fig.tight_layout()

class Measurement_MSE_Loss(nn.Module):
    """
    Given a signal x, observed measurements y, and observed indices kept_inds,
        return the mse over the measurements of x vs true measurements y.

    Args:
        kept_inds: Array with the indices of the kept measurements.
        per_param: Whether to reduce the MSE for each S-param individually
                    before reducing the loss.
                   This can help with robustly fitting each S-param well.
        reduction: ["mean", "sum"]
    """

    def __init__(self, kept_inds, per_param=False, reduction="mean"):
        super().__init__()

        self.kept_inds = kept_inds
        self.per_param = per_param
        self.reduction = reduction

        if not self.per_param:
            self.mse_loss = nn.MSELoss(reduction=self.reduction)

    def forward(self, x, y):
        if not self.per_param:
            return self.mse_loss(x[:, :, self.kept_inds], y)

        else:
            square_error = torch.square(x[:, :, self.kept_inds] - y) #[1, 2 * N_sparams, m]

            if self.reduction == "mean":
                mse_per_chan = torch.mean(square_error, dim=2) #[1, 2 * N_sparams]
                rmse_per_chan = torch.sqrt(mse_per_chan) #[1, 2 * N_sparams]

                return torch.mean(rmse_per_chan)

            elif self.reduction == "sum":
                sse_per_chan = torch.sum(square_error, dim=2) #[1, 2 * N_sparams]
                rsse_per_chan = torch.sqrt(sse_per_chan) #[1, 2 * N_sparams]

                return torch.sum(rsse_per_chan)

class Smoothing_Loss(nn.Module):
    """
    Loss function that penalizes nth-order differences in a time series.

    Args:
        per_param: Whether to reduce the loss for each S-param individually
                    before reducing the loss.
                   This can help with robustly fitting each S-param well.
        reduction: ["mean", "sum"]
    """
    def __init__(self, per_param=False, reduction="mean", order=2, norm=2):
        super().__init__()

        self.per_param = per_param
        self.reduction = reduction
        self.order = order
        self.norm = norm

    def forward(self, x):
        if self.order == 2:
            diffs = torch.diff(torch.diff(x, dim=2), dim=2)
        elif self.order == 3:
            diffs = torch.diff(torch.diff(torch.diff(x, dim=2), dim=2), dim=2)

        if self.norm == 1:
            diffs = torch.abs(diffs)
        elif self.norm == 2:
            diffs = torch.square(diffs)

        if not self.per_param:
            if self.reduction == "mean":
                return torch.mean(diffs)
            elif self.reduction == "sum":
                return torch.sum(diffs)

        else:
            if self.reduction == "mean":
                loss_per_chan = torch.mean(diffs, dim=2) #[1, 2 * N_sparams]
                rloss_per_chan = torch.sqrt(loss_per_chan) #[1, 2 * N_sparams]

                return torch.mean(rloss_per_chan)

            elif self.reduction == "sum":
                loss_per_chan = torch.sum(diffs, dim=2) #[1, 2 * N_sparams]
                rloss_per_chan = torch.sqrt(loss_per_chan) #[1, 2 * N_sparams]

                return torch.sum(rloss_per_chan)


import logging
import json

from cpc.network.server_to_server_message import ServerToServerMessage
from cpc.network.com.input import Input
from cpc.network.server_request import ServerRequest
from cpc.util import json_serializer

log=logging.getLogger(__name__)

class ServerMessage(ServerToServerMessage):
    """Server-to-server messages.
       These messages can be sent to any node in the network
    """
    def pingServer(self,serverId):
        cmdstring='ping'
        fields = []
        input = Input('cmd', cmdstring)
        fields.append(input)
        fields.append(Input('version', "1"))
        headers = dict()
        if serverId!= None:
            headers['server-id'] = serverId
        msg = ServerRequest.prepareRequest(fields,[],headers)
        response= self.putRequest(msg)
        return response

    def workerReadyForwardedRequest(self, workerID, archdata, topology,
                                    originatingServer, heartbeatInterval,
                                    originatingClient=None):
        cmdstring='worker-ready-forward'
        fields = []
        fields.append(Input('cmd', cmdstring))
        fields.append(Input('version', "1"))
        fields.append(Input('worker', archdata))
        fields.append(Input('worker-id', workerID))
        fields.append(Input('heartbeat-interval', str(heartbeatInterval)))
        topologyInput = Input('topology',
            # a json structure that needs to be dumped
            json.dumps(topology,
                default = json_serializer.toJson,
                indent=4))
        fields.append(topologyInput)
        headers = dict()
        headers['originating-server-id'] = originatingServer
        if originatingClient is not None:
            headers['originating-client'] = originatingClient
        response= self.putRequest(ServerRequest.prepareRequest(fields, [],
            headers))
        return response

    def commandFinishedForwardedRequest(self, cmdID, workerServer,
                                        projectServer, returncode,
                                        cputime, haveData):
        """A server-to-sever request doing command-finished. Used in
            forwarding non-local command-finished requests."""
        cmdstring='command-finished-forward'
        fields = []
        input = Input('cmd', cmdstring)
        fields.append(input)
        fields.append(Input('cmd_id', cmdID))
        fields.append(Input('version', "1"))
        fields.append(Input('worker_server', workerServer))
        fields.append(Input('project_server', projectServer))
        if returncode is not None:
            fields.append(Input('return_code', returncode))
        fields.append(Input('used_cpu_time', cputime))
        if haveData:
            fields.append(Input('run_data', 1))

        #the files are not sent in this message, instead they are pulled
        # from the project server upon receiving this message (for now)
        files = []
        headers = dict()
        #headers['end-node'] = self.host
        #headers['end-node-port'] = self.port
        #self.connect()
        #log.debug("forwarding command finished to %s"%self.endNode)
        response= self.putRequest(ServerRequest.prepareRequest(fields, files,
            headers))
        return response

    def heartbeatForwardedRequest(self, workerID, workerDir, workerServer,
                                  iteration, heartbeatItemsXML):
        """A server-to-sever request doing heartbeat signal. Used in
           forwarding non-local heartbeat requests."""
        cmdstring='heartbeat-forward'
        fields = []
        fields.append(Input('cmd', cmdstring))
        fields.append(Input('version', "1"))
        fields.append(Input('worker_id', workerID))
        fields.append(Input('worker_dir', workerDir))
        fields.append(Input('iteration', iteration))
        fields.append(Input('worker_server', workerServer))
        fields.append(Input('heartbeat_items', heartbeatItemsXML))
        files = []
        headers = dict()
        #headers['end-node'] = self.host
        #headers['end-node-port'] = self.port
        #self.connect()
        #log.debug("forwarding command finished to %s"%self.endNode)
        response= self.putRequest(ServerRequest.prepareRequest(fields, files,
            headers))
        return response

    def deadWorkerFetchRequest(self, workerDir, runDir):
        """A server-to-sever request for fetching a set of run directories
           from a dead worker's output."""
        cmdstring='dead-worker-fetch'
        fields = []
        fields.append(Input('cmd', cmdstring))
        fields.append(Input('version', "1"))
        fields.append(Input('worker_dir', workerDir))
        fields.append(Input('run_dir', runDir))
        files = []
        headers = dict()
        #self.connect()
        response= self.putRequest(ServerRequest.prepareRequest(fields, files,
            headers))
        return response

    def pullAssetRequest(self, cmdID, assetType):
        cmdstring='pull-asset'
        fields = []
        fields.append(Input('cmd', cmdstring))
        fields.append(Input('version', "1"))
        fields.append(Input('cmd_id', cmdID))
        fields.append(Input('asset_type', assetType))
        headers = dict()
        headers['end-node'] = self.host
        headers['end-node-port'] = self.port

        #self.connect()
        response= self.putRequest(ServerRequest.prepareRequest(fields, [],
            headers))
        return response

    def clearAssetRequest(self, cmdID):
        cmdstring='clear-asset'
        fields = []
        fields.append(Input('cmd', cmdstring))
        fields.append(Input('version', "1"))
        fields.append(Input('cmd_id', cmdID))
        headers = dict()
        headers['end-node'] = self.host
        headers['end-node-port'] = self.port
        #self.connect()
        response= self.putRequest(ServerRequest.prepareRequest(fields, [],
            headers))
        return response


import arcade
import pygame
import math
import random
from copy import deepcopy

class simplePoint():

	def __init__(self, x, y):
		self.x = x
		self.y = y

	def __str__(self):
		return "x: " + str(self.x) + " y: " + str(self.y)

	def __repr__(self):
		return "x: " + str(self.x) + " y: " + str(self.y)

	def __eq__(self, point):
		return self.convert_to_tuple() == point.convert_to_tuple()

	def __ne__(self, point):
		return not self == point

	def convert_to_tuple(self):
		return (self.x, self.y)

	def draw(self, colour, size, surface):
		#arcade.draw_point(self.x, self.y, colour, size)
		pygame.draw.line(surface, colour, [self.x, self.y], [self.x, self.y], size)

class simpleEdge():

	def __init__(self, p1, p2):
		self.p1 = p1
		self.p2 = p2
		self.length = distance_between(p1, p2)

	def draw(self, colour, size, surface):
		#arcade.draw_line(self.p1.x, self.p1.y, self.p2.x, self.p2.y, colour, size)
		pygame.draw.line(surface, colour, [self.p1.x, self.p1.y], [self.p2.x, self.p2.y], size)

class simpleCircle():

	def __init__(self, centre, radius):
		self.centre = centre
		self.radius = radius

	def point_inside(self, point):
		dist = distance_between(self.centre, point)
		if (dist <= self.radius):
			return True
		else:
			return False

	def draw(self, colour, size, filled, surface):
		if (filled):
			#arcade.draw_circle_filled(self.centre.x, self.centre.y, self.radius, colour)
			pygame.draw.circle(surface, colour, [self.centre.x, self.centre.y], self.radius)
		else:
			#arcade.draw_circle_outline(self.centre.x, self.centre.y, self.radius, colour, size)
			pygame.draw.circle(surface, colour, [self.centre.x, self.centre.y], self.radius, size)

class simpleEllipse():

	def __init__(self, centre, xRadius, yRadius, angle):
		self.centre = centre
		self.xRadius = xRadius
		self.yRadius = yRadius
		self.angle = angle

	def point_inside(self, point):
		cosa=math.cos(self.angle)
		sina=math.sin(self.angle)
		dx=self.xRadius/2*self.xRadius/2
		dy=self.yRadius/2*self.yRadius/2

		a =math.pow(cosa*(point.x-self.centre.x)+sina*(point.y-self.centre.y),2)
		b =math.pow(sina*(point.x-self.centre.x)-cosa*(point.y-self.centre.y),2)
		ellipse=(a/dx)+(b/dy)

		if ellipse <= 1:
			return True
		else:
			return False

	def draw(self, colour, size, filled, surface):
		if (filled):
			#arcade.draw_ellipse_filled(self.centre.x, self.centre.y, self.xRadius, self.yRadius, colour, self.angle)
			aRect = pygame.Rect([self.centre.x - self.xRadius, self.centre.y - self.yRadius, self.xRadius*2, self.yRadius*2])
			aRect.normalize()
			pygame.draw.ellipse(surface, colour, aRect)
		else:
			#arcade.draw_ellipse_outline(self.centre.x, self.centre.y, self.xRadius, self.yRadius, colour, size, self.angle)
			aRect = pygame.Rect([self.centre.x - self.xRadius, self.centre.y - self.yRadius, self.xRadius*2, self.yRadius*2])
			aRect.normalize()
			pygame.draw.ellipse(surface, colour, aRect, size)

class simplePolygon():

	def __init__(self, pointList):
		self.points = pointList
		self.edges = []
		for i in range(len(self.points)):
			edge = (self.points[i],self.points[i-1])
			self.edges.append(edge)

	def point_inside(self, point):

		poly = deepcopy(self.points)
		n = len(poly)
		inside =False

		p1 = poly[0]
		for i in range(n+1):
			p2 = poly[i % n]
			if point.y > min(p1.y,p2.y):
				if point.y <= max(p1.y,p2.y):
					if point.x <= max(p1.x,p2.x):
						if p1.y != p2.y:
							xinters = (point.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x
						if p1.x == p2.x or point.x <= xinters:
							inside = not inside
			p1.x,p1.y = p2.x,p2.y

		return inside

	def draw(self, colour, size, filled, surface):
		pointList = []
		for point in self.points:
			pointList.append(point.convert_to_tuple())
		if (filled):
			pygame.draw.polygon(surface, colour, pointList, 0)
		else:
			pygame.draw.polygon(surface, colour, pointList, size)

def round_to_base(x, base=5):
    return int(base * round(float(x)/base))

def normalise(numberRange, newMin, newMax):
	oldMin = min(numberRange)
	oldMax = max(numberRange)
	output = []
	for x in numberRange:
		y = (((newMax - newMin) * (x - oldMin)) / (oldMax - oldMin)) + newMin
		output.append(y)
	return output

def normalise_angle(angle):
	adjustedAngle = 270 - angle
	if (adjustedAngle >= 360):
		adjustedAngle -= 360
	return adjustedAngle

def distance_between(p1, p2):
	x = p2.x - p1.x
	y = p2.y - p1.y
	return math.sqrt(x*x + y*y)

def angle_between(p1, p2):
	dy = p1.y - p2.y
	dx = p1.x - p2.x
	return math.degrees(math.atan2(dy, dx))

def midpoint(p1, p2):
	x = (p1.x + p2.x)/2
	y = (p1.y + p2.y)/2
	return simplePoint(x, y)

def generate_polygon(centre, minDist, maxDist, numberOfPoints, randomise=True):
	random.seed()
	angleRange = 360/numberOfPoints
	points = []
	for index in range(numberOfPoints):
		dist = random.uniform(minDist, maxDist)
		if (randomise):
			angle = math.radians(random.uniform(index * angleRange, (index + 1) * angleRange))
		else:
			angle = math.radians(angleRange)
		x = dist * math.sin(angle) + centre.x
		y = dist * math.cos(angle) + centre.y
		points.append(simplePoint(x, y))
	poly = simplePolygon(points)
	return poly


import NBC
import cPickle

def loadModel():
    global summaries
    f = open('cgi-bin/NBCweight.txt','r')
    summaries = cPickle.load(f)

def predict(inputX):
    #testSet = NBC.loadCsv(filename)
    loadModel()
    testSet = inputX
    # make predictions
    predictions = NBC.getPredictions(summaries, testSet)
    ##accuracy = NBC.getAccuracy(testSet, predictions)
    ##print accuracy
    return predictions

if __name__ == '__main__':
    loadModel()
    predict('vectorize-tfidf-967.csv')


#!/usr/bin/python3
""" Change comes from within
"""

def makeChange(coins, total):
    """ Return: fewest number of coins needed to meet total
    """
    if total <= 0:
        return 0

    coins.sort(reverse=True)

    result = 0
    count = 0
    x = 0
    while (x < len(coins) and result != total):
        if result + coins[x] > total:
            x += 1
        else:
            result += coins[x]
            count += 1

    if result == total:
        return count
    return -1


import sys
input = lambda: sys.stdin.readline().rstrip("\n\r")
from collections import Counter

def solve():
    n = int(input())
    a = list(map(int, input().split()))

    pre = [a[0]]
    for i in range(1, n):
        pre.append(pre[-1] + a[i])

    zind = []
    for i in range(n):
        if a[i] == 0:
            zind.append(i)
    zind.append(n)

    ans = pre[:zind[0]].count(0)
    for i in range(len(zind) - 1):
        x = sorted(pre[zind[i]: zind[i + 1]])
        ans += max(Counter(x).values())

    print(ans)

for _ in range(int(input())):
    solve()


from django.contrib.auth import get_user_model
from django.conf import settings
from django.template.loader import render_to_string

def email_or_mobile(value):
    UserModel = get_user_model()
    if settings.EMAIL_PATTERN.search(value):
        return {UserModel.EMAIL_FIELD: value}
    if settings.MOBILE_PATTERN.search(value):
        return {UserModel.USERNAME_FIELD: value}
    return None

def user_exists(**kwargs):
    model = get_user_model()
    try:
        user = model.objects.get(**kwargs)
    except model.DoesNotExist:
        return False
    return user

def verification_mail(user, token, time_validity):
    # token_message = _("SMAS OTP Verification {token}")
    # token_message = token_message.format(token=token)
    try:
        html_message = render_to_string(
            'mailer/verification.html',
            {'name': user.get_full_name().title(), 'otp': token, 'time_validity': time_validity})
        user.email_user("SMAS OTP Verification", None, "admin@smas.com", html_message=html_message)
    except Exception as ex:
        raise ex.args
    return True


from itertools import *
from collections import *
from heapq import *
from bisect import *
from copy import *
from array import *
import math
import sys
sys.setrecursionlimit(1<<20)
INF = float('inf')
n,m,k = map(int,input().split())
A = list(map(int,input().split()))
MOD = 10**9+7
B = [[0]*n for _ in range(n)]
g = [[] for _ in range(n)]
for i in range(m):
    x,y = map(int,input().split())
    x-=1;y-=1
    g[x].append(y)
    g[y].append(x)
m1 = pow(2*m,MOD-2,MOD)
for i in range(n):
    t = len(g[i])
    B[i][i] = (1-t*m1)%MOD
for i in range(n):
    for j in g[i]:
        if i!=j:
            B[i][j] = m1

def mat_mul(a,b):
    I,J,K = len(a),len(b[0]),len(b)
    c = [[0]*J for _ in range(I)]
    for i in range(I):
        for j in range(J):
            for k in range(K):
                c[i][j] += a[i][k]*b[k][j]
                c[i][j] %= MOD
    return c

def mat_pow(x,n):
    y = [[0]*len(x) for _ in range(len(x))]
    for i in range(len(x)):
        y[i][i] = 1
    while n:
        if n&1:
            y = mat_mul(x,y)
        x = mat_mul(x,x)
        n>>=1
    return y
AA = mat_pow(B,k)
ANS = [0]*n
for i in range(n):
    for j in range(n):
        ANS[i]+=AA[i][j]*A[j]
        ANS[i]%=MOD
print(*ANS,sep="\n")


# 1225 - 암호 생성기
import sys
sys.stdin = open('input.txt')
from collections import deque

T = 10
for t in range(1, T+1) :
    tc = int(input())
    queue = deque(list(map(int, input().split())))  # 큐

    while True :
        for i in range(1, 6) :  # 한 사이클
            if (queue[0] - i) <= 0 :    # i 만큼 뺀 값이 0보다 작거나 같아질 때
                queue[0] = 0    # 0 으로 바꾸고
                queue.append(queue.popleft())   # 뒤로 보내준 후 브레이크
                break
            else :
                queue[0] -= i   # i 만큼 빼준 후
                queue.append(queue.popleft())   # 뒤로 보내기

        if queue[-1] == 0 : # while문 빠져나가기
            break

    print(f'#{t}', *queue)


r = int(input("podaj wielkosc tablicy: "))

def fib(i, j):
    if j in {0, 1}:
        return j
    return fib(j - 1) + fib(j - 2)

F = [fib(j) for j in range(j)]
print(F)


# 1. chain.from_iterable():
# This function is implemented similarly as a chain() but the argument
# here is a list of lists or any other iterable container.
# 2. It takes only one argument and argument needs to be 2D container.
import itertools

l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = [7, 8, 9]
t1 = (1, 2, 3)

l4 = [t1, l2]
t2 = (l1, l2)

print(list(itertools.chain.from_iterable(t1)))


import random
import time
import threading
from var import *
from util import *
import pyWinhook as pyHook

RUNNING = True
PAUSE = False

def execute(target, order: list):
    global RUNNING
    if order is None:
        RUNNING = False
        raise Exception("Order Cannot be None!")
    for i in order:
        while PAUSE:
            time.sleep(1)
        xs = random.randint(-i[1][0], i[1][0])
        px = i[0][0] + xs
        ys = random.randint(-i[1][1], i[1][1])
        py = i[0][1] + ys
        wait = i[2] + random.uniform(0, i[3] + 0.01)
        rep = random.randint(1, i[4])
        print(i[5], file=STDOUT)
        for _ in range(rep):
            click(target, pos_x=int(px / 1.2), pos_y=int(py / 1.2))
            rwait = random.uniform(0, 0.05)
            time.sleep(rwait)
        print("DEBUG:", px, xs, py, ys, wait, rep, file=G2)
        time.sleep(wait)

def supervisor():
    def onKeyboardEvent(event: pyHook.KeyboardEvent):
        global PAUSE
        if event.KeyID == 36:
            if not RUNNING:
                exit(0)
            # home
            if PAUSE:
                print("resumed")
            else:
                print("paused")
            PAUSE = not PAUSE
        return 1

    print("supervisor started")
    hm = pyHook.HookManager()
    hm.KeyDown = onKeyboardEvent
    hm.HookKeyboard()

    win32gui.PumpMessages()

def start_round(target, order, rounds: int = 50):
    print("rounds started")
    global RUNNING
    try:
        for i in range(0, rounds):
            print(f"======= Round {i} =======")
            execute(target, order)
    finally:
        RUNNING = False

    RUNNING = False

if __name__ == '__main__':
    # find_window()
    dbg_target = 44107804
    t1 = threading.Thread(target=supervisor)
    t2 = threading.Thread(target=start_round, args=(dbg_target, camp_star))
    t1.start()
    t2.start()
    t1.join()
    t2.join()


import svgwrite
from bootstrap import application

STYLE = {
    "up-to-date": {
        "text": "up-to-date",
        "rect_size": (95, 20),
        "rect_fill": "green",
        "paragraph_fill": "white",
        "text_fill": "white",
    },
    "update-available": {
        "text": "update available",
        "rect_size": (140, 20),
        "rect_fill": "orange",
        "paragraph_fill": "white",
        "text_fill": "white",
    },
    "security-update-available": {
        "text": "security update available",
        "rect_size": (360, 20),
        "rect_fill": "red",
        "paragraph_fill": "white",
        "text_fill": "white",
    },
    "unknown": {
        "text": "unknown",
        "rect_size": (95, 20),
        "rect_fill": "grey",
        "paragraph_fill": "white",
        "text_fill": "white",
    },
}

def simple_text(name, style, text=None):
    """Draw a text in a rectangle."""
    dwg = svgwrite.Drawing(name, style["rect_size"])

    rect = dwg.rect(insert=(0, 0), size=style["rect_size"], fill=style["rect_fill"])
    dwg.add(rect)

    paragraph = dwg.add(
        dwg.g(font_size=14, font_family="DejaVu Sans", fill=style["paragraph_fill"])
    )
    if not text:
        text = style["text"]
    text_elem = dwg.text(
        text, insert=(5, 15), font_weight="bold", fill=style["text_fill"]
    )
    paragraph.add(text_elem)

    file_name = "{}.svg".format(name.replace(" ", "-"))
    file_path = application.config["GENERATED_SVG_FOLDER"] + file_name

    dwg.saveas(file_path)
    return file_name

if __name__ == "__main__":
    for state in ["up-to-date", "update available", "security update available"]:
        simple_text("{}.svg".format(state.replace(" ", "-")), state, STYLE[state])


from typing import List

def remove_neg(num_list: List[float]) -> None:
    """리스트 num_list에서 음수를 삭제한다.

    >>> numbers = [-5, 1, -3, 2]
    >>> remove_neg(numbers)
    >>> numbers
    [1, 2]
    """

    for item in num_list:
        if item < 0:
            num_list.remove(item)


from django.db import transaction
from django.shortcuts import render, redirect
from django.template import loader

from datetime import datetime

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from user.models import Attendee
from user.forms import UserAuthForm, UserExtendForm
from food.models import FoodOrder
from event.models import Event, EventAttendee

def register(request):
    if request.method == 'POST':
        user_auth_form = UserAuthForm(request.POST)
        user_extended_form = UserExtendForm(request.POST)
        if user_auth_form.is_valid() and user_extended_form.is_valid():
            user = user_auth_form.save(commit=False)
            user.set_password(user.password)
            user.save()
            user.refresh_from_db()
            user_extended = user_extended_form.save(commit=False)
            user_extended.user_auth = user
            user_extended.save()
            return render(request, 'registration/login.html', {'form': user_auth_form}, status=200)
        return render(request, 'registration/registration.html', {'error_form': user_auth_form}, status=400)

    elif request.method == 'GET':
        loader.get_template('registration/registration.html')
        user_auth_form = UserAuthForm()
        user_extended_form = UserExtendForm()
        return render(request, 'registration/registration.html',
                      {'user_auth_form': user_auth_form, 'user_extended_form': user_extended_form})

class EventAttendeeResources(APIView):
    permission_classes = ()
    authentication_classes = ()

    @transaction.atomic
    def post(self, request, event_date, event_name):
        try:
            event_date = datetime.strptime(event_date, "%Y-%m-%d").date()
        except ValueError:
             return Response({'failue': 'event date is not well formated'},
                         status=status.HTTP_400_BAD_REQUEST)

        events = Event.objects.filter(name = event_name,
            event_date = event_date)
        if not events.exists():
            return Response({'reason': f"there is no event with the name:\
                     {event_name} and the date {str(event_date)} "},
                      status=status.HTTP_404_NOT_FOUND)

        current_event = events[0]

        attendee_first_name = request.data.get('first_name')
        attendee_last_name = request.data.get('last_name')
        number_of_guests = request.data.get('number_of_guests')

        foods  = current_event.food_types.all()
        food_list = {}

        food_types = foods.values_list('food_type', flat=True)

        for key, value in request.data.items():
            if (key  in food_types) and (value is not None) and int(value) > 0:
                food_list[key] = int(value)

        if ((attendee_first_name in [[], '', None, {}])
            or (attendee_last_name in [[], '', None, {}])
            or (food_list in [[], '', None, {}])):
            return Response({'failue': 'some of the inputs are empty'},
                        status=status.HTTP_400_BAD_REQUEST)

        food_orders = []

        for food_type, number in food_list.items():
            food_order = FoodOrder(food = foods.get(food_type=food_type),
                                number = number)
            food_order.save()
            food_orders.append(food_order)
        try:
            attendee, _ = Attendee.objects.get_or_create(
                first_name = attendee_first_name,
                last_name = attendee_last_name)
        except ValueError:
            return Response({"reason": "attendee format is wrong"},
                    status=status.HTTP_400_BAD_REQUEST)
        try:
            event_attendee = EventAttendee(event = current_event,
                attendee = attendee, number_of_guests = number_of_guests)
            event_attendee.save()
        except ValueError:
            return Response({"reason": "event_attendee format is wrong"},
                    status=status.HTTP_400_BAD_REQUEST)

        for food_order in food_orders:
            event_attendee.food_orders.add(food_order)

        return render(request, 'user/attend.html')


T = int(input())

sheldonWins = 'Bazinga!'
rajWins = 'Raj trapaceou!'
tie = 'De novo!'

for cases in range(T):
    sheldonAnswer, rajAnswer = input().split()

    case = f'Caso #{cases + 1}: '

    if sheldonAnswer == 'papel' and (rajAnswer == 'pedra' or rajAnswer == 'Spock'):
        print(case + sheldonWins)
    elif sheldonAnswer == 'tesoura' and (rajAnswer == 'papel' or rajAnswer == 'lagarto'):
        print(case + sheldonWins)
    elif sheldonAnswer == 'pedra' and (rajAnswer == 'lagarto' or rajAnswer == 'tesoura'):
        print(case + sheldonWins)
    elif sheldonAnswer == 'lagarto' and (rajAnswer == 'Spock' or rajAnswer == 'papel'):
        print(case + sheldonWins)
    elif sheldonAnswer == 'Spock' and (rajAnswer == 'tesoura' or rajAnswer == 'pedra'):
        print(case + sheldonWins)
    elif rajAnswer == 'papel' and (sheldonAnswer == 'pedra' or sheldonAnswer == 'Spock'):
        print(case + rajWins)
    elif rajAnswer == 'tesoura' and (sheldonAnswer == 'papel' or sheldonAnswer == 'lagarto'):
        print(case + rajWins)
    elif rajAnswer == 'pedra' and (sheldonAnswer == 'lagarto' or sheldonAnswer == 'tesoura'):
        print(case + rajWins)
    elif rajAnswer == 'lagarto' and (sheldonAnswer == 'Spock' or sheldonAnswer == 'papel'):
        print(case + rajWins)
    elif rajAnswer == 'Spock' and (sheldonAnswer == 'tesoura' or sheldonAnswer == 'pedra'):
        print(case + rajWins)
    elif sheldonAnswer == rajAnswer:
        print(case + tie)


import unittest
from dictlib.convert import Converter, JsonConverter
from dictlib.schema import Schema, UnicodeField, DatetimeField
import datetime

class TestConverter(unittest.TestCase):
    def test_from_schema_exclude(self):
        # test if fields are excluded correctly
        converter = Converter(exclude=[u'x', u'y'])
        self.assertEquals({u'z': u'c'}, converter.from_schema({u'x': u'a',
                                                               u'y': u'b',
                                                               u'z': u'c'}))

    def test_to_schema_exclude(self):
        # nothing should happen when converting to the schema
        converter = Converter(exclude=[u'x', u'y'])
        self.assertEquals({u'x': u'a', u'y': u'b', u'z': u'c'},
                          converter.to_schema({u'x': u'a', u'y': u'b', u'z': u'c'}))

    def test_schema_exclude_recursive(self):
        converter = Converter(exclude=[u'a.b'])
        self.assertEquals({u'a': {}, u'x': u'y'},
                           converter.from_schema({u'a': {u'b': 666},
                                                  u'x': u'y'}))

    def test_from_schema_rename(self):
        # test if fields are renamed correctly
        converter = Converter(rename=[(u'x', u'g'), (u'y', u'h')])
        self.assertEquals({u'g': u'a', u'h': u'b', u'z': u'c'},
                          converter.from_schema({u'x': u'a',
                                                 u'y': u'b',
                                                 u'z': u'c'}))

    def test_to_schema_rename(self):
        # test if fields are reverse-renamed correctly
        converter = Converter(rename=[(u'x', u'g'), (u'y', u'h')])
        self.assertEquals({u'x': u'a', u'y': u'b', u'z': u'c'},
                          converter.to_schema({u'g': u'a',
                                               u'h': u'b',
                                               u'z': u'c'}))
    def test_rename_inverse(self):
        converter = Converter(rename=[(u'x', u'g'), (u'y', u'h')])
        doc = {u'x': u'a', u'y': u'b', u'z': u'c'}
        self.assertEquals(doc, converter.to_schema(converter.from_schema(doc)))

        doc = {u'g': u'a', u'h': u'b', u'z': u'c'}
        self.assertEquals(doc,
                          converter.from_schema(converter.to_schema(doc)))

    def test_converter_rename_and_exclude(self):
        # test if fields are reverse-renamed correctly
        converter = Converter(exclude=[u'x'],
                              rename=[(u'z', u'i')])
        self.assertEquals({u'y': u'b', u'i': u'c'},
                converter.from_schema({u'x': u'a', u'y': u'b', u'z': u'c'}))
        self.assertEquals({u'y': u'b', u'z': u'c'},
                converter.to_schema({u'y': u'b', u'i': u'c'}))

        # test Converter where order of exclude and rename is important
        # (here, 'x' is excluded first, and then *not* renamed because)
        converter = Converter(exclude=[u'x'],
                              rename=[(u'x', u'a')])
        self.assertEquals({u'y': u'b'}, converter.from_schema({u'x': u'a', u'y': u'b'}))

    def test_map_from(self):
        class MyConverter(Converter):
            def map_from(self, key, value):
                if isinstance(value, unicode):
                    value = u'YYY%s' % value
                return key, value

            def map_to(self, key, value):
                if isinstance(value, unicode) and value.startswith(u'YYY'):
                    value = value[3:]
                return key, value

        converter = MyConverter()
        self.assertEquals({u'x': u'YYYa'},
                          converter.from_schema({u'x': u'a'}))

    def test_json_converter(self):
        schema = Schema({u'a': UnicodeField(),
                         u'b': DatetimeField()})
        json_converter = JsonConverter(schema)
        result_doc = json_converter.from_schema({u'a': u'x',
                                                 u'b': datetime.datetime(2011, 9, 11, 17, 29, 0)})
        self.assertEquals({'a': 'x', 'b': '2011-09-11T17:29:00Z'}, result_doc)
        self.assertEquals({'a': 'x',
                           'b': '2011-09-11T17:29:00Z'},
                          json_converter.from_schema({u'a': u'x',
                                                      u'b': datetime.datetime(2011, 9, 11, 17, 29, 0)}))
        self.assertTrue(isinstance(result_doc.keys()[0], str))
        self.assertTrue(isinstance(result_doc.keys()[1], str))
        self.assertTrue(isinstance(result_doc['a'], str))
        self.assertEquals({u'a': u'x',
                           u'b': datetime.datetime(2011, 9, 11, 17, 29, 0)},
                          json_converter.to_schema({'a': u'x',
                                                    'b': '2011-09-11T17:29:00Z'}))


from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from urllib.parse import urlparse

class DefaultPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 30

    def get_paginated_response(self, data):
        return Response(
            {
                "links": {
                    "next": self.get_next_link(),
                    "previous": self.get_previous_link(),
                    "current": self.request.query_params.get("page", 1),
                },
                "total_items": self.page.paginator.count,
                "total_pages": self.page.paginator.num_pages,
                "results": data,
            }
        )


import os,re
path="C:/Users/86740/Desktop/Python学习/第一阶段作业/task"
dirs=os.listdir(path)
for filename in dirs:
            txt=""
            file=open("C:/Users/86740/Desktop/Python学习/第一阶段作业/task/"+filename,"r" )
            file_content=file.readlines()
            file.close()
            for line in file_content:
                        for character in line:
                                    if(character.isdigit()):
                                                character=character.replace(character,"")
                                    txt=txt+character

            print(txt)
            file=open("C:/Users/86740/Desktop/Python学习/第一阶段作业/task/"+filename,"w")
            file.write(txt)
            file.close()


import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.utils import shuffle
from sklearn.metrics import accuracy_score
from flaskr.task2 import data_cleansing, get_data
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression,SGDClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC,LinearSVC
import matplotlib.pyplot as plt
from sklearn.model_selection import learning_curve
import numpy as np
from sklearn.model_selection import ShuffleSplit
from sklearn.neural_network import MLPClassifier
import json

def load_data(file_path,split_percentage):
    #use get_data method
    df=get_data(file_path)
    df=data_cleansing(df)
    # the shuffle function alters the data seq
    df = shuffle(df)
    input_val = df.drop('target', axis=1).values
    output_val = df['target'].values

    split_point = int(len(input_val) * split_percentage)
    input_train = input_val[:split_point]
    output_train = output_val[:split_point]
    input_test = input_val[split_point:]
    output_test = output_val[split_point:]

    return input_train, output_train, input_test, output_test

# 0 incurrs person is healthy
# 1 incurrs person is infected
def assign_labels(row):
    if row['target']==0:
        return 0
    else:
        return 1

# assign labels to exisitng data frame based on target values
def load_labelled_data(split_percentage):
    file_path='processed.cleveland.data'
    df=get_data(file_path)
    df=data_cleansing(df)
    df=shuffle(df)
    # add column label which is derived from target
    df['label']=df.apply(lambda row: assign_labels(row), axis=1)
    # remove label and target columns as they won't be a part of user input
    input_data=df.drop(['label','target'], axis=1).values
    output_data=df['label'].values
    # define split point
    split_point = int(len(input_data) * split_percentage)
    # split data to train and test values
    input_train=input_data[:split_point]
    output_train=output_data[:split_point]
    input_test=input_data[split_point:]
    output_test=output_data[split_point:]

    return input_train,output_train,input_test,output_test

# UserData should be a list of user inputs
# for eg [[34.0,1.0,1.0,118.0,182.0,0.0,2.0,174.0,0.0,0.0,1.0,0.0,3.0]]
def predict_data(UserData):
    input_train, output_train, _, _ = load_labelled_data(split_percentage=0.99)
    GNB=GaussianNB()
    GNB.fit(input_train,output_train)
    #print(GNB.predict(UserData).tolist())
    # return values are either [0] or [1] depending if person is healthy or infected
    return (GNB.predict(UserData))

# return the accurcy of each classifier
def accuracy_analysis():
    iris_X, iris_y, _, _ = load_labelled_data(split_percentage=1)
    classifiers = [KNeighborsClassifier(),
                   DecisionTreeClassifier(),
                   LinearDiscriminantAnalysis(),
                   LogisticRegression(solver="lbfgs",max_iter=2000),
                   GaussianNB(priors=None, var_smoothing=1e-09),
                   SGDClassifier(max_iter=1000, tol=1e-3),
                   MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(5, 2), random_state=1)]
    classifier_accuracy_list = []
    for i, classifier in enumerate(classifiers):
        # split the dataset into 5 folds; then test the classifier against each fold one by one
        accuracies = cross_val_score(classifier, iris_X, iris_y, cv=10)
        classifier_accuracy_list.append((accuracies.mean(), type(classifier).__name__))
    classifier_accuracy_list = sorted(classifier_accuracy_list, reverse=True)
    for item in classifier_accuracy_list:
        print(item[1], ':', item[0])
    return classifier_accuracy_list

def plot_learning_curve(estimator, title, X, y, ylim=(0.7, 1.01), cv=None,
                        n_jobs=None, train_sizes=np.linspace(.1, 1.0, 5)):
    plt.figure()
    plt.title(title)
    if ylim is not None:
        plt.ylim(*ylim)
    # assign labels to coordinates
    plt.xlabel("Training examples")
    plt.ylabel("Score")
    train_sizes, train_scores, test_scores = learning_curve(
        estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    plt.grid()

    plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
                     train_scores_mean + train_scores_std, alpha=0.1,
                     color="r")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
                     test_scores_mean + test_scores_std, alpha=0.1, color="g")
    plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
             label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
             label="Cross-validation score")

    plt.legend(loc="best")
    return plt

def build_json(estimator=GaussianNB(),n_jobs=4,train_sizes=np.linspace(.1, 1.0, 5)):
    X, y, _, _ = load_labelled_data(split_percentage=0.90)
    cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0)
    train_sizes, train_scores, test_scores = learning_curve(
        estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    result=[]
    obj={}

    title={}
    title['text']=type(estimator).__name__
    obj['title']=title

    xAxis={}
    title['text']='Accuracy'
    xAxis['title']=title
    obj['xAxis']=xAxis

    yAxis={}
    title['text']='Iterations'
    yAxis['title']=title
    obj['yAxis']=yAxis

    #series property
    series=[]
    #line1 data
    line1={}
    line1['name']='Training score'
    data=[]
    for i,j in zip(train_sizes,train_scores_mean):
        data_sub=[]
        data_sub.append(float(i))
        data_sub.append(float(j))
        data.append(data_sub)
    line1['data']=data
    line1['zIndex']=1
    marker={}
    marker['fillColor']='white'
    marker['lineWidth']=2
    marker['lineColor']='red'
    line1['marker']=marker
    line1['lineColor']='red'
    series.append(line1)
    range1={}
    range1['name']='Range1'
    data=[]
    for i,j,k in zip(train_sizes,train_scores_mean-train_scores_std,train_scores_mean+train_scores_std):
        data_sub=[]
        data_sub.append(float(i))
        data_sub.append(float(j))
        data_sub.append(float(k))
        data.append(data_sub)
    range1['data']=data
    range1['type']='arearange'
    range1['lineWidth']=0
    range1['linkedTo']=':previous'
    range1['color']='rgb(196, 10, 0)'
    range1['fillOpacity']=0.2
    range1['zIndex']=0
    marker={}
    marker['enabled']="false"
    range1['marker']=marker
    series.append(range1)
    #line2 data
    line2={}
    line2['name']='Test Score'
    data=[]
    for i,j in zip(train_sizes,test_scores_mean):
        data_sub=[]
        data_sub.append(float(i))
        data_sub.append(float(j))
        data.append(data_sub)
    line2['data']=data
    line2['zIndex']=2
    marker={}
    marker['fillColor']='white'
    marker['lineWidth']=2
    marker['lineColor']='green'
    line2['marker']=marker
    line2['lineColor']='green'
    series.append(line2)
    range2={}
    range2['name']='Range2'
    data=[]
    for i,j,k in zip(train_sizes,test_scores_mean-test_scores_std,test_scores_mean+test_scores_std):
        data_sub=[]
        data_sub.append(float(i))
        data_sub.append(float(j))
        data_sub.append(float(k))
        data.append(data_sub)
    range2['data']=data
    range2['type']='arearange'
    range2['lineWidth']=0
    range2['linkedTo']=':previous'
    range2['color']='rgb(19, 196, 0)'
    range2['fillOpacity']=0.2
    range2['zIndex']=0
    marker={}
    marker['enabled']="false"
    range2['marker']=marker
    series.append(range2)

    obj['series']=series
    # obj=json.dumps(obj)
    result.append(obj)
    return result

if __name__ == '__main__':
    file_path='processed.cleveland.data'

    # input_train, output_train, input_test, output_test = load_labelled_data(split_percentage=1)
    estimator = GaussianNB()
    # title = "Learning Curves (Naive Bayes)"
    # cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0)
    # plot_learning_curve(DecisionTreeClassifier(), title, input_train, output_train, ylim=(0.5, 1.01), cv=cv, n_jobs=4)
    # plt.show()
    '''estimators=[KNeighborsClassifier(),
                   DecisionTreeClassifier(),
                   LinearDiscriminantAnalysis(),
                   LogisticRegression(solver="lbfgs",max_iter=2000),
                   GaussianNB(priors=None, var_smoothing=1e-09),
                   SGDClassifier(max_iter=1000, tol=1e-3),
                   ]'''
    '''To use the build_json function use any estimator mentioned above'''
    #For eg. build_json(GaussianNB())
    json_data=build_json(estimator)
    print(json_data)


# coding:utf-8

from functools import wraps

from Crypto.Cipher import AES

class CustomException(Exception):
    def __init__(self, msg=None, code=None):
        super(BaseException, self).__init__()
        self.msg = msg
        self.code = code

    def __str__(self):
        return u"code:{0}, msg:{1}".format(self.msg, self.code)

class NeedCaptchaError(CustomException):
    def __init__(self, msg=None, code=None):
        super(NeedCaptchaError, self).__init__()
        self.msg = msg or u"需要图片验证码"
        self.code = code or 10001

class CaptchaError(CustomException):
    def __init__(self, msg=None, code=None):
        super(CaptchaError, self).__init__()
        self.msg = msg or u"图片验证码错误"
        self.code = code or 10002

def aes_decrypt(raw_str, key, iv, mode=None):
    try:
        if isinstance(raw_str, unicode):
            raw_str = raw_str.decode("hex")
        if isinstance(key, unicode):
            key = key.encode("utf-8")
        mode = mode or AES.MODE_CBC
        cipher = AES.new(key=key, IV=iv, mode=mode)
        msg = cipher.decrypt(raw_str)
        padding_len = 0 if len(msg) % len(key) == 0 else ord(msg[-1])
        ret = msg[:-padding_len].decode("utf-8")
        return ret
    except Exception as e:
        raise e

def catch_exception(func):
    @wraps(func)
    def _handle(self, response):
        logger = self.logger
        logger.debug("--->func:{0}, status:{1}, url:{2}".format(func.__name__, response.status, response.url))
        try:
            ret = func(self, response)
            return ret
        except Exception as e:
            logger.exception("--->func:{0}, error:{1}".format(func.__name__, str(e)))
            return

    return _handle


# practice.py

import random

def dice(count = 3, sides = 6):
	num = 0
	for d in range(count):
		num+= random.randint(1,sides)
	return num

stats = {
	'str' : 0,
	'int' : 0,
	'wis' : 0,
	'dex' : 0,
	'con' : 0,
	'cha' : 0,
}

for key in stats.keys():
	stats[key] = dice()

if __name__ == "__main__":
	print(stats)


from prettytable import PrettyTable
from utils import *

class Node:

   def __init__(self, name):
       self.parent = 0
       self.name = name
       self.edges = []
       self.value = 0

class Edge:
   #self ist der Konstruktor
   def __init__(self, edge):
      self.start = edge[0]
      self.end = edge[1]
      self.value = edge[2]

class Graph:

   def __init__(self, node_list, edges):
      self.nodes = []
      for name in node_list:
         self.nodes.append(Node(name))

      for e in edges:
        e = (getNode(e[0],self.nodes), getNode(e[1], self.nodes), e[2])

        self.nodes[next((i for i,v in enumerate(self.nodes) if v.name == e[0].name), -1)].edges.append(Edge(e))
        self.nodes[next((i for i,v in enumerate(self.nodes) if v.name == e[1].name), -1)].edges.append(Edge((e[1], e[0], e[2])))

   def print(self):
      node_list = self.nodes

      t = PrettyTable(['  '] +[i.name for i in node_list])
      for node in node_list:
         edge_values = ['X'] * len(node_list)
         for edge in node.edges:
            edge_values[ next((i for i,e in enumerate(node_list) if e.name == edge.end.name) , -1)] = edge.value
         t.add_row([node.name] + edge_values)
      print(t)

romania = Graph( ['Or', 'Ne', 'Ze', 'Ia', 'Ar', 'Si', 'Fa',
 'Va', 'Ri', 'Ti', 'Lu', 'Pi', 'Ur', 'Hi',
 'Me', 'Bu', 'Dr', 'Ef', 'Cr', 'Gi'],
[
   ('Or', 'Ze', 71), ('Or', 'Si', 151),
   ('Ne', 'Ia', 87), ('Ze', 'Ar', 75),
   ('Ia', 'Va', 92), ('Ar', 'Si', 140),
   ('Ar', 'Ti', 118), ('Si', 'Fa', 99),
   ('Si', 'Ri', 80), ('Fa', 'Bu', 211),
   ('Va', 'Ur', 142), ('Ri', 'Pi', 97),
   ('Ri', 'Cr', 146), ('Ti', 'Lu', 111),
   ('Lu', 'Me', 70), ('Me', 'Dr', 75),
   ('Dr', 'Cr', 120), ('Cr', 'Pi', 138),
   ('Pi', 'Bu', 101), ('Bu', 'Gi', 90),
   ('Bu', 'Ur', 85), ('Ur', 'Hi', 98),
   ('Hi', 'Ef', 86)
])

class Queue:
    procedure = 'lifo'
    structeredData = list()

    def __init__(self, procedure):
        if (procedure in {'lifo', 'fifo', 'prio'}):
            self.procedure = procedure
            self.structeredData = list()
        else:
            print("Invalid Constructor Parameter")

    def push(self, data):
      if (self.procedure == 'lifo'):
         self.structeredData.insert(0, data)
      elif (self.procedure == 'fifo'):
         self.structeredData.append(data)
      elif (self.procedure == 'prio'):
         total_cost, node = data
         index = 0
         while (index < len(self.structeredData) and int(self.structeredData[index][0]) < total_cost):
               index += 1
         if (index >= len(self.structeredData)):
               self.structeredData.append((total_cost, node))
         else:
               self.structeredData.insert(index, (total_cost, node))

    def pop(self):
        if (not self.structeredData):  # empty Queue
            print('Queue is empty!!')
            return None
        else:
            return self.structeredData.pop(0)

    def contains(self, value):
        for element in self.structeredData:
            if(value == element):
                return True
        return False

    def empty(self):
        return (not self.structeredData)

    def contains(self, val):
        return val in self.structeredData

    def print(self):
        for element in self.structeredData:
            print(element, end=' , ')
        print('')

#nachbarn aus der adjazenzmatrix entnehmen
def neighbors(node_name):
   map = []
   for node in romania.nodes:
      if(node.name == node_name):
         for edges in node.edges:
            map.append({
                  "from": edges.start.name,
                  "to": edges.end.name,
                  "cost": edges.value
                })

   return map

"""
liste = adj_matrix('Or')
for edge in liste:
        print(edge['cost'])
"""
# minimum total cost - takes the cheapest path

def ucs(start_node,end_node):
    visited = set()
    queue = Queue('prio')
    start = getNode(start_node,romania.nodes)
    queue.push((0,start))
    paths = {start: [start]}
    while not queue.empty():
        r = queue.pop()
        cost = int(r[0])
        node = r[1]

        if node not in visited:
            visited.add(node)

            if node.name == end_node:
                return paths[node]
            n = neighbors(node.name)
            for neigh in n:
                toNode = getNode(neigh['to'], romania.nodes)
                if toNode not in visited:
                    total_cost = cost + int(neigh['cost'])
                    if toNode not in paths:
                        paths[toNode] = paths[node] + [toNode]
                    queue.push((total_cost,toNode))

def bfs(start_node, end_node):
    visited = []
    queue = Queue('fifo')
    start = getNode(start_node,romania.nodes)
    end = getNode(end_node,romania.nodes)
    queue.push(start)
    while not queue.empty():
        node = queue.pop()
        if node == end:
            visited.append(node)
            break
        if node not in visited:
            visited.append(node)
           #print(node.name)
            n = neighbors(node.name)
            for neighbour in n:
                neighbor_node = getNode(neighbour['to'], romania.nodes)
                if neighbor_node not in visited:
                    neighbor_node.parent = node
                    queue.push(neighbor_node)
    if end not in visited:
        print("Ziel nicht enthalten!")
        return []
    path = []
    node = end
    while node != start:
        path.insert(0, node)
        node = node.parent
    path.insert(0, start)
    return path

def dfs(start_node, end_node, path=None, visited=None):
    if path is None:
        path = []
    if visited is None:
        visited = set()

    start = getNode(start_node, romania.nodes)

    path.append(start)
    visited.add(start)

    if start.name == end_node:

        return path
    n = neighbors(start.name)
    for neigh in n:
        new_neigh = getNode(neigh['to'],romania.nodes)
        if new_neigh not in visited:
            result = dfs(neigh['to'], end_node, path, visited)
            if result is not None:
                return result
    path.pop()
    return path

bfs_test = bfs("Bu","Ti")
for t in bfs_test:
    print("BFS " +t.name)
print("\n")

dfs_test = dfs("Bu", "Ti")

for t in dfs_test:
    print( "DFS " + t.name)

print("\n")

ucs_test = ucs("Bu", "Ti")

for t in ucs_test:
    print("UCS " +t.name)


"""
function for molecule
"""

from .measure import *

def build_bond_list(coordinates, max_bond=1.5, min_bond=0):

    # Find the bonds in a molecule
    bonds = {}
    num_atoms = len(coordinates)
    if min_bond < 0:
        raise ValueError("minimum bond should be more then zero.")
    for atom1 in range(num_atoms):
        for atom2 in range(atom1, num_atoms):
            distance = calculate_distance(coordinates[atom1], coordinates[atom2])
            if distance > min_bond and distance < max_bond:
                bonds[(atom1, atom2)] = distance

    return bonds


import json
import os
from scene import Scene

class ModelController:
    def __init__(self, game_file_directory: str):
        self.game_data = {}
        self.game_file_directory = game_file_directory
        self._load_game_data()     # Populate the game_data dict

    def _is_valid_game_file_directory(self):
        return os.path.exists(self.game_file_directory)

    def _load_game_data(self):
        """
        Populates the game_data dict with a SceneFile object for each
        game file in the game_file directory.
        """
        if not self._is_valid_game_file_directory():
            raise Exception("Invalid game file directory")
        else:
            for file in os.listdir(self.game_file_directory):
                scene = Scene()
                if str(file).endswith("json"):
                    try:
                        with open(self.game_file_directory + file) as f:
                            json_file = json.load(f)
                            scene.scene_id = json_file["scene_id"]
                            scene.presentation_style = json_file[
                                "presentation_style"
                                ]
                            scene.print_slowly = json_file["print_slowly"]
                            scene.options_string = json_file["options_string"]
                            scene.choice_target_dict = json_file[
                                "choice_target_dict"
                                ]
                            try:
                                scene.roll_message = json_file["roll_message"]
                            except Exception:
                                print("no roll message")
                            self.game_data[scene.scene_id] = scene
                    except Exception:
                        raise Exception("Unable to update Scene object from " +
                                        "JSON file.")

            for file in os.listdir(self.game_file_directory):
                if str(file).endswith("txt"):
                    try:
                        with open(self.game_file_directory + file) as f:
                            list_text = f.readlines()
                            scene_string = ""
                            for line in list_text:
                                scene_string += line

                            file_prefix = os.path.splitext(file)[0]
                            if file_prefix in self.game_data.keys():
                                tmp_scene_object = self.game_data[file_prefix]
                                tmp_scene_object.scene_string = scene_string
                                print(tmp_scene_object.scene_string)
                    except Exception:
                        raise Exception("Unable to open game text file.")