from typing import Union, Tuple, Type

from rest_framework import serializers, generics

class ExportFileMixin:
    """
    Mixin which allows the override of the filename being
    passed back to the user when the file is downloaded.
    """

    json_filename = "protrend_data.json"
    xml_filename = "protrend_data.xml"
    excel_filename = "protrend_data.xlsx"
    csv_filename = "protrend_data.csv"
    nucleotide_fasta_filename = "protrend_data.fna"
    amino_acid_fasta_filename = "protrend_data.faa"
    nucleotide_gnb_filename = "protrend_data.gbff"
    amino_acid_gnb_filename = "protrend_data.gpff"
    motif_jaspar_filename = "protrend_data.jaspar"
    motif_transfac_filename = "protrend_data.dat"
    xlsx_ignore_headers = []

    def get_renderers(self: Union['ExportFileMixin', generics.GenericAPIView], *args, **kwargs):
        """
        Return the list of renderers that can be used to render the response.
        """
        # noinspection PyUnresolvedReferences
        renderers = super().get_renderers(*args, **kwargs)

        if 'format' in self.request.query_params:
            return [renderer for renderer in renderers if renderer.format == self.request.query_params['format']]

        return [renderer for renderer in renderers if renderer.format == 'api']

    def finalize_response(self: Union['ExportFileMixin', generics.GenericAPIView], request, response, *args, **kwargs):
        """
        Return the response with the proper content disposition and the customized
        filename instead of the browser default (or lack thereof).
        """
        response = super(ExportFileMixin, self).finalize_response(request, response, *args, **kwargs)

        if response.accepted_renderer.format == 'json':
            filename = self.json_filename
            response["content-disposition"] = f"attachment; filename={filename}"

        elif response.accepted_renderer.format == 'xml':
            filename = self.xml_filename
            response["content-disposition"] = f"attachment; filename={filename}"

        elif response.accepted_renderer.format == 'xlsx':
            filename = self.excel_filename
            response["content-disposition"] = f"attachment; filename={filename}"

        elif response.accepted_renderer.format == 'csv':
            filename = self.csv_filename
            response["content-disposition"] = f"attachment; filename={filename}"

        elif response.accepted_renderer.format == 'fna':
            filename = self.nucleotide_fasta_filename
            response["content-disposition"] = f"attachment; filename={filename}"

        elif response.accepted_renderer.format == 'faa':
            filename = self.amino_acid_fasta_filename
            response["content-disposition"] = f"attachment; filename={filename}"

        elif response.accepted_renderer.format == 'gbff':
            filename = self.nucleotide_gnb_filename
            response["content-disposition"] = f"attachment; filename={filename}"

        elif response.accepted_renderer.format == 'gpff':
            filename = self.amino_acid_gnb_filename
            response["content-disposition"] = f"attachment; filename={filename}"

        elif response.accepted_renderer.format == 'jaspar':
            filename = self.motif_jaspar_filename
            response["content-disposition"] = f"attachment; filename={filename}"

        elif response.accepted_renderer.format == 'transfac':
            filename = self.motif_transfac_filename
            response["content-disposition"] = f"attachment; filename={filename}"

        return response

    def get_renderer_context(self: Union['ExportFileMixin', generics.GenericAPIView]):
        # noinspection PyUnresolvedReferences
        context = super().get_renderer_context()

        serializer_cls = self.get_serializer_class()
        header, ignore_headers = get_header(serializer_cls=serializer_cls)
        self.xlsx_ignore_headers = ignore_headers

        context['header'] = header
        return context

def get_header(serializer_cls: Type[serializers.Serializer], nested_fields: Tuple = None) -> Tuple:
    serializer = serializer_cls()

    if not nested_fields:
        nested_fields = ()

    header = []
    ignore_headers = []
    for key, value in serializer.fields.items():

        if value.write_only:
            ignore_headers.append(key)
            continue

        if key in nested_fields:

            if hasattr(value, 'child'):
                value = value.child

            for sub_key in value.fields.keys():
                nested_key = f'{key}.{sub_key}'
                header.append(nested_key)

        else:
            header.append(key)

    return tuple(header), ignore_headers


import os
import cv2 as cv
import requests

path_URLs = r''
output_DIR = r''

rows = open(path_URLs.read().strip().split('\n'))
total = 0

def loopURLs(rows):
    for url in rows:
        try:
            # Try to download the image from the URL
            request = requests.get(url, timeout=60)

            # save the image to disk
            downloaded = os.path.sep.join(output_DIR, f'{str(total).zfill(8)}.jpg')
            file = open(p, "wb")
            file.write(r.content)
            file.close()

            # update the counter
            print(f'Downloaded: {downloaded}')
            total += 1

        # handle if any exceptions are thrown during the download process
        except:
            print(f'Error downloading {downloaded}')

def doesExist(output_DIR):
    # loop over the image paths we just downloaded
    for imagePath in paths.list_images(output_DIR):
        delete = False

        # Attempting to load the image
        try:
            image = cv2.imread(imagePath)

            if image is None:
                delete = True

        # if OpenCV cannot load the image, then the image is likely corrupt so we delete it
        except:
            delete = True

        if delete:
            print(f'Deleting {imagePath}')
            os.remove(imagePath)

# Calling both functions
loopURLs(rows)
doesExist(output_DIR)


from sqlalchemy import Table, Column, UniqueConstraint, ForeignKey, Integer, String
from sqlalchemy.orm import relationship

from .Base import Base

connection = Table(
    'PlanetConnection', Base.metadata,
    Column('planet_a_id', Integer, ForeignKey('planets.id'), index=True),
    Column('planet_b_id', Integer, ForeignKey('planets.id')),
    UniqueConstraint('planet_a_id', 'planet_b_id', name='unique_connections')
)

class Planet(Base):
    __tablename__ = "planets"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)

    # ships = relationship('Ship', backref="location")
    connections = relationship('Planet',
                               secondary=connection,
                               primaryjoin=id == connection.c.planet_a_id,
                               secondaryjoin=id == connection.c.planet_b_id
                               )

    def make_connection(self, other):
        if other not in self.connections:
            self.connections.append(other)
            other.connections.append(self)

    def __repr__(self):
        return '<Planet(name="%s")>' % self.name


from odmantic import Model, EmbeddedModel
from typing import Optional, List, Union

class Conditions(EmbeddedModel):
    min_size: float
    min_floors: int
    max_floors: int
    price: float

class InterestModel(Model):  # 이렇게 하는 것이 나을까? 아님, user 하나당 하나의 row만 가지게 하는 것이 좋을까??
    user_id: str
    complex_id: int
    complex_name: str
    conditions: Conditions

    class Config:
        collection = "interest"


from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import render
from BTsuperintendent.user_access_test import is_Superintendent
from BTco_ordinator.forms import OpenElectiveRegistrationsForm
from BTco_ordinator.models import BTStudentRegistrations, BTSubjects, BTStudentRegistrations_Staging
from BTsuperintendent.forms import OpenElectiveRegistrationsFinalizeForm
from ADUGDB.models import BTRegistrationStatus
from import_export.formats.base_formats import XLSX

@login_required(login_url="/login/")
@user_passes_test(is_Superintendent)
def open_elective_regs(request):
    user = request.user
    groups = user.groups.all().values_list('name', flat=True)
    regIDs =None
    if 'Superintendent' in groups:
        regIDs = BTRegistrationStatus.objects.filter(Status=1, OERegistrationStatus=1, Mode='R')
    if regIDs:
        regIDs = [(row.AYear, row.ASem, row.BYear, row.BSem, row.Dept, row.Mode, row.Regulation) for row in regIDs]
    necessary_field_msg = False
    subjects=[]
    if(request.method == "POST"):
        depts = ['BTE','CHE','CE','CSE','EEE','ECE','ME','MME','CHEMISTRY','PHYSICS']
        years = {1:'I',2:'II',3:'III',4:'IV'}
        deptDict = {dept:ind+1 for ind, dept  in enumerate(depts)}
        rom2int = {'I':1,'II':2,'III':3,'IV':4}
        regId = request.POST['regID']
        subId = request.POST['subId']
        data = {'regID':regId, 'subId':subId}
        form = OpenElectiveRegistrationsForm(regIDs,subjects,data)
        if 'file' not in request.POST.keys():
            file = request.FILES['file']
        else:
            file = request.POST['file']
        if regId != '--Choose Event--' and subId != '--Select Subject--' and file != '':
            strs = regId.split(':')
            dept = deptDict[strs[0]]
            ayear = int(strs[3])
            asem = int(strs[4])
            byear = rom2int[strs[1]]
            bsem = rom2int[strs[2]]
            regulation = int(strs[5])
            mode = strs[6]
            data = bytes()
            for chunk in file.chunks():
                data += chunk
            dataset = XLSX().create_dataset(data)
            currentRegEventId = BTRegistrationStatus.objects.filter(AYear=ayear,ASem=asem,BYear=byear,BSem=bsem,\
                    Dept=dept,Mode=mode,Regulation=regulation)
            currentRegEventId = currentRegEventId[0].id
            for i in range(len(dataset)):
                regNo = int(dataset[i][0])
                reg = BTStudentRegistrations_Staging(student__student__RegNo=regNo, RegEventId=currentRegEventId, Mode=1,sub_id=subId)
                reg.save()
            return render(request, 'BTsuperintendent/OecRegistrationsSuccess.html')
        elif regId != '--Choose Event--':
            strs = regId.split(':')
            dept = deptDict[strs[0]]
            ayear = int(strs[3])
            asem = int(strs[4])
            byear = rom2int[strs[1]]
            bsem = rom2int[strs[2]]
            regulation = int(strs[5])
            mode = strs[6]
            currentRegEventId = BTRegistrationStatus.objects.filter(AYear=ayear,ASem=asem,BYear=byear,BSem=bsem,\
                    Dept=dept,Mode=mode,Regulation=regulation)
            currentRegEventId = currentRegEventId[0].id
            subjects = BTSubjects.objects.filter(RegEventId=currentRegEventId, Category__in=['OEC','OPC'])
            subjects = [(sub.id,str(sub.SubCode)+" "+str(sub.SubName)) for sub in subjects]
            form = OpenElectiveRegistrationsForm(regIDs,subjects,data)
    else:
        form = OpenElectiveRegistrationsForm(regIDs)
    return render(request, 'BTsuperintendent/OpenElectiveRegistrations.html',{'form':form,'msg':necessary_field_msg})

@login_required(login_url="/login/")
@user_passes_test(is_Superintendent)
def open_elective_regs_finalize(request):
    user = request.user
    groups = user.groups.all().values_list('name', flat=True)
    regIDs =  []
    msg = ''
    if 'Superintendent' in groups:
        regIDs = BTRegistrationStatus.objects.filter(Status=1, OERegistrationStatus=1, Mode='R')
    if request.method == 'POST':
        form = OpenElectiveRegistrationsFinalizeForm(regIDs, request.POST)
        if form.is_valid():
            staging_regs = BTStudentRegistrations_Staging.objects.filter(RegEventId_id=form.cleaned_data.get('regID'), sub_id_id=form.cleaned_data.get('sub'))
            for reg in staging_regs:
                final_reg = BTStudentRegistrations(RegNo=reg.RegNo, RegEventId=reg.RegEventId, Mode=reg.Mode, sub_id=reg.sub_id)
                final_reg.save()
            msg = 'Open elective registrations are finalized.'
        return render(request, 'BTsuperintendent/OpenElectiveRegistrationsFinalize.html', {'form':form, 'msg':msg})
    else:
        form = OpenElectiveRegistrationsFinalizeForm(regIDs)
    return render(request, 'BTsuperintendent/OpenElectiveRegistrationsFinalize.html', {'form':form})


#%% IMPORTS

import os
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
from datetime import datetime
import time
import csv
import pymongo

import sys
sys.path.append("../Library/")
import image_download as imd
import image_manipulation as ima
import db_connection as dbcon

from dotenv import load_dotenv
load_dotenv("../.env")
dotenv_path = ('../.env')
load_dotenv(dotenv_path)

