# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

import ast
from math import *

import bpy
from bpy.props import BoolProperty, StringProperty, EnumProperty, FloatVectorProperty, IntProperty
from mathutils import Vector
import json
import io

from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import fullList, updateNode, dataCorrect, match_long_repeat

"""
JSON format:
    {
        "vertices": [[1, 2, 3], [2, 3, 4], [4,5,6]],
        "edges": [[0,1]],
        "faces": [[0,1,2]]
    }
    In vertices list, any of numbers can be replaced by string (variable name).
"""

# To be extended?
safe_names = dict(sin=sin, cos=cos, pi=pi, sqrt=sqrt)

def get_variables(string):
    root = ast.parse(string, mode='eval')
    result = {node.id for node in ast.walk(root) if isinstance(node, ast.Name)}
    return result.difference(safe_names.keys())

# It could be safer...
def safe_eval(string, variables):
    env = dict()
    env.update(safe_names)
    env.update(variables)
    env["__builtins__"] = {}
    root = ast.parse(string, mode='eval')
    return eval(compile(root, "<expression>", 'eval'), env)

def evaluate(json, variables):
    result = {}
    result['edges'] = json['edges']
    result['faces'] = json['faces']
    result['vertices'] = []

    groups = {}

    for idx, vertex in enumerate(json['vertices']):
        v = []
        if isinstance(vertex, (list, tuple)) and len(vertex) == 3:
            coords = vertex
        elif isinstance(vertex, (list, tuple)) and len(vertex) == 4 and isinstance(vertex[-1], (str, list, tuple)):
            coords = vertex[:-1]
            g = vertex[-1]
            if isinstance(g, str):
                groupnames = [g]
            else:
                groupnames = g
            for groupname in groupnames:
                if groupname in groups:
                    groups[groupname].append(idx)
                else:
                    groups[groupname] = [idx]

        for c in coords:
            if isinstance(c, str):
                try:
                    val = safe_eval(c, variables)
                    #self.debug("EVAL: {} with {} => {}".format(c, variables, val))
                except NameError as e:
                    self.exception(e)
                    val = 0.0
            else:
                val = c
            v.append(val)
        result['vertices'].append(v)
    return result, groups

def selected_masks_adding(node):
    """ adding new list masks nodes if none """
    if node.outputs[0].is_linked: return
    loc = node.location

    tree = bpy.context.space_data.edit_tree
    links = tree.links

    mo = tree.nodes.new('MaskListNode')
    mv = tree.nodes.new('SvMoveNodeMK2')
    rf = tree.nodes.new('SvGenNumberRange')
    vi = tree.nodes.new('GenVectorsNode')
    mi = tree.nodes.new('SvMaskJoinNode')
    vd = tree.nodes.new('ViewerNode2')
    mo.location = loc+Vector((300,0))
    mv.location = loc+Vector((550,0))
    vi.location = loc+Vector((350,-225))
    rf.location = loc+Vector((0,-225))
    mi.location = loc+Vector((800,0))
    vd.location = loc+Vector((1000,0))

    links.new(node.outputs[0], mo.inputs[0])   #verts
    links.new(node.outputs[3], mo.inputs[1])   #mask
    links.new(mo.outputs[0], mi.inputs[0])   #mask
    links.new(mo.outputs[3], mv.inputs[0])   #True out
    links.new(vi.outputs[0], mv.inputs[1])   #vector
    links.new(rf.outputs[0], vi.inputs[2])   #range
    links.new(mv.outputs[0], mi.inputs[1])   #True in
    links.new(mo.outputs[4], mi.inputs[2])   #False
    links.new(mi.outputs[0], vd.inputs[0])   #Verts
    links.new(node.outputs[2], vd.inputs[1])   #Faces
    mi.Level = 2
    mo.level = 2
    rf.mode='FRANGE_COUNT'
    rf.stop_=4
    rf.count_=4

class SvJsonFromMesh(bpy.types.Operator):
    "JSON from selected mesh"
    bl_idname = "node.sverchok_json_from_mesh"
    bl_label = "JSON from mesh"
    bl_options = {'REGISTER'}

    nodename: StringProperty(name='nodename')
    treename: StringProperty(name='treename')

    def execute(self, context):
        node = bpy.data.node_groups[self.treename].nodes[self.nodename]
        if not bpy.context.selected_objects[0].type == 'MESH':
            node.info("JSON from mesh: selected object is not mesh")
            self.report({'INFO'}, 'It is not a mesh selected')
            return

        object = bpy.context.selected_objects[0]
        mesh = object.data
        result = {}
        verts = []
        isselected = False
        for v in mesh.vertices:
            names = set()
            for grp in v.groups:
                name = object.vertex_groups[grp.group].name
                names.add(name)
            if v.select:
                names.add('Selected')
                isselected = True
            if names:
                vertex = self.round(v) + [list(sorted(names))]
            else:
                vertex = self.round(v)
            verts.append(vertex)

        if isselected:
            if not 'Selected' in node.inputs.keys() and not node.outputs[0].is_linked:
                node.outputs.new('SvStringsSocket', 'Selected')
                if node.sample_tree:
                    selected_masks_adding(node)
        result['vertices'] = verts
        result['edges'] = mesh.edge_keys
        result['faces'] = [list(p.vertices) for p in mesh.polygons]

        self.write_values(self.nodename, json.dumps(result, indent=2))
        bpy.data.node_groups[self.treename].nodes[self.nodename].filename = self.nodename
        return{'FINISHED'}

    def round(self, vector):
        precision = bpy.data.node_groups[self.treename].nodes[self.nodename].precision
        vector = [round(x, precision) for x in vector.co[:]]
        return vector

    def write_values(self,text,values):
        texts = bpy.data.texts.items()
        exists = False
        for t in texts:
            if bpy.data.texts[t[0]].name == text:
                exists = True
                break

        if not exists:
            bpy.data.texts.new(text)
        bpy.data.texts[text].clear()
        bpy.data.texts[text].write(values)

class SvMeshEvalNode(bpy.types.Node, SverchCustomTreeNode):
    '''Parametric mesh JSON'''
    bl_idname = 'SvMeshEvalNode'
    bl_label = 'Mesh Expression'
    bl_icon = 'OUTLINER_OB_EMPTY'
    sv_icon = 'SV_MESH_EXPRESSION'

    def on_update(self, context):
        self.adjust_sockets()
        updateNode(self, context)

    filename: StringProperty(default="", update=on_update)
    precision: IntProperty(name = "Precision",
                    description = "Number of decimal places used for coordinates when generating JSON from selection",
                    min=0, max=10, default=8,
                    update=updateNode)

    sample_tree: BoolProperty(name = "Example tree",
                    description = "Create example nodes when generating JSON from selection",
                    default = False,
                    update=updateNode)

    def draw_buttons(self, context, layout):
        row = layout.row()
        row.prop_search(self, 'filename', bpy.data, 'texts', text='', icon='TEXT')
        row = layout.row()

        do_text = row.operator('node.sverchok_json_from_mesh', text='from selection')
        do_text.nodename = self.name
        do_text.treename = self.id_data.name

    def draw_buttons_ext(self, context, layout):
        self.draw_buttons(context, layout)
        layout.prop(self, "precision")
        layout.prop(self, "sample_tree")

    def sv_init(self, context):
        self.inputs.new('SvStringsSocket', "a")

        self.outputs.new('SvVerticesSocket', "Vertices")
        self.outputs.new('SvStringsSocket', "Edges")
        self.outputs.new('SvStringsSocket', "Faces")

    def load_json(self):
        internal_file = bpy.data.texts[self.filename]
        f = io.StringIO(internal_file.as_string())
        json_data = json.load(f)
        self.validate_json(json_data)
        return json_data

    def validate_json(self, json):
        if not "vertices" in json:
            raise Exception("JSON does not have `vertices' key")
        if not "edges" in json:
            raise Exception("JSON does not have `edges' key")
        if not "faces" in json:
            raise Exception("JSON does not have `faces' key")

    def get_variables(self):
        variables = set()
        json = self.load_json()
        if not json:
            return variables

        for vertex in json["vertices"]:
            if isinstance(vertex, (list, tuple)) and len(vertex) == 3:
                coords = vertex
            elif isinstance(vertex, (list, tuple)) and len(vertex) == 4 and isinstance(vertex[-1], (str, list, tuple)):
                coords = vertex[:-1]

            for c in coords:
                if isinstance(c, str):
                    vs = get_variables(c)
                    variables.update(vs)

        return list(sorted(list(variables)))

    def get_group_names(self):
        groups = set()
        json = self.load_json()
        if not json:
            return groups

        for vertex in json["vertices"]:
            if isinstance(vertex, (list, tuple)) and len(vertex) == 4 and isinstance(vertex[-1], (str, list, tuple)):
                g = vertex[-1]
                if isinstance(g, str):
                    names = [g]
                else:
                    names = g
                for name in names:
                    if name in ['Vertices', 'Edges', 'Faces']:
                        raise Exception("Invalid name for vertex group. It should not be Vertices, Edges or Faces.")
                    groups.add(name)

        return list(sorted(list(groups)))

    def get_defaults(self):
        result = {}
        json = self.load_json()
        if not json or 'defaults' not in json:
            return result
        if not isinstance(json['defaults'], dict):
            return result
        return json['defaults']

    def adjust_sockets(self):
        variables = self.get_variables()
        #self.debug("adjust_sockets:" + str(variables))
        #self.debug("inputs:" + str(self.inputs.keys()))
        for key in self.inputs.keys():
            if key not in variables:
                self.debug("Input {} not in variables {}, remove it".format(key, str(variables)))
                self.inputs.remove(self.inputs[key])
        for v in variables:
            if v not in self.inputs:
                self.debug("Variable {} not in inputs {}, add it".format(v, str(self.inputs.keys())))
                self.inputs.new('SvStringsSocket', v)

        groups = self.get_group_names()
        for key in self.outputs.keys():
            if key in ['Vertices', 'Edges', 'Faces']:
                continue
            if key not in groups:
                self.debug("Output {} not in groups {}, remove it".format(key, str(groups)))
                self.outputs.remove(self.outputs[key])
        for name in sorted(groups):
            if name not in self.outputs:
                self.debug("Group {} not in outputs {}, add it".format(name, str(self.outputs.keys())))
                self.outputs.new('SvStringsSocket', name)

    def update(self):
        '''
        update analyzes the state of the node and returns if the criteria to start processing
        are not met.
        '''

        # keeping the file internal for now.
        if not (self.filename in bpy.data.texts):
            return

        self.adjust_sockets()

    def get_input(self):
        variables = self.get_variables()
        defaults = self.get_defaults()
        result = {}
        default_results = {}

        for var in defaults.keys():
            d = defaults[var]
            if isinstance(d, (int, float)):
                default_results[var] = d

        for var in variables:
            if var in self.inputs and self.inputs[var].is_linked:
                result[var] = self.inputs[var].sv_get()[0]
                default_results[var] = result[var][0]
            else:
                value = defaults.get(var, 1.0)
                if isinstance(value, str):
                    #self.debug("Eval: {} = {}, {}".format(var, value, default_results))
                    value = safe_eval(value, default_results)
                    default_results[var] = value
                result[var] = [value]
            #self.debug("get_input: {} => {}".format(var, result[var]))
        return result

    def groups_to_masks(self, groups, size):
        result = {}
        for name in groups:
            result[name] = [idx in groups[name] for idx in range(size)]
        return result

    def process(self):

        if not self.outputs[0].is_linked:
            return

        var_names = self.get_variables()
        inputs = self.get_input()

        result_vertices = []
        result_edges = []
        result_faces = []
        result_masks_dict = {}

        template = self.load_json()

        if var_names:
            input_values = [inputs[name] for name in var_names]
            parameters = match_long_repeat(input_values)
        else:
            parameters = [[[]]]
        for values in zip(*parameters):
            variables = dict(zip(var_names, values))

            json, groups = evaluate(template, variables)
            verts = json['vertices']
            result_vertices.append(verts)
            result_edges.append(json['edges'])
            result_faces.append(json['faces'])

            masks = self.groups_to_masks(groups, len(verts))
            for name in masks.keys():
                if name in result_masks_dict:
                    result_masks_dict[name].add(masks[name])
                else:
                    result_masks_dict[name] = [masks[name]]

        self.outputs['Vertices'].sv_set(result_vertices)
        self.outputs['Edges'].sv_set(result_edges)
        self.outputs['Faces'].sv_set(result_faces)

        for name in result_masks_dict.keys():
            self.outputs[name].sv_set(result_masks_dict[name])

    def storage_set_data(self, storage):
        geom = storage['geom']
        filename = storage['params']['filename']

        bpy.data.texts.new(filename)
        bpy.data.texts[filename].clear()
        bpy.data.texts[filename].write(geom)

    def storage_get_data(self, storage):
        if self.filename and self.filename in bpy.data.texts:
            text = bpy.data.texts[self.filename].as_string()
            storage['geom'] = text
        else:
            self.warning("Unknown filename: {}".format(self.filename))