#%% PARAMETERS

# PROCESSING PARAMETERS
PROCESS_RAW_IMAGES = False
MOVE_PROCESSED_IMAGES = False
DEGRADE_IMAGES = False
SAVE_LABELS = False

# IMAGE PARAMETERS
SIZE = 1000 # in pixels
BASE_RESOLUTION = 0.3 # in meter
LABELS = [0, 1, 2]

# THESE ARE ONLY APPROXIMATE -->  integer(SIZE/DEGRADED_RESOLUTION)
DEGRADED_RESOLUTIONS = [0.6, 1, 2, 3, 5, 10, 15, 20, 30] # in meter

DEGRADED_SIZES = [SIZE/(res/BASE_RESOLUTION) for res in DEGRADED_RESOLUTIONS]
print("Degraded sizes are", DEGRADED_SIZES, "pixels. This is rounded to the nearest integer!")
# THESE ARE ONLY APPROXIMATE -->  integer(SIZE/DEGRADED_RESOLUTION)

# FOLDER PARAMETERS
GDRIVE_FOLDER = os.getenv('GDRIVE_FOLDER')
RAW_IMAGE_FOLDER = GDRIVE_FOLDER + 'MFP - Satellogic/images/raw_images_usgs_0.3m/'
PROCESSED_IMAGE_FOLDER = RAW_IMAGE_FOLDER + 'processed/'
MFP_IMG_FOLDER = GDRIVE_FOLDER + 'MFP - Satellogic/images/'
CATEGORIES = ['agriculture', 'shrubland-grassland', 'city', 'forest-woodland', 'semi-desert']

# Compute more parameters
params = {'size': SIZE, 'res': BASE_RESOLUTION, 'res_degr': DEGRADED_RESOLUTIONS}
subfolder_size = MFP_IMG_FOLDER + 'usgs_' + str(SIZE) + "/"
subfolder_base_res = subfolder_size + "usgs_" + str(SIZE) + "_" + str(BASE_RESOLUTION) + "m/"

#%% Processing

print("\nUSGS PIPELINE:\n")
t0 = time.time()
db = dbcon.connect("../credentials/mlab_db.txt", "mfp")
images_usgs_col = db["images_lib_usgs"]
labels_usgs_col = db["labels_lib_usgs"]
ima.create_directory(subfolder_size)
ima.create_directory(subfolder_base_res)

for category in CATEGORIES:
    # Process raw images and save
    if PROCESS_RAW_IMAGES:
        print("\nProcessing raw images of category", category.upper(), "...")
        t1 = time.time()
        output_folder = subfolder_base_res + category + "/"
        raw_images_fullnames = ima.list_path_of_images_by_category(RAW_IMAGE_FOLDER, category)
        imd.process_raw_images_and_save_usgs(raw_images_fullnames, params, category, output_folder, images_usgs_col)
        if MOVE_PROCESSED_IMAGES:
            ima.move_folder_content(RAW_IMAGE_FOLDER + category, PROCESSED_IMAGE_FOLDER + category)
        t2 = time.time()
        print("[{:.2f} s]".format(t2 - t1))

    # Degrade images and save
    if DEGRADE_IMAGES:
        print("\nDegrading images of category", category.upper(), "...")
        t1 = time.time()
        images_fullnames = ima.list_path_of_images_by_category(subfolder_base_res, category)
        ima.degrade_images_and_save(images_fullnames, params, subfolder_size, category, images_usgs_col)
        t2 = time.time()
        print("[{:.2f} s]".format(t2 - t1))
    #%%
    if SAVE_LABELS:
        print("\nSave labels of category", category.upper(), "to csv ...")
        t1 = time.time()
        ima.create_csv_with_labels_by_category_usgs(subfolder_base_res, category, LABELS)
        t2 = time.time()
        print("[{:.2f} s]".format(t2 - t1))

#%%
print("\nDONE! [{:.2f} s]\n".format(t2 - t0))

#%%

#%% DEPRECATED
def write_labels_from_csv_to_db_usgs(db_collection, folder_name, csv_filename):
    """

    :param db_collection: mongodb connection and define collection
    :param folder_name: str
    :param csv_filename: str
    :return:
    """
    with open(folder_name + csv_filename) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print("loading labels from file " + csv_filename + " to db ...")
                line_count += 1
            else:
                query = {"filename": row[0]}
                label = {"$set": {"label": row[1]}}
                db_collection.update(query, label)
                line_count += 1
        print(str(line_count - 1) + ' labels added to db!')
    return


from datetime import datetime, timedelta, timezone
from functools import wraps
from typing import Union, Any, Callable
import httpx
from fastapi import Depends, HTTPException
from pydantic import ValidationError
from starlette import status

from models.auth_model.auth_model import PayloadToken
from service.parser import ParseEnv

def auth_required(func: Callable) -> Callable:
    @wraps(func)
    async def wrapper(*args: Any, **kwargs: Any):
        try:
            _LOGIN_URL = "http://"+'127.0.0.1'+":"+'8000'+'/api/v1/user/get-user'
            async with httpx.AsyncClient() as client:
                response = await client.get(
                    url=_LOGIN_URL,
                    headers={
                        "Authorization": "Bearer " + kwargs["authorize"],
                    },
                )
                if response.status_code == 200:
                    return await func(*args, **kwargs)
                raise HTTPException(status_code=403)
        except httpx.HTTPError as error:
            return HTTPException(status_code=500)

    return wrapper

async def decode_token(token):
    try:
        from jose import jwt
        payload = jwt.decode(
            token,
            ParseEnv.JWT_SECRET_KEY,
            algorithms=ParseEnv.ALGORITHM
        )
        token_data = PayloadToken(**payload)
        if token_data.exp < datetime.utcnow().replace(tzinfo=timezone.utc):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Token expired",
                headers={"WWW-Authenticate": "Bearer"},
            )
    except(jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return token_data


from channels.auth import AuthMiddlewareStack
from channels.routing import ChannelNameRouter, ProtocolTypeRouter, URLRouter

from django.urls import path

from . import batch, consumers

application = ProtocolTypeRouter({
    # Empty for now (http->django views is added by default)
    "websocket": AuthMiddlewareStack(
        URLRouter([
        	path('chat/<str:room_name>', consumers.ChatConsumer),
        ])
    ),
    "channel": ChannelNameRouter({
        "send-email": batch.SendEmailConsumer,
    }),
})
"""
from channels.routing import route

channel_routing = [
    route('send-invite', batch.send_invite),
]

chat_routing = [
    route('websocket.connect', consumers.ws_connect),
    route('websocket.receive', consumers.ws_receive),
    route('websocket.disconnect', consumers.ws_disconnect),
]

default_routing = channel_routing + chat_routing
"""


# -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 12:41:05 2019

@author: fida-stage1
"""
import numpy as np
import pandas as pd

import unsupervised_learning_def as unsupervised
import supervised_learning_def as supervised
from sklearn.decomposition import PCA

'''Selecting dataframes and variables'''
df=df_mixed
variables=variables_mixed

'''Selecting cluster number based on number of existing classes'''
label='cat_descrizione'
k=df[label].nunique()

'''Alternative: manual choice of cluster number'''
#k=15 es. di numero scelto discrezionalmente

'''Missing values imputation methods'''
method='kneighbors'
#df_arr=np.array(df[variables_return])
df_arr=supervised.impute_missing_values(df[variables_return],df[anagrafica],variables_return,label,method)
df_arr=pd.DataFrame(df_arr,columns=variables_return)
#df=df[anagrafica+variables_pol].join(df_arr[variables_return])
df=df[anagrafica+variables_pol].join(df_arr[variables_return])

"""HIERARCHICAL clustering"""

clust_hier=unsupervised.hierarchical_clustering(df,variables,"clust_hier.xlsx",k,method="ward",metric="euclidean", plot=True,ndim=3)

'''Silhouette score with respect to real classes'''
unsupervised.silhouette_score (df[variables],df["cat_descrizione"], metric='euclidean')
'''Silhouette score with respect to clusters'''
unsupervised.silhouette_score (df[variables],clust_hier[1], metric='euclidean')

'''Comparing clusters against classes and find % of funds that inside a cluster belong to the same dominant class (purity score)'''
unsupervised.purity(clust_hier[3])[1]

from sklearn.metrics.cluster import normalized_mutual_info_score
veri_cluster=unsupervised.lista_cluster(df)
normalized_mutual_info_score(clust_hier[3],veri_cluster)

"""KMEANS clustering"""

multiple_kmeans(df,variables,5)

clust_k=unsupervised.kmeans_clustering(df,variables,"clust_k.xlsx",k, True,ndim=3)
'''Silhouette score with respect to real classes'''
unsupervised.silhouette_score (df[variables],df["cat_descrizione"], metric='euclidean')
'''Silhouette score with respect to clusters'''
unsupervised.silhouette_score (df[variables],clust_k[1], metric='euclidean')

'''Comparing clusters against classes and find % of funds that inside a cluster belong to the same dominant class (purity score)'''
unsupervised.purity(clust_k[3])[1]

"""Experiment: intersection clustering """
"""Intersection procedure by selecting different variables and clustering on these, then verify if
   the clustering is consistent with the past ones each time"""

variables1=variables_return
variables2=variables_pol

clust_hier1=unsupervised.hierarchical_clustering(df,variables1,"clust_hier.xlsx",100,method="ward",metric="euclidean", plot=False, ndim=3)
clust_hier2=unsupervised.hierarchical_clustering(df,variables2,"clust_hier.xlsx",100,method="complete",metric="euclidean", plot=False, ndim=3)

clust_k1=unsupervised.kmeans_clustering(df,variables1,"clust_k.xlsx",k, False)
clust_k2=unsupervised.kmeans_clustering(df,variables2,"clust_k.xlsx",k, False)

'''Choosing the clusters to intersecate'''
lista=[clust_hier1[2],clust_hier2[2]]
titoli=df_return["ana_name"]

intersection = unsupervised.cluster_intersection(lista,titoli)
intersectionlist = unsupervised.intersection_df(intersection,df)
intersectionlist[0].to_excel(excel_writer="intersection.xlsx")

'''Comparing clusters against classes and find % of funds that inside a cluster belong to the same dominant class (purity score)'''
unsupervised.purity(intersectionlist[2])[1]

'''Silhouette score with respect to real classes'''
unsupervised.silhouette_score(df.sort_values("ana_name")[variables],intersectionlist[0].sort_values("ana_name")["new_cat_ID"], metric='euclidean')

"""Experimenting with PCA (Principal Components Analysis)"""

pca = PCA(n_components=3)

pca.fit(df[variables])
X=pca.transform(df[variables])
print(pca.explained_variance_ratio_)
sum(pca.explained_variance_ratio_)
print(pca.singular_values_)
pca.components_.round(2)

unsupervised.PCA_plot(df,variables,2)
unsupervised.PCA_plot(df,variables,3)


#!/usr/bin/python2
# -*- encoding: utf-8 -*-
'''
 * USB Geiger counter manager
 * 2013 Michał Słomkowski
 * This code is distributed under the terms of GNU General Public License version 3.0.
'''

import argparse
import ConfigParser
import usbcomm
import sys
import os
import signal
import time
import logging

__version__ = '1.1'
__author__ = 'Michał Słomkowski'
__copyright__ = 'GNU GPL v.3.0'

# default config file name
CONFIG_FILE_NAME = 'configuration.ini'
# directories with configuration file
CONFIG_PATH = [".", os.path.dirname(__file__), os.path.expanduser("~/.geiger"), "/etc/geiger"]

CONFIG_PATH = [os.path.realpath(os.path.join(directory, CONFIG_FILE_NAME)) for directory in CONFIG_PATH]

def signalHandler(signum, frame):
	"""Handles stopping signals, closes all updaters and threads and exits."""
	if args.monitor:
		global logger
		logger.info("Catched signal no. %d, stopping.", signum)
		global monitor
		monitor.stop()
		logging.shutdown()
		sys.exit(1)

# parse command-line arguments
description = "Geiger manager v. " + __version__ + ', ' + __author__ + ". "
description += """This program is a daemon which monitors constantly the radiation measured by USB Geiger device
and sends the results to cosm.com, MySQL database or CSV file. All configuration is stored in the file '"""
description += CONFIG_FILE_NAME + """' which is essential to run. Program uses pyusb library and MySQLdb, if MySQL is enabled."""

parser = argparse.ArgumentParser(description = description)
parser.add_argument("-c", "--config", nargs = 1, help = "reads given configuration file")
parser.add_argument("-v", "--verbose", action = 'store_true', help = "shows additional information")
parser.add_argument("-b", "--background", action = 'store_true', help = "runs as background process")
group = parser.add_mutually_exclusive_group()
group.add_argument("-m", "--monitor", action = 'store_true', help = "starts program in monitor mode")
group.add_argument("-s", "--status", action = 'store_true', help = "reads data from Geiger device and leaves (enabled by default)")

args = parser.parse_args()

if args.verbose and not args.background:
	print("Geiger manager v. " + __version__ + ', ' + __author__)

# become a daemon and fork
if args.background:
	if os.fork() != 0:
		os._exit(0)

if args.config:
	CONFIG_PATH = []
	CONFIG_PATH.append(args.config[0])
	if args.verbose and not args.background:
		print("Using configuration file '%s'" % args.config[0])

# load configuration file
conf = ConfigParser.SafeConfigParser()

for filePath in CONFIG_PATH:
	try:
		conf.readfp(open(filePath))
		configurationLoaded = True
		if args.verbose and not args.background:
			print("Configuration file loaded from: " + filePath)
		break
	except IOError:
		configurationLoaded = False

if not configurationLoaded:
	print >> sys.stderr, ("Error at loading configuration file.")
	sys.exit(1)

try:
	loggingEnabled = conf.getboolean('general', 'log_enabled')
	logFilePath = conf.get('general', 'log_file')
except ConfigParser.Error as exp:
	print >> sys.stderr, ("Could not load logging options: %s" % str(exp))
	sys.exit(1)

logger = logging.getLogger("geiger")
logFormatter = logging.Formatter('%(asctime)s %(name)s %(message)s', datefmt = '[%Y-%m-%d %H:%M:%S]')
if args.verbose:
	logger.setLevel(logging.INFO)
else:
	logger.setLevel(logging.ERROR)

if not args.background:
	consoleLog = logging.StreamHandler(sys.stdout)
	consoleLog.setFormatter(logFormatter)
	logger.addHandler(consoleLog)

if not args.monitor:
	loggingEnabled = False

if loggingEnabled:
	try:
		fileLog = logging.FileHandler(logFilePath)
		fileLog.setFormatter(logFormatter)
		logger.addHandler(fileLog)
	except IOError as exp:
		print >> sys.stderr, ("Could open log file to write: %s" % str(exp))
		sys.exit(1)

# establish USB connection
try:
	logger.info("Initializing Geiger device...")
	comm = usbcomm.Connector(conf)
except usbcomm.CommException as exp:
	logger.critical("Error at initializing USB device: %s", str(exp))
	sys.exit(1)

# register SIGINT (Ctrl-C) signal handler
signal.signal(signal.SIGINT, signalHandler)
signal.signal(signal.SIGTERM, signalHandler)

# start monitor mode
if args.monitor:
	import monitor
	monitor = monitor.Monitor(configuration = conf, usbcomm = comm)
	monitor.start()

	while True:
		time.sleep(5)

# default behavior: display values from Geiger device and leave
print(comm)
sys.exit()


import numpy as np
import tensorflow as tf
import gym

# Parameters
EPISODES = 10000
LEARNING_RATE = 0.1
DISCOUNT_FACTOR = 0.99
EPSILON = 0.1

# Create the FrozenLake environment
env = gym.make('FrozenLake-v1')
num_actions = env.action_space.n
num_states = env.observation_space.n

# Deep Q-Network model
model = tf.keras.Sequential([
    tf.keras.layers.Dense(64, activation='relu', input_shape=(num_states,)),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(num_actions, activation='linear')
])

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE),
              loss='mean_squared_error')

# Function to select an action using epsilon-greedy strategy
def choose_action(state, epsilon):
    if np.random.uniform(0, 1) < epsilon:
        return np.random.randint(num_actions)
    else:
        Q_values = model.predict(np.array([state]))
        return np.argmax(Q_values)

# Function to perform the Q-learning update
def q_learning_update(state, action, reward, next_state, done):
    target = reward
    if not done:
        Q_next = model.predict(np.array([next_state]))
        target += DISCOUNT_FACTOR * np.max(Q_next)

    Q_values = model.predict(np.array([state]))
    Q_values[0][action] = target

    model.fit(np.array([state]), Q_values, epochs=1, verbose=0)

# Deep Q-Learning
@tf.function
def deep_q_learning():
    epsilon = EPSILON
    rewards = []

    for episode in range(EPISODES):
        state = env.reset()
        total_reward = 0

        while True:
            # Convert the integer state to one-hot encoded array and reshape it
            state_one_hot = np.zeros(num_states)
            state_one_hot[state] = 1
            state_one_hot = np.reshape(state_one_hot, (1, num_states))

            action = choose_action(state_one_hot, epsilon)
            next_state, reward, done, _ = env.step(action)
            total_reward += reward

            # Convert the integer next_state to one-hot encoded array and reshape it
            next_state_one_hot = np.zeros(num_states)
            next_state_one_hot[next_state] = 1
            next_state_one_hot = np.reshape(next_state_one_hot, (1, num_states))

            q_learning_update(state_one_hot, action, reward, next_state_one_hot, done)

            state = next_state

            if done:
                rewards.append(total_reward)
                break

        # Decay epsilon over episodes
        epsilon = max(0.1, epsilon * 0.999)

        # Print progress
        if episode % 100 == 0:
            print(f"Episode {episode}, Average Reward: {np.mean(rewards[-100:])}")

if __name__ == "__main__":
    deep_q_learning()


import pygame
import sys
import pyautogui
import easygui
import Ndepth
#import FullSearch
from config import *

# Initialization
pygame.init()

clock = pygame.time.Clock()

screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
pygame.display.set_caption("1. praktiskais darbs")

icon = pygame.image.load('img/games.png')
pygame.display.set_icon(icon)

# Fonts and texts in game

# NewGame texts
HeadFont = pygame.font.Font('fonts/Roboto/Roboto-Black.ttf', 20)
SmallFont = pygame.font.Font('fonts/Roboto/Roboto-Black.ttf', 17)
NewGameFont = pygame.font.Font('fonts/Roboto/Roboto-Medium.ttf', 50)

NewGame = NewGameFont.render('New game', False, "White", 'Red')
NewGameRect = NewGame.get_rect(topleft=((SCREEN_W - NewGame.get_width()) / 2, 300))

Header = NewGameFont.render('Game: Nims', False, "Yellow")
HeaderRect = Header.get_rect(topleft=((SCREEN_W - Header.get_width()) / 2, 50))

ValidText = HeadFont.render('Input error', False, "White")
ValidTextRect = ValidText.get_rect(topleft=((SCREEN_W - ValidText.get_width()) / 2, 400))

ValidGameText = HeadFont.render('Input error', False, "Black")
ValidGameTextRect = ValidText.get_rect(topleft=((SCREEN_W - ValidText.get_width()) / 2, 500))

AIStep = pygame.Surface((200, 100))
AIStep.fill('Red')
AIStepRect = AIStep.get_rect(topleft=((SCREEN_W / 2 - AIStep.get_width()), 400))
AIText = SmallFont.render('First step - AI', False, "Black")
AITextRect = AIText.get_rect(topleft=(AIStepRect.x + 40, AIStepRect.y + 40))

UserStep = pygame.Surface((200, 100))
UserStep.fill('Green')
UserStepRect = UserStep.get_rect(topleft=((SCREEN_W / 2), 400))
UserText = SmallFont.render('First step - User', False, "Black")
UserTextRect = UserText.get_rect(topleft=(UserStepRect.x + 40, UserStepRect.y + 40))

stick = pygame.image.load('img/billiard.png')
stick = pygame.transform.scale(stick, (50, 50))

# Print current game condition - N and count of stick taken by each player
def printres(N, cnt1, cnt2):
    Score = SmallFont.render('Current N: ' + str(N), False, "Black")
    ScoreRect = Score.get_rect(topleft=((SCREEN_W - Score.get_width()) / 2, 130))
    screen.blit(Score, ScoreRect)
    Score = SmallFont.render('Users taken sticks: ' + str(cnt1), False, "Black")
    ScoreRect = Score.get_rect(topleft=(50, 430))
    screen.blit(Score, ScoreRect)
    Score = SmallFont.render('AI taken sticks: ' + str(cnt2), False, "Black")
    ScoreRect = Score.get_rect(topleft=(50, 450))
    screen.blit(Score, ScoreRect)

# Logical variable for drawing

IsNewGame = True
ValidBlock = False

# Initialization values

UserScore = 0
AIScore = 0
color = 'Black'

N = -1
K = -1
AIFirst = False
ShowSteps = False
UserCount = 0
AICount = 0

while True:
    screen.fill(color)
    screen.blit(Header, HeaderRect)

    # New Game screen
    if IsNewGame:
        color = 'Black'
        mouse = pygame.mouse.get_pos()
        keys = pygame.key.get_pressed()

        # Draw
        screen.blit(NewGame, NewGameRect)
        Score = SmallFont.render('User ' + str(UserScore) + ': ' + str(AIScore) + ' AI', False, 'White')
        ScoreRect = Score.get_rect(topleft=((SCREEN_W - Score.get_width()) / 2, 130))
        screen.blit(Score, ScoreRect)
        if ShowSteps:
            screen.blit(UserStep, UserStepRect)
            screen.blit(UserText, UserTextRect)
            screen.blit(AIStep, AIStepRect)
            screen.blit(AIText, AITextRect)
        if ValidBlock:
            screen.blit(ValidText, ValidTextRect)

        # User actions
        if NewGameRect.collidepoint(mouse) and pygame.mouse.get_pressed()[0]:
            ShowSteps = True
            ValidBlock = False

        if (UserStepRect.collidepoint(mouse) or AIStepRect.collidepoint(mouse)) and pygame.mouse.get_pressed()[0]:
            UserCount = 0
            AICount = 0
            ShowSteps = False

            if UserStepRect.collidepoint(mouse):
                AIFirst = False
            else:
                AIFirst = True
            try:
                N = int(easygui.enterbox("Enter N - the number of sticks at the beginning:"))
                K = int(easygui.enterbox("Enter K - the number of sticks can be taken per turn"))
                if N <= 0 or K <= 0:
                    raise Exception()

                IsNewGame = False
                color = 'White'
            except ValueError:
                ValidBlock = True
            except Exception:
                ValidBlock = True
    else:
        # Game Screen

        # End game condition
        if N <= 0:
            if AIFirst:
                UserScore += 1
                pyautogui.alert("User wins")
            else:
                AIScore += 1
                pyautogui.alert("AI wins")
            IsNewGame = True
            continue

        # Vizualization

        for i in range(0, int(N / 10) + 1):
            for j in range(0, min(N - i * 10, 10)):
                screen.blit(stick, ((SCREEN_W - (50 * min(N - i * 10, 10))) / 2 + j * 50, 200 + i * 75))
        printres(N, UserCount, AICount)
        pygame.display.flip()

        # Step logic
        if AIFirst:
            curK = Ndepth.getnewK(N, K)  # Algorithm "Pārlūkošana uz priekšu pār ngājieniem"
            #curK = FullSearch.getnewK(N, K) # Alhorithm "Minimaksa" with full detour of the graph
            AICount += curK
            N -= curK
        else:
            # User step - input "K" and decrease number of the sticks
            while True:
                try:
                    if ValidBlock:
                        screen.blit(ValidGameText, ValidGameTextRect)
                        pygame.display.flip()
                    curK = int(easygui.enterbox("Ievadiet skaitli, cik serkocinu janonem [1:" + str(min(N, K)) + "]"))
                    if curK <= 0 or curK > min(N, K):
                        raise Exception()
                    ValidBlock = False
                    break
                except ValueError:
                    ValidBlock = True
                except Exception:
                    ValidBlock = True
            UserCount += curK
            N -= curK

        AIFirst = not AIFirst

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.flip()
    clock.tick(100)