def register():
    bpy.utils.register_class(SvJsonFromMesh)
    bpy.utils.register_class(SvMeshEvalNode)

def unregister():
    bpy.utils.unregister_class(SvJsonFromMesh)
    bpy.utils.unregister_class(SvMeshEvalNode)


import wikipedia

def print_wikipedia_results(word):
    """
    Searches for pages that match the specified word
    """
    results = wikipedia.search(word)

    for result in results:
        try:
            page = wikipedia.page(result)
        except wikipedia.exceptions.DisambiguationError:
            print('DisambiguationError')
            continue
        except wikipedia.exceptions.PageError:
            print('PageError for result: ' + result)
            continue

        print(page.summary)

if __name__ == '__main__':
    print_wikipedia_results('wombat')


from flask import Flask, render_template, url_for, redirect, request
import pandas as pd
from datetime import datetime

from Predictor import predict

app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

#@app.route("/")
#def index(res):
#    return render_template('index.html')

@app.route("/", methods=['POST'])
def handle_data():
    #projectpath = request.form['projectFilepath']
    #if request.method == "POST":
    bud = request.form["bud"]
    pop = request.form["pop"]
    runtime = request.form["runt"]
    date = request.form["rel"]
    dt = datetime.strptime(date, '%Y-%m-%d')

    weekday = dt.weekday() + 1

    data = pd.DataFrame([[bud, pop, runtime, dt.day, weekday, dt.month, dt.year]], columns=["budget", "popularity", "runtime", "release_day", "release_weekday", "release_month", "release_year"])

    print("data:", data)

    result = int(predict(data)[0])

    print ("Prediction:", result)

    return render_template("index.html", res = result)

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


__author__ = 'Ian'

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import os
import pandas as pd
import numpy as np
from sklearn.metrics import accuracy_score
from Data.scripts.data import data
from pandas.tools.plotting import autocorrelation_plot
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix

def run_strategy(Y_pred, Y_actual):

    #make negative returns 0 valued

    #Y_pred = Y_pred.where(Y_pred > 6e-06, 0)
    Y_pred = np.clip(Y_pred, a_min=0, a_max=None)

    # normalize rows to a sum of 1
    # sum the rows of the prediction, divide by that number

    Y_pred_sum = Y_pred.sum(axis=1)

    #if any sum is 0, meaning no investment, turn to 1 so as to avoid divide by 0

    #Y_pred_sum = Y_pred_sum.where(Y_pred_sum > 1e-06, 1)
    #Y_pred_sum = np.clip(Y_pred_sum, a_min= 0.01, a_max= None)
    Y_pred_sum = Y_pred_sum.replace(to_replace=0, value=1)

    Y_pred = Y_pred.divide(Y_pred_sum, axis= 'index')

    #strat_returns_series = (Y_pred.multiply(Y_actual + 1, axis= 'index')).sum(axis=1)
    strat_returns_series = (Y_pred.multiply(Y_actual, axis='index')).sum(axis=1)

    #if at any point not invested in the market, hold value

    #strat_returns_series = strat_returns_series.replace(to_replace = 0, value= 1)

    #return strat_returns_series
    return strat_returns_series + 1

def strat_metrics(strat_series):

    metrics = {}

    metrics['return'] = strat_series[-1] - 1

    risk_free = 0

    metrics['sharpe'] = ((strat_series[-1]-1) - risk_free)/(np.std(strat_series))

    metrics['max_drawdown'] = (1 - strat_series.div(strat_series.cummax())).max()

    return metrics

def returns_df_to_01(returns_df):

    for column in returns_df.columns:
        returns_df[column] = returns_df[column].where(returns_df[column] > 0, other = 0)

        returns_df[column] = returns_df[column].where(returns_df[column] == 0, other = 1)

    return returns_df.astype(int)

def find_accuracy(Y_pred, Y_actual):

    if Y_pred.shape[0] < Y_actual.shape[0]:
        Y_actual = Y_actual.loc[Y_pred.index]
    else:
        Y_pred = Y_pred.loc[Y_actual.index]

    Y_pred_01 = returns_df_to_01(returns_df= Y_pred).as_matrix().flatten()
    Y_actual_01 = returns_df_to_01(returns_df= Y_actual).as_matrix().flatten()

    return accuracy_score(y_true= Y_actual_01, y_pred= Y_pred_01)

def find_confusion_matrix(Y_pred, Y_actual):

    if Y_pred.shape[0] < Y_actual.shape[0]:
        Y_actual = Y_actual.loc[Y_pred.index]
    else:
        Y_pred = Y_pred.loc[Y_actual.index]

    Y_pred_01 = returns_df_to_01(returns_df= Y_pred).as_matrix().flatten()
    Y_actual_01 = returns_df_to_01(returns_df= Y_actual).as_matrix().flatten()

    return confusion_matrix(y_true= Y_actual_01, y_pred= Y_pred_01)

class eval_model:

    '''
    A class to evaluate models
    '''

    # def __init__(self,y_pred_file, set= 'train'):
    #
    #     self.y_pred = pd.read_csv(y_pred_file, index_col=0)
    #
    #     _, self.y_actual = data.import_data(set=set)
    #
    #     self.y_pred.columns = self.y_actual.columns

    def __init__(self,y_pred_df, y_actual_df):

        self.y_pred = y_pred_df.copy()

        self.y_actual = y_actual_df.copy()

        self.y_pred.columns = self.y_actual.columns

    def backtest(self, printer= True):

        self.strat_series = (run_strategy(Y_pred=self.y_pred, Y_actual=self.y_actual)).cumprod()

        self.strat_series.index = pd.to_datetime(self.strat_series.index, format='%Y-%m-%d %H:%M:%S')

        self.metrics = strat_metrics(self.strat_series)

        if printer:
            print(self.metrics)

    def plot_backtest(self, file_path):

        fig_ts = plt.figure()

        # Plotting
        self.strat_series.plot(rot=45)
        plt.xlabel('Date')
        plt.ylabel('Returns')
        plt.title('Time Series of Signal Returns')

        fig_ts.savefig(file_path)

    def plot_loss(self, loss_csv_path, loss_plot_path):

        loss_df = pd.read_csv(loss_csv_path, index_col=0)

        loss_series = loss_df['loss']

        fig_loss = plt.figure()
        loss_series.plot()
        # returns_series.plot(rot=45)
        # plt.gcf().autofmt_xdate()
        # myFmt = mdates.DateFormatter('%m/%Y')
        # plt.gca().xaxis.set_major_formatter(myFmt)

        # locator = mdates.MonthLocator()
        # plt.gca().xaxis.set_major_locator(locator)
        #
        # plt.gcf().autofmt_xdate()
        plt.xlabel('Epoch')
        plt.ylabel('Loss')
        plt.title('MSE Loss by Epoch')

        fig_loss.savefig(loss_plot_path)

    def accuracy(self, printer= True):

        self.accuracy_score = find_accuracy(Y_pred= self.y_pred, Y_actual= self.y_actual)

        self.confusion_matrix = find_confusion_matrix(Y_pred= self.y_pred, Y_actual= self.y_actual).ravel()

        self.confusion_matrix = self.confusion_matrix/(self.confusion_matrix.sum())

        if printer:

            print('Accuracy Score (tp + tn)/(total): {}'.format(self.accuracy_score))

            print('tn, fp, fn, tp: {}'.format(self.confusion_matrix))


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

from zope.interface import Interface
from zope.schema import InterfaceField
from zope.schema.interfaces import IField

class IClassField(IField):
    """Field requiring a valid class with an interface to validate.
    """
    schema = InterfaceField(
        required = False,
        title = u"Validation interface",
        description = u"Mandatory interface, needed to validate the value.",
        default = Interface
        )


import json
from datetime import datetime

# crud.py
# crud.py

class Teacher:
    def __init__(self, teacher_id, name, age, dob, classes_taught, contact):
        self.teacher_id = teacher_id
        self.name = name
        self.age = age
        self.dob = dob
        self.classes_taught = classes_taught
        self.contact = contact

    def cal_age(self):

        t = datetime.today()
        bd = datetime.strptime(self.dob, "%Y-%m-%d")
        age = t.year - bd.year - ((t.month, t.day) < (bd.month, bd.day))
        return age