# **************** SAE特征提取+ t-SNE可视化 + DBSCAN聚类 *****************
# 待完成： SAE的优化， DBSCAN编写

import pandas as pd
from sklearn import preprocessing
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn import manifold

import TE_function as TE

#%% 选择样本
# 1类正常，11类故障：1,2,4,6,7,11,13,14,17,19,20
fault_classes = 1, 2, 4, 6, 7, 11, 13, 14, 17, 19, 20  # 故障类别
train_x, train_y = TE.get_data('train', fault_classes, onehot=False)

#%% SAE特征提取
n_input = 52  # 输入节点数
n_hidden = 20  # 隐层节点数
n_output = 52  # 输出节点数
learning_rate = 0.5  # 学习率
dropout_keep_prob = 1  # dropout参数
epochs = 200  # 迭代次数
lamda = 0.0001  # 正则化参数

x = tf.placeholder(tf.float32, [None, n_input])
weights = {
    'encoder_W': tf.Variable(tf.random_normal([n_input, n_hidden])),
    'decoder_W': tf.Variable(tf.random_normal([n_hidden, n_output]))
}
biases = {
    'encoder_b': tf.Variable(tf.zeros(n_hidden)),
    'decoder_b': tf.Variable(tf.zeros(n_output))
}

def encoder(input_):
    # feature_x = tf.nn.sigmoid(tf.matmul(x, weights['encoder_W']) + biases['encoder_b'])  # 特征层sigmoid输出
    feature_ = tf.matmul(input_, weights['encoder_W']) + biases['encoder_b']  # 特征层线性输出
    return feature_

def dropout(feature_):  # 加入dropout层，防止过拟合
    feature_dropout_ = tf.nn.dropout(feature_, dropout_keep_prob)
    return feature_dropout_

def decoder(feature_dropout_):
    reconstruction_ = tf.nn.sigmoid(tf.matmul(feature_dropout_, weights['decoder_W']) + biases['decoder_b'])
    return reconstruction_

feature = encoder(x)  # 特征
feature_dropout = dropout(feature)  # dropout输出
reconstruction = decoder(feature_dropout)  # 重建输入

cost = tf.reduce_mean(tf.reduce_sum(tf.pow(reconstruction - x, 2), axis=1)) \
       + lamda * (tf.nn.l2_loss(weights['encoder_W']) + tf.nn.l2_loss(weights['decoder_W']))  # L2范数
optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

batch_size = 256
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    ds = TE.DataSet(train_x, train_x)
    batch_num = int(train_x.shape[0] / batch_size)
    cost_history = {'Epoch': [], 'cost': []}

    print("******** 自编码器开始学习特征 ********")
    for epoch in range(epochs):
        total_cost = 0
        for _ in range(batch_num):
            batch_xs, batch_ys = ds.next_batch(batch_size)
            batch_xs_noise = batch_xs + 0.3*np.random.randn(batch_size, n_input)
            _, c = sess.run([optm, cost], feed_dict={x: batch_xs_noise})
            total_cost += c
        cc = total_cost / batch_num
        cost_history['Epoch'].append(epoch)
        cost_history['cost'].append(cc)
        if epoch % 10 == 0:
            print("Epoch:%5d     cost:%.6f" % (epoch, cc))
    print("******** 自编码器特征提取完成 ********\n")

    plt.plot(cost_history['Epoch'], cost_history['cost'])
    plt.xlabel('epcoh')
    plt.ylabel('cost')
    plt.title('Autoencoder: Feature extraction')
    plt.show()

    # 得到训练集的特征
    train_feature = sess.run(feature, feed_dict={x: train_x})

#%% t-SNE可视化
print('t-SNE拟合... ...')
tsne = manifold.TSNE(n_components=2)
train_tsne = tsne.fit_transform(train_feature)
print('t-SNE拟合完成.')

plt.scatter(train_tsne[:, 0], train_tsne[:, 1], s=2)
plt.show()
plt.scatter(train_tsne[:, 0], train_tsne[:, 1], c=train_y, s=2)
plt.show()


# 벽 부수고 이동하기 ( 시간초과 )

import sys
from collections import deque

# N,M 입력
n,m = map(int,sys.stdin.readline().split())

# arr 입력
arr = []
for _ in range(n):
    arr.append(list(map(int,sys.stdin.readline().strip())))

# 우 하 좌 상
ind_x = [0, -1, 0, 1]
ind_y = [1, 0, -1, 0]

q = deque()

for i in range(n):
    for j in range(m):
        if arr[i][j] == 1:
            q.append((i,j))

minlen=[]

while q:
    i,j = q.popleft()
    arr[i][j] = 0
    count = 0
    visited = []
    queue = deque()
    queue.append((0,0,1))
    while queue:
        x,y,c = queue.popleft()
        for k in range(4):
            xm = x + ind_x[k]
            ym = y + ind_y[k]
            if xm < 0 or xm >= n or ym < 0 or ym >= m or (xm,ym) in visited:
                continue
            elif xm == n-1 and ym == m-1:
                minlen.append(c+1)
                break
            elif arr[xm][ym] == 0:
                queue.append((xm,ym,c+1))
                visited.append((xm,ym))
            else:
                continue

    arr[i][j] = 1

if len(minlen) == 0:
    print(-1)
else:
    print(min(minlen))


"""user_add_field_telegram_blocked

Revision ID: 73c0ad19dc7a
Revises: c58512d0c0c1
Create Date: 2023-01-25 12:07:03.075311

"""
import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = '73c0ad19dc7a'
down_revision = 'c58512d0c0c1'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('users', sa.Column('telegram_blocked', sa.Boolean(), nullable=True))
    op.execute("UPDATE users SET telegram_blocked = False")
    op.alter_column('users', 'telegram_blocked', nullable=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('users', 'telegram_blocked')
    # ### end Alembic commands ###


# from collections.abc import Generator
#
#
# def tree(cls, level=0):
#     yield cls, level
#     for c in cls.__subclasses__():
#         yield from tree(c, level+1)
#
#
# def display(cls) -> Generator:
#     for sub_class, level in tree(cls):
#         indent = level * '\t'
#         print(f"{indent}{sub_class.__name__}")
import functools
import itertools
from collections.abc import Iterator
from operator import add, mul
from typing import TypeAlias

if __name__ == '__main__':

    # IntIter: TypeAlias = Iterator[int | str]
    #
    # def fibonacci() -> IntIter:
    #     a, b = 0, 1
    #     while True:
    #         yield a
    #         a, b = b, b + a
    #         if a > 10:
    #             return "Vlad fryed LErka"
    #
    # it = fibonacci()
    # print(next(it))
    # print(next(it))
    # print(next(it))
    # print(next(it))
    # print(next(it))
    # print(next(it))
    # print(next(it))
    # try:
    #     print(next(it))
    # except StopIteration as exp:
    #     print(exp.value)

    money_additions = (10_000, 1.1, 1.05, 1.5, 0.67, 0.43,
                       0.1, 1.4, 2.6, 5.8, 58.8, 683.6)

    def refactor(obj: float):
        if obj == 0:
            return "000"
        if obj < 10:
            return round(obj * 100)
        if obj < 100:
            return round(obj * 10)
        return round(obj)

    def transform_money(money: float):
        ext: str = ''
        while money >= 1000:
            money, res = divmod(money, 1000)
            ext += f'_{refactor(res)}'
        return f"{int(money)}{ext}"

    print(*map(lambda i: f"{transform_money(i)}$",
               itertools.accumulate(money_additions, mul)))


from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from information import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.render_html, name="index"),
    url(r'^successful-entrepreneur/$', views.onboard_successful_entrepreneur,
        name="founder"),
    url(r'^angel/$', views.onboard_angel, name="angel"),
    url(r'^entrepreneur/$', views.onboard_entrepreneur, name="entrepreneur"),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,
                          document_root=settings.STATIC_ROOT)
else:
    urlpatterns += static(settings.STATIC_URL,
                          document_root=settings.STATIC_ROOT)


from pymysql.err import IntegrityError
from fastapi import Request, status
from fastapi.responses import JSONResponse

class HasUsedException(Exception):
    """
    参数值与数据库中数据重复，已被使用
    """
    def __init__(self, name, value=None):
        self.name = name
        self.value = value

async def has_used_exception_handler(request: Request, exc: HasUsedException):
    if exc.value is not None:
        message = f'"{exc.value}",the value of param "{exc.name}",has been used'
    else:
        message = f'The value of param "{exc.name}" has been used'
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content={'detail': message}
    )

async def integrity_error_handler(request: Request, exc: IntegrityError):
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content={'detail': str(exc)}
    )


#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'hina'

# 传说中的ORM技术：Object-Relational Mapping，把关系数据库的表结构映射到对象上

# 在Python中，最有名的ORM框架是SQLAlchemy

from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = "user"

    id = Column(String(20), primary_key = True)
    name = Column(String(20))

engine = create_engine("mysql+mysqlconnector://root:57235742@localhost:3306/test")
DBSession = sessionmaker(bind=engine)

session = DBSession()
new_user = User(id = "5", name = "Bob")
session.add(new_user)
session.commit()
session.close()

session = DBSession()
user = session.query(User).filter(User.id == "5").one()
print("type", type(user))
print("name", user.name)
session.close()


import logging
import time
from datetime import datetime
import json
from app import startup, db, settings
from mailing import Postman
from models import Email, Statuses

class MailService(object):
    """
    1. Query the Database.
    2. Fetch a single item.
    3. Mark that item in_progress
    4. Once sent, set item free either finished/queued to be retried soon
    """
    def __init__(self, db):
        self.postman = Postman(**{'mailgun_key': settings.get('default', 'mailgun_key'),
                                  'mailgun_domain': settings.get("default", "mailgun_domain"),
                                  'sendgrid_key': settings.get('default', 'sendgrid_key')})
        self.db = db

    def lock_instance(self, mail):

        mail.status = Statuses.inprogress
        mail.updated_at = datetime.utcnow()
        self.db.session.add(mail)
        self.db.session.commit()

    def release_instance(self, mail, status=Statuses.success, result=None):

        mail.status = status
        mail.lock = None
        mail.updated_at = datetime.utcnow()
        mail.result = json.dumps(result) if result is not None else None

        self.db.session.add(mail)
        self.db.session.commit()

    def send_mail(self, mail):
        # handle timeouts. what if the service does not return a response in X seconds/minutes ?
        delivery_result = self.postman.deliver(mail.from_address, mail.to_address, mail.subject, mail.mail)

        logging.info(mail.id, delivery_result)
        status_code = delivery_result['status']

        if status_code >= 429:  # classic 5xx + 429 (Too many requests)
            logging.error("Mail service error", extra=dict(mail_id=mail.id, http_res=delivery_result))
            self.postman.switch()
            self.release_instance(mail, status=Statuses.queued)
        elif delivery_result['success']:
            self.release_instance(mail, Statuses.success, delivery_result)
        else:
            # handle 3xx and 4xx errors.
            # if there's a change in the API, and receive 4xx for all
            # we will set the whole queue status into ERROR mode.
            logging.error("Mail service warning", extra=dict(mail_id=mail.id, http_res=delivery_result))
            self.release_instance(mail, Statuses.error, delivery_result)

    def query(self):
        logging.info("Query Mail Queue")
        eq = Email.query.filter(Email.status == Statuses.queued)

        for mail in eq:
            self.lock_instance(mail)
            self.send_mail(mail)
            break

    def forever(self):
        while True:
            self.query()
            time.sleep(10)

if __name__ == "__main__":
    ms = MailService(db)
    ms.forever()


from os import path
import pygame.sprite

class Boss(pygame.sprite.Sprite):
    def __init__(self,level):
        pygame.sprite.Sprite.__init__(self)
        #self.image = pygame.Surface([500, 500])
        self.width = 200
        self.height = 100
        self.level = 0
        self.id = "boss1"
        if level == 0:
            self.width = 200
            self.height = 100
            self.hp = 30
            self.level = 0
            self.id = "boss1"
        elif level == 1:
            self.width = 150
            self.height = 200
            self.hp = 60
            self.level = 1
            self.id = "boss2"
        elif level == 2:
            self.width = 200
            self.height = 100
            self.hp = 90
            self.level = 2
            self.id = "boss3"

        self.image = pygame.Surface([self.width, self.height])
        self.color = "#FFEB3B"
        self.rect = self.image.get_rect()
        self.rect.center = (600, 80)

        self.dir = 10
        self.bullets = pygame.sprite.Group()
        self.times_up = 3
        self.counter = 0
        self.hp = 100

    def get_bullets(self):
        return self.bullets

    def _gen_bullets(self, count: int = 1, gap:int = 0, y:int = 0, speed:int = 10.5):
        sum = 0
        for i in range(count):
            # add food to group
            bullet = Bullet(self.bullets, self.rect.centerx, self.rect.centery+sum, 0, y, speed)
            sum += gap

    def _gen_bullets_side(self, count: int = 1, gap:int = 0, y:int = 0, speed:int = 10.5):
        sum = 0
        for i in range(count):
            # add food to group
            bullet = Bullet(self.bullets, self.rect.centerx+self.width/2, self.rect.centery+sum, 0, y, speed)
            bullet = Bullet(self.bullets, self.rect.centerx-self.width/2, self.rect.centery+sum, 0, y, speed)
            sum += gap

    def recycle(self,items):
        for item in items:
            if(item.rect.centery < 0 or item.rect.centery > 600 or item.rect.centerx < 0 or item.rect.centerx > 600):
                items.remove(item)

        return items

    def _fire(self, times_up, b_num, gap, y:int = 0, speed:int = 10.5, side:bool = False):
        if side:
            if(self.counter % times_up == 0):
                self._gen_bullets_side(b_num, gap, y, speed)
        else:
            if(self.counter % times_up == 0):
                self._gen_bullets(b_num, gap, y, speed)

    def update(self):
        #body
        self.rect.centerx += self.dir
        if(self.rect.centerx < 0 or self.rect.centerx > 1280):
            self.dir = -self.dir

        #bullet
        self.counter +=1
        self._fire(10,1, 0)
        if self.level >= 1:
            self._fire(30,30, 7, 300, 30)
        if self.level >= 2:
            self._fire(15,15, 7, 100, 50, True)

        #self.recycle(self.bullets)

    @property
    def game_object_data(self):
        return {"type": "image",
                "x": self.rect.x,
                "y": self.rect.y,
                "angle": 0,
                "width": self.rect.width,
                "height": self.rect.height,
                "image_id": self.id
                }

class Bullet(pygame.sprite.Sprite):
    def __init__(self, group, x, y, dir, speed_up_y:int = 0, speed: int = 10.5):
        pygame.sprite.Sprite.__init__(self, group)
        self.image = pygame.Surface([8, 8])
        self.color = "#FF90A0"
        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.centery = y
        self.angle = 0
        self.dir = dir
        self.speed = 10.5
        self.speed_up_y = speed_up_y
        self.changeSpeed = speed

    def update(self) -> None:
        if(self.speed_up_y > 0 and self.rect.centery > self.speed_up_y):
            self.rect.centery += self.changeSpeed
        else:
            self.rect.centery += self.speed

    @property
    def game_object_data(self):
        return {"type": "rect",
                "name": "ball",
                "x": self.rect.x,
                "y": self.rect.y,
                "angle": 0,
                "width": self.rect.width,
                "height": self.rect.height,
                "color": self.color
                }


from requests import Session, Response

# Shamelessly stolen from: https://stackoverflow.com/a/6798042/11985743
class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class SdarotController(Session, metaclass=Singleton):
    """
    Maybe in future, using a singleton is better since
    it will use only 1 request for the entire session.
    """

    def __init__(self, sdarot_base: str = None) -> None:
        super().__init__()

        # The first time we are called, we must get the Sdarot base URL
        # If we call this later, the singleton metaclass will catch it.
        # Therefore, if we get 'None' now as the parameter, there is an issue.
        if not sdarot_base:
            raise Exception(
                "No Sdarot URL found, make sure you have made an instance of the PySdarot class at least once. "
                "If you have and are still facing this issue, then please report this as a bug."
            )

        # Singletons don't need static classes, we can write this directly to the property
        self.__sdarot_base = sdarot_base

        # Initialize the session with fake UA
        self.headers.update({
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/83.0.4103.97 Safari/537.36',
            'origin': self.__sdarot_base,
            'referer': self.__sdarot_base
        })

        # Get initial 'anon'/guest cookies
        self.get(self.__sdarot_base)

        # Add base URL to relative paths
        self.request = self.request_override

    def request_override(self, method: str, relative_url: str, full_url: bool = False, **kwargs) -> Response:
        # Don't modify URL
        if full_url:
            return super().request(method, relative_url, **kwargs)
        else:
            # Attach relative URL to base
            # Pretty weird practice, but it's annoying to pass the base URL around using parameters
            # If someone has a better suggestion, feel free to drop a PR! :)
            return super().request(
                method=method,
                url=self.__sdarot_base + relative_url,
                **kwargs
            )


#!/usr/bin/env python
from flask import Flask
import logging
import logging.handlers
from flask_restful import Api
from utils import LocalConfigParser
import os

#shokabetsports api classes
from api import Bet, Balance, ScorepesaApiSendSms,\
 TelegramRequest, MQRequest, Withdraw, JackpotBet, ScorepesaTestApiSendSms,\
 JackpotMatches, BingwaMatches, ProfileMgt, BetCancel, ScorepesaPointJackpot,\
 ScorepesaPointAward, ScorepesaReferral, BonusPromo, JpBonusAward, TransactionMgt, UssdMatch,\
 SpecialsBet, XposeAPI, BetDetail

#virtuals api classes
from virtuals_api import BetVirtual

#casino api classes
from casino_api import ReserveFunds, CreditRequest, ConfirmPaymentRequest,\
 ConfirmRequest, CancelPaymentRequest, CancelRequest, ReSettleRequest, UserFundsRequest,\
 SessionCheckRequest, PlayerDetail

#mobile app api classes
from mobile_api import (ScorepesaAppVersion, ScorepesaAppRegDevice,
	ScorepesaAppDownload, Xposed, Matches, Sports,
	CompetitionSport, JackpotAndroidMatches, SignupAndroid, Login,
        AndroidBalance, MyBets, BetDetails, AndroidVerify, AndroidCode)

cur_dir = os.path.dirname(__file__)

filename = '/var/log/scorepesa-mo/scorepesa_mo_api.log'
redis_cfgs = LocalConfigParser.parse_configs("SCOREPESAREDIS")

#attributes
app = Flask(__name__)

app.config['redis_host'] = redis_cfgs['redis_host']
app.config['redis_port'] = redis_cfgs['redis_port']
app.config['db']=redis_cfgs['redis_db']
app.config['redis_passwd']=redis_cfgs['redis_password']

api = Api(app)

#Scorepesa URIs
app.add_url_rule('/bet', view_func=Bet.as_view('bet'))
app.add_url_rule('/balance', view_func=Balance.as_view('balance'))
app.add_url_rule('/bet-detail', view_func=BetDetail.as_view('bet-detail'))
app.add_url_rule('/bet_virtual', view_func=BetVirtual.as_view('bet_virtual'))
api.add_resource(JackpotBet, '/jp/bet')
api.add_resource(ScorepesaApiSendSms, '/sendsms')
api.add_resource(TelegramRequest, '/tlg_bot')
api.add_resource(MQRequest, '/mq_request')
api.add_resource(Withdraw, '/macatm')
api.add_resource(ScorepesaTestApiSendSms, '/testInj')
#api.add_resource(UssdMatch, '/ussd/match')
api.add_resource(UssdMatch, '/ussd/match/<string:reqparam>')
api.add_resource(JackpotMatches, '/jp_matches')
api.add_resource(BingwaMatches, '/bingwa_matches')
api.add_resource(ProfileMgt, '/profilemgt')
api.add_resource(BetCancel, '/bet_cancel')
api.add_resource(ScorepesaPointJackpot, '/free/jp')
api.add_resource(ScorepesaPointAward, '/award/shokabetpoints')
api.add_resource(ScorepesaReferral, '/referral/award')
api.add_resource(BonusPromo, '/bonus_promo/award')
api.add_resource(JpBonusAward, '/jp_bonuses/award')
api.add_resource(TransactionMgt, '/dc/trx')
api.add_resource(SpecialsBet, '/specials/bet')
api.add_resource(XposeAPI, '/shokabet/<string:reqparam>')
api.add_resource(Xposed, '/misc/<string:reqparam>')
#virtuals URIs
api.add_resource(BetVirtual, '/bet_virtual/bet')

#Android APILS
api.add_resource(Matches, '/v1/matches')
api.add_resource(Sports, '/v1/sports')
api.add_resource(CompetitionSport, '/v1/sports/competition')
api.add_resource(JackpotAndroidMatches, '/v1/matches/jackpot')
api.add_resource(SignupAndroid, '/v1/signup')
api.add_resource(Login, '/v1/login')
api.add_resource(AndroidBalance, '/v1/balance')
api.add_resource(MyBets, '/v1/mybets')
api.add_resource(BetDetails, '/v1/betdetails')
api.add_resource(AndroidVerify, '/v1/verify')
api.add_resource(AndroidCode, '/v1/code')
#casino URIs
api.add_resource(ReserveFunds, '/reserve')
api.add_resource(CreditRequest, '/credit')
api.add_resource(ConfirmPaymentRequest, '/confirmPayment')
api.add_resource(ConfirmRequest, '/confirm')
api.add_resource(CancelPaymentRequest, '/cancelPayment')
api.add_resource(CancelRequest, '/cancel')
api.add_resource(ReSettleRequest, '/reSettle')
api.add_resource(UserFundsRequest, '/userFunds')
api.add_resource(SessionCheckRequest, '/sessionCheck')
api.add_resource(PlayerDetail, '/playerDetail')

#Mobile app URIs
api.add_resource(ScorepesaAppVersion, '/checkVersion')
api.add_resource(ScorepesaAppRegDevice, '/registerDevice')
api.add_resource(ScorepesaAppDownload, '/shokabetApp/<string:ops>')

log_formatter = logging.Formatter(
    "%(asctime)s %(levelname)-8s %(name)-5s %(filename)s:%(lineno)d:%("
    "funcName)-10s %(message)s", datefmt="%m-%d-%y %H:%M:%S")

app.logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
handler.setFormatter(log_formatter)
app.logger.addHandler(handler)

#handler2 = logging.handlers.RotatingFileHandler(filename,
#    maxBytes=1000*1024*1024, backupCount=100)
handler2 = logging.handlers.TimedRotatingFileHandler(filename,
    when='midnight', interval=1, backupCount=100, encoding=None,
    delay=False, utc=False)
handler2.setFormatter(log_formatter)
app.logger.addHandler(handler2)

if __name__ == '__main__':
    #app.run(port=5000, host='0.0.0.0')
    app.run(port=5000)


"""Import avro file into BigQuery."""

import os

from google.cloud import bigquery