class CRUD:
    def __init__(self, teachers):
        self.teachers = teachers

    def view(self):
        print("Teachers:")
        for i in self.teachers:
            print(  "Name: " + i.name + ", Age: " + str(i.age) + ",DOB: " + str(i.dob) +
                  ", Classes: " + str(i.classes_taught) + ", Contact: " + i.contact)

    def add(self, name, dob, classes_taught, contact):
        id = len(self.teachers) + 1
        t = Teacher(id, name, None, dob, classes_taught, contact)
        t.age = t.cal_age()  # No need to pass dob here
        self.teachers.append(t)
        print("Teacher " + name + " added")

        self.save_data()

    def update_teacher(self, teacher_id, new_name, new_dob, new_classes_taught, new_contact):
        for i in self.teachers:
            if i.teacher_id == int(teacher_id):
                i.name = new_name
                i.age = i.cal_age()
                i.dob = new_dob
                i.classes_taught = new_classes_taught
                i.contact = new_contact

                print("Teacher " + str(teacher_id) + " updated")
                break
        else:
            print("Teacher with ID " + str(teacher_id) + " not found")
        self.save_data()

    def delete_teacher(self, teacher_id):
        filterteach = []

        for i in self.teachers:
            if i.teacher_id != int(teacher_id):
                filterteach.append(i)

        self.teachers = filterteach

        print("Teacher " + str(teacher_id) + " deleted")
        self.save_data()

    def save_data(self):
        try:
            with open("tmsData.json", "w") as file:
                data = []

                for teacher in self.teachers:
                    teacher_data = {
                        "teacher_id": teacher.teacher_id,
                        "name": teacher.name,
                        "age": teacher.age,
                        "dob": teacher.dob,
                        "classes_taught": teacher.classes_taught,
                        "contact": teacher.contact
                    }
                    data.append(teacher_data)

                json.dump(data, file, indent=2)
        except Exception as e:
            print("Error saving data: " + str(e))


# -*- coding: utf-8 -*-
"""
Created on Fri Sep 23 00:22:58 2016

@author: Azunai
"""

from bs4 import BeautifulSoup
import urllib
import pandas as pd
import time
import numpy as np
from multiprocessing import Pool

uiks_file_path = 'uik.csv'
result_file_path = 'result.csv'
n_proc = 8
columns_list = ['uik',
               'voters',
               'bulletin',
               'bulletin_before_ellections',
               'bulletin_on_ellections_in_uik',
               'bulletin_on_ellections_outside_uik',
               'ended_bulletin',
               'bulletin_in_portable_box',
               'bulletin_in_stationary_box',
               'invalid_bulletin',
               'not_invalid_bulletin',
               'got_absentee_ballot',
               'given_absentee_ballot',
               'voters_by_absentee_on_uik',
               'ended_absentee_ballot',
               'given_absentee_ballot_by_tik',
               'lost_absentee_ballot',
               'lost_bulletin',
               'not_counted_bulletin',
               'votes_RODINA',
               'votes_KPKR',
               'votes_RPPS',
               'votes_ER',
               'votes_REP_GREEN',
               'votes_GP',
               'votes_LDPR',
               'votes_PARNAS',
               'votes_PR',
               'votes_GS',
               'votes_JABLOKO',
               'votes_KPRF',
               'votes_PATRIOTS',
               'votes_SR']

def parser(uik):
    uik = uik[1]
    if 'kaliningrad' not in uik['url']:
        url = uik['url'].replace('&type=0','&type=242')
        row = []
        page = ''
        row.append(uik['tik'])
        row.append(uik['uik'])
        i = 0
        while page == '' and i < 10:
            try:
                page = urllib.urlopen(url).read()
                i += 1
            except:
                time.sleep(5)
                i += 1
        if page != '':
            page = page.decode('windows-1251')
            soup = BeautifulSoup(page, from_encoding='windows-1251')
            table = soup.find('table', attrs={'bgcolor': '#ffffff'})
            tr = table.find_all('tr')
            for j in xrange(len(tr)):
                td = tr[j].find_all('td')
                if len(td)>2:
                    if j<18:
                        row.append(int(td[2].get_text()))
                    else:
                        row.append(int(str(td[2].contents[0]).replace('<b>','').replace('</b>','')))
        if len(row)<33:
            for k in xrange(33-len(row)):
                row.append(np.NaN)
        return row

if __name__ == '__main__':
    uiks = pd.read_csv(uiks_file_path,
                       delimiter = ';')
    rows  = []
    pool = Pool(processes=n_proc)
    result_list = pool.map(parser, (uik for uik in uiks.iterrows()))
    df = pd.DataFrame(data=result_list, columns=columns_list)
    df.to_csv(result_file_path, delimiter=';', encoding='utf-8')


import logging
from logging.config import dictConfig
from typing import List

import uvicorn
from fastapi import Depends, FastAPI, Query
from fastapi.routing import APIRouter

from src.auth.router import auth_router
from src.groups.router import group_router
from src.settings import logger_config, settings
from src.users.dependencies import get_current_active_user, get_user_service
from src.users.router import user_router
from src.users.schemas import UserGet
from src.users.service import UserService

dictConfig(logger_config.logger_setup)
logger = logging.getLogger("applogger")

app = FastAPI(title="user-management-project")

main_router = APIRouter()
main_router.include_router(user_router, prefix="/user", tags=["user"])
main_router.include_router(auth_router, prefix="/auth", tags=["auth"])
main_router.include_router(group_router, prefix="/group", tags=["group"])
app.include_router(main_router)

@app.get("/")
async def root():
    return {"message": "User Management Project"}

@app.get("/healthcheck")
async def healthcheck():
    logger.info(f"Testing the custom logger for route {healthcheck.__name__}")
    return {"message": "healthy"}

@app.get("/users", response_model=List[UserGet])
async def get_users(
    page: int = Query(ge=1, default=1, description="Page number"),
    limit: int = Query(ge=1, le=30, default=5, description="Number of users per page"),
    filter_by_name: str = Query(None, description="Filter users by name or surname"),
    sort_by: str = Query("created_at", description="Field to sort by"),
    order_by: str = Query("asc", description="Sort order asc or desc"),
    admin_user: UserGet = Depends(get_current_active_user),
    service: UserService = Depends(get_user_service),
) -> List[UserGet]:
    return await service.filter_users(
        page=page,
        limit=limit,
        filter_by=filter_by_name,
        sort_by=sort_by,
        order_by=order_by,
        admin_user=admin_user,
    )

# if __name__ == "__main__":
#     try:
#         uvicorn.run(
#             "src.main:app",
#             host=settings.server_host,
#             port=settings.server_port,
#             reload=True,
#             log_config=logger_config.logger_setup,
#         )
#     except Exception as e:
#         logger.error("Error: %s", "error occurred", stack_info=True, exc_info=True)


import json
import zipfile

from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import redirect, reverse
from django.template import Context, Template
from django.utils import timezone
from django.utils.datastructures import MultiValueDictKeyError
from django.utils.decorators import method_decorator
from django.utils.safestring import SafeString
from django.views.generic.detail import DetailView
from django.views.decorators.cache import cache_page

from ddm.models.core import (
    DonationBlueprint, DonationProject, Participant, QuestionnaireResponse,
    FileUploader
)
from ddm.models.logs import ExceptionLogEntry, ExceptionRaisers
from ddm.models.questions import QuestionBase

def get_participation_session_id(project):
    """
    Return id under which project related information is stored in a
    participant's session.
    """
    return f'project-{project.pk}'

def create_participation_session(request, project):
    """ Creates a new participation session if none does yet exist. """
    session_id = get_participation_session_id(project)

    if not request.session.get(session_id):
        participant = Participant.objects.create(
            project=project,
            start_time=timezone.now()
        )
        request.session[session_id] = {'participant_id': participant.id}
        request.session.modified = True
    return

class ParticipationFlowBaseView(DetailView):
    """
    Base class for participation flow views that implements base get and post
    methods, redirects and session management.
    """
    model = DonationProject
    context_object_name = 'project'

    steps = [
        'briefing',
        'data-donation',
        'questionnaire',
        'debriefing'
    ]
    participant = None
    current_step = None
    step_name = None

    def setup(self, request, *args, **kwargs):
        """ Initialize attributes shared by all participation steps. """
        super().setup(request, *args, **kwargs)
        self._initialize_values(request)

    def get(self, request, *args, **kwargs):
        # Redirect to previous step if necessary.
        if not self.steps[self.current_step] == self.step_name:
            return redirect(self.steps[self.current_step], slug=self.object.slug)

        # Render current view.
        context = self.get_context_data(object=self.object)
        self.extra_before_render(request)
        return self.render_to_response(context)

    def post(self, request, *arges, **kwargs):
        # Account for 'page back' action in browser
        if self.steps[self.current_step] == self.step_name:
            self.set_step_completed()
            return redirect(self.steps[self.current_step + 1],
                            slug=self.object.slug)
        else:
            return redirect(self.steps[self.current_step], slug=self.object.slug)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'default_header_left': getattr(settings, 'DDM_DEFAULT_HEADER_IMG_LEFT', None),
            'default_header_right': getattr(settings, 'DDM_DEFAULT_HEADER_IMG_RIGHT', None),
        })
        return context

    def get_participant_from_session(self, request):
        """
        Gets participant from session. If participant has not yet been created,
        creates new participant and saves it to session.
        """
        session_id = get_participation_session_id(self.object)
        participant_id = request.session[session_id]['participant_id']
        try:
            participant = Participant.objects.get(pk=participant_id)
        except Participant.DoesNotExist:
            participant = Participant.objects.create(
                project=self.object,
                start_time=timezone.now()
            )
            request.session[session_id]['participant_id'] = participant.id
            request.session.modified = True
        return participant

    @staticmethod
    def get_current_step_from_participant(participant):
        """
        Gets current step from information stored in participant's session.
        """
        step = participant.current_step
        if step is None:
            current_step = 0
            participant.current_step = 0
            participant.save()
        else:
            current_step = step
        return current_step

    def set_step_completed(self):
        """
        Updates the last_completed_step attribute in current session.
        """
        self.participant.current_step += 1
        self.participant.save()
        return

    def extra_before_render(self, request):
        """
        Placeholder for stage specific code executed before rendering the
        response.
        """
        pass

    def _initialize_values(self, request):
        self.object = self.get_object()
        create_participation_session(request, self.object)
        self.participant = self.get_participant_from_session(request)
        self.current_step = self.get_current_step_from_participant(self.participant)
        return

def participation_redirect_view(request, slug):
    """
    Redirect user to briefing page if url does not contain a step indicator.
    """
    return redirect('briefing', slug)