def iot_transformed_data(data,context) :

    client = bigquery.Client()

    bucketname = data['bucket']

    timeCreated = data['timeCreated']

    dataset_id = "streaming_data_analysis"

    dataset_ref = client.dataset(dataset_id)

    job_config = bigquery.LoadJobConfig()

    job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE

    job_config.autodetect = True

    job_config.ignore_unknown_values = True

    job_config.source_format = bigquery.SourceFormat.AVRO

    uri = bucketname+"/iot_transformed_data/*.avro"

    load_job = client.load_table_from_uri(uri,dataset_ref.table('device_energy_consumption'),job_config=job_config)

    print("Starting Job {}".format(load_job.job_id))

    load_job.result()

    print("Job Finished")

    destination_table = client.get_table(dataset_ref.table('device_energy_consumption'))
    print('Loaded {} rows.' .format(destination_table.num_rows))


import utils

# Anzahl aller Knoten im Netzwerk
nodes_number = 256
# Anzahl der korrumpierten Knoten
corrupted_number = 200
# Anzahl der Cluster im Netzwerk
cluster_number = 2
# Anzahl der ausgewählten Nodes pro Cluster
picked_nodes_number = 8
# Anzahl der Iterationen für die Simulation
iteration_number = 100
# Anzahl der gleichen Ergebnisse im gesamten Quorum
threshold = 0.5
# Anzahl der gleichen Ergebnisse im Nested Quorum
nested_threshold = 0.5

debug = False

for v in [4, 8, 16, 32, 64]:

    for c in [1, 2, 4, 8, 16, 32, 64]:
        successful_corrupted_number = 0
        cluster_number = c
        picked_nodes_number = int(v / c)
        corrupted_number = picked_nodes_number

        if picked_nodes_number == 0:
            break

        for _ in range(iteration_number):
            # Create clusters
            clusters = utils.create_clusters(nodes_number, cluster_number)
            if debug:
                print('clusters:' + str(clusters))

            # Create corrupted nodes
            corrupted_clusters = utils.create_corrupted_clusters(clusters, corrupted_number)
            if debug:
                print('corrupted clusters:' + str(corrupted_clusters))

            successful_corrupted_clusters = utils.filter_corrupted_clusters(corrupted_clusters, picked_nodes_number, nested_threshold)
            if debug:
                print('successful corrupted clusters:' + str(successful_corrupted_clusters))

            successful_corrupted_cluster_number = len(successful_corrupted_clusters)
            successful_corrupted_ratio = successful_corrupted_cluster_number / cluster_number
            if successful_corrupted_ratio > threshold:
                successful_corrupted_number += 1

        print('V: ' + str(v))
        print('Cluster count: ' + str(cluster_number))
        print('Picked nodes count: ' + str(picked_nodes_number))
        print('Successful corrupted: ' + str(successful_corrupted_number))
        print('Successful corrupted ratio: ' + str(successful_corrupted_number / iteration_number))
        print('-'*100)


"""
All models for core app are defined here.
"""
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.shortcuts import reverse
from django_countries.fields import CountryField

class Actor(models.Model):
    """
    Actor model.
    """
    name = models.CharField(max_length=100)  # Name of the actor

    class Meta:
        ordering = ["name"]  # Order actors by name

    def __str__(self):
        return self.name

class Director(models.Model):
    """
    Director model.
    """
    name = models.CharField(max_length=100)  # Name of the director

    class Meta:
        ordering = ["name"]  # Order directors by name

    def __str__(self):
        return self.name

class Genre(models.Model):
    """
    Genre model.
    """
    name = models.CharField(max_length=100)  # Name of the genre

    class Meta:
        ordering = ["name"]  # Order genres by name

    def __str__(self):
        return self.name

class Movie(models.Model):
    """
    Movie model.
    """

    title = models.CharField(max_length=100)  # Title of the movie
    runtime = models.IntegerField(blank=True, null=True)  # Movie runtime
    year = models.IntegerField()  # Release year of the movie
    description = models.TextField(null=True)  # Basic movie description

    # IMDb rating for the movie
    rating = models.DecimalField(decimal_places=1, max_digits=2)
    genre = models.ManyToManyField(Genre)  # Movie genres, foreign key to Genre

    # Movie director, foreign key to Director
    directors = models.ManyToManyField(Director)

    # Movie actors, foreign key to Actor
    actors = models.ManyToManyField(Actor)
    certificate = models.TextField(max_length=4)  # Age rating for the movie
    icon_url = models.SlugField(max_length=220, null=True)
    poster_url = models.SlugField(max_length=220, null=True)
    big_poster_url = models.SlugField(max_length=220, null=True)

    class Meta:
        ordering = ["runtime"]  # Order movies by runtime

    def get_absolute_url(self):
        """
        Returns the url to access a particular instance of the model.
        """
        return reverse("core:movie", kwargs={
            "pk": self.pk
        })

    def get_add_to_cart_url(self):
        """
        Returns the url to add the movie to cart.
        """
        return reverse("core:add-to-cart", kwargs={
            "pk": self.pk
        })

    def get_remove_from_cart_url(self):
        """
        Returns the url to add the movie to cart.
        """
        return reverse("core:remove-from-cart", kwargs={
            "pk": self.pk
        })

    def get_add_to_wishlist_url(self):
        """
        Returns the url to add the movie to cart.
        """
        return reverse("core:add-to-wishlist", kwargs={
            "pk": self.pk
        })

    def get_remove_from_wishlist_url(self):
        """
        Returns the url to add the movie to cart.
        """
        return reverse("core:remove-from-wishlist", kwargs={
            "pk": self.pk
        })

    def __str__(self):
        return self.title

class OrderItem(models.Model):
    """
    Links the Movie model. When a Movie object is added to the cart it becomes an OrderItem object.
    """
    # User who added the movie to the cart
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE)
    item = models.ForeignKey(Movie, on_delete=models.CASCADE)
    ordered = models.BooleanField(default=False)  # If the order is completed

    DURATION_CHOICES = [
        ("D", "One Day"),
        ("W", "One Week"),
        ("P", "Permanent"),
    ]
    duration = models.CharField(
        max_length=1,
        choices=DURATION_CHOICES,
        default="D"
    )

    price = models.DecimalField(  # Price of the movie
        max_digits=5,
        decimal_places=2,
        default=100.00,
    )

    def __str__(self):
        return f"{self.item.title} rented for {self.get_duration_display()}"

    def save(self, *args, **kwargs):
        """
        Overriding default save() function to set price dynamically.
        """
        if self.duration == "P":
            self.price = 300.00
        elif self.duration == "W":
            self.price = 200.00
        else:
            self.price = 100.00

        super().save(*args, **kwargs)

class Order(models.Model):
    """Stores all the movies in the cart. Can be thought of as the model for the User's cart."""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE
    )  # User who made the order

    items = models.ManyToManyField(OrderItem)  # Movies in the cart

    start_date = models.DateTimeField(
        auto_now_add=True
    )  # Date when the order was started

    ordered_date = models.DateTimeField()  # Date when the order was confirmed

    ordered = models.BooleanField(default=False)  # If the order is completed

    address = models.ForeignKey(
        "Address", on_delete=models.SET_NULL, blank=True, null=True)

    def __str__(self):
        return f"{self.id}: {self.start_date}"

    def get_total(self):
        """
        Returns the total price of the order.
        """
        total = 0
        for order_item in self.items.all():
            total += order_item.price
        return total

class Address(models.Model):
    """The address model."""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    address1 = models.CharField(max_length=100)
    address2 = models.CharField(max_length=100)
    country = CountryField(multiple=False)
    pincode = models.CharField(max_length=100)
    default = models.BooleanField(default=False)

    def __str__(self) -> str:
        return self.user.username

class WishlistItem(models.Model):
    """Add movies to wishlist"""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE)
    item = models.ForeignKey(Movie, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.item.title}"

class Wishlist(models.Model):
    """Stores all movies in wishlist"""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE
    )  # User who added to the wishlist

    items = models.ManyToManyField(WishlistItem)  # Movies in the wishlist

class Profile(models.Model):
    """
    User profile model.
    """
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    phone_number = models.CharField(max_length=10, blank=True)
    profile_pic = models.ImageField(
        upload_to="profile_pics/", blank=True, null=True)

    def __str__(self):
        return self.user.username

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_profile(sender, instance=None, created=False, **kwargs):
    """
    Create a profile for the user when user is created.
    """
    if created:
        Profile.objects.create(user=instance)


from PyQt5.QtWidgets import QDialog, QLabel, QLineEdit, QComboBox, QPushButton, QFormLayout, QMessageBox, QPlainTextEdit

class InputDialogWindow(QDialog):
    # def __init__(self, windowTitle, parent = None):
    #     super(inputdialogdemo, self).__init__(parent)
    def __init__(self, winTitle, slt=False, ansopts=None, parent=None):
        super(InputDialogWindow, self).__init__(parent)
        QDialog.__init__(self, parent)

        self.slt = slt
        print('slt --->', slt)
        layout = QFormLayout()

        if self.slt==False:
            self.lb = QLabel("Пожалуйста напишите 'ans' аттрибут:")
            self.le = QLineEdit()
            self.le.setPlaceholderText("option1**?**option2**?**option3")
            layout.addRow(self.lb,self.le)

        self.lb1 = QLabel("Пожалуйста напишите 'text' аттрибут:")
        self.le1 = QLineEdit()
        self.le1.setPlaceholderText("Это текст вашего вопроса")
        if self.slt==True:
            self.le1 = QPlainTextEdit()
        layout.addRow(self.lb1,self.le1)

        if winTitle=="Вторичный вопрос в 'questionnaire' вопроснике" and self.slt==False:
            self.lb3 = QLabel("Пожалуйста выберите 'g_ans':")
            #self.btn1.clicked.connect(self.gettext)
            self.cb0 = QComboBox()
            self.cb0.addItems(ansopts.split("**?**"))
            layout.addRow(self.lb3,self.cb0)
        elif self.slt==True:
            self.le1.setPlaceholderText("Текст ответа")
            self.lb3 = QLabel("Пожалуйста, выберите 'g_ans'")
            self.cb0 = QComboBox()
            self.cb0.addItems(ansopts.split("**?**"))
            layout.addRow(self.lb3, self.cb0)

        self.lb2 = QLabel("Пожалуйста, выберите 'type' тип вопроса")
        #self.btn1.clicked.connect(self.gettext)
        self.cb = QComboBox()
        self.cb.addItems(["rb", "le"])
        layout.addRow(self.lb2,self.cb)

        self.btn1 = QPushButton("Создать тег")
        self.btn1.clicked.connect( lambda: (self.validateInfo(self.slt)) )
        self.btn2 = QPushButton("Отмена")
        self.btn2.clicked.connect(self.reject)
        #self.btn2.clicked.connect(self.getint)
        layout.addRow(self.btn1,self.btn2)
        self.setLayout(layout)
        #self.setWindowTitle(windowTitle)

    def validateInfo(self, sltCheck=False):
        print('проверка информации которая была введена...')
        if (sltCheck==True and self.le1.toPlainText()):
            self.accept()
        elif (sltCheck==False and self.le1.text() and self.le.text()):
            self.accept()
        else:
            QMessageBox.warning(self, "Недостаточно информации", "Пожалуйста, введите все поля",buttons=QMessageBox.Close, defaultButton=QMessageBox.Close)


import os
import sys
import json
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    if len(sys.argv) == 2:
        path = sys.argv[1]
    else:
        path = './train_log'
    #path = './temp'
    for logdir in os.listdir(path):
        logdir = path + '/' + logdir

        #with open(logdir + '/best.json') as f:
        #    best = json.load(f)

        with open(logdir + '/stats.json') as f:
            stats = json.load(f)

        errors = [x['validation_error_top1'] for x in stats]
        idx = errors.index(min(errors))

        best = stats[idx]

        errors1 = [x['validation_error_top1'] for x in stats]
        errors5 = [x['validation_error_top5'] for x in stats]

        cnt = 5

        sma1 = np.zeros(len(errors1) - cnt)
        sma5 = np.zeros(len(errors1) - cnt)

        for i in range(len(sma1)):
            sma1[i] = np.sum(errors1[i:i+cnt]) / cnt
            sma5[i] = np.sum(errors5[i:i+cnt]) / cnt

        idx = np.where(sma1 == min(sma1))[0][0]

        best['sma_error_top1'] = '{:.4f}'.format(sma1[idx])
        best['sma_error_top5'] = '{:.4f}'.format(sma5[idx])
        best['sma_epoch_num'] = int(idx + cnt)
        #best['sma_last_error_top1'] = '{:.4f}'.format(sma1[-1])
        #best['sma_last_error_top5'] = '{:.4f}'.format(sma5[-1])

        with open(logdir + '/best.json', 'w') as outfile:
            json.dump(best, outfile)