class BriefingView(ParticipationFlowBaseView):
    template_name = 'ddm/public/briefing.html'
    step_name = 'briefing'

    def post(self, request, *args, **kwargs):
        """
        Checks whether participant has provided briefing consent to continue with
        the study. If briefing consent is not given, redirects to end page.
        If briefing consent is not within the expected values, the briefing page
        is again returned with a form error.
        """
        # Check briefing consent if enabled for project.
        if self.get_object().briefing_consent_enabled:
            return self.check_consent(request, **kwargs)

        return super().post(request, **kwargs)

    def check_consent(self, request, **kwargs):
        """
        Checks whether post data contains information on briefing consent.
        Renders briefing view with error message if consent information is invalid.
        Renders debriefing view if no consent has been given.
        Renders next step if consent has been given.
        """
        # Check that answer has been provided and is valid.
        consent = request.POST.get('briefing_consent', None)
        if consent not in ['0', '1']:
            # Render briefing view again with error message.
            context = self.get_context_data(object=self.object)
            context.update({'briefing_error': True})
            return self.render_to_response(context)

        # Save consent to participant data.
        self.participant.extra_data['briefing_consent'] = consent
        self.participant.save()

        if consent == '0':
            # Redirect to debriefing page.
            self.participant.current_step = len(self.steps) - 1
            self.participant.save()
            return redirect(self.steps[-1], slug=self.object.slug)
        else:
            return super().post(request, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['participant'] = self.participant
        template_context = {
            'participant': self.participant.get_context_data()
        }
        briefing_template = Template(self.object.briefing_text)
        context['briefing'] = briefing_template.render(Context(template_context))
        return context

    def extra_before_render(self, request):
        """ Extract URL parameters if this option has been enabled. """
        if self.object.url_parameter_enabled:
            # Only extract URL parameters on the first call of the view.
            if not self.participant.extra_data['url_param']:
                for param in self.object.get_expected_url_parameters():
                    self.participant.extra_data['url_param'][param] = request.GET.get(param, None)
                self.participant.save()
        return

@method_decorator(cache_page(0), name='dispatch')
class DataDonationView(ParticipationFlowBaseView):
    template_name = 'ddm/public/data_donation.html'
    step_name = 'data-donation'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['uploader_configs'] = SafeString(self.get_uploader_configs())
        context['project_id'] = self.object.pk
        return context

    def get_uploader_configs(self):
        project_uploaders = FileUploader.objects.filter(project=self.object)
        uploader_configs = [fu.get_configs(self.participant.get_context_data()) for fu in project_uploaders]
        return json.dumps(uploader_configs)

    def post(self, request, *args, **kwargs):
        super().post(request, **kwargs)  # TODO: Check if this is obsolete
        self.process_uploads(request.FILES)
        redirect_url = reverse(self.steps[self.current_step + 1],
                               kwargs={'slug': self.object.slug})
        return HttpResponseRedirect(redirect_url)

    def process_uploads(self, files):
        try:
            file = files['post_data']
        except MultiValueDictKeyError as err:
            msg = ('Data Donation Processing Exception: Did not receive '
                   f'expected data file from client. {err}')
            ExceptionLogEntry.objects.create(
                project=self.object,
                raised_by=ExceptionRaisers.SERVER,
                message=msg
            )
            return

        if not zipfile.is_zipfile(file):
            msg = ('Data Donation Processing Exception: Data file received '
                   'from client is not a zip file.')
            ExceptionLogEntry.objects.create(
                project=self.object,
                raised_by=ExceptionRaisers.SERVER,
                message=msg
            )
            return

        # Check if zip file contains expected file.
        unzipped_file = zipfile.ZipFile(file, 'r')
        if 'ul_data.json' not in unzipped_file.namelist():
            msg = ('Data Donation Processing Exception: "ul_data.json" is not '
                   'in namelist.')
            ExceptionLogEntry.objects.create(
                project=self.object,
                raised_by=ExceptionRaisers.SERVER,
                message=msg
            )
            return

        # Process donation data.
        try:
            file_data = json.loads(unzipped_file.read('ul_data.json').decode('utf-8'))
        except UnicodeDecodeError:
            try:
                file_data = json.loads(unzipped_file.read('ul_data.json').decode('latin-1'))
            except ValueError:
                msg = (
                    'Donated data could not be decoded - '
                    'tried both utf-8 and latin-1 decoding.'
                )
                ExceptionLogEntry.objects.create(
                    project=self.object,
                    raised_by=ExceptionRaisers.SERVER,
                    message=msg
                )
                return

        for upload in file_data.keys():
            blueprint_id = upload
            blueprint_data = file_data[upload]
            try:
                blueprint = DonationBlueprint.objects.get(pk=blueprint_id,
                                                          project=self.object)
            except DonationBlueprint.DoesNotExist as e:
                msg = ('Data Donation Processing Exception: Referenced '
                       f'blueprint with id={blueprint_id} does not exist for '
                       'this project.')
                ExceptionLogEntry.objects.create(
                    project=self.object,
                    raised_by=ExceptionRaisers.SERVER,
                    message=msg
                )
                return
            blueprint.process_donation(blueprint_data, self.participant)

class QuestionnaireView(ParticipationFlowBaseView):
    template_name = 'ddm/public/questionnaire.html'
    step_name = 'questionnaire'

    def setup(self, request, *args, **kwargs):
        """ Reset extra_scripts """
        super().setup(request, *args, **kwargs)
        self.extra_scripts = []

    def get(self, request, *args, **kwargs):
        """
        Skip questionnaire if no questions are defined and redirect to next step.
        Otherwise, render questionnaire.
        """
        # Redirect to previous step if necessary.
        if not self.steps[self.current_step] == self.step_name:
            return redirect(self.steps[self.current_step], slug=self.object.slug)

        context = self.get_context_data(object=self.object)
        if not len(context['q_config']) > 2:
            self.set_step_completed()
            return redirect(self.steps[self.current_step + 1],
                            slug=self.object.slug)
        else:
            return self.render_to_response(context)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        question_config = self.object.get_questionnaire_config(self.participant, self)
        context['q_config'] = json.dumps(question_config)
        context['extra_scripts'] = set(self.extra_scripts)
        return context

    def post(self, request, *args, **kwargs):
        super().post(request, **kwargs)
        self.process_response(request.POST)
        return redirect(self.steps[self.current_step + 1],
                        slug=self.object.slug)

    def process_response(self, response):
        try:
            post_data = json.loads(response['post_data'])
        except MultiValueDictKeyError:
            msg = ('Questionnaire Post Exception: POST did not contain '
                   'expected key "post_data".')
            ExceptionLogEntry.objects.create(
                project=self.object,
                raised_by=ExceptionRaisers.SERVER,
                message=msg
            )
            return

        for question_id in post_data:
            try:
                question = QuestionBase.objects.get(pk=int(question_id))
            except QuestionBase.doesNotExist:
                msg = ('Questionnaire Post Exception:'
                       f'Question with id={question_id} does not exist.')
                ExceptionLogEntry.objects.create(
                    project=self.object,
                    raised_by=ExceptionRaisers.SERVER,
                    message=msg
                )
                continue
            except ValueError:
                msg = ('Questionnaire Post Exception: Received invalid '
                       f'question_id ({question_id}) in questionnaire '
                       f'post_data.')
                ExceptionLogEntry.objects.create(
                    project=self.object,
                    raised_by=ExceptionRaisers.SERVER,
                    message=msg
                )
                continue
            question.validate_response(post_data[question_id]['response'])

        self.save_response(response)

    def save_response(self, response):
        QuestionnaireResponse.objects.create(
            project=self.object,
            participant=self.participant,
            time_submitted=timezone.now(),
            data=response['post_data']
        )

class DebriefingView(ParticipationFlowBaseView):
    template_name = 'ddm/public/debriefing.html'
    step_name = 'debriefing'

    def get_context_data(self, **kwargs):
        """ Inject url parameters in redirect target. """
        context = super().get_context_data(**kwargs)

        template_context = {
            'participant': self.participant.get_context_data(),
            'project_id': self.object.pk
        }
        debriefing_template = Template(self.object.debriefing_text)
        context['debriefing'] = debriefing_template.render(Context(template_context))

        if self.object.redirect_enabled:
            redirect_template = Template(self.object.redirect_target)
            context['redirect_target'] = redirect_template.render(Context(template_context))
        else:
            context['redirect_target'] = None
        return context

    def extra_before_render(self, request):
        """Set step to completed and update participant information."""
        if not self.participant.completed:
            self.participant.end_time = timezone.now()
            self.participant.completed = True
            self.participant.save()
        return

class ContinuationView(DetailView):
    """
    Enables the continuation of the study at a later stage.
    Retrieves the session for a participant id passed as a URL parameter (?p=)
    and redirects to the last initiated stage of the study by the given
    participant.
    """
    model = DonationProject
    context_object_name = 'project'
    template_name = 'ddm/public/continuation_not_found.html'

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = super().get_context_data(**kwargs)
        participant_id = request.GET.get('p', None)
        try:
            participant = Participant.objects.get(external_id=participant_id)
        except Participant.DoesNotExist:
            # render continuation failed view with option to start new
            return self.render_to_response(context)

        self.initialize_session(request, participant.pk)
        return redirect(ParticipationFlowBaseView.steps[0], slug=self.object.slug)

    def initialize_session(self, request, participant_id):
        request.session[f'project-{self.object.pk}'] = {
            'participant_id': participant_id
        }
        request.session.modified = True
        return


import torch
import torch.nn as nn
import torch.nn.functional as F

class View(nn.Module):
    def __init__(self, size):
        super(View, self).__init__()
        self.size = size

    def forward(self, tensor):
        return tensor.view(self.size)

class Diagonal(nn.Module):
    def __init__(self, dim):
        super(Diagonal, self).__init__()
        self.dim = dim
        self.weight = nn.Parameter(torch.ones(1, self.dim))
        self.bias = nn.Parameter(torch.zeros(1, self.dim))

    def forward(self, x):
        return x * self.weight + self.bias

class FCClassifier(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.dim = dim

    def forward(self, x):
        return torch.sigmoid(x)

class FCCondPrior(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.dim = dim
        self.diag_loc_true = nn.Parameter(torch.zeros(self.dim))
        self.diag_loc_false = nn.Parameter(torch.zeros(self.dim))
        self.diag_scale_true = nn.Parameter(torch.ones(self.dim))
        self.diag_scale_false = nn.Parameter(torch.ones(self.dim))

    def forward(self, x):
        loc = x * self.diag_loc_true + (1 - x) * self.diag_loc_false
        scale = x * self.diag_scale_true + (1 - x) * self.diag_scale_false
        return (10*x - 5) + torch.tanh(loc), torch.clamp(F.softplus(scale), min=1e-3, max=1.)

class FCCondPrior_v2(nn.Module):
    def __init__(self, z_dim, num_classes):
        super().__init__()
        self.fc = nn.Sequential(
            nn.Linear(num_classes, z_dim),
            nn.ReLU(),
        )
        self.locs = nn.Linear(z_dim, z_dim)
        self.scales = nn.Linear(z_dim, z_dim)
    def forward(self, x):
        x = self.fc(x)
        return torch.clamp(self.locs(x), -5, 5), torch.clamp(F.softplus(self.scales(x)), min=1e-3, max=1.)

class FCEncoder(nn.Module):
    def __init__(self, z_dim, p_dropout):
        super().__init__()

        self.encoder = nn.Sequential(
            View((-1,1,64,64)),
            nn.Conv2d(1, 8, kernel_size=(5,5), stride=(2,2), padding=(2,2)),
            nn.Dropout(p_dropout),
            nn.ReLU(),
            nn.Conv2d(8, 8, kernel_size=(5,5), stride=(2,2), padding=(2,2)),
            nn.Dropout(p_dropout),
            nn.ReLU(),
            nn.Conv2d(8, 16, kernel_size=(5,5), stride=(2,2), padding=(2,2)),
            nn.Dropout(p_dropout),
            nn.ReLU(),
            nn.Conv2d(16, 16, kernel_size=(5,5), stride=(2,2), padding=(2,2)),
            nn.Dropout(p_dropout),
            nn.ReLU(),
            nn.Conv2d(16, 8, kernel_size=(5,5), stride=(1,1), padding=(2,2)),
            nn.Dropout(p_dropout),
            nn.ReLU(),
            View((-1,8*4*4)),
        )

        self.locs = nn.Linear(128, z_dim)
        self.scales = nn.Linear(128, z_dim)

    def forward(self, x):
        x = self.encoder(x)
        return 10*torch.sigmoid(self.locs(x))-5, torch.clamp(F.softplus(self.scales(x)), min=1e-3, max=1.)

class FCEncoder_v2(nn.Module):
    def __init__(self, z_dim, p_dropout):
        super().__init__()

        self.encoder = nn.Sequential(
            View((-1,1,64,64)),
            nn.Conv2d(1, 16, kernel_size=(3,3), stride=(2,2), padding=(1,1)),
            nn.Dropout(p_dropout),
            nn.ReLU(),
            nn.Conv2d(16, 16, kernel_size=(3,3), stride=(2,2), padding=(1,1)),
            nn.Dropout(p_dropout),
            nn.ReLU(),
            nn.Conv2d(16, 16, kernel_size=(3,3), stride=(2,2), padding=(1,1)),
            nn.Dropout(p_dropout),
            nn.ReLU(),
            nn.Conv2d(16, 8, kernel_size=(3,3), stride=(2,2), padding=(1,1)),
            nn.Dropout(p_dropout),
            nn.ReLU(),
            View((-1,8*16)),
        )

        self.locs = nn.Linear(128, z_dim)
        self.scales = nn.Linear(128, z_dim)

    def forward(self, x):
        x = self.encoder(x)
        return torch.clamp(self.locs(x), -5, 5), torch.clamp(F.softplus(self.scales(x)), min=1e-3, max=1.)

class FCDecoder(nn.Module):
    def __init__(self, z_dim, p_dropout):
        super().__init__()

        self.locs = nn.Sequential(
            nn.Linear(z_dim, 8*4*4),
            nn.ReLU(),
            View((-1,8,4,4)),
            nn.ConvTranspose2d(8,16,(5,5),(2,2),(3,3)),
            nn.ReLU(),
            nn.ConvTranspose2d(16,16,(5,5),(2,2),(2,2)),
            nn.ReLU(),
            nn.ConvTranspose2d(16,8,(5,5),(2,2),(2,2)),
            nn.ReLU(),
            nn.ConvTranspose2d(8,8,(5,5),(2,2),(2,2)),
            nn.ReLU(),
            nn.ConvTranspose2d(8,1,(5,5),(2,2),(2,2)),
            View((-1,65,65))
        )

        self.fc_scales = nn.Sequential(
            nn.Linear(z_dim, 32),
        )
        self.m_scales = nn.Parameter(torch.randn(32, 1))

    def forward(self, x):
        locs = self.locs(x)[:,:64,:64]
        locs = locs.tril(-1)
        locs = locs + locs.transpose(-1,-2)
        scales = torch.matmul(self.fc_scales(x), self.m_scales).unsqueeze(-1)
        return locs, torch.clamp(F.softplus(scales), min=1e-3, max=1.)


import sys
sys.setrecursionlimit(500*500)

from math import gcd
from functools import reduce
# product('ABCD', repeat=2) => AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
from itertools import product
# permutations('ABCD', 2) => AB AC AD BA BC BD CA CB CD DA DB DC
from itertools import permutations
# combinations('ABCD', 2) => AB AC AD BC BD CD
from itertools import combinations
from itertools import accumulate # 累積和作るやつ
from collections import deque
from collections import defaultdict
from heapq import heappop, heappush
from bisect import bisect_left
# 0埋めされた二進数表現
f'{9:05b}'

alpha2num = lambda c: ord(c) - ord('a')
num2alpha = lambda c: chr(c+97)
popcnt = lambda x: bin(x).count("1")

dh = [-1, 0, 1, 0]
dw = [0, -1, 0, 1]
dh8 = [-1, -1, -1,  0,  0,  1,  1,  1]
dw8 = [-1,  0,  1, -1,  1, -1,  0,  1]

def resolve():
  from collections import deque
  mod = 10**9+7
  N = int(input())

  # EDGES[n]: 頂点 n に繋がっている頂点
  EDGES = [[] for _ in range(N)]
  for _ in range(N-1):
    x, y = [int(x)-1 for x in input().split(" ")]
    EDGES[x].append(y)
    EDGES[y].append(x)

  # checked[n]: 頂点 n が既にチェックされているかどうか
  checked = [False]*N
  checked[0] = True

  # parents[n]: 頂点 n の親。根の親は -1 になる。
  parents = [-1]*N

  # dp[n][c] := 頂点 n が c 色のケースのパターン数
  dp = [[1, 1] for _ in range(N)]

  # DFS をやっていく。
  # 帰り道で子の状態から白、黒のそれぞれのパターン数を計算する。
  que = deque([~0, 0])
  while que:
    current = que.pop()
    if current < 0:
      current = ~current
      for n in EDGES[current]:
        # 子だけを見るので、親ノードだった場合はスキップする。
        if n == parents[current]: continue
        dp[current][0] *= sum(dp[n])
        dp[current][1] *= dp[n][0]

        if dp[current][0] >= mod: dp[current][0]%=mod
        if dp[current][1] >= mod: dp[current][1]%=mod
      continue
    for n in EDGES[current]:
      if checked[n]: continue
      checked[n] = True
      parents[n] = current
      que.append(~n)
      que.append(n)

  print(sum(dp[0])%mod)

resolve()

def resolve():
  mod = 10**9+7
  N = int(input())
  A = [[int(x) for x in input().split(" ")] for _ in range(N)]
  # MATCHES[i]: i 番目の男性と相性の良い女性の index
  MATCHES = [[j for j in range(N) if A[i][j] == 1] for i in range(N)]

  #
  que = deque()


from scapy.all import *
import pandas as pd
import os
import dpkt
import time
import numpy as np

#=================================================================
def print_progress(count, total):   #可视化转换进度
    # Percentage completion.
    pct_complete = float(count) / total

    # Status-message.
    # Note the \r which means the line should overwrite itself.
    msg = "\r- Progress: {0:.1%}".format(pct_complete)

    # Print it.
    sys.stdout.write(msg)  #3.x版本中的用法 同print类似
    sys.stdout.flush()
#=================================================================

def get_flagsKindNumber(flags): #统计每一个pcap包的协议标识种类数

    kinds=[]
    for f in flags:

        if f in kinds:
            continue
        else:
            kinds.append(f)
    return len(kinds)/8

def get_portKindNumber(sport,dport):#统计每一个pcap包的端口号数目
    kinds=[]
    for p in sport:
        if p in kinds:
            continue
        kinds.append(p)
    for p in dport:
        if p in kinds:
            continue
        kinds.append(p)
    return len(kinds)

def get_TranSpeed(tmp):   #返回对流比
    b=tmp['sip']
    a=tmp['dip']
    d={}

    for i in range(len(b)):
        c1 = b[i] + a[i]
        if c1 in d:
            d[c1] = d[c1] + 1
        else:
            d[c1] = 1
   # print(d)
    for i in range(len(b)):
        c1 = b[i] + a[i]
        c2 = a[i] + b[i]
        if c1 in d and d[c1] == 0:
            del d[c1]
        if c2 in d and d[c2] == 0:
            del d[c2]
        if c1 in d and c2 in d:
            d[c1] = d[c1] - 1
            d[c2] = d[c2] - 1
    #print (d)
    sum = 0
    for key, value in d.items():
        if value > 0:
            sum = sum + value
    #print(sum)
    kind = (len(b) - sum) / 2
    return kind*2/len(b)

def get_pkttransrate(Timestamp,flow_size):#t时间内从源ip到目的ip传送的packet数目
    t=Timestamp[len(Timestamp)-1]-Timestamp[0]
    if t==0:
        rate=0
    else:
        rate=flow_size/t
    return rate

def get_pkttranstimerate(filename):#相邻数据包传送时间间隔均值
    f = open(filename, 'rb')
    Timestamp = []
    pcap = dpkt.pcap.Reader(f)
    for timestamp, buf in pcap:
        Timestamp.append(timestamp)
    interval = 0
    for i in range(len(Timestamp) - 1):
        interval += Timestamp[i + 1] - Timestamp[i]
    if len(Timestamp)==1:
        interval_mean = interval
    else:
        interval_mean = interval / (len(Timestamp) - 1)
    return Timestamp,interval_mean

def get_pktpayloadsize(payload_size):
    tmp=np.array(payload_size)
    return tmp.mean()

def get_StatisticFeatures():
    # 用于返回指定的文件夹包含的文件或文件夹的名字的列表
    start=time.clock()
    pcap_files=os.listdir("./train_data")
    i=0
    num = len(pcap_files)
    x_name = ["flags_kind",  "flow_size","pkttrans_timerate","pkttrans_rate","payload_size_mean"]
    x_name.append("label0")
    x_name.append("label1")
    output = pd.DataFrame(columns=x_name)
    output.to_csv("data_stat_raw.csv", index=False)
    # output.to_csv("data_stat_normalise.csv", index=False)  # 把一个DataFrame写入csv文件

    for pcap_file in pcap_files:
        i = i + 1
        print_progress(i, num)
        filename="./train_data/" + pcap_file
         # 一共七个基本信息
        # src = []
        # dst = []
        sport = []
        dport = []
        flags = []
        payload_size = []
        flow_size=0
        packages = rdpcap("./train_data/" + pcap_file)
        for data in packages:
            flow_size+=1
            if 'TCP' in data:
                # src.append(data['IP'].src)
                # dst.append(data['IP'].dst)
                sport.append(data['TCP'].sport)
                dport.append(data['TCP'].dport)
                flags.append(data['TCP'].flags)
                payload_size.append(len(data.payload))
            else:
                # src.append(data['IP'].src)
                # dst.append(data['IP'].dst)
                sport.append('-1')
                dport.append('-1')
                flags.append('A')
                payload_size.append(len(data.payload))
       # print(tmp)
        flags_kind = get_flagsKindNumber(flags)
        # print("flags_kind:", flags_kind)
        #port_Kind = get_portKindNumber(sport,dport)
        # print("port_Kind:", port_Kind)
        # pairflow_rate = get_TranSpeed(tmp)
        #print("pairflow_rate:", pairflow_rate)

        # print("flow_size:",flow_size)
        Timestamp,pkttrans_timerate=get_pkttranstimerate(filename)
        pkttrans_rate = get_pkttransrate(Timestamp,flow_size)
        payload_size_mean = get_pktpayloadsize(payload_size)
        if "ddos" in pcap_file:
            label=[1,0]  # 标记为包含ddos攻击的pcap
        else:
            label = [0, 1]  # 标记为正常的pcap

        feature = [flags_kind] + [flow_size] + [
            pkttrans_timerate] + [pkttrans_rate] + [
                      payload_size_mean] + label
        f = open("data_stat_raw.csv", 'a')
        f.write(str(feature).strip('[]') + '\n')

        # #归一化 sigmoid
        # # 1 / (1 + np.exp(-x))
        # feature = [1 / (1 + np.exp(-flags_kind))]+[1 / (1 + np.exp(-flow_size))]+[1 / (1 + np.exp(-pkttrans_timerate))]+[1 / (1 + np.exp(-pkttrans_rate))]+[1 / (1 + np.exp(-payload_size_mean))]+label
        # f=open("data_stat_normalise.csv", 'a')
        # f.write(str(feature).strip('[]') + '\n')
    tran_time=time.clock()-start
    print(tran_time)

get_StatisticFeatures()


from os import environ
from os.path import dirname, join
# environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
from joblib import load
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from deep_translator import GoogleTranslator

NUM_WORDS = 189
MAX_TEXT_LEN = 910
MODEL_PATH = "training_1/model"
model_dir = dirname(MODEL_PATH)

if __name__ == "__main__":
    translator = GoogleTranslator(source="it", target="en")
    model = tf.keras.models.load_model(MODEL_PATH)
    tokenizer_path = join(model_dir, "tokenizer.joblib")
    tokenizer: Tokenizer = load(tokenizer_path)
    while True:
        messages = [input("Message: ")]
        translated_messages = list(map(translator.translate, messages))
        for translated_message in translated_messages:
            print(f"Translated Message: {translated_message}")
        sequences = tokenizer.texts_to_sequences(translated_messages)
        X = pad_sequences(sequences, maxlen=NUM_WORDS)
        print(sequences)
        y = model.predict(X, verbose=0).flatten()
        for prediction in y:
            if y > 0.5:
                print("Not SPAM")
            else:
                print("SPAM")


import io

with open('000.jpg','rb') as inf:
    jpgdata = inf.read()

if jpgdata.startswith(b'\xff\xd8'):
    text = u'is JPEG(%d bytes long)\n'
else:
    text = u'is random(%d bytes long)\n'

with io.open('summary.txt','w',encoding='gbk') as  outf:
    outf.write(text %len(jpgdata))


import streamlit as st

from components.faq import faq

def set_huggingface_api_token(api_key: str):
    st.session_state["HF_API_TOKEN"] = api_key
    st.session_state["api_key_configured"] = True

def sidebar():
    with st.sidebar:
        st.markdown(
            "## How to use\n"
            "1. Enter your [ðŸ¤—HuggingFace API token](https://huggingface.co/settings/tokens) belowðŸ”‘\n"  # noqa: E501
            "2. Ask a question about the podcastsðŸ’¬\n"
        )
        api_key_input = st.text_input(
            "HuggingFace API Token",
            type="password",
            placeholder="Paste your HuggingFace API token here (hf_...)",
            help="You can get your API token from https://huggingface.co/settings/tokens.",  # noqa: E501
            value=st.session_state.get("HF_API_TOKEN", ""),
        )

        if api_key_input:
            set_huggingface_api_token(api_key_input)

        st.markdown("---")
        st.markdown("# About")
        st.markdown(
            ":snake: Explore Talk Python To Me allows you to ask questions about "
            "the wonderful podcasts hosted in [Talk Python To Me](https://talkpython.fm/episodes/all). "
        )
        st.markdown(
            "This tool is a work in progress. "
            "You can contribute to the project on [GitHub](https://github.com/plaguss/talking-python) "  # noqa: E501
            "with your feedback and suggestionsðŸ’¡"
        )
        st.markdown(
            "Made by [Agus](https://github.com/plaguss), thanks to [Michael Kennedy](https://talkpython.fm/)"
        )
        st.markdown("---")

        faq()


import pygame
from pygame.sprite import Sprite

class Ship(Sprite):

    def __init__(self, ai_seetings, screen):
        # 初始化飞船并设置其初始位置
        super(Ship, self).__init__()
        self.screen = screen
        self.ai_seetings = ai_seetings

        # 加载飞船图像并获取其外接矩形
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # 将每搜新飞船放在屏幕底部中央
        # 将飞船中心的x坐标设置为屏幕矩形的中心x坐标
        # 将飞船下边缘坐标设置为屏幕矩形的下边缘
        self.rect.centerx = self.screen_rect.centerx
        # 这里能看出来,self.rect=self.image.get_rect()是将类给赋值到这个属性上去了。
        # 所以这里是又在给self.rect这个类设置属性
        self.rect.bottom = self.screen_rect.bottom
        # 在飞船的属性center中存储小数值
        self.center = float(self.rect.centerx)
        self.moving_right = False
        self.moving_left = False

    def blitme(self):
        """在指定的位置绘制飞船"""
        self.screen.blit(self.image, self.rect)

    def update(self):
        """根据移动标志调整飞船的位置"""
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.center += self.ai_seetings.ship_speed_factor
        if self.moving_left and self.rect.left > 0:
            self.center -= self.ai_seetings.ship_speed_factor

        self.rect.centerx = self.center

    def center_ship(self):
        """让飞船在屏幕上居中"""
        self.center = self.screen_rect.centerx


# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/23 下午7:18
# @Author  : Zheng Xingtao
# @File    : spider_30_taohua.py

import asyncio
import os
from pprint import pprint
import urllib.request
import aiohttp
from lxml import etree

loop = asyncio.get_event_loop()

base_url = "http://taohuazu9.com/"
start_url = "http://taohuazu9.com/forum.php?gid=190"
save_path = "/home/zheng/Videos/"

async def get_category():
    """获取分类信息"""
    async with aiohttp.ClientSession() as session:
        while True:
            try:
                async with session.get(start_url) as response:
                    html = await response.text()
                    x_html = etree.HTML(html)

                    category_href_list = x_html.xpath("//div[@id='category_190']//tr/td[2]/h2/a/@href")
                    category_title_list = x_html.xpath("//div[@id='category_190']//tr/td[2]/h2/a/text()")
                    for category_href, category_title in zip(category_href_list, category_title_list):
                        category_task = {
                            'category_title': category_title,
                            'category_href': base_url + category_href,
                        }
                        loop.create_task(parse_detail(session, category_task))
            except Exception as e:
                print(e)
            await asyncio.sleep(5)

async def parse_detail(session, task):
    """获取帖子的详细信息"""
    try:
        async with session.get(task["category_href"]) as response:
            html = await response.text()
            x_html = etree.HTML(html)

            detail_href_list = x_html.xpath("//ul[@id='waterfall']/li//h3/a/@href")
            detail_title_list = x_html.xpath("//ul[@id='waterfall']/li//h3/a/text()")
            image_href = x_html.xpath("""//ul[@id='waterfall']/li/div/a[@onclick="atarget(this)"]/img/@src""")[0]
            for detail_href, detail_title in zip(detail_href_list, detail_title_list):
                detail_task = {
                    'category_title': task["category_title"],
                    'category_href': task["category_href"],
                    'detail_title': detail_title.replace(" ", "").replace("/", "-"),
                    'detail_href': base_url + detail_href,
                    'image_href': image_href,
                }
                # pprint(detail_task)
            loop.create_task(get_torrent_page(session, detail_task))
    except Exception as e:
        print(e)
    await asyncio.sleep(5)

async def get_torrent_page(session, detail_task):
    """获取torrent下载页面"""
    try:
        async with session.get(detail_task["detail_href"]) as response:
            html = await response.text()
            x_html = etree.HTML(html)
            torrent_href = x_html.xpath("""//span[@onmouseover="showMenu({'ctrlid':this.id,'pos':'12'})"]/a/@href""")[0]
            torrent_name = x_html.xpath("""//span[@onmouseover="showMenu({'ctrlid':this.id,'pos':'12'})"]/a/text()""")[
                0]
            torrent_task = {
                "category_title": detail_task["category_title"],
                "category_href": detail_task["category_href"],
                "detail_title": detail_task["detail_title"],
                "detail_href": detail_task["detail_href"],
                "image_href": detail_task["image_href"],
                "torrent_href": base_url + torrent_href,
                "torrent_name": torrent_name,
            }
            # pprint(torrent_task)
            # print(randam, torrent_task)
            loop.create_task(get_torrent(session, torrent_task))
    except Exception as e:
        print(e)
    await asyncio.sleep(5)

async def get_torrent(session, torrent_task):
    """获取torrent下载链接"""
    try:
        async with session.get(torrent_task["torrent_href"]) as response:
            html = await response.text()
            x_html = etree.HTML(html)
            torrent_href = x_html.xpath("""//a[@onclick="hideWindow('imc_attachad')"]/@href""")[0]
            file_task = {
                "category_title": torrent_task["category_title"],
                "category_href": torrent_task["category_href"],
                "detail_title": torrent_task["detail_title"],
                "detail_href": torrent_task["detail_href"],
                "torrent_href": torrent_task["torrent_href"],
                "torrent_name": torrent_task["torrent_name"],
                "image_href": torrent_task["image_href"],
                "file_url": torrent_href
            }
            # pprint(file_task)
            loop.create_task(save_torrent(session, file_task))
    except Exception as e:
        print(e)
    await asyncio.sleep(5)

async def save_torrent(session, file_task):
    try:
        image_name = file_task["detail_title"] + ".jpg"
        torrent_name = file_task["torrent_name"]

        file_save_path = save_path + file_task["category_title"] + "/" + file_task["detail_title"] + "/"
        if not os.path.exists(file_save_path):
            os.makedirs(file_save_path)

        # 使用urllib.request
        urllib.request.urlretrieve(file_task["image_href"], file_save_path + image_name)
        urllib.request.urlretrieve(file_task["file_url"], file_save_path + torrent_name)

        # async with session.get(file_task["file_url"]) as torrent:
        #     pprint(file_task)
        #     with open(file_save_path + torrent_name, "w") as code:
        #         code.write(torrent.content)

        # a bytes-like object is required, not 'StreamReader'
        # async with session.get(file_task["image_href"]) as image:
        #     with open(file_save_path + image_name, "wb") as code:
        #         code.write(image.content.encode())

        print(os.getpid(), "{} 保存完成！".format(file_task["category_title"] + "--" + file_task["detail_title"]))
    except Exception as e:
        print(e)
    await asyncio.sleep(5)

# python 3.7
# asyncio.run(get_category())

# python 3.5
asyncio.get_event_loop().run_until_complete(get_category())


from django.db import models

class Team(models.Model):
    name = models.CharField(max_length=100,primary_key=True)
    coach = models.CharField(max_length=150,null=True,blank=True)

    class Meta:
      ordering = ["name"]
      verbose_name = "Time"
      verbose_name_plural = "Times"

    def __str__(self):
      return f'Time:{self.name.upper()}'

class Color(models.Model):
    teams      = models.ManyToManyField(Team)
    definition = models.CharField(max_length=40,unique=True)

    class Meta:
        ordering = ["definition"]
        verbose_name_plural = "Colors"

    def __str__(self):
        return self.definition.lower()

class SoccerPlayer(models.Model):
    team     = models.ForeignKey(Team,on_delete=models.SET_NULL,null=True)
    name     = models.CharField(max_length=150)
    number   = models.IntegerField()

    class Meta:
        ordering = ["number","-team"]
        verbose_name_plural = "SoccerPlayers"
        constraints = [
            models.UniqueConstraint(
                fields=('team', 'name','number'), name='unique_team_name_number'
            )
        ]

    def __str__(self):
        return self.name.upper()

class Match(models.Model):
    team_home      = models.ForeignKey(Team,on_delete=models.CASCADE,related_name='related_home_team')
    team_visiting  = models.ForeignKey(Team,on_delete=models.CASCADE,related_name='related_visiting_team')
    tournament     = models.CharField(max_length=100)
    goal_home      = models.IntegerField(default=0)
    goal_visiting  = models.IntegerField(default=0)
    date           = models.DateTimeField()

    class Meta:
        ordering = ["-date"]
        verbose_name_plural = "Matchs"
        constraints = [
            models.UniqueConstraint(
                fields=('tournament', 'team_home','team_visiting'), name='unique_tournament_team_home_visiting'
            )
        ]

    def __str__(self):
        return f'{self.tournament.upper()}: {self.team_home.name.upper()} x {self.team_visiting.name.upper()}'

class PlayGame(models.Model):
    GOL = 'GL'
    LAT_DIR = 'LD'
    LAT_ESQ = 'LE'
    ZAG = 'ZA'
    VOL = 'VL'
    MEIA = 'ME'
    ATAC = 'TK'
    POSITIONS = (
        (GOL,'Goleiro'),
        (LAT_DIR,'Lateral Direita'),
        (LAT_ESQ,'Lateral Esquerda'),
        (ZAG,'Zagueiro'),
        (VOL,'Volante'),
        (MEIA,'Meia'),
        (ATAC,'Atacante'),
    )

    soccerplayer = models.ForeignKey(SoccerPlayer,on_delete=models.CASCADE)
    match        = models.ForeignKey(Match,on_delete=models.CASCADE)
    position     = models.CharField(max_length=2,choices=POSITIONS)

    class Meta:
        verbose_name_plural = "Play Games"
        constraints = [
            models.UniqueConstraint(
                fields=('soccerplayer', 'match','position'), name='unique_soccerplayer_match_position'
            )
        ]

    def __str__(self):
        return f'{self.soccerplayer.name.upper()} - {self.get_position_display().upper()}'


import pytest
from assertpy import assert_that

from pcluster.api.models import GetClusterStackEventsResponseContent
from pcluster.cli.entrypoint import run
from pcluster.cli.exceptions import APIOperationException

class TestGetClusterStackEventsCommand:
    def test_helper(self, test_datadir, run_cli, assert_out_err):
        command = ["pcluster", "get-cluster-stack-events", "--help"]
        run_cli(command, expect_failure=False)

        assert_out_err(expected_out=(test_datadir / "pcluster-help.txt").read_text().strip(), expected_err="")

    @pytest.mark.parametrize(
        "args, error_message",
        [
            ([""], "error: the following arguments are required: -n/--cluster-name"),
            (["--cluster-name"], "error: argument -n/--cluster-name: expected one argument"),
            (["--cluster-name", "cluster", "--invalid"], "Invalid arguments ['--invalid']"),
            (
                ["--cluster-name", "cluster", "--region", "eu-west-"],
                "Bad Request: invalid or unsupported region 'eu-west-'",
            ),
        ],
    )
    def test_invalid_args(self, args, error_message, run_cli, capsys):
        command = ["pcluster", "get-cluster-stack-events"] + args
        run_cli(command, expect_failure=True)

        out, err = capsys.readouterr()
        assert_that(out + err).contains(error_message)

    def test_execute(self, mocker):
        response_dict = {
            "nextToken": "99/nexttoken",
            "events": [
                {
                    "eventId": "00000000-aaaa-1111-bbbb-000000000000",
                    "physicalResourceId": "arn:aws:cloudformation:eu-west-1:000000000000:stack/cluster/aa",
                    "resourceStatus": "UPDATE_COMPLETE",
                    "stackId": "arn:aws:cloudformation:eu-west-1:000000000000:stack/cluster/aaa",
                    "stackName": "cluster",
                    "logicalResourceId": "cluster",
                    "resourceType": "AWS::CloudFormation::Stack",
                    "timestamp": "2021-01-01T00:00:00.000Z",
                }
            ],
        }

        response = GetClusterStackEventsResponseContent().from_dict(response_dict)
        get_cluster_stack_events_mock = mocker.patch(
            "pcluster.api.controllers.cluster_logs_controller.get_cluster_stack_events",
            return_value=response,
            autospec=True,
        )

        out = run(["get-cluster-stack-events", "--cluster-name", "cluster"])
        assert_that(out).is_equal_to(response_dict)
        assert_that(get_cluster_stack_events_mock.call_args).is_length(2)  # this is due to the decorator
        expected_args = {"region": None, "cluster_name": "cluster", "next_token": None}
        get_cluster_stack_events_mock.assert_called_with(**expected_args)

    def test_error(self, mocker):
        api_response = {"message": "error"}, 400
        mocker.patch(
            "pcluster.api.controllers.cluster_logs_controller.get_cluster_stack_events",
            return_value=api_response,
            autospec=True,
        )

        with pytest.raises(APIOperationException) as exc_info:
            command = ["get-cluster-stack-events", "--region", "eu-west-1", "--cluster-name", "name"]
            run(command)
        assert_that(exc_info.value.data).is_equal_to(api_response[0])


from flask import Flask, make_response, render_template
import io
import csv

app = Flask(__name__)

import grpc
import report_pb2
import report_pb2_grpc
from google.protobuf.json_format import MessageToDict

def obj_to_dict(obj):
    return obj.__dict__

@app.route("/")
def index():
    try:
        data = get_covid_data_by_state()
        return render_template("index.html", data=data)

    except Exception as e:
        return e

@app.route("/download")
def download():

    try:
        data = get_covid_data_by_state()
        csv_data = covid_data_as_csv(data)
        si = io.StringIO()
        csv_writer = csv.writer(si)
        csv_writer.writerows(csv_data)
        output = make_response(si.getvalue())
        output.headers["Content-Disposition"] = "attachment; filename=us_covid_data.csv"
        output.headers["Content-type"] = "text/csv"
        return output

    except Exception as e:
        return e

def get_covid_data_by_state():
    try:
        channel = grpc.insecure_channel('localhost:3000')
        stub = report_pb2_grpc.ReportStub(channel)
        reportRequest = report_pb2.ReportRequest()
        reportResponse = stub.GetCovidDataForAllStates(reportRequest)

        return [MessageToDict(r) for r in reportResponse]

    except Exception as e:
        return e

def covid_data_as_csv(state_data_as_dicts):
    headers = state_data_as_dicts[0].keys()
    data = [s.values() for s in state_data_as_dicts]
    data.insert(0, headers)

    return data

if __name__ == '__main__':
    app.run()


from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {
    "packages": ["message"],
    "excludes": [
        "tkinter",
        "ssl",
        "sqlite3",
    ],
    "optimize": 2,
    'include_files': [
        "templates",
        "static"
    ],
}

setup(
    name='ne_music_controller',
    version='0.0.1',
    url='https://github.com/winkidney/NetEaseMusicController',
    license='MIT',
    author='winkidney',
    author_email='winkidney@gmail.com',
    description='mobile controller for  NetEase Music on PC',
    options={"build_exe": build_exe_options},
    executables=[
        Executable(
            "music_switcher.py",
            packages=["flask", "autopy"],
        )
    ]
)


#!/usr/bin/env python3
from pathlib import Path

import acts
import acts.examples
from acts.examples.simulation import addParticleGun, addGeant4, EtaConfig
from acts.examples.odd import getOpenDataDetector
from common import getOpenDataDetectorDirectory

u = acts.UnitConstants

def runGeant4(
    detector,
    trackingGeometry,
    field,
    outputDir,
    s: acts.examples.Sequencer = None,
):
    s = s or acts.examples.Sequencer(events=100, numThreads=1)
    s.config.logLevel = acts.logging.INFO
    rnd = acts.examples.RandomNumbers()
    addParticleGun(
        s,
        EtaConfig(-2.0, 2.0),
        rnd=rnd,
    )
    outputDir = Path(outputDir)
    addGeant4(
        s,
        detector,
        trackingGeometry,
        field,
        outputDirCsv=outputDir / "csv",
        outputDirRoot=outputDir,
        rnd=rnd,
    )
    return s

if "__main__" == __name__:
    detector, trackingGeometry, decorators = getOpenDataDetector(
        getOpenDataDetectorDirectory()
    )

    field = acts.ConstantBField(acts.Vector3(0, 0, 2 * u.T))

    runGeant4(detector, trackingGeometry, field, Path.cwd()).run()


from datetime import datetime
from unittest import mock
from entities.book import Book
from entities.order import Order
from entities.customer import Customer
from UserInterface import UserInterface
from repositories.book_repository import BookRepository
from repositories.customer_repository import CustomerRepository
from repositories.order_repository import OrderRepository
import unittest

class TestGeral(unittest.TestCase):
    def test_registration(self):
        with mock.patch('builtins.input', side_effect=[2,"asd",2]):
            user = UserInterface(CustomerRepository(), BookRepository(), OrderRepository())
            user_input = user.register_new_customer()
            user_input2 = user.register_new_customer()

            self.assertEquals(user_input, "Client cadastrado com sucesso!")
            self.assertEquals(user_input2, "Cliente já existe")

    def test_validate_sell(self):
        customer_repository = CustomerRepository()
        book_repository = BookRepository()
        order_repository = OrderRepository()
        user_interface = UserInterface(customer_repository, book_repository, order_repository)

        customer1 = Customer(1,'c1')
        customer_repository.list_customers.append(customer1)

        book1 = Book(1, "Livro1", "a", "autor1", "tipo1", 10)
        book2 = Book(2, "Livro2", "b", "autor2","tipo2", 15)
        book3 = Book(3, "Livro3", "c", "autor3", "tipo3", 20)
        book4 = Book(4, "Livro4", "d", "autor4","tipo4", 0)
        book_repository.list_books.append(book4)
        book_repository.list_books.append(book2)
        book_repository.list_books.append(book3)

        book_repository.down_stock(book3.id)

        order1 = Order(1,customer1,datetime.today())
        order_repository.list_orders.append(order1)

        book_not_exist = user_interface.verify_if_sell_is_possible(2,customer1.id,book1)
        book_zeroed = user_interface.verify_if_sell_is_possible(2,customer1.id,book3)
        book_invalid_price = user_interface.verify_if_sell_is_possible(2,customer1.id,book4)
        invalid_order = user_interface.verify_if_sell_is_possible(order1.id,customer1.id,book2)
        invalid_customer = user_interface.verify_if_sell_is_possible(2,2,book1)

        self.assertEqual(book_not_exist, "Livro não cadastrado")
        self.assertEqual(book_zeroed, "Livro esgotado")
        self.assertEqual(book_invalid_price, "Livro com preço invalido")
        self.assertEqual(invalid_order, "Pedido já existe")
        self.assertEqual(invalid_customer, "Cliente não existe")

def test_selling(monkeypatch):
    customer_repository = CustomerRepository()
    book_repository = BookRepository()
    order_repository = OrderRepository()
    user_interface = UserInterface(customer_repository, book_repository, order_repository)

    book1 = Book(1, "livro1", "a", "autor1", "tipo1", 15)
    book_repository.list_books.append(book1)

    customer1 = Customer(1, "c1")
    customer_repository.list_customers.append(customer1)

    inputs = iter([1, customer1.id, book1.id])
    monkeypatch.setattr('builtins.input', lambda _: next(inputs))
    vendido = user_interface.selling_book()

    inputs = iter([2, 2, 2])
    monkeypatch.setattr('builtins.input', lambda _: next(inputs))
    nao_vendido = user_interface.selling_book()

    assert vendido == "Pedido cadastrado com sucesso!"
    assert nao_vendido == "Algo deu errado :/"


from fastapi import File, UploadFile, APIRouter, Request, Depends
from fastapi.templating import Jinja2Templates
from fastapi.responses import RedirectResponse
from endpoints.jwt_auth import encode_auth_token, jwt_required_wrap, decode_auth_token
from fastapi_jwt_auth import AuthJWT
import json
import os
import random
from datetime import datetime as dt
router = APIRouter()
templates = Jinja2Templates(directory='templates')
class csv:
    def __init__(self, csv_name, date_uploaded, user_upload_by):
        self.csv_name =csv_name
        self.date_uploaded = date_uploaded
        self.user_upload_by = user_upload_by
@router.post('/upload_csv')
async def create_upload_file(request: Request, file : UploadFile = File(...)):
    file_id = random.randint(111111,999999)
    auth_cookie = request.cookies["access_token_cookie"]
    user = decode_auth_token(auth_cookie)

    if file.filename.endswith('.csv'):
        path = 'upload_files/' + str(file_id) + '.csv'
    else:
        return {"error":"file extension must be .csv"}
    with open(path, 'wb+') as f:
        f.write(file.file.read())
        f.close()

    json_path = 'db/user_uploads.json'

    with open(json_path, 'r') as f:
        current_data = json.loads(f.read())
        f.close()
    print(type(file.filename))
    try:
        users_data = current_data[user]
        current_data[user].append({"file":file.filename,"date":str(dt.utcnow()), "file_id":file_id})
    except Exception as e:
        print(e)
        current_data[user] = []
        current_data[user].append({"file":file.filename, "date":str(dt.utcnow()), "file_id":file_id})

    with open(json_path, 'w') as fp:
        print(type(current_data))
        json.dump(current_data, fp)
    return RedirectResponse('/my_csvs', status_code=303)

@router.get('/upload_csv')
async def get_upload_file(request: Request, Authorise: AuthJWT = Depends()):
    Authorise.jwt_required()
    user = Authorise.get_jwt_subject()
    return templates.TemplateResponse("upload_csv.html", {"request":request, "user":user})


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import copy

times = 1
distance = 4.1
neighbors = []

# def neighbor(points):

def move(x, y, t):
    # moving: y = x*2
    resx = x+t
    resy = y + t*2

def show(points):
    global times
    fig = plt.figure(times)
    plt.scatter(points[:, 0], points[:, 1], c='r')
    print(points)
    plt.plot(16,16,'bo')
    plt.plot(0, 0, 'bo')
    plotx = []
    ploty = []
    for index in range(len(points)):
        plotx.append(points[index][0])
        ploty.append(points[index][1])
        plt.annotate(s=index, xy=(points[index][0], points[index][1]), xytext=(-5, 5), textcoords='offset points')

    times = times + 1

def anim(list_points):
    fig = plt.figure()
    ax = plt.axes(xlim=(-2, 30), ylim=(-2, 30))
    length = len(list_points)
    new_points = np.array(list_points[0])
    scat = ax.scatter(new_points[:, 0], new_points[:, 1], c='r')

    def update(frame_number):
        global new_points
        new_points = np.array(list_points[frame_number])
        new_points = new_points[:,0:2]
        print('update ', frame_number, list_points[frame_number])
        scat.set_offsets(new_points)
        return scat,

    animate = animation.FuncAnimation(fig, update, frames=length, interval=200, blit=False)  # interval是每隔70毫秒更新一次，可以查看help
    animate.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
    plt.show()

points = np.loadtxt('./node.npy')
points = points[0:11, :]
list_points = []
list_points.append(copy.deepcopy(points))
iterator_time = 30
robot_num = len(points)
time = 1
# show(points)
while iterator_time > 0:
    for index in range(robot_num):
        if index == 0 or index == 1 or index == 10:
            points[index][0] = points[index][0] + (np.random.random()-0.5) + 0.5
            points[index][1] = points[index][1] + (np.random.random() - 0.5) + 0.5
    # print('iteraotr_time is ', iterator_time, points)
    list_points.append(copy.deepcopy(points))
    # show(points)
    for index in range(robot_num):
        if index != 0 and index != 1 and index != 10:
            points[index][0] = points[index][0] + (np.random.random()-0.5) + 0.5
            points[index][1] = points[index][1] + (np.random.random() - 0.5) + 0.5
            rand = np.random.randint(0, 3)
            if rand == 0:
                points[index][0] = points[index][0] + (np.random.random() - 0.5)
                points[index][1] = points[index][1] + (np.random.random() - 0.5) * 3
    # print('iteraotr_time is ', iterator_time, points)
    list_points.append(copy.deepcopy(points))
    # show(points)
    iterator_time = iterator_time - 1

anim(list_points)
# print(list_points)
# plt.show()

#
# import numpy as np
# import matplotlib
# import matplotlib.pyplot as plt
# from matplotlib.animation import FuncAnimation
# # from matplotlib import animation
# # No toolbar
# matplotlib.rcParams['toolbar'] = 'None'
# # New figure with white background
# fig = plt.figure(figsize=(6,6), facecolor='white')
# # New axis over the whole figureand a 1:1 aspect ratio
# # ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1)
# ax = fig.add_axes([0.005,0.005,0.990,0.990], frameon=True, aspect=1)
# # Number of ring
# n = 50
# size_min = 50
# size_max = 50*50
# # Ring position ，圆环位置，范围在[0,1]之间
# P = np.random.uniform(0,1,(n,2))
# # Ring colors环的颜色
# C = np.ones((n,4)) * (0,1,0,1)
# #C = np.ones((n,3)) * (1,0,1)
# # Alpha color channel goes from 0 (transparent) to 1 (opaque)
# # 透明度，数值在[0,1]之间
# C[:,2] = np.linspace(0,1,n)
# # Ring sizes环的大小，范围在[50,2500]
# S = np.linspace(size_min, size_max, n)
# # Scatter plot
# # 散点图绘制
# scat = ax.scatter(P[:,0], P[:,1], s=S, lw = 0.5,
#          edgecolors = C, facecolors='None')
# # Ensure limits are [0,1] and remove ticks
# #保证x,y的范围在[0,1]之间,移除坐标轴标记
# ax.set_xlim(0,1), ax.set_xticks([])
# ax.set_ylim(0,1), ax.set_yticks([])
# def update(frame):
#   global P, C, S
#   # Every ring is made more transparent每个环变得更透明
#   C[:,3] = np.maximum(0, C[:,3] - 1.0/n)
#   # Each ring is made larger每个环都比原来的大
#   S += (size_max - size_min) / n
#   # Reset ring specific ring (relative to frame number)
#   i = frame % 50
#   P[i] = np.random.uniform(0,1,2) # P[i] = P[i,:],同时改变了x,y两个位置的值
#   S[i] = size_min #从最小的形状开始
#   C[i,3] = 1   #设置透明度为1
#   # Update scatter object
#   # 更新scatter绘图对象的属性，例如edgecolors,sizes,offsets等
#   scat.set_edgecolors(C) #设置边缘颜色
#   scat.set_sizes(S)    #设置大小
#   scat.set_offsets(P)   #设置偏置
#   print('update ',frame)
#   return scat,
# animate = FuncAnimation(fig, update, frames = 300,interval=70)#interval是每隔70毫秒更新一次，可以查看help
# # FFwriter = animation.FFMpegWriter(fps=20)  #frame per second帧每秒
# # animate.save('rain.mp4', writer=FFwriter,dpi=360)#设置分辨率
# plt.show()


import pickle
import matplotlib.pyplot as plt
from src.image_classification.experiment import configuration, plot_results, get_best_configuration_per_k, plot_time_vs_accuracy

config = configuration()
resdir = f'{config["basepath"]}/results/image-classification/eval/'
savdir = f'{config["basepath"]}/results/image-classification/figs/'
savfig = True
mode = 'efficient'  # best, efficient
threshold = 0.05

fig1, axs1 = plt.subplots(4, 5, figsize=(12, 8))
fig2, axs2 = plt.subplots(4, 3, figsize=(7.2, 8))

for i, dataset in enumerate(config['datasets']):
    with open(f'{resdir}{dataset}.pickle', 'rb') as h:
        results = pickle.load(h)

    for j, k in enumerate(config['K']):
        times, accuracies, configs, duration, accuracy, best = get_best_configuration_per_k(results, k, mode, threshold)
        plot_time_vs_accuracy(
            dataset,
            k,
            times,
            accuracies,
            threshold,
            duration,
            accuracy,
            fig2,
            axs2[i, j],
            i == 0,
            i == len(config['datasets']) - 1,
            j == 0,
            i == 0 and j == 0
        )

    plot_results(dataset, results, 'model', config['models'], fig1, axs1[i, 0], x_bool=i == len(config['datasets']) - 1, y1_bool=True, y2_bool=False)
    plot_results(dataset, results, 'k', config['K'], fig1, axs1[i, 1], x_bool=i == len(config['datasets']) - 1, y1_bool=False, y2_bool=False)
    plot_results(dataset, results, 'iterations', config['iterations'], fig1, axs1[i, 2], x_bool=i == len(config['datasets']) - 1, y1_bool=False, y2_bool=False)
    plot_results(dataset, results, 'learning_rate', config['learning_rates'], fig1, axs1[i, 3], x_bool=i == len(config['datasets']) - 1, y1_bool=False, y2_bool=False)
    plot_results(dataset, results, 'batch_size', config['batch_sizes'], fig1, axs1[i, 4], x_bool=i == len(config['datasets']) - 1, y1_bool=False, y2_bool=True)

if savfig:
    fig1.savefig(f'{savdir}results.jpg')
    if mode == 'efficient':
        fig2.savefig(f'{savdir}time-vs-accuracy.jpg')


import requests

# truyền vào url website mình muốn thao tác
url = 'https://api.github.com/events'

r = requests.get(url=url)

# trạng thái truy cập trả về
#  200 thì trang web truy cập ổn định
# trả về 400 thì trang web ko thể truy cập
status = r.json

# lấy dữ liệu dạng json, json() là 1 kiểu dữ  liệu trong javascript
# ở đây là lấy ra actor của người đăng kí github mới nhất
data = r.json()[0]['actor']

print(status)
print(data)