import numpy as np

from utils import gauss

class CVTarget:
    def __init__(self,
                 x: np.float,
                 y: np.float,
                 F: np.array,
                 H: np.array,
                 Q: np.array,
                 R: np.array,
                 g: np.float,
                 P_D: np.float,
                 lam: np.float):
        self.lam = lam
        self.x = np.array([
            [x],
            [y],
            [0],
            [0],
        ])
        self.F = F
        self.H = H
        self.Q = Q
        self.R = R
        self.P = np.eye(4, 4)
        self.S = self.innov_cov(self.H, self.P, self.R)
        self.g = g
        self.P_D = P_D

    @staticmethod
    def innov_cov(H, P, R):
        return H@P@np.transpose(H) + R

    def predict(self):
        self.x = self.F@self.x
        self.P = self.F@self.P@np.transpose(self.F) + self.Q
        self.S = self.innov_cov(self.H, self.P, self.R)

    def update(self, Z: list):
        self.S = self.innov_cov(self.H, self.P, self.R)
        zpred = self.zpred()
        innovations = []
        betas_unorm = []
        for z in Z:
            if z.size != 2:
                raise Exception("z has wrong dimension", z)
            innovations.append(z - zpred)
            betas_unorm.append(self.P_D * gauss(z, zpred, self.S))
        betas = betas_unorm / np.sum(betas_unorm)

        # Reduce the mixture to a single innovation weighted by betas
        ny = np.zeros_like(zpred)
        for j, assoc_ny in enumerate(innovations):
            ny += betas[j] * assoc_ny
        W = self.P@np.transpose(self.H)@np.linalg.inv(self.S)

        self.x = self.x + W@ny

        beta_boi = 0
        for j, assoc_ny in enumerate(innovations):
            beta_boi += betas[j]*assoc_ny@assoc_ny.T
        sprd_innov = W@(beta_boi - ny@ny.T)@W.T
        beta_0 = self.lam * (1 - self.P_D)

        self.P = self.P - (1 - beta_0)*W@self.S@W.T + sprd_innov

    def zpred(self):
        return self.H@self.x

    def gate(self, Z):
        zpred = self.zpred()  # declare this first for efficiency
        gated = np.array([z for z in Z if np.transpose(z - zpred)@np.linalg.inv(self.S)@(z - zpred) < self.g**2])
        return gated.reshape((gated.size // 2, 2, 1))


import numpy as np
import topojson.ops

def test_ops_remove_colinear_points():

    test = np.array([[0, 0], [0, 1], [0, 2]])
    result = topojson.ops.remove_collinear_points(test)
    assert result.tolist() == [[0, 0], [0, 2]]

    test = np.array([[0, 0], [1, 1], [0, 2]])
    result = topojson.ops.remove_collinear_points(test)
    assert result.tolist() == test.tolist()


from flask import current_app

def pricing_service(line_items):
    subtotal = 0.0
    item_cnt = 0
    for line_item in line_items:
        unit_price = line_item.unit_price
        qty = line_item.quantity

        item_cnt += qty
        subtotal += unit_price*qty

    tax_rate = current_app.config['TAX_RATE']
    flat_fee_price = current_app.config['FLAT_FEE']
    cost_fee_rate = current_app.config['COST_FEE']

    subtotal = round(subtotal, 2)
    taxes = round(subtotal * tax_rate, 2)

    flat_fee = flat_fee_price * item_cnt
    cost_fee = cost_fee_rate * subtotal
    fees = round(flat_fee + cost_fee, 2)

    total = subtotal + taxes + fees

    return total, subtotal, taxes, fees


import asyncio
import websockets
import json

def setup(handlers):
    @asyncio.coroutine
    def new_connection(websocket, uri):
        while websocket.open:
            raw_json = yield from websocket.recv()
            data = json.loads(raw_json)
            handler = handlers.get(uri, lambda d: raw_json)
            websocket.send(handler(data))
        websocket.close()
    return new_connection

def handle_message(message):
    print("[{room}] {from}: {text}".format(**message))
    return "Thanks, {}".format(message['from'])

server = setup({'/chatroom/': handle_message})
start_server = websockets.serve(server, 'localhost', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()


import csv
import datetime
import logging

import importer
import model

DATE_FORMAT = '%d.%m.%Y'

logger = logging.getLogger(__name__)

class DkbCheckingImporter(importer.Importer):
    """Importer for DKB checking accounts (http://www.dkb.de/).
    """

    def import_transactions(self, file=None, filename=None, currency=None):
        with importer.open_input_file(file, filename, 'iso-8859-1') as file:
            reader = csv.reader(file, delimiter=';', quotechar='"')

            # Read header.
            account_row = next(reader)
            next(reader)
            from_date_row = next(reader)
            to_date_row = next(reader)
            balance_row = next(reader)
            next(reader)
            headers_row = next(reader)

            # Get transactions.
            transactions = []
            for row in reader:
                if len(row) < 8:
                    continue
                settled_date = row[0]
                value_date = row[1]
                booking_type = row[2]
                counterpart = importer.normalize_text(row[3])
                memo = importer.normalize_text(row[4])
                counterpart_account = row[5]
                counterpart_routing = row[6]
                amount = importer.parse_decimal_number(row[7], 'de_DE')
                date = datetime.datetime.strptime(settled_date, DATE_FORMAT)
                memo_parts = (
                        memo, counterpart, counterpart_account,
                        counterpart_routing)
                memo = '. '.join(filter(bool, memo_parts))
                transactions.append(model.Payment(date, amount, memo=memo))
            logger.debug("Imported %d transactions." % len(transactions))
            return transactions

class DkbCreditCardImporter(importer.Importer):
    """Importer for DKB credit cards (http://www.dkb.de/).
    """

    def import_transactions(self, file=None, filename=None, currency=None):
        with importer.open_input_file(file, filename, 'iso-8859-1') as file:
            reader = csv.reader(file, delimiter=';', quotechar='"')

            # Read header.
            card_row = next(reader)
            next(reader)
            from_date_row = next(reader)
            to_date_row = next(reader)
            balance_row = next(reader)
            date_row = next(reader)
            next(reader)
            headers_row = next(reader)

            # Get transactions.
            transactions = []
            for row in reader:
                print(row)
                if len(row) < 5:
                    continue
                value_missing_from_balance = row[0]
                value_date = row[1]
                receipt_date = row[2]
                date = datetime.datetime.strptime(receipt_date, DATE_FORMAT)
                memo =  importer.normalize_text(row[3].strip())
                amount = importer.parse_decimal_number(row[4], 'de_DE')
                orig_amount = row[5] if row[5] else None
                if orig_amount:
                    memo = memo + '. Original amount: ' + orig_amount + '.'
                transactions.append(model.Payment(date, amount, memo=memo))
            logger.debug("Imported %d transactions." % len(transactions))
            return transactions


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import argparse
import collections
from easydict import EasyDict as edict
import logging
import numpy as np

from mindspore.mindrecord import FileWriter
import src.tokenization as tokenization

class SampleInstance():
    """A single sample instance (sentence pair)."""

    def __init__(self, source_sos_tokens, source_eos_tokens, target_sos_tokens, target_eos_tokens):
        self.source_sos_tokens = source_sos_tokens
        self.source_eos_tokens = source_eos_tokens
        self.target_sos_tokens = target_sos_tokens
        self.target_eos_tokens = target_eos_tokens

    def __str__(self):
        s = ""
        s += "source sos tokens: %s\n" % (" ".join(
            [tokenization.printable_text(x) for x in self.source_sos_tokens]))
        s += "source eos tokens: %s\n" % (" ".join(
            [tokenization.printable_text(x) for x in self.source_eos_tokens]))
        s += "target sos tokens: %s\n" % (" ".join(
            [tokenization.printable_text(x) for x in self.target_sos_tokens]))
        s += "target eos tokens: %s\n" % (" ".join(
            [tokenization.printable_text(x) for x in self.target_eos_tokens]))
        s += "\n"
        return s

    def __repr__(self):
        return self.__str__()

def write_instance_to_file(writer, instance, tokenizer, max_seq_length):
    """Create files from `SampleInstance`s."""

    def _convert_ids_and_mask(input_tokens):
        input_ids = tokenizer.convert_tokens_to_ids(input_tokens)
        input_mask = [1] * len(input_ids)
        assert len(input_ids) <= max_seq_length

        while len(input_ids) < max_seq_length:
            input_ids.append(0)
            input_mask.append(0)

        assert len(input_ids) == max_seq_length
        assert len(input_mask) == max_seq_length

        return input_ids, input_mask

    source_sos_ids, source_sos_mask = _convert_ids_and_mask(instance.source_sos_tokens)
    source_eos_ids, source_eos_mask = _convert_ids_and_mask(instance.source_eos_tokens)
    target_sos_ids, target_sos_mask = _convert_ids_and_mask(instance.target_sos_tokens)
    target_eos_ids, target_eos_mask = _convert_ids_and_mask(instance.target_eos_tokens)

    features = collections.OrderedDict()
    features["source_sos_ids"] = np.asarray(source_sos_ids,dtype=np.int32)
    features["source_sos_mask"] = np.asarray(source_sos_mask,dtype=np.int32)
    features["source_eos_ids"] = np.asarray(source_eos_ids,dtype=np.int32)
    features["source_eos_mask"] = np.asarray(source_eos_mask,dtype=np.int32)
    features["target_sos_ids"] = np.asarray(target_sos_ids,dtype=np.int32)
    features["target_sos_mask"] = np.asarray(target_sos_mask,dtype=np.int32)
    features["target_eos_ids"] = np.asarray(target_eos_ids,dtype=np.int32)
    features["target_eos_mask"] = np.asarray(target_eos_mask,dtype=np.int32)
    writer.write_raw_data([features])
    return features

def create_training_instance(source_words, target_words, max_seq_length):
    """Creates `SampleInstance`s for a single sentence pair."""
    EOS = "</s>"
    SOS = "<s>"

    source_sos_tokens = [SOS] + source_words
    source_eos_tokens = source_words + [EOS]
    target_sos_tokens = [SOS] + target_words
    target_eos_tokens = target_words + [EOS]

    instance = SampleInstance(
        source_sos_tokens=source_sos_tokens,
        source_eos_tokens=source_eos_tokens,
        target_sos_tokens=target_sos_tokens,
        target_eos_tokens=target_eos_tokens)
    return instance

cfg = edict({
        'input_file': './data/ch_en_all.txt',
        'vocab_file': './data/ch_en_vocab.txt',
        'train_file_mindrecord': './path_cmn/train.mindrecord',
        'eval_file_mindrecord': './path_cmn/test.mindrecord',
        'train_file_source': './path_cmn/source_train.txt',
        'eval_file_source': './path_cmn/source_test.txt',
        'num_splits':1,
        'clip_to_max_len': False,
        'max_seq_length': 40
})

def main(eval_idx):
    os.mkdir('path_cmn')
    tokenizer = tokenization.WhiteSpaceTokenizer(vocab_file=cfg.vocab_file)

    writer_train = FileWriter(cfg.train_file_mindrecord, cfg.num_splits)
    writer_eval = FileWriter(cfg.eval_file_mindrecord, cfg.num_splits)
    data_schema = {"source_sos_ids": {"type": "int32", "shape": [-1]},
                   "source_sos_mask": {"type": "int32", "shape": [-1]},
                   "source_eos_ids": {"type": "int32", "shape": [-1]},
                   "source_eos_mask": {"type": "int32", "shape": [-1]},
                   "target_sos_ids": {"type": "int32", "shape": [-1]},
                   "target_sos_mask": {"type": "int32", "shape": [-1]},
                   "target_eos_ids": {"type": "int32", "shape": [-1]},
                   "target_eos_mask": {"type": "int32", "shape": [-1]}
                   }

    writer_train.add_schema(data_schema, "tranformer train")
    writer_eval.add_schema(data_schema, "tranformer eval")

    index = 0
    f_train = open(cfg.train_file_source, 'w', encoding='utf-8')
    f_test = open(cfg.eval_file_source,'w',encoding='utf-8')
    f = open(cfg.input_file, "r", encoding='utf-8')
    for s_line in f:
        line = tokenization.convert_to_unicode(s_line)

        source_line, target_line = line.strip().split("\t")
        source_tokens = tokenizer.tokenize(source_line)
        target_tokens = tokenizer.tokenize(target_line)

        if len(source_tokens) >= (cfg.max_seq_length-1) or len(target_tokens) >= (cfg.max_seq_length-1):
            if cfg.clip_to_max_len:
                source_tokens = source_tokens[:cfg.max_seq_length-1]
                target_tokens = target_tokens[:cfg.max_seq_length-1]
            else:
                continue

        index = index + 1
        print(source_tokens)
        instance = create_training_instance(source_tokens, target_tokens, cfg.max_seq_length)

        if index in eval_idx:
            f_test.write(s_line)
            features = write_instance_to_file(writer_eval, instance, tokenizer, cfg.max_seq_length)
        else:
            f_train.write(s_line)
            features = write_instance_to_file(writer_train, instance, tokenizer, cfg.max_seq_length)
    f.close()
    f_test.close()
    f_train.close()
    writer_train.commit()
    writer_eval.commit()

if __name__ == "__main__":
    sample_num = 23607
    eval_idx = np.random.choice(sample_num, int(sample_num*0.2), replace=False)
    parser = argparse.ArgumentParser(description='Transformer creating dataset')
    parser.add_argument('--data_url', required=True, default=None, help='Location of data.')
    parser.add_argument('--train_url', required=True, default=None, help='Location of training outputs.')
    args_opt = parser.parse_args()

    import moxing as mox
    mox.file.copy_parallel(src_url=args_opt.data_url, dst_url='./data/')

    main(eval_idx)
    mox.file.copy_parallel(src_url='./path_cmn/', dst_url=args_opt.train_url)


import os
import logging

DEV_CHAT_ID  = os.getenv("DEVELOPER_CHAT_ID")
PUNCTUATION_LITERALS  = ['?', '!', '&', '>', '|', '\\', '$', '+', '@', '-', '`', '/', ':', '_', '%', ';', '{', ')', '^', '.', '[', '"', '}', '~', ']', '<', '#', '(', '=', '*', ',', "'"]
NUMBER_EMOJI_MAP = {"0": "0⃣", "1": "1⃣", "2": "2⃣", "3": "3⃣", "4": "4⃣","5": "5⃣", "6": "6⃣","7": "7⃣","8": "8⃣","9": "9⃣"}
DICT_TYPING_REPLY, DICT_TYPING_CHOICE, DICT_SELECTING_DEF = range(3)
TRANS_TYPING_REPLY = range(3, 4)
FILES_TYPING_CHOICE, FILES_TYPING_REPLY = range(4, 6)
COMMANDS = {
    '/start': 'Start the conversation with the bot',
    '/quote': 'Get a random quote rendered in form of beautiful image',
    '/files': 'Convert files from one format to another',
    '/dictionary': 'Get benefit of using all dictionaries from a single place',
    '/transliterate': 'Write a Hindi meesage to bot using English literals and get its Hindi transliteration'
}
MEDIC_DICT_TAGS = {"{b}": "*", "{\/b}": "*", "{bc}": "*:* ", "{inf}": "", "{\/inf}": "", "{it}": "_", "{\/it}": "_", "{\/it}": "_", "{ldquo}": "'", "{rdquo}": "'", "{sc}": "", "{\/sc}": "", "{sup}": "", "{\/sup}": "", }

def print_sender_info(update, sender_text=None):
    sender_user = update.message.chat.username
    sender_name = update.message.chat.first_name + " " + update.message.chat.last_name if update.message.chat.last_name else update.message.chat.first_name
    if not sender_text:
        sender_text = update.message.text
    logging.info(f"{sender_user} [{sender_name}] sent: {sender_text}")

def print_sender_choice_and_info(update, choice, sender_text=None):
    sender_user = update.message.chat.username
    sender_name = update.message.chat.first_name + " " + update.message.chat.last_name if update.message.chat.last_name else update.message.chat.first_name
    if not sender_text:
        sender_text = update.message.text
    logging.info(f"{sender_user} [{sender_name}] chose: {choice}")
    logging.info(f"{sender_user} [{sender_name}] sent: {sender_text}")


from flask import Blueprint, request, jsonify
from src.model.user import User
from src.model.movie import Movie
from src.database import db
from src.api_consumption import query_omdb
from src.custom_log import custom_logger

favmovies = Blueprint('favmovies', __name__, template_folder='templates')
MOVIE_NOT_FOUND = {'Response': 'Movie not found'}
USER_NOT_FOUND = {'Response': 'User not found'}

@favmovies.route('/restful/favmovies/<user_id>', methods=['GET'])
def favmovies_get(user_id):
    user = User.query.get(user_id)
    if user:
        custom_logger('favmovies_get: getting user {}'.format(user.email))
        return jsonify(favmovies=[movie.serialize for movie in user.movies])
    else:
        custom_logger('favmovies_get: user id {} not found'.format(user_id))
        return jsonify(USER_NOT_FOUND)

@favmovies.route('/restful/favmovies/<user_id>/<imdbID>', methods=['GET'])
def favmovies_get_single(user_id, imdbID):
    user = User.query.get(user_id)
    if user:
        movie = user.get_movie_by_imdbID(imdbID)
        if movie:
            return jsonify(movie.serialize) if movie is not None\
                                            else jsonify({})
        else:
            return jsonify(MOVIE_NOT_FOUND)
    else:
        return jsonify(USER_NOT_FOUND)

@favmovies.route('/restful/favmovies/<user_id>', methods=['POST'])
def favmovies_post(user_id):
    user = User.query.get(user_id)
    if user is None:
        return jsonify(USER_NOT_FOUND)
    checked_movies = request.form.getlist('movies')
    added_movies = []
    for imdbID in checked_movies:
        result = query_omdb({'i': imdbID})
        if result.get('Response') == "True":
            movie = Movie(imdbID=result['imdbID'],
                          title=result['Title'], plot=result['Plot'],
                          type=result['Type'], poster=result['Poster'],
                          year=result['Year'], comment='')
            if user.get_movie_by_imdbID(movie.imdbID) is None:
                user.movies.append(movie)
                added_movies.append(movie)
        else:
            custom_logger('favmovies_post: movie id {} not'
                          ' found'.format(imdbID))
    db.session.commit()
    return jsonify(added_movies=[movie.serialize for movie in added_movies])

@favmovies.route('/restful/favmovies/<user_id>/<imdbID>', methods=['PUT'])
def favmovies_put(user_id, imdbID):
    user = User.query.get(user_id)
    if user:
        movie = user.get_movie_by_imdbID(imdbID)
        if movie:
            movie.comment = request.form['comment']
            db.session.commit()
            return jsonify({'Response': 'Updated successfully'})
        else:
            return jsonify(MOVIE_NOT_FOUND)
    else:
        return jsonify(USER_NOT_FOUND)

@favmovies.route('/restful/favmovies/<user_id>/<imdbID>', methods=['DELETE'])
def favmovies_delete(user_id, imdbID):
    user = User.query.get(user_id)
    if user:
        movie = user.get_movie_by_imdbID(imdbID)
        if movie:
            db.session.delete(movie)
            db.session.commit()
            return jsonify({'Response': 'Deleted successfully'})
        else:
            return jsonify(MOVIE_NOT_FOUND)
    else:
            return jsonify(USER_NOT_FOUND)


from pycoin.serialize import b2h, h2b
import rlp
from ethereum import utils, transactions
import requests
import json
import time
from ethereum.abi import ContractTranslator
import getopt, sys

def make_transaction(src_priv_key, dst_address, value, data):
    src_address = b2h(utils.privtoaddr(src_priv_key))
    nonce = get_num_transactions(src_address)
    gas_price = get_gas_price_in_wei()
    data_as_string = b2h(data)
    start_gas = eval_startgas(src_address, dst_address, value, data_as_string, gas_price)

    nonce = int(nonce, 16)
    gas_price = int(gas_price, 16)
    start_gas = int(start_gas, 16) + 100000

    tx = transactions.Transaction(nonce,
                                  gas_price,
                                  start_gas,
                                  dst_address,
                                  value,
                                  data).sign(src_priv_key)

    tx_hex = b2h(rlp.encode(tx))
    tx_hash = b2h(tx.hash)
    if use_ether_scan:
        params = [{"hex": "0x" + tx_hex}]
    else:
        params = ["0x" + tx_hex]
    return_value = json_call("eth_sendRawTransaction", params)
    if return_value == "0x0000000000000000000000000000000000000000000000000000000000000000":
        print
        "Transaction failed"
        return False
    wait_for_confirmation(tx_hash)
    return return_value


import pdfkit

path_to_wkhtmltopdf = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"

url= "https://www.google.com/"

config = pdfkit.configuration(wkhtmltopdf = path_to_wkhtmltopdf )

pdfkit.from_url(url ,output_path = 'webpage.pdf' , configuration = config)

# def conver_html_to_pdf(html_page,save_name):
#     pdfkit.from_url(html_page , save_name)
#     # pdfkit.from_file()

# conver_html_to_pdf("https://www.google.com/", "out.pdf")

# from flask import  Flask, make_response , render_template
# import pdfkit

# app=Flask(__name__)

# # config = pdfkit.configuration(wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe')
# config = pdfkit.configuration(wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe')

# @app.route("/<name>")
# def home(name):
#     res =render_template('index.html', name = name)
#     responseString = pdfkit.from_string(res, False)

#     response=make_response(responseString)
#     response.headers['Content-Type']= 'application/pdf'
#     response.headers['Content-Disposition']= 'inline;filename=output.pdf'
#     response.headers['Content-config']= 'configuration=config'

#     return response

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


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/11/28 下午8:02
# @Author  : LeonHardt
# @File    : Bagging_knn.py

from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import BaggingClassifier
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    '''
    Read data
    '''
    X = np.loadtxt('x_sample.csv', delimiter=',')
    y = np.loadtxt('y_label.csv', delimiter=',', dtype='int8')
    le = LabelEncoder()
    y = le.fit_transform(y)
    # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1)

    '''
    KNN
    '''
    knn = KNeighborsClassifier(n_neighbors=3, p=2, metric='minkowski')

    result = []
    pic = plt.figure(figsize=(8, 6), dpi=80)
    plt.ion()
    for time in range(1, 150, 2):
        plt.cla()
        print('the %d times' % time)
        bag = BaggingClassifier(base_estimator=knn, n_estimators=time, max_samples=1.0, max_features=1.0, bootstrap=True,
                            bootstrap_features=False, n_jobs=1, random_state=1)
        scores = cross_val_score(estimator=bag, X=X, y=y, cv=10, n_jobs=-1)

        result.append([time, np.mean(scores), np.std(scores)])
        if time > 2:
            result_plot = np.array(result)
            x_data = result_plot[:, 0]
            y_data = result_plot[:, 1]

            plt.title('Bagging_2NN')
            plt.grid(True)
            plt.xlabel('Accuracy')
            plt.xlim(0, 170)
            plt.ylabel('Times')
            plt.ylim(0, 1)

            plt.plot(x_data, y_data, "b--", label='cos')
            plt.legend(loc="upper left", shadow=True)
            plt.pause(0.001)

    plt.ioff()
    plt.show()
    plt.savefig('result_knn_3_150')
    np.savetxt('result_knn_3_150', result)