# lstsq_eigs.py
"""Volume 1: Least Squares and Computing Eigenvalues.
<Name> Elaine Swanson
<Class> MTH 420
<Date> 2/10/2021
"""

import numpy as np
from scipy import linalg as la
from matplotlib import pyplot as plt

# (Optional) Import functions from your QR Decomposition lab.
# import sys
# sys.path.insert(1, "../QR_Decomposition")
# from qr_decomposition import qr_gram_schmidt, qr_householder, hessenberg

# Problem 1
def least_squares(A, b):
    """Calculate the least squares solutions to Ax = b by using the QR
    decomposition.

    Parameters:
        A ((m,n) ndarray): A matrix of rank n <= m.
        b ((m, ) ndarray): A vector of length m.

    Returns:
        x ((n, ) ndarray): The solution to the normal equations."""
    Q,R = la.qr(A,mode="economic")
    b2 = Q.T @ b #Or we can do... np.dot(Q.T, b)
    x = la.solve_triangular(R, b2)

    return x

A = np.random.random((5,2))
b = np.random.random(5)
print(least_squares(A, b))

# Problem 2
def line_fit():
    """Find the least squares line that relates the year to the housing price
    index for the data in housing.npy. Plot both the data points and the least
    squares line."""
    x,b = np.load('housing.npy').T
    A = np.column_stack((x,np.ones((x.shape[0], 1)))) #stack col of 1s to matrix
    k, m = least_squares(A, b)
    plt.scatter(x, b)
    plt.plot([0,16],[m,10*k+m])
    return plt.show()

print(line_fit())

# Problem 3
def polynomial_fit():
    """Find the least squares polynomials of degree 3, 6, 9, and 12 that relate
    the year to the housing price index for the data in housing.npy. Plot both
    the data points and the least squares polynomials in individual subplots."""

    x,b = np.load("housing.npy").T
    """x_dup = np.column_stack([x]*4) #stack col four times vertically
    A_m = np.column_stack((x_dup,np.ones((x_dup.shape[0], 1))))
    A12 = np.vander(A_m[:,0], 13)
    A9 = np.vander(A_m[:,1], 10)
    A6 = np.vander(A_m[:,2], 7)
    A3 = np.vander(A_m[:,3], 4)

    x12, res12, rnk12, s12 = la.lstsq(A12,b) #Won't work with getting x alone, why?
    x9, res9, rnk9, s9 = la.lstsq(A9,b)
    x6, res6, rnk6, s6 = la.lstsq(A6,b)
    x3, res3, rnk3, s3 = la.lstsq(A3,b)

    #x: least-squares solution. Return shape matches shape of b.
    #residue: square of the 2-norm for each column in b - a x, if M > N and ndim(A) == n
    #s: singular values of a."""

    p12 = np.poly1d(np.polyfit(x,b,12)) #Polynomial with coef. from np.polyfit
    p9 = np.poly1d(np.polyfit(x,b,9))
    p6 = np.poly1d(np.polyfit(x,b,6))
    p3 = np.poly1d(np.polyfit(x,b,3))

    x_fig = np.linspace(0,16)
    y12_fig = p12(x_fig)
    y9_fig = p9(x_fig)
    y6_fig = p6(x_fig)
    y3_fig = p3(x_fig)

    fig, axs = plt.subplots(2, 2)
    fig.suptitle('Polynomial curve fitting')
    fig.subplots_adjust(hspace=.5)

    axs[0, 0].scatter(x, b, marker = '.', color = 'steelblue', label = 'Housing data')
    axs[0, 0].plot(x_fig, y12_fig, color = 'orangered', label = 'Fit line')
    axs[0, 0].set_title('Polynomials of degree 12')
    axs[0, 0].legend(loc = 'lower right')

    axs[0, 1].scatter(x, b, marker = '.', color = 'steelblue', label = 'Housing data')
    axs[0, 1].plot(x_fig, y9_fig, color = 'orangered', label = 'Fit line')
    axs[0, 1].set_title('Polynomials of degree 9')
    axs[0, 1].legend(loc = 'lower right')

    axs[1, 0].scatter(x, b, marker = '.', color = 'steelblue', label = 'Housing data')
    axs[1, 0].plot(x_fig, y6_fig, color = 'orangered', label = 'Fit line')
    axs[1, 0].set_title('Polynomials of degree 6')
    axs[1, 0].legend(loc = 'lower right')

    axs[1, 1].scatter(x, b, marker = '.', color = 'steelblue', label = 'Housing data')
    axs[1, 1].plot(x_fig, y3_fig, color = 'orangered', label = 'Fit line')
    axs[1, 1].set_title('Polynomials of degree 3')
    axs[1, 1].legend(loc = 'lower right')

    return plt.show()
print(polynomial_fit())


from http.server import BaseHTTPRequestHandler, HTTPServer
import cv2

# HTTPRequestHandler class
class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):

	# GET
	def do_GET(self):
		# Send response status code

		if self.path.endswith('.mjpg'):
			self.send_response(200)
			self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary')
			self.end_headers()

			while True:

				rc, img = capture.read()
				if not rc:
					pass
				r, buf = cv2.imencode(".jpg", img)
				self.wfile.write("--jpgboundary\r\n".encode())
				self.end_headers()
				self.wfile.write(bytearray(buf))
			return

		elif self.path.endswith('.html') or self.path == "/":
			self.send_response(200)
			self.send_header('Content-type', 'text/html')
			self.end_headers()
			self.wfile.write('')
			self.wfile.write('')
			self.wfile.write('')

def run():

	global capture

	capture = cv2.VideoCapture(0)

	print('starting server...')

	# Server settings
	# Choose port 8080, for port 80, which is normally used for a http server, you need root access
	server_address = ('localhost', 8081)
	httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
	print('running server...')
	httpd.serve_forever()

run()


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

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

import json
import random
import requests
from scrapy import signals

class CookiesMiddleware():

    @classmethod
    def from_crawler(cls, crawler):
        settings = crawler.settings
        return cls(cookies_url = settings["COOKIE_URL"])

    def __init__(self, cookies_url):
        #self.logger = logging.get_Logger(__name__)
        self.cookies_url = cookies_url

    def get_cookie(self):
        try:
            res = requests.get(self.cookies_url)
            if res.status_code == 200:
                cookie = json.loads(res.text)
                return cookie
        except Exception as e:
            print("get cookie err %s" % str(e))
            return False

    def process_request(self, request, spider):
        """
            请求url的时候会先调用该函数
        """
        cookie = self.get_cookie()
        if cookie:
            #设置cookie
            request.cookies = cookie
            print("succ set cookie")

class ProxyMiddleware():

    @classmethod
    def from_crawler(cls, crawler):
        settings = crawler.settings
        return cls(proxy_url = settings["PROXY_URL"])

    def __init__(self, proxy_url):
        self.proxy_url = proxy_url

    def get_proxy(self):
        try:
            print(self.proxy_url)
            res = requests.get(self.proxy_url)
            if res.status_code == 200:
                proxy = res.text
                return proxy
        except Exception as e:
            print("get proxy err: %s" % str(e))
            return False

    def process_request(self, request, spider):
        if request.meta.get("retry_times"):
            proxy = self.get_proxy()
            if proxy:
                uri = "https://{proxy}".format(proxy=proxy)
                request.meta["proxy"] = uri
                print("succ set proxy")

class UserAgentMiddleware():

    def __init__(self):
        self.user_agents = [
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36"
        ]

    def process_request(self, request, spider):
        request.headers["User-Agent"] = random.choice(self.user_agents)


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

import torch
import os, cv2
import time
import numpy as np
from Nets.SR_Net import *
from Nets.PYNET import PyNET_smaller
from collections import OrderedDict
from torch.utils.data import Dataset, DataLoader

class TEST_DATA(Dataset):
    def __init__(self, test_dir, count):

        self.test_path = []

        test_caselist = os.listdir(test_dir)
        test_caselist.sort(key=lambda x: int(x.split('e')[1]))
        print("there are {} cases".format(len(test_caselist)))

        for case in test_caselist:
            test_files = os.listdir(os.path.join(test_dir, case))
            test_files.sort(key=lambda x: int((x.split('_', 5)[5]).split('_')[0]))
            for test_file in test_files[:count]:
                test_file_dir = os.path.join(test_dir, case, test_file)
                self.test_path.append(test_file_dir)

    def __len__(self):
        print("test dataset--------->len=", len(self.test_path))
        return len(self.test_path)

    def __getitem__(self, index):
        test_raw = np.load(self.test_path[index])
        source = (test_raw / 4095.).astype(np.float32)

        '# Unet的设计导致要32对齐'
        _, h, w = source.shape  # H W C
        if w % 16 != 0:
            w = (w // 16) * 16
        if h % 16 != 0:
            h = (h // 16) * 16
        source = source[:, :h, :w]

        '# saving the input'
        source_a = (source * 255.).astype(np.uint8)
        cv2.imwrite(save_path + "/" + "orig_" + str(index + 1) + ".jpg", source_a[0])    # h265: .jpg

        source = torch.from_numpy(source)

        return source

def test(test_dir, count, model, weights_dir, save_path):
    test_data = TEST_DATA(test_dir=test_dir, count=count)
    test_loader = DataLoader(test_data, batch_size=1, shuffle=False, num_workers=1, pin_memory=True, drop_last=False)

    state_dict = torch.load(weights_dir)

    new_state_dict = OrderedDict()
    for k, v in state_dict.items():
        name = k[7:]  # remove `module.`
        new_state_dict[name] = v

    # model.load_state_dict(new_state_dict)
    model.load_state_dict(new_state_dict, strict=False)

    model = model.cuda()
    model.eval()
    with torch.no_grad():
        for idx, source in enumerate(test_loader):

            source = source.cuda()

            torch.cuda.synchronize()
            start = time.time()
            for _ in range(100):
                test_output = model(source)
            torch.cuda.synchronize()
            end = time.time()
            print("test time:", (end - start) / 100)
            print("FPS: %f" % (1.0 / ((end - start) / 100)))

            test_output = test_output.permute(0, 2, 3, 1).cpu().data.numpy()
            test_output = np.minimum(np.maximum(test_output, 0), 1)
            print(test_output.shape)
            test_output = (test_output[0, ...] * 255.).astype(np.uint8)
            print(test_output.shape)
            test_output = cv2.cvtColor(test_output, cv2.COLOR_RGB2BGR)
            cv2.imwrite(save_path + '/' + str(idx + 1) + '.jpg', test_output)
            print("saving the {} images\n".format(str(idx + 1)))

if __name__ == "__main__":
    os.environ["CUDA_VISIBLE_DEVICES"] = '3'

    test_dir = '/media/ps/2tb/yjz/data/ISP/NPY/test_raw-npy'
    weights_dir = './model/PyNET_smaller-8/level0/weights/best_psnr/best_psnr.pt'
    save_path = './model/PyNET_smaller-8/level0/results'
    if not os.path.isdir(save_path):
        os.mkdir(save_path)

    count = 1
    model = PyNET_smaller(level=0, channel=8, instance_norm=True, instance_norm_level_1=True)
    test(test_dir=test_dir, count=count, model=model, weights_dir=weights_dir, save_path=save_path)


from django import forms
from .models import Story,Comment

class StoryForm(forms.ModelForm):
    class Meta:
        model = Story
        fields = ('story_title','story_body')
        widgets = {
            'story_title': forms.TextInput( attrs={'class': 'form-control ', 'type':"text",'id':"fname",'placeholder':"All great stories have great names like 'Lorem Ipsum'"}),
            'story_body': forms.Textarea( attrs={'class': 'form-control ','id':"message", 'cols':'50', 'rows':'25' , 'placeholder':'Once upon a time ...'}),
            }

class CommentForm(forms.ModelForm):
    class Meta:
       model = Comment
       fields = ('comment_body',)
       widgets = {
            'comment_body': forms.Textarea(
                attrs={'class': 'form-control ','id':"message",  'cols':'25','rows':'2' , 'placeholder':'Cool Story Bruh  ...'}
            ),
            }


import logging

logger = logging.getLogger('piasync')

SIMPLE_TYPES = {
    'b': lambda x: bool(int(x)),
    'y': int,
    'n': int,
    'q': int,
    'i': int,
    'u': int,
    'x': int,
    't': int,
    'd': float,
    's': str,
    'o': str,
}

ARRAY_TYPE = 'a'
VARIANT_TYPE = 'v'

DICT_ENTRY_START = '{'
DICT_ENTRY_END = '}'

STRUCT_ENTRY_START = '('
STRUCT_ENTRY_END = ')'

def _sig_iter(signature):
    remaining = str(signature)
    while remaining:
        character = remaining[0]
        remaining = remaining[1:]
        if character in SIMPLE_TYPES:
            yield character, remaining
        elif character == VARIANT_TYPE:
            yield character, remaining
        elif character == ARRAY_TYPE:
            array_type, remaining = next(_sig_iter(remaining))
            yield character + array_type, remaining
        elif character == DICT_ENTRY_START:
            # Return the whole {k, v}
            key_type, remaining = next(_sig_iter(remaining))
            value_type, remaining = next(_sig_iter(remaining))
            end_type, remaining = next(_sig_iter(remaining))
            assert end_type == DICT_ENTRY_END
            yield character + key_type + value_type + end_type, remaining
        elif character == STRUCT_ENTRY_START:
            struct_type = [character]
            while True:
                struct_member_type, remaining = next(_sig_iter(remaining))
                struct_type.append(struct_member_type)
                if struct_member_type == STRUCT_ENTRY_END:
                    break
            yield "".join(struct_type), remaining
        elif character == DICT_ENTRY_END:
            yield character, remaining
        elif character == STRUCT_ENTRY_END:
            yield character, remaining
        else:
            raise ValueError

def sig_iter(signature):
    for sig, remaining in _sig_iter(signature):
        yield(sig)

def decode_single(type_indication, element):
    result = None
    logger.debug("Single element %s: %r", type_indication, element)
    if type_indication.startswith(ARRAY_TYPE):
        result = decode_sequence(type_indication, element)
    elif type_indication == VARIANT_TYPE:
        result = decode_variant(element)
    else:
        result = decode_simple_type(type_indication, element)
    return result

def decode_sequence(type_indication, sequence):
    # Whether we're dealing with an array or dict, we must exhaust all
    # PDU elements
    decoded_sequence = None
    logger.debug("Decoding sequence of type %s: %r", type_indication, sequence)
    if type_indication[1] == DICT_ENTRY_START:
        kv_sig_iter = sig_iter(type_indication[2:-1])
        key_sig = next(kv_sig_iter)
        value_sig = next(kv_sig_iter)
        logger.debug("Dict-type sequence %s -> %s", key_sig, value_sig)
        decoded_sequence = {}
        for k_v in sequence:
            key = decode_simple_type(key_sig, k_v[0])
            # This causes single to be called twice?
            value = decode_single(value_sig, k_v[1])
            decoded_sequence.update({key: value})
    else:
        array_sig_iter = sig_iter(type_indication[1:])
        array_type = next(array_sig_iter)
        logger.debug("List-type sequence %s", array_type)
        # The problem with this is that p, being an element of the pdu
        # iterable may _itself_ be an iterable, that's how we end up
        # decoding 4 out of '45' (for sig 'i')
        decoded_sequence = [decode_single(array_type, p) for p in sequence]
    return decoded_sequence

def decode_simple_type(type_sig, encoded_type):
    logger.debug("Simple element %s: %r", type_sig, encoded_type)
    try:
        return SIMPLE_TYPES[type_sig](encoded_type)
    except KeyError:
        raise ValueError

def decode_variant(variant_value):
    assert isinstance(variant_value, tuple)
    assert 2 == len(variant_value)
    # import pdb
    # pdb.set_trace()
    # pass
    # The type in a variant may be an array!
    return decode_single(variant_value[0], variant_value[1])

def decode(signature, pdu):
    result = []
    # Iterate on the sequence in the signature
    for type_indication, pdu_element in zip(sig_iter(signature), pdu):
        logger.debug(
            "Decoding PDU element %s: %r", type_indication, pdu_element
        )
        if type_indication[0] == ARRAY_TYPE:
            # decode_sequence can return a dict or a list
            decoded_element = decode_sequence(type_indication, pdu)
            result.append(decoded_element)
        elif type_indication == VARIANT_TYPE:
            decoded_element = decode_single(type_indication, pdu_element)
            result.append(decoded_element)
        else:
            decoded_element = decode_single(type_indication, pdu_element)
            result.append(decoded_element)
    return result

def encode_sequence(type_indication, sequence):
    # Whether we're dealing with an array or dict, we must exhaust all
    # PDU elements
    encoded_sequence = []
    logger.debug("Encoding sequence of type %s: %r", type_indication, sequence)
    if type_indication[1] == DICT_ENTRY_START:
        kv_sig_iter = sig_iter(type_indication[2:-1])
        key_sig = next(kv_sig_iter)
        value_sig = next(kv_sig_iter)
        logger.debug("Dict-type sequence %s -> %s", key_sig, value_sig)
        # ('ipv4',
        # [('address-data', ('aa{sv}', [])),
        # ('addresses', ('aau', [])),
        # ('dns', ('au', [])),
        # ('dns-search', ('as', [])),
        # ('method', ('s', 'auto')),
        # ('route-data', ('aa{sv}', [])),
        # ('routes', ('aau', []))]),

        # for k_v in sequence.items():
        #     key = encode_simple_type(key_sig, k_v[0])
        #     # We already have nice variants, let's pass them straight
        #     # value = encode_single(value_sig, k_v[1])
        #     encoded_sequence.append((key, k_v[1]))
        return list(sequence.items())
    else:
        array_sig_iter = sig_iter(type_indication[1:])
        array_type = next(array_sig_iter)
        logger.debug("List-type sequence %s", array_type)
        # The problem with this is that p, being an element of the pdu
        # iterable may _itself_ be an iterable, that's how we end up
        # encoding 4 out of '45' (for sig 'i')
        encoded_sequence = [encode_single(array_type, p) for p in sequence]
    return tuple(encoded_sequence)

def encode_simple_type(type_sig, native_type):
    logger.debug("Simple element %s: %r", type_sig, native_type)
    try:
        return str(native_type)
    except KeyError:
        raise ValueError

def encode_single(type_indication, element):
    result = None
    logger.debug("Single element %s: %r", type_indication, element)
    if type_indication.startswith(ARRAY_TYPE):
        result = encode_sequence(type_indication, element)
    elif type_indication == VARIANT_TYPE:
        result = encode_variant(type_indication, element)
    else:
        result = encode_simple_type(type_indication, element)
    return result

def encode_variant(type_indication, variant_value):
    # XXX Figure out something clever to determine the variant's type
    return ('s', encode_single('s', variant_value))

def encode(signature, pdu):
    result = []
    # Iterate on the sequence in the signature
    logger.debug("Encoding PDU packet %s: %r", signature, pdu)
    for type_indication, pdu_element in zip(sig_iter(signature), pdu.items()):
        logger.debug(
            "Encoding PDU element %s: %r", type_indication, pdu_element
        )
        if type_indication[0] == ARRAY_TYPE:
            encoded_element = encode_sequence(type_indication, pdu)
            result.append(encoded_element)
        elif type_indication == VARIANT_TYPE:
            encoded_element = encode_single(type_indication, pdu_element)
            result.append(encoded_element)
        else:
            encoded_element = encode_single(type_indication, pdu_element)
            result.append(encoded_element)
    return tuple(result)


import socketio
import cv2

class SocketClient:
    sio = socketio.Client()

    def __init__(self, url):
        self.sio.connect(url)

    def emit(self, event, data):
        self.sio.emit(event, data)

    def wait(self):
        self.sio.wait()

    def send_data(self, img, data_dict, format=".png"):
        img_bin = self._ndarray2img(img, format=format)
        data_dict["img"] = img_bin
        socket.emit("msg", data_dict)

    @staticmethod
    @sio.event
    def connect():
        print("connection established")

    @staticmethod
    @sio.on("connect_success")
    def on_message(data):
        print(data)

    @staticmethod
    def _ndarray2img(img_array, format=".png"):
        return cv2.imencode(format, img_array)[1].tostring()

if __name__ == "__main__":

    # create Socket
    socket = SocketClient("http://localhost:3000")

    # get image
    img = cv2.imread("./img.png")

    # send data (image, data dictionary)
    socket.send_data(
        img,
        {
            "total_people": 10,
            "mask_weared": 5,
            "mask_off": 3,
            "mask_incorrect": 2,
            "conjestion": 3.2342,
            "risk": 3.3423,
        },
    )

    # wait socket event
    socket.wait()


from flask import Flask, render_template, request
import pandas as pd
import numpy as np
import joblib

app = Flask(__name__)

ml_model = joblib.load("titanic_model.pkl")

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

@app.route("/predict", methods=['GET', 'POST'])
def predict():
    #print("I was here 1")
    if request.method == 'POST':
        print(request.form.get('Sex'))
        try:
            Sex = float(request.form['Sex'])
            Age = float(request.form['Age'])
            SibSp = float(request.form['SibSp'])
            Parch = float(request.form['Parch'])
            Pclass = float(request.form['Pclass'])
            pred_args = [Sex, Age, SibSp, Parch, Pclass]
            pred_args_arr = np.array(pred_args)
            pred_args_arr = pred_args_arr.reshape(1, -1)
            model_prediction = ml_model.predict(pred_args_arr)
            if model_prediction == 0:
                final_result = "Not Survived"
            else:
                final_result = "Survived"
        except ValueError:
            return "Please check if the values are entered correctly"
    return render_template('predict.html', prediction = final_result)

if __name__ == "__main__":
    app.run(host='0.0.0.0')


# !pip install pymorphy2
import nltk
import random
import json
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from pymorphy2 import MorphAnalyzer
import pickle
with open('/content/BOT_CONFIG - 22.06.2021.json') as f:
  BOT_CONFIG = json.load(f)

# BOT_CONFIG = {
#     'intents': {
#         'hello': {
#             'examples': ['Привет!', 'Хэлло', 'Хей'],
#             'responses': ['Добрый день', 'Добрый вечер', 'Здравствуйте']
#         },
#         'bye': {
#             'examples': ['Пока...', 'Увидимся!', 'До скорого'],
#             'responses': ['До свиданья', 'До встречи', 'Хорошего дня!']
#         }
#     }
# }
def clean(text):
  cleaned_text = ''
  for char in text.lower():
    if char in 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя ':
      cleaned_text += char #cleaned_text = cleaned_text + char
  return cleaned_text

def get_intent(in_text):
  for intent in BOT_CONFIG['intents'].keys():
    for example in BOT_CONFIG['intents'][intent]['examples']:
      text1 = clean(example)
      text2 = clean(in_text)
      if nltk.edit_distance(text1, text2) / max(len(text1), len(text2)) < 0.4:
        return intent
  return 'Не удалось определить интент'

def bot(in_text):
  intent = get_intent(in_text)

  if intent == 'Не удалось определить интент':
    return 'Извите, я ничего не понял'
  else:
    return random.choice(BOT_CONFIG['intents'][intent]['responses'])

in_text = ''
while in_text != 'Выход':
  in_text = input()
  out_text = bot(in_text)
  print(out_text)

#Обучение Модели
X, y = [], []

for intent in BOT_CONFIG['intents']:
  for example in BOT_CONFIG['intents'][intent]['examples']:
    X.append(example)
    y.append(intent)

morph = MorphAnalyzer()

def lemmatize(text):
  lemmatized_text = []
  for word in text.lower().split():
    lemmatized_text.append(morph.parse(word)[0].normal_form)
  return ' '.join(lemmatized_text)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)

X_train = [lemmatize(text) for text in X_train]
X_test = [lemmatize(text) for text in X_test]

vectorizer = CountVectorizer(analyzer='word', ngram_range=(1,3))
vectorizer.fit(X_train)
X_vectors = vectorizer.transform(X_train)
len(vectorizer.get_feature_names())

classifier = LogisticRegression(max_iter=200)
classifier.fit(X_vectors, y_train)

classifier.score(X_vectors, y_train)

classifier.score(vectorizer.transform(X_test), y_test)

with open('/content/our_ml_model.pickle', 'wb') as f:
  pickle.dump(classifier, f)

with open('/content/our_vectorizer.pickle', 'wb') as f:
  pickle.dump(vectorizer, f)

with open('/content/our_ml_model.pickle', 'rb') as f:
  loaded_classifier = pickle.load(f)

with open('/content/our_vectorizer.pickle', 'rb') as f:
  loaded_vectorizer = pickle.load(f)

loaded_classifier.predict(loaded_vectorizer.transform(['как дела?']))

#Тестирование
def get_intent_by_ml_model(in_text):
  return classifier.predict(vectorizer.transform([in_text]))[0]

def bot(in_text):
  intent = get_intent_by_ml_model(in_text)

  if intent == 'Не удалось определить интент':
    return 'Извите, я ничего не понял'
  else:
    return random.choice(BOT_CONFIG['intents'][intent]['responses'])

# in_text = ''
# while in_text != 'Выход':
#   in_text = input()
#   out_text = bot(in_text)
#   print(out_text)

#Подключение к Telegram
import logging

from telegram import Update, ForceReply
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)

logger = logging.getLogger(__name__)

# Define a few command handlers. These usually take the two arguments update and
# context.
def start(update: Update, context: CallbackContext) -> None:
    """Send a message when the command /start is issued."""
    user = update.effective_user
    update.message.reply_markdown_v2(
        fr'Hi {user.mention_markdown_v2()}\!',
        reply_markup=ForceReply(selective=True),
    )

def help_command(update: Update, context: CallbackContext) -> None:
    """Send a message when the command /help is issued."""
    update.message.reply_text('Help!')

def echo(update: Update, context: CallbackContext) -> None:
    update.message.reply_text(bot(update.message.text))

def main() -> None:
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    updater = Updater("1893870572:AAHYJA6Lhp0iaJo2GQHTqFk_Polas8l0jL8")

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher

    # on different commands - answer in Telegram
    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("help", help_command))

    # on non command i.e message - echo the message on Telegram
    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

main()


import pygame,time,sys,json
a=[]
b=[]
c=0
pygame.init()
pygame.key.set_repeat(100, 150)
clock=pygame.time.Clock()
screen=pygame.display.set_mode((300,300),0,32)
pygame.mixer.init()
pygame.mixer.music.load(".\\assets\\start\\start_game\\game\\arknight.wav")
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play(0)
while True:
    time.sleep(0.1)
    c=c+0.1
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_f:
                c=round(c,2)
                a.append(c)
                print(a)
    for event1 in pygame.event.get():
        if event1.type == pygame.KEYDOWN:
            if event1.key == pygame.K_j:
                c=round(c,2)
                b.append(c)
                print(b)
    for event2 in pygame.event.get():
        if event2.type==pygame.QUIT:
            run=False
            pygame.quit()
            quit()
    pygame.display.update()
    clock.tick(60)


from typing import List

class Solution:
    def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
        n = len(arr)
        arr.sort()

        min_diff, ans = float('inf'), []
        for i in range(n - 1):
            delta = arr[i + 1] - arr[i]
            if delta < min_diff:
                min_diff = delta
                ans = [[arr[i], arr[i+1]]]
            elif delta == min_diff:
                ans.append([arr[i], arr[i+1]])

        return ans


from argparse import ArgumentParser
from ipaddress import IPv4Address
from subprocess import Popen
import threading
import socket
import os
__version__ = "0.0.1"

class ChatServer(threading.Thread):

    def __init__(self, host, port):
        threading.Thread.__init__(self)
        self.port = port
        self.host = host
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.users = {}

        try:
            self.server.bind((self.host, self.port))
            print("SERVER SUCCESSFULLY BINDED")
        except socket.error:
            print('Bind failed %s' % (socket.error))

        self.server.listen(10)

    # Not currently used. Ensure sockets are closed on disconnect
    def exit(self):
        self.server.close()

    def run_thread(self, conn, addr):
        print('Client connected with ' + addr[0] + ':' + str(addr[1]))
        while True:
            data = conn.recv(1024)
            reply = b'OK...' + data
            print(reply)
            conn.sendall(reply)

        conn.close() # Close

    def run(self):
        print('Waiting for connections on port %s' % (self.port))
        # We need to run a loop and create a new thread for each connection
        while True:
            conn, addr = self.server.accept()
            threading.Thread(target=self.run_thread, args=(conn, addr)).start()

if __name__ == "__main__":

    parser = ArgumentParser(usage="hostIP, port", description="simple async HTTP server")
    parser.add_argument("hostIP",type=str)
    parser.add_argument("port",type=int)

    args = parser.parse_args()
    try:
        hostip = str(IPv4Address(args.hostIP))
        port = args.port
    except:
        print("Bad parameters")
    os.system("python ")
    sv = ChatServer(hostip,port)

    sv.run()

    input("press enter to close server")


import heapq
import collections
class Solution:
    def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
        graph=collections.defaultdict(list)
        heap=[]
        heapq.heapify(heap)
        heapq.heappush(heap,[0,K])
        inf=float('inf')
        dist=[inf for _ in range(N+1)]
        dist[K]=0
        dist[0]=0
        for time in times:
            u,v,w=time
            graph[u].append([w,v])
        while len(heap)>0:
            u=heapq.heappop(heap)
            for ele in graph[u[1]]:
                w=ele[0]
                v=ele[1]
                if w+u[0]<dist[v]:
                    dist[v]=w+u[0]
                    heapq.heappush(heap,[w+u[0],v])

        for i in range(1,len(dist)):
            if dist[i]==inf:
                return -1

        return max(dist)


from unittest import TestCase

from datetime import datetime
import pytz

from draft_kings_client.data.models.available_player import Team, MatchUp
from draft_kings_client.data.models.available_players_team_series import AvailablePlayersTeamSeries
from draft_kings_client.data.translators.available_players_team_series_translator import AvailablePlayersTeamSeriesTranslator

class TestAvailablePlayersTeamSeriesTranslator(TestCase):
    def test_translation(self):
        ts_1_id = 1
        ts_1_id_formatted_value = unicode(ts_1_id)
        ts_1_home_team_abbreviation = unicode('jae')
        ts_1_home_team_id = Team.atlanta_hawks.value['id']
        ts_1_away_team_id = Team.boston_celtics.value['id']
        ts_1_away_team_abbreviation = unicode('bradley')
        ts_1_timestamp = long(4)
        ts_1_datetime = datetime.fromtimestamp(timestamp=ts_1_timestamp / 1e3, tz=pytz.utc)
        ts_1_formatted_timestamp = unicode("/Date({})/".format(ts_1_timestamp))
        ts_1_weather = unicode('sunny with a chance of meatballs')
        ts_1_sport_id = 1
        ts_1_status = 9

        ts_2_id = 5
        ts_2_id_formatted_value = unicode(ts_2_id)
        ts_2_home_team_abbreviation = unicode('jae')
        ts_2_home_team_id = Team.brooklyn_nets.value['id']
        ts_2_away_team_id = Team.cleveland_cavaliers.value['id']
        ts_2_away_team_abbreviation = unicode('bradley')
        ts_2_timestamp = long(8)
        ts_2_datetime = datetime.fromtimestamp(timestamp=ts_2_timestamp / 1e3, tz=pytz.utc)
        ts_2_formatted_timestamp = unicode("/Date({})/".format(ts_2_timestamp))
        ts_2_weather = unicode('cloudy with a chance of meatballs')
        ts_2_sport_id = 12
        ts_2_status = 10

        expected_team_series_1_match_up = MatchUp(home_team=Team.value_of(draft_kings_id=ts_1_home_team_id),
                                                  away_team=Team.value_of(draft_kings_id=ts_1_away_team_id),
                                                  match_up_id=ts_1_id)
        expected_team_series_2_match_up = MatchUp(home_team=Team.value_of(draft_kings_id=ts_2_home_team_id),
                                                  away_team=Team.value_of(draft_kings_id=ts_2_away_team_id),
                                                  match_up_id=ts_2_id)

        expected_team_series_1 = AvailablePlayersTeamSeries(match_up=expected_team_series_1_match_up,
                                                            start_timestamp=ts_1_datetime,
                                                            weather=ts_1_weather,
                                                            status=ts_1_status)

        expected_team_series_2 = AvailablePlayersTeamSeries(match_up=expected_team_series_2_match_up,
                                                            start_timestamp=ts_2_datetime,
                                                            weather=ts_2_weather,
                                                            status=ts_2_status)

        response = {
            ts_1_id_formatted_value: {
                'ht': ts_1_home_team_abbreviation,
                'htid': ts_1_home_team_id,
                'at': ts_1_away_team_abbreviation,
                'atid': ts_1_away_team_id,
                'tz': ts_1_formatted_timestamp,
                'wthr': ts_1_weather,
                's': ts_1_sport_id,
                'status': ts_1_status
            },
            ts_2_id_formatted_value: {
                'ht': ts_2_home_team_abbreviation,
                'htid': ts_2_home_team_id,
                'at': ts_2_away_team_abbreviation,
                'atid': ts_2_away_team_id,
                'tz': ts_2_formatted_timestamp,
                'wthr': ts_2_weather,
                's': ts_2_sport_id,
                'status': ts_2_status
            }
        }

        team_series = AvailablePlayersTeamSeriesTranslator.translate(response=response)
        self.assertIsNotNone(team_series)
        self.assertEqual(team_series.__len__(), 2)
        self.assertEqual(team_series[0], expected_team_series_1)
        self.assertEqual(team_series[1], expected_team_series_2)


#!/usr/bin/python3
from scanconfig import ScanConfig
from scan import Scan
from colorama import Fore
import multiprocessing as multp

# Main block
if __name__ == '__main__':
    multp.set_start_method("spawn")
    conf = ScanConfig('conf.yaml')
    scan = Scan()

    # Checks if Nmap is installed on the system prior to operation
    if scan.checkInstall() == False:
        print(Fore.RED + 'nmap is not installed on the system.\n')
    else:
        print(Fore.GREEN + scan.checkVersion().decode('utf-8'))

    # Function to create a "hosts.txt" file if one does not yet exist
    conf.createCIDR_File(conf.getConf('cidr-range'))

    # Opens the file with targets in them and enumerates through them individually
    with open('hosts.txt', 'r') as file:
        agg_hosts = file.readlines()
        while len(agg_hosts) != 0:
            instr = multp.Process
            try:
                # This loop will create the processes ("threads") and subsequently executes them
                for process_count in range(int(conf.getConf('threads'))):
                    # Empty list of all the processes (scans) to be executed
                    processes = []
                    scan_attempt = instr(target=scan.scanTarget, args=(agg_hosts[process_count], conf.parseListArgs(conf.getConf('args')), conf.getConf('ports')))
                    processes.append(scan_attempt)
                    # Starts the "thread"
                    scan_attempt.start()
                    agg_hosts.pop(process_count)

                # Joins the processes
                for process in processes:
                    process.join()

            except IndexError:
                try:
                    multp.Process(target=scan.scanTarget(agg_hosts[0], conf.parseListArgs(conf.getConf('args')), conf.getConf('ports'))).start()
                    agg_hosts.pop(0)
                except IndexError:
                    print('No more hosts left to scan.')
                    break
                print('No more hosts left to scan.')
                break

    file.close()


#!/usr/bin/env python3
import atexit
import os
import shutil
import click
from langdetect import detect

import pysrt
from smart import fit_subtitles_to_audio
from utils import SCRATCH
import better_exceptions; better_exceptions.hook()

def cleanup():
    shutil.rmtree(SCRATCH)

@click.command(help='Resync the subtitles of a movie file')
@click.argument('movie_file', type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True))
def main(movie_file):
    click.echo('Resyncing subtitles for movie file: {}'.format(movie_file))
    validate(movie_file)
    subtitles: pysrt.SubRipFile = read_subtitles(movie_file)
    language = detect_language(subtitles.text)
    fit_subtitles_to_audio(subtitles, movie_file)

def detect_language(text):
    language = detect(text)
    return language

def validate(movie_file):
    is_movie(movie_file)
    get_subtitle_file(movie_file)

def is_movie(movie_file):
    video_extensions = [".mp4", ".mkv", ".avi", ".flv", ".wmv", ".mov", ".3gp", ".m4v", ".ts"]
    return any(movie_file.endswith(extension) for extension in video_extensions)

def get_subtitle_file(movie_file):
    subtitle_extensions = [".srt"]
    base_file, _ = os.path.splitext(movie_file)
    for extension in subtitle_extensions:
        if os.path.exists(base_file + extension):
            return base_file + extension

def read_subtitles(movie_file):
    return pysrt.open(get_subtitle_file(movie_file))

if __name__ == '__main__':
    atexit.register(cleanup)
    main()


from django.conf.urls import url
from mysale import urls
from user import views,views_login,views_pub,views_reply

app_name = 'comments'
urlpatterns = [
    url(r'^test/$',views_pub.test),

    url(r'index/$',views_pub.index),
    url(r'publish/$',views_pub.publish),
    url(r'publish_handler/$',views_pub.publish_handler),

    url(r'reply/$', views_reply.reply),
    # url(r'^reply/post/(?P<publish_pk>[0-9]+)/$', views_reply.post_comment),
    url(r'comment/d(publish_pk)+/$', views_reply.post_comment),

]


from keras.layers import Input, GRU, Lambda, Conv3D, UpSampling3D, MaxPooling3D, Reshape, concatenate
from keras.models import Model

#routine to create a multi-output recurrent autoencoder
#the input parameter is the weight for each different loss function: ex.: loss_weights = [0.33, 0.33, 0.33];

def create_mora_model(weights):

    #specifying the input shape (24-frames clips) -> # timesteps, frames, height, width, channels
    #24 frames representing a composed input with 8-frame for each modality
    input = Input(batch_shape=(4,24,112,112,3), name='main_input')

    #encoding input into a higher level representation - 1st group
    encoding = Conv3D(24, (3,3,3), activation='relu', padding='same')(input)
    encoding = Conv3D(64, (3,3,3), activation='relu', padding='same')(encoding)
    encoding = MaxPooling3D(pool_size=(2, 2, 2), strides=(2, 2, 2),
                           border_mode='valid', name='pool1')(encoding)

    encoding = Conv3D(128, (3,3,3), activation='relu', padding='same')(encoding)
    encoding = Conv3D(128, (3,3,3), activation='relu', padding='same')(encoding)
    encoding = MaxPooling3D(pool_size=(2, 2, 2), strides=(2, 2, 2),
                           border_mode='valid', name='pool2')(encoding)

    encoding = Conv3D(64, (3,3,3), activation='relu', padding='same')(encoding)
    encoding = Conv3D(64, (3,3,3), activation='relu', padding='same')(encoding)
    encoding = MaxPooling3D(pool_size=(2, 2, 2), strides=(2, 2, 2),
                           border_mode='valid', name='pool3')(encoding)

    encoding = Conv3D(64, (1,3,3), activation='relu', padding='same')(encoding)
    encoding = Conv3D(32, (1,3,3), activation='relu', padding='same')(encoding)
    encoding = Conv3D(12, (1,3,3), activation='relu', padding='same')(encoding)

    #reshaping tensor to return with GRU
    reshaped = Reshape((7056,1))(encoding)
    encoder = GRU(392, activation='sigmoid', recurrent_activation='hard_sigmoid', use_bias=True, return_state = True, stateful = False)(reshaped)

    #concatenating both states and outputs
    encoder = concatenate([encoder[0], encoder[1]], axis = 1)
    encoder = Reshape((4,14,14,1))(encoder)
    encoding = Reshape((36,14,14,1))(encoding)

    #creating a mixed representation with GRU representation and encoded representation for each time step
    concatenateLayer = concatenate([encoding, encoder], axis = 1)
    encoding = Reshape((1,14,14,40))(concatenateLayer)

    #decoding step -> getting back to original representation
    decoding = Conv3D(16, (1,3,3), activation='relu', padding='same')(encoding)
    decoding = Conv3D(32, (1,3,3), activation='relu', padding='same')(decoding)
    decoding = Conv3D(64, (1,3,3), activation='relu', padding='same')(decoding)
    decoding = UpSampling3D((3,1,1))(decoding)

    decoding = Conv3D(64, (3,3,3), activation='relu', padding='same')(decoding)
    decoding = Conv3D(64, (3,3,3), activation='relu', padding='same')(decoding)
    decoding = UpSampling3D((2,2,2))(decoding)

    decoding = Conv3D(128, (3,3,3), activation='relu', padding='same')(decoding)
    decoding = Conv3D(128, (3,3,3), activation='relu', padding='same')(decoding)
    decoding = UpSampling3D((2,2,2))(decoding)

    decoding = Conv3D(64, (3,3,3), activation='relu', padding='same')(decoding)
    decoding = Conv3D(8, (3,3,3), activation='relu', padding='same')(decoding)
    decoding = UpSampling3D((2,2,2))(decoding)

    #lambda layers to split the representation into 3 portions
    out1 = Lambda(slice_tensor1)(decoding)
    out2 = Lambda(slice_tensor2)(decoding)
    out3 = Lambda(slice_tensor3)(decoding)

    #this is the first output of the model -> hand shape
    output1 = Conv3D(3, (3,3,3), activation='sigmoid', padding='same')(out1)

    #this is the second output of the model -> motion
    output2 = Conv3D(3, (3,3,3), activation='sigmoid', padding='same')(out2)

    #this is the second output of the model -> motion
    output3 = Conv3D(3, (3,3,3), activation='sigmoid', padding='same')(out3)

    #autoencoder = Model([input], [output1, output2, output3])
    autoencoder = Model([input], [output1, output2, output3])
    autoencoder.compile(optimizer='adadelta', loss='mean_squared_error', loss_weights = weights)
    autoencoder.summary()

    return autoencoder

#methods to slice intermediate representation into 3 different portions
def slice_tensor1(input):
    return input[:,0:8,:,:,:]

def slice_tensor2(input):
    return input[:,8:16,:,:,:]

def slice_tensor3(input):
    return input[:,16:24,:,:,:]

#method to perform the fit on a MORA model
#list of parameters: mora model previously created, 8frame sequences of RGB videos, 8frame sequences of flow videos, 8frame sequences of depth videos, number of training epochs

def mora_fit(model, rgb_sequence, flow_sequence, depth_sequence, number_of_epochs):

    #reshaping inputs to be suitable for the model
    rgb_sequence = np.reshape(rgb_sequence, (len(rgb_sequence), 8, 112, 112, 3))
    flow_sequence = np.reshape(flow_sequence, (len(flow_sequence),8, 112, 112, 3))
    depth_sequence = np.reshape(depth_sequence, (len(depth_sequence),8, 112, 112, 3))

    #concatenating and creating a 24-frame representation; containing RGB, Flow and depth
    composed_input = np.concatenate((rgb_sequence, flow_sequence), axis=1)
    composed_input = np.concatenate((composed_input, depth_sequence), axis=1)

    #model fit -> provide a validation set if you have one
    #batch size must be a multiple of the timestep dimension
    #no shuffle should be performed in order to maintain the time correlation between timesteps
    model.fit(composed_input, [rgb_sequence, flow_sequence, depth_sequence],
                epochs=number_of_epochs,
                batch_size=4,
                shuffle=False,
                validation_data=(composed_input, [rgb_sequence, flow_sequence, depth_sequence]),
                callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])

    return model


"""Example implementation of the Coordinate Descent algorithm in Python

- The minimum value of F(x) is computed iteratively by minimizing individual coordinates in a cyclic manner
- On each iteration the active coordinate is updated as follows

  X_k+1 = X_k - alpha * [del_F(xk)] * e

  Where
  * alpha : step length,
  * e : the active co-ordinate vector(required to make vector addition to Xk possible),
  * del_F(xk) : component of the gradient corresponding to the active coordinate
"""

import logging
import numpy as np
import math

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)

__author__ = "@NdamuleloNemakh"
__version__ = 0.01

class CoordinateDescent:
    def __init__(self, max_iterations=500, no_of_dimensions=2, step_length=1, fixed_step_length=True):
        self.Dimensions = no_of_dimensions
        self.StepLength = step_length
        self.FixedStepLength = fixed_step_length
        self.MaxIterations = max_iterations
        self.CurrentIteration = 0
        self.Minimiser: np.ndarray = np.array([0, 0])
        self.ConvergenceThreshold = 10e-4

    def __preview_config(self):
        configs = f'''
                   Configuration Preview
                   ========================
                   n                   = {self.Dimensions}
                   Step Length         = {self.StepLength}
                   Fixed Step Length   = {self.FixedStepLength}
                   Max Iterations      = {self.MaxIterations}
                   '''
        log.debug(configs)
        return configs

    @property
    def _current_coordinate_idx(self):
        # Choose next cordinate to optimize, in a CYCLIC manner
        next_idx = lambda i: i % 2 + 1
        return next_idx(self.CurrentIteration)

    @property
    def _ith_coordinate_vector(self):
        v = np.zeros(self.Dimensions)
        active_idx = self._current_coordinate_idx - 1
        v[active_idx] = 1
        return v

    @staticmethod
    def __current_gradient(xk) -> np.ndarray:
        #  Example: F(X1, X2) = X1 - X2 + 2X1**2 + 2X1X2 + X2**2
        x1 = xk[0]
        x2 = xk[1]
        del_fx1 = 1 + 4 * x1 + 2 * x2
        del_fx2 = 2 * x1 + 2 * x2 - 1
        del_f = np.array([del_fx1, del_fx2])
        return del_f

    @staticmethod
    def f(xk, decimal_places=3):
        x1 = xk[0]
        x2 = xk[1]
        fn_value = x1 - x2 + 2 * math.pow(x1, 2) + 2 * x1 * x2 * math.pow(x2, 2)
        return round(fn_value, decimal_places)

    @property
    def __current_gradient_value(self):
        del_f = self.__current_gradient(self.Minimiser)
        # sqaured_sum = functools.reduce(lambda a, b: a ** 2 + b ** 2, del_f)
        return np.sqrt(del_f.dot(del_f))

    @property
    def __current_coordinate_gradient(self):
        del_f = self.__current_gradient(self.Minimiser)
        return del_f[self._current_coordinate_idx - 1]

    def __find_next_candidate(self):
        """Compute the next potential minimiser point, i.e. Xk+1"""
        xk = self.Minimiser
        del_f = self.__current_coordinate_gradient
        xk_plus_1 = xk - self.StepLength * del_f * self._ith_coordinate_vector
        log.debug(f"X**{self.CurrentIteration} = {xk} - {self.StepLength} * {del_f} * {self._ith_coordinate_vector}")
        return xk_plus_1

    def execute(self):
        log.info('Coordinate descent iteration started')
        self.__preview_config()
        for k in range(self.MaxIterations):
            log.debug(f"-----------Iteration {k}--------------")
            self.CurrentIteration = k
            self.Minimiser = self.__find_next_candidate()
            log.debug(f"------Minimiser = {self.Minimiser}. Gradient = {self.__current_gradient(self.Minimiser)} or "
                      f"{self.__current_gradient_value}--------\n")
            if self.__current_gradient_value <= self.ConvergenceThreshold:
                log.warning('Convergence condition satisfied, STOP!')
                break
        log.info(f"------Minimiser = {self.Minimiser}. Gradient = {self.__current_gradient_value}--------")
        log.info(f'Coordinate descent completed successfully. Total Iterations={self.CurrentIteration}')
        return self.Minimiser, self.f(self.Minimiser), round(self.__current_gradient_value, 3)


#importing the nesescary librarys
import pygame
import pygame_textinput
from pygame.locals import *
import random
import math
from FileManager import FileManager

fileManager = FileManager("gameDatabase.db")

def weighted_choice(choices):  # function to weight the probability of certian tiles being generated
    total = sum(w for c, w in choices) #returns the total of all of the choices
    r = random.uniform(0, total) #returns a random number in the range of 0 to the total sum
    upto = 0
    for c, w in choices: #loops through every choice
        if upto + w >= r: #if the selected probabilty is greater than the random number
            return c #returns the weighted item in the array
        upto += w
    assert False, "Shouldn't get here" #for debugging purposes

def dist(x1, y1, x2, y2): #function to generate circle distances
    return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) #pythagorases theorem

def generatePonds(numOfPonds): #generates the randomly positioned ponds
    for i in range(numOfPonds): #loops numOfPonds times
        r = random.randint(3, 7) #random radius of pond between 3 and 7
        cx = random.randint(0 + r, MAPHEIGHT - r)
        cy = random.randint(0 + r, MAPWIDTH - r)
        for x in range(cx - r, cx + r):
            for y in range(cy - r, cy + r):
                if dist(cx, cy, x, y) <= r:
                    tileMap[x][y][0] = WATER #appends pond tile to tile map array

def generateNpc(num, size):
    x = random.randint(0, MAPHEIGHT)
    y = random.randint(0, MAPWIDTH)
    #if num % 2 == 0:
        #for i in range(size):
            #for j in range(size):
                #tileMap[x + i][y + j][0] = WOOD

def generatePortal(): #function to randomly generate one portal per level
    x = random.randint(0, MAPWIDTH) #random x coord
    y = random.randint(1, MAPHEIGHT) #random y coord
    for i in range(len(tileMap)):
        for j in range(len(tileMap[i])):
            if i == y and j == x:
                if tileMap[i][j][0] != WATER: #makes sure the portal isn't generated on water
                    tileMap[i][j][0] = PORTAL #sets the specified tile to water
                else:
                    generatePortal() #generate new portal
            else:
                tileMap[i][j][1] = recourceValue[tileMap[i][j][0]]

def generateTileMap(): #generating the 2D tile array
    generateMonster(playerLevel) #first generating monsters
    # generating the tile map below
    global tileMap #setting the array variable global
    tileMap = [[[weighted_choice(tiles), 0]
                for i in range(MAPWIDTH)]
                for j in range(MAPHEIGHT)] #creating a 2D array in the size of the width and height specified
    generatePonds(random.randint(1, 6)) # generate ponds
    generateNpc(random.randint(0, 100), random.randint(3, 5)) #generate NPCs
    generatePortal() #generate portal

def renderEnviroment(): #function to render the tilemap
    for row in range(MAPHEIGHT):
        for column in range(MAPWIDTH):
            pygame.draw.rect(screen, colours[(tileMap[row][column])[0]],
                             (column * TILESIZE, row * TILESIZE, TILESIZE, TILESIZE)) #draw a rectangle for each item in the tile map with the specific colour
            screen.blit(font_player.render(str(tileMap[row][column][1]), True, (0, 0, 0)),
                        (column * TILESIZE, row * TILESIZE))
    pygame.draw.rect(screen, BLACK, (0, 0, TILESIZE * MAPWIDTH, TILESIZE)) #drawing a black menue bar at the top of the screen

def generateMonster(playerLevel): #generating monsters
    for i in range(random.randint(0,TILESIZE)): #random ammount of monsters
        monsterHealth = playerLevel*MONSTERHEALTH #monster health is relative to the player's level
        x=random.randint(0,MAPWIDTH)
        y=random.randint(0,MAPHEIGHT)
        monsters.append([x,y,monsterHealth]) #adding a monster to the monster array

def renderMonster(): #function to render monsters
    if len(monsters) > 0: #making sure the monster list isn't empty
        for i in range(len(monsters)): #looping through the monster array
            pygame.draw.rect(screen, PINK, ( monsters[i][0] * TILESIZE, monsters[i][1] * TILESIZE, TILESIZE, TILESIZE))  # rendering the monster
            screen.blit(font_monster.render(str(monsters[i][2]), True, (0, 0, 0)),(monsters[i][0] * TILESIZE, monsters[i][1] * TILESIZE))  # redering the monster health

def moveMonster(): #function to move each monster
    if len(monsters) > 0: #making sure the array isn't empty
        for i in range(len(monsters)): #looping through the monster array
            moveChance = random.randint(0,10)
            if moveChance > 5:
                if (playerx//TILESIZE - monsters[i][0]) > 0:
                    x = monsterMovementPoints
                else:
                    x = - monsterMovementPoints
                if playery//TILESIZE - monsters[i][1] > 0:
                    y = monsterMovementPoints
                else:
                    y = - monsterMovementPoints
            else:
                x = random.randint(-monsterMovementPoints, monsterMovementPoints)
                y = random.randint(-monsterMovementPoints, monsterMovementPoints)
            monsters[i] = [monsters[i][0] + x, monsters[i][1] + y, monsters[i][2]]
            if monsters[i][0] == playerTilex and monsters[i][1] == playerTiley:
                monsterAttack()

def monsterAttack(): #function to make the monster attack
    global playerHealth #making the playerHealth variable global so it can be accessed anywhere
    if random.randint(0,10) // 2 == 0:
        playerHealth = playerHealth - MONSTERATTACK #removing health off the player
        if playerHealth < 0: #check if the player is dead
            global died #making the dead variable global so it can be accessed anywhere
            died = True #setting the dead variable true so the game knows the player is dead

def renderPlayer(): #function to render the player and all related variables
    pygame.draw.rect(screen, RED, (playerx, playery, TILESIZE, TILESIZE))  # rendering the player
    screen.blit(font_player.render("health: "+str(playerHealth), True, (255, 255, 255)),(0, 0))  # redering the player health
    screen.blit(font_player.render("xp: " + str(xp), True, (255, 255, 255)),(100, 0))  # redering the player xp
    screen.blit(font_player.render("level: " + str(playerLevel), True, (255, 255, 255)), (150, 0))  # redering the player xp
    screen.blit(font_player.render("recource points: "+str(playerPoints), True, (255, 255, 255)),(300, 0))  # redering the player recource points
    screen.blit(font_player.render("iron: " + str(iron), True, (255, 255, 255)),(440, 0))  # redering the player iron
    screen.blit(font_player.render("water: " + str(water), True, (255, 255, 255)),(500, 0))  # redering the player water
    screen.blit(font_player.render(username, True, (255, 255, 255)),(width-85, 0))  # redering the username

def playerAttack(i): #function to make the player attack #i being the specific monster in the array
    monsters[i][2]=monsters[i][2]-playerAttackPoints #removing health from the indexed monster
    if monsters[i][2]<=0: #checking if the monster is dead
        del monsters[i] #deleting the monster from the array
        global xp #making the player xp variable global so it can be accessed anywhere
        xp=xp+1 #incrementing the player xp variable by 1

def saveOptions():
    pygame.draw.rect(screen, WHITE, (width/2-(width/4), height/2-(height/4), width/2, height/2))
    pygame.draw.rect(screen, BLACK, (width / 2 - (width / 4), height / 2 - (height / 4), width / 2, height / 2), 5)

    screen.blit(font_saveOptions.render("SAVE GAME", True, (0, 0, 0)), ((width/2)-175, (height/2)-130))
    pygame.draw.rect(screen, (169, 169, 169), ((width / 2) - 140, (height / 2) - 50, width / 16, height / 16))
    pygame.draw.rect(screen, BLACK, ((width / 2) - 140, (height / 2) - 50, width / 16, height / 16), 5)
    screen.blit(font_saveOptions.render("save", True, (0, 0, 0)), ((width / 2) - 130, (height / 2) - 50))

    screen.blit(font_saveOptions.render("LOAD GAME", True, (0, 0, 0)), ((width / 2) + 25, (height / 2) - 130))
    pygame.draw.rect(screen, (169, 169, 169), ((width / 2) + 60, (height / 2) - 50, width / 16, height / 16))
    pygame.draw.rect(screen, BLACK, ((width / 2) + 60, (height / 2) - 50, width / 16, height / 16), 5)
    screen.blit(font_saveOptions.render("load", True, (0, 0, 0)), ((width / 2) + 75, (height / 2) - 47))

    # fileManager = FileManager("gameDatabase.db")
    # name = input("username")
    # fileManager.saveGame(name, done)

def renderInput(usernameText, save_load):
    # Feed it with events every frame
    usernameText.update(pygame.event.get())
    if save_load == True:
        # Blit its surface onto the screen
        screen.blit(usernameText.get_surface(), ((width / 2) -175, (height / 2) -100))
    else:
        # Blit its surface onto the screen
        screen.blit(usernameText.get_surface(), ((width / 2) + 30, (height / 2) - 100))

def loadData(data): #function to load the save data
    global username
    username=data[0]
    global playerHealth
    playerHealth=data[1]
    global playerAttackPoints
    playerAttackPoints=data[2]
    global playerLevel
    playerLevel=data[3]
    global xp
    xp=data[4]
    global playerx
    playerx=data[5]
    global playery
    playery=data[6]

def generateBoss():
    size = random.randint(3,8)
    x=random.randint(0,MAPWIDTH)
    y=random.randint(0,MAPHEIGHT)
    global bossHealth

    for i in range(size):
        for j in range(size):
            boss.append([i+x, j+y])  # adding a monster to the monster array

def moveBoss():
    x = random.randint(-monsterMovementPoints, monsterMovementPoints)
    y = random.randint(-monsterMovementPoints, monsterMovementPoints)
    if len(boss) > 0: #making sure the array isn't empty
        for i in range(len(boss)): #looping through the monster array
            boss[i] = [boss[i][0] + x, boss[i][1] + y]

def renderBoss():
    if len(boss) > 0: #making sure the boss array isn't empty
        for i in range(len(boss)): #looping through the boss array
            pygame.draw.rect(screen, GREEN, (boss[i][0] * TILESIZE, boss[i][1] * TILESIZE, TILESIZE, TILESIZE))  # rendering the boss
            screen.blit(font_monster.render(str(bossHealth), True, (0, 0, 0)),(boss[i][0] * TILESIZE, boss[i][1] * TILESIZE))  # redering boss health

def bossBattle(mousex,mousey,xDist,yDist):
    global boss
    global bossDied
    global playerLevel
    if bossDied == False:
        if abs(xDist // TILESIZE) < movementPoints: #checking how close the player is on the x axis
            if abs(yDist // TILESIZE) < movementPoints: #checking how close the player is on the y axis
                for i in range(len(boss)): #looping through the boss array
                    if mousex == boss[i][0] and mousey == boss[i][1]:
                        global bossHealth
                        bossHealth=bossHealth-playerAttackPoints
                        if bossHealth <= 0:
                            del boss[:]
                            bossDied = True
                            playerLevel=playerLevel+100
                            break

def deathAnimation():
    x = random.randint(0, MAPWIDTH)
    y = random.randint(0, MAPHEIGHT)
    global deathAnimationArray
    deathAnimationArray.append([x, y])  # adding a monster to the monster array

    if len(deathAnimationArray) > 0: #making sure the monster list isn't empty
        for i in range(len(deathAnimationArray)): #looping through the monster array
            pygame.draw.rect(screen, BLACK, (deathAnimationArray[i][0] * TILESIZE, deathAnimationArray[i][1] * TILESIZE, TILESIZE, TILESIZE))  # rendering the boss

#game dimenions
TILESIZE = 20 #the size in pixels of each square tile
MAPWIDTH = 60 #the ammount of tiles on the x axis
MAPHEIGHT = 30 #the ammount of tiles on the y axis

#tile valuesz
DIRT = 0
STONE = 1
IRON = 2
WATER = 3
PORTAL = 4
WOOD = 5

tiles = [(STONE,5),(DIRT,0),(IRON,0.25),(WATER,0)]

recourceValue = {
    DIRT : 0,
    IRON : 3,
    STONE : 0,
    WATER : 1,
    WOOD : 4
}

#item ids
HEALTHPOTION = 0
ATTACKPOTION = 1
HELMET = 2
CHESTPLATE = 3
CHAPS = 4
BOOTS = 5
SWORD = 6

#colour RGB values
BLACK = (0,0,0)
GRAY = (168, 168, 168)
BROWN = (153,76,0)
IRONBROWN = (210,105,30)
GREEN = (92, 214, 94)
LIGHTGREEN = (66, 244, 98)
BLUE = (0,0,255)
RED = (255,0,0)
PINK = (255,0,255)
MAHOGANY = (103,10,10)
WHITE = (255,255,255)

colours = { #library linking each tile ID to a colour
    DIRT : BROWN,
    IRON : IRONBROWN,
    STONE: GRAY,
    WATER: BLUE,
    PORTAL: BLACK,
    WOOD: MAHOGANY
}

pygame.init() #initialise all imported PyGame modules

#set the screen size of the grid and making the window resizable
screen = pygame.display.set_mode((MAPWIDTH*TILESIZE, MAPHEIGHT*TILESIZE),pygame.RESIZABLE)

#inititalising fonts
font_player = pygame.font.SysFont('Arial', 15)
font_monster = pygame.font.SysFont('Arial', 10)
font_timer = pygame.font.SysFont('Arial', 50)
font_died = pygame.font.SysFont('Arial', 200)
font_saveOptions = pygame.font.SysFont('Arial', 25)

width, height = pygame.display.get_surface().get_size() #storing width and height of screen in variables
done = False #variable to be used when exiting
pause = False #variable to pause the game
showInput = False

CURSOR = Rect(0, 0, TILESIZE, TILESIZE) #initialising a rectangle to be used as a cursor

#main player variables
playerHealth = 100
playerAttackPoints = 50
playerPoints = 0
playerLevel = 1
movementPoints = 2
iron=0
water=0
xp=0
died = False
deathAnimationArray =[]

# Create TextInput-object
usernameText = pygame_textinput.TextInput()
username = ""

#monster variables
monsters = []
MONSTERHEALTH = 100
MONSTERATTACK = 30
monsterMovementPoints = 2
MOVEMONSTER = 1000
moveMonsterEvent = pygame.USEREVENT

genBoss = False
boss=[]
bossHealth=500
bossDied = False

clock = pygame.time.Clock()

pygame.time.set_timer(moveMonsterEvent, MOVEMONSTER) #clock to move monster

playerx = random.randint(0,MAPWIDTH)*TILESIZE #giving the player a random x coord on the grid
playery = random.randint(0,MAPHEIGHT)*TILESIZE #giving the player a random x coord on the grid

generateTileMap()

while not done:
    playerTilex = playerx//TILESIZE
    playerTiley = playery // TILESIZE

    mousex, mousey = pygame.mouse.get_pos()
    mousex = mousex - (mousex % TILESIZE) + TILESIZE / 2  # getting the x tile the mouse is on
    mousey = mousey - (mousey % TILESIZE) + TILESIZE / 2  # getting the y tile the mouse is on

    if pause == False and died == False:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            if event.type == moveMonsterEvent:
                moveMonster()
                moveBoss()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pause = not pause

            if event.type == pygame.MOUSEBUTTONDOWN:
                (button1, button2, button3,) = pygame.mouse.get_pressed()  # get button pressed

                if button1:

                    xDist = ((mousex - playerx) - TILESIZE / 2)#distance to travel
                    yDist = ((mousey - playery) - TILESIZE / 2)#distance to travel

                    xTilePos = (mousex-(TILESIZE/2))/TILESIZE
                    yTilePos = (mousey-(TILESIZE/2))/TILESIZE

                    if genBoss == True: #only attacking boss if boss has been generated
                        bossBattle(xTilePos, yTilePos, xDist, yDist) #managing boss battle

                    # move player
                    if tileMap[int(yTilePos)][int(xTilePos)][0] != WATER: #making sure the player cant move onto water
                        # making sure the player can only move a certian distance per click
                        if abs(xDist // TILESIZE) > movementPoints:
                            if xDist > 0:
                                xDist = 2 * TILESIZE
                            else:
                                xDist = -(2 * TILESIZE)
                        if abs(yDist // TILESIZE) > movementPoints:
                            if yDist > 0:
                                yDist = 2 * TILESIZE
                            else:
                                yDist = -(2 * TILESIZE)

                        if tileMap[int((playery + yDist)//TILESIZE)][int((playerx + xDist)//TILESIZE)][0] != WATER: #making sure the player cant land on water/stone
                            #moving player
                            playerx = playerx + xDist
                            playery = playery + yDist
                            cursorColour = LIGHTGREEN
                            for i in range(len(monsters)): #checking if player is attacking monster
                                if monsters[i][0] == int(playerTilex) and monsters[i][1] == int(playerTiley):
                                    playerAttack(i)
                                    monsterAttack()
                                    break

                                    #indicating the player cannot move to the selected tile
                        elif tileMap[int((playery + yDist) // TILESIZE)][int((playerx + xDist) // TILESIZE)][0] == WATER:
                            cursorColour = RED
                    else:
                        cursorColour = RED

                    ## moving the player through portals
                    if tileMap[int(playerTiley)][int(playerTilex)][0] == PORTAL:
                        del monsters[::]
                        generateTileMap()

                elif button3:

                    ##### GETTING TILE POSITIONS OF TILES AND PLAYER ###
                    xTilePos = (mousex - (TILESIZE / 2)) / TILESIZE
                    yTilePos = (mousey - (TILESIZE / 2)) / TILESIZE
                    xPlayerPos = (playerx //TILESIZE)
                    yPlayerPos = (playery //TILESIZE)

                    if -2 < xTilePos-xPlayerPos < 2 and -2 < yTilePos-yPlayerPos < 2:
                        if tileMap[int(yTilePos)][int(xTilePos)][1] > 0:
                            cursorColour=PINK
                            playerPoints=playerPoints+1 #adding player points
                            tileMap[int(yTilePos)][int(xTilePos)][1]=(tileMap[int(yTilePos)][int(xTilePos)][1])-1 #removing points from tile
                            if tileMap[int(yTilePos)][int(xTilePos)][0] == IRON: #adding points to iron stash
                                iron=iron+1
                            elif tileMap[int(yTilePos)][int(xTilePos)][0] == WATER: #adding points to iron stash
                                water=water+1

        renderEnviroment()  # call the function to render the enviroment
        renderPlayer()  # call the function to render the player
        renderMonster()  # call the function to render the monsters
        renderBoss()
        if xp == 10:  # check if the player's xp level is 10
            playerLevel = playerLevel + 1  # increment the player's level by 1
            playerHealth = playerHealth + 100 # adding health to the player
            xp = 0  # reset the xp level back to 0

        if event.type == pygame.MOUSEBUTTONDOWN:
            (button1, button2, button3,) = pygame.mouse.get_pressed()  # get button pressed
        else:
            cursorColour = (0, 0, 0)
        CURSOR.center = (mousex, mousey)
        pygame.draw.rect(screen, cursorColour, CURSOR, 2)
        ##########################

    if pause == True:
        (button1, button2, button3,) = pygame.mouse.get_pressed()
        x, y = pygame.mouse.get_pos()
        if showInput == False:
            for event in pygame.event.get():
                if button1:  # checking if player clicked buttons
                    if x > ((width / 2) - 125) and x < ((width / 2) - 75):  # x bounds of save button
                        if y > ((height / 2) - 50) and y < ((height / 2) + 25):  # y bounds of save button
                            showInput = True
                            save_load = True

                    if x > ((width / 2) + 80) and x < ((width / 2) + 180):  # x bounds of load button
                        if y > ((height / 2) - 50) and y < ((height / 2) + 25):  # y bounds of load button
                            showInput = True
                            save_load = False

        saveOptions()
        if showInput == True:
            renderInput(usernameText, save_load)
            if len(usernameText.get_text()) > 9:
                username = usernameText.get_text()
                if save_load == True:
                    fileManager.saveGame(username, playerHealth, playerAttackPoints, playerLevel, xp, playerx, playery)
                else:
                    fileManager.loadGame(username)
                    loadData(fileManager.data)

                pause = False

    if playerLevel%10 ==0  and genBoss == False:
        generateBoss()
        genBoss = True

    if died == True:
        deathAnimation()
        screen.blit(font_died.render("YOU DIED", True, (255,255,255)), (width/2-500, height/2-100))  #redering the player health
    pygame.display.update()
    clock.tick(60)


import uuid

from django.core.exceptions import ValidationError
from django.db import models

from sagepaypi.constants import COUNTRY_CHOICES, US_STATE_CHOICES
from sagepaypi.models import CardIdentifier

from tests.test_case import AppTestCase

class TestModel(AppTestCase):

    # fields

    def test_id(self):
        field = self.get_field(CardIdentifier, 'id')
        self.assertModelField(field, models.UUIDField)
        self.assertFalse(field.editable)
        self.assertTrue(field.primary_key)

    def test_created_at(self):
        field = self.get_field(CardIdentifier, 'created_at')
        self.assertModelField(field, models.DateTimeField, blank=True)
        self.assertTrue(field.auto_now_add)

    def test_first_name(self):
        field = self.get_field(CardIdentifier, 'first_name')
        self.assertModelField(field, models.CharField)
        self.assertEqual(field.max_length, 100)

    def test_last_name(self):
        field = self.get_field(CardIdentifier, 'last_name')
        self.assertModelField(field, models.CharField)
        self.assertEqual(field.max_length, 100)

    def test_billing_address_1(self):
        field = self.get_field(CardIdentifier, 'billing_address_1')
        self.assertModelField(field, models.CharField)
        self.assertEqual(field.max_length, 255)

    def test_billing_address_2(self):
        field = self.get_field(CardIdentifier, 'billing_address_2')
        self.assertModelField(field, models.CharField, True, True)
        self.assertEqual(field.max_length, 255)

    def test_billing_city(self):
        field = self.get_field(CardIdentifier, 'billing_city')
        self.assertModelField(field, models.CharField)
        self.assertEqual(field.max_length, 255)

    def test_billing_postal_code(self):
        field = self.get_field(CardIdentifier, 'billing_postal_code')
        self.assertModelField(field, models.CharField, True, True)
        self.assertEqual(field.max_length, 12)

    def test_billing_country(self):
        field = self.get_field(CardIdentifier, 'billing_country')
        self.assertModelField(field, models.CharField)
        self.assertEqual(field.max_length, 2)

    def test_billing_state(self):
        field = self.get_field(CardIdentifier, 'billing_state')
        self.assertModelField(field, models.CharField, True, True)
        self.assertEqual(field.max_length, 2)

    def test_merchant_session_key(self):
        field = self.get_field(CardIdentifier, 'merchant_session_key')
        self.assertModelField(field, models.CharField)
        self.assertEqual(field.max_length, 100)

    def test_card_type(self):
        field = self.get_field(CardIdentifier, 'card_type')
        self.assertModelField(field, models.CharField)
        self.assertEqual(field.max_length, 255)

    def test_last_four_digits(self):
        field = self.get_field(CardIdentifier, 'last_four_digits')
        self.assertModelField(field, models.CharField)
        self.assertEqual(field.max_length, 4)

    def test_expiry_date(self):
        field = self.get_field(CardIdentifier, 'expiry_date')
        self.assertModelField(field, models.CharField)

    def test_card_identifier(self):
        field = self.get_field(CardIdentifier, 'card_identifier')
        self.assertModelField(field, models.CharField)
        self.assertEqual(field.max_length, 100)

    # properties

    def test_str(self):
        pk = uuid.uuid4()
        self.assertEqual(CardIdentifier(pk=pk).__str__(), str(pk))

    def test_billing_address(self):
        card = CardIdentifier(
            billing_address_1='88 The Road',
            billing_address_2='Some Estate',
            billing_postal_code='412',
            billing_city='City',
            billing_country='US',
            billing_state='AL'
        )
        self.assertEqual(
            card.billing_address,
            {
                'address1': card.billing_address_1,
                'address2': card.billing_address_2,
                'city': card.billing_city,
                'country': card.billing_country,
                'postalCode': card.billing_postal_code,
                'state': card.billing_state
            }
        )

    def test_display_text(self):
        self.assertEqual(
            CardIdentifier(card_type='Visa', last_four_digits='1234').display_text,
            'Visa (1234)'
        )

    # validation

    def test_postal_code_required_when_country_not_IE(self):
        card = CardIdentifier(
            first_name='Foo',
            last_name='User',
            billing_address_1='88 The Road',
            billing_city='City',
            billing_country='GB'
        )
        with self.assertRaises(ValidationError) as e:
            card.clean()

        self.assertEqual(e.exception.args[0], {'billing_postal_code': 'This field is required.'})

    def test_postal_code_not_required_when_country_is_IE(self):
        card = CardIdentifier(
            first_name='Foo',
            last_name='User',
            billing_address_1='88 The Road',
            billing_city='City',
            billing_country='IE'
        )
        card.clean()

    def test_state_required_when_country_is_US(self):
        card = CardIdentifier(
            first_name='Foo',
            last_name='User',
            billing_address_1='88 The Road',
            billing_postal_code='412',
            billing_city='City',
            billing_country='US'
        )
        with self.assertRaises(ValidationError) as e:
            card.clean()

        self.assertEqual(e.exception.args[0], {'billing_state': 'This field is required.'})

    def test_state_not_required_when_country_is_not_US(self):
        card = CardIdentifier(
            first_name='Foo',
            last_name='User',
            billing_address_1='88 The Road',
            billing_city='City',
            billing_country='IE'
        )
        card.clean()


import telnetlib
import sys
#TELENET AL HOST XXXX

HOST = sys.argv[1]
try :
    tn=telnetlib.Telnet(HOST, 9998)
    #TELENET CREDENCIALS
    # print('conectandose a telnet ingresando credenciales...')
    # tn.read_until(b"Username:",timeout=1)
    # tn.write(user123.encode('ascii')+b"\n")
    # print('conectandose a telnet ingresando contraseña...')
    # tn.read_until(b"Password:",timeout=1)
    # tn.write(password123.encode('ascii')+b"\n")
    # print('conectado con host')

    tn.write('pin 123'.encode('ascii')+ b'\n' )

    #Configuration
    tn.write(b"exec showdriverhealth\n")
    tn.write(b"exit\n")

    print(tn.read_all().decode('ascii') )

    tn.close()
except :
    print('Error de conexion!')


from country_list import country_list
#from anonum_pars import proxy

HEADERS = {
    "user-agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"
}

#PROXY = proxy

SITE = 'habr'
page = 1
if SITE == 'habr':
    DOMEN = "https://habrahabr.ru/"

elif SITE == 'mendo':
    AGE_MIN = 18
    AGE_MAX = 35
    COUNTRY = "Russia"
    DOMEN = "http://www.meendo.com"
    payload = {"gender": 2, "amin": AGE_MIN, "amax": AGE_MAX, "photo": 1, "country": country_list.get(COUNTRY),
               "region": 0, "city": 0}
    SEARCH_URL = (DOMEN + "/search/#/search/")


from scipy.spatial import distance
import numpy as np

def interpol_alt(x,y):
    # Determine which slices have a prediction
    t_true = np.where(x != -1)[0]

    if len(t_true) > 0:
        x_true = x[t_true]
        y_true = y[t_true]

        # Skip the very bottom and very top of the image; we do not extrapolate
        start_point = np.min(t_true)
        end_point = np.max(t_true)

        # Define the range of slices on which to interpolate
        t_interpol = np.arange(start_point, end_point)

        # Perform the interpolation and save to array
        x1 = np.interp(t_interpol, t_true, x_true)
        y1 = np.interp(t_interpol, t_true, y_true)
        x[start_point:end_point] = np.round(x1)
        y[start_point:end_point] = np.round(y1)

    return x,y

def find_outliers(x_list, y_list, reference_slice, threshold):
    # Define array for distances
    dist=np.zeros(len(x_list))

    # Work from the reference slice upwards
    for i in range(reference_slice, len(x_list)):
        m=1
        while x_list[i-m]==-1:
            m+=1
        else:
            # Calculate previous and current point
            previous_point=(x_list[i-m], y_list[i-m])
            point=(x_list[i], y_list[i])

            # Calculate distance; if this distance is too high, drop this point
            dist=distance.euclidean(previous_point,point)
            if dist>threshold:
                x_list[i]=-1
                y_list[i]=-1

    # Work from the reference slide downwards
    for i in range(reference_slice-2,-1,-1):
        m=1
        while x_list[i+m]==-1:
            m+=1
        else:
            # Calculate previous and current point
            previous_point=(x_list[i+1], y_list[i+1])
            point=(x_list[i], y_list[i])

            # Calculate distance; if this distance is too high, drop this point
            dist=distance.euclidean(previous_point,point)
            if dist>threshold:
                x_list[i]=-1
                y_list[i]=-1

    # Interpolate the points that have just been dropped
    interpolation=interpol_alt(x_list, y_list)
    final_x=interpolation[0]
    final_y=interpolation[1]
    return final_x,final_y


import os
import cv2

class DeepRoiDetection(object):
    """
    This is the DRoiD you are looking for!
    Base interface for Deep Neural Network based region of interest detection and video_worker.
    This module supports bounding boxes in the xyxy or xywh formats. We set default as xyxy for AccessMath.
    """
    def __init__(self,
                 net,
                 name = 'DRoiD',
                 detection_threshold=0.6,
                 bbox_format='xyxy'):
        self.name = name
        self.net = net # use a util.model_loader object to pass a model here
        self.detected_rois = {}
        self.detection_threshold = detection_threshold
        self.bbox_format = 'xyxy' if bbox_format not in ['xyxy', 'xywh'] else bbox_format

    def initialize(self, width, height):
        pass

    def set_debug_mode(self, active, start_time, end_time, out_dir, video_name):
        self.debug_mode = active
        self.debug_start = start_time
        self.debug_end = end_time
        self.debug_out_dir = '{}_{}_debug({})'.format(video_name, self.name, self.detection_threshold)
        self.debug_video_name = video_name
        if not os.path.isdir(self.debug_out_dir) and self.debug_mode:
            os.makedirs(self.debug_out_dir)

    def handleFrame(self, frame, last_frame, v_index, abs_time, rel_time, abs_frame_idx):
        img = frame
        frameID = abs_frame_idx
        H, W, C = img.shape
        self.detected_rois[frameID] = {}
        self.detected_rois[frameID]['abs_time'] = abs_time
        self.detected_rois[frameID]['height'] = H
        self.detected_rois[frameID]['width'] = W
        self.detected_rois[frameID]['bboxes'] = bboxes = []
        self.detected_rois[frameID]['labels'] = labels = []
        self.detected_rois[frameID]['confidences'] = confidences = []
        self.detected_rois[frameID]['features'] = features = []

        self.fprop(img, bboxes, labels, confidences, features)

        self.detected_rois[frameID]['bboxes'] = [bbox for i, bbox in enumerate(bboxes)\
                                                 if confidences[i] >= self.detection_threshold]
        self.detected_rois[frameID]['labels'] = [label for i, label in enumerate(labels)\
                                                 if confidences[i] >= self.detection_threshold]
        self.detected_rois[frameID]['confidences'] = [conf for conf in confidences\
                                                      if conf >= self.detection_threshold]
        self.detected_rois[frameID]['visible'] = len(self.detected_rois[frameID]['bboxes']) > 0

        if self.debug_mode:
            self.debug_frame(img, frameID)

    def fprop(self, img, bboxes, labels, confidences, features):
        """
        This function needs to be implemented according the neural network architecture you have chosen.
        We expect the derived classes to implement this method based on the model of choice and append to
        bboxes, labels and confidences arrays, *the same ones passed as args*
        If your model returns an RoI which is not bounding box in self.format then it should be converted so.
        If your model returns only one kind of class append a string that describes it for each bbox.
        If your model does not return a confidence append 1.0 for each bbox.

        :param img: Input frame as np array in BGR channel ordering
        :param bboxes: List of xyxy or xywh tuples detections in the image, to be appended in implementation
        :param labels: Corresponding list of xyxy or xywh tuples labels, to be appended in implementation
        :param confidences: Corresponding list of xyxy or xywh tuples confidences, to be appended in implementation
        :param features: Corresponding list of feature vectors describing the roi, to be appended in implementation
        """
        raise NotImplementedError

    def debug_frame(self, frame, frameID):
        bboxes = self.detected_rois[frameID]['bboxes']
        for i, bbox in enumerate(bboxes):
            score = self.detected_rois['confidences'][i]
            label = self.detected_rois['labels'][i]
            if score >= self.detection_threshold:
                cv2.rectangle(frame, (bbox[0], bbox[1]), (bbox[2], bbox[3]), color=(255, 0, 0))
                cv2.putText(frame, str(label) + ' ' + str(score), (bbox[0], bbox[1]),
                            cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0))
        cv2.imwrite('{}/{}.jpg'.format(self.debug_out_dir, frameID), frame)

    def getWorkName(self):
        return self.name

    def finalize(self):
        pass

    def get_results(self):
        return self.detected_rois

    @staticmethod
    def getCentroid(bbox, bbox_format):
        if bbox_format == 'xyxy':
            x, y, x2, y2 = bbox
            w = x2 - x
            h = y2 - y
        else:
            x, y, w, h = bbox
        return (x + (w // 2), y + (h // 2))

    @staticmethod
    def getArea(bbox, bbox_format):
        if bbox_format == 'xyxy':
            x, y, x2, y2 = bbox
            w = x2 - x
            h = y2 - y
        else:
            x, y, w, h = bbox
        return w * h


from django.shortcuts import render
from django.views.decorators.http import require_http_methods
import time
import json
import logger
import base64

import gunicorn
from flask import Flask, request, jsonify, make_response
from predictor import Predictor

# Create your views here.
@require_http_methods(['GET'])  # Health check URL for consul
def check():
    return "success"

"""config path"""
_CONF_PATH = "conf/conf.json"

# load model
predictor_instance = Predictor()
@require_http_methods(['POST'])
def inference(request):
    """app entry"""
    start = time.time()

    json_data = request.get_data()
    json_info = json.loads(json_data.decode("utf-8"))
    traceId = json_info.get("traceId")
    mode = json_info.get("mode")
    od_pair = json_info.get("od_pair")

    status = 0
    response = {}
    response["errorMsg"] = ""
    try:
        od_pair = tuple(od_pair.split('-'))
        predictor_instance.do_predict(od_pair, mode=mode)
    except Exception as e:
        response["errorMsg"] = "sorry, unknown exception, server failed."
        status = -1
        logger.error('Failed to execute process function, traceId:{}, error:{}'.format(traceId, e))

    response['traceId'] = traceId
    response['status'] = status

    response = make_response(
        jsonify(response),
        200, # status
        {'content-type': 'application/json'}
    )

    end = time.time()
    logger.info('traceId: ' + traceId + '\t' + 'monitor TotalTime' + '\t' + str((end-start)*1000) + 'ms')

    return response


import torch
import numpy as np
from model import Transformer_prediction
from plot_module import model_plot
from data_progress import get_data

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
input_sequence_length = 14
output_sequence_length = 1
file = 'data/china_pred.xlsx'

data, label = get_data(input_sequence_length, output_sequence_length, file)
# print(np.shape(data))
data, label = data.to(device), label.to(device)

model = Transformer_prediction()
filename = r'china_model/net_961_0.002793417545.pt'
checkpoint = torch.load(filename, map_location=torch.device('cpu'))
model.load_state_dict(checkpoint['net'])
model.to(device)

# model.eval()

with torch.no_grad():
    # print(np.shape(data))
    output = model(data.unsqueeze(1), device).squeeze()
    output = output.to(device)
    pred_seq = output.cpu().numpy().tolist()

model_plot(data, label, pred_seq, device, file)


import asyncio
import websockets

async def message(websocket, path):
    user_id = None
    if len(CLIENTS) < 2:
        CLIENTS.add(websocket)
        user_id = len(CLIENTS)
        CONNECTIONS[user_id] = websocket
        await websocket.send(f"You are player {user_id}")
        print(f"{websocket.remote_address[0]} joined.")
        print(f"{len(CLIENTS)} connected players.")
    else:
        print(f"{websocket.remote_address[0]} tried to join but server is full.")
        await websocket.send("Server is full!")
        await websocket.close()

    while True:
        if user_id == 1:
            other_user_id = 2
        else:
            other_user_id = 1
        try:
            message = await CONNECTIONS[user_id].recv()
        except websockets.ConnectionClosed:
            print(f"Connection closed for player {user_id}")
            CLIENTS.remove(user_id)
            break

        if message == "Respawn":
            await CONNECTIONS[other_user_id].send("Respawn")
            print(f"Player {user_id} respawned.")
        elif message == "Shoot":
            await CONNECTIONS[other_user_id].send("Shoot")
            print(f"Player {user_id} shot.")
        elif message == "Up":
            await CONNECTIONS[other_user_id].send("Up")
            print(f"Player {user_id} moved up.")
        elif message == "Left":
            await CONNECTIONS[other_user_id].send("Left")
            print(f"Player {user_id} moved left.")
        elif message == "Down":
            await CONNECTIONS[other_user_id].send("Down")
            print(f"Player {user_id} moved down.")
        elif message == "Right":
            await CONNECTIONS[other_user_id].send("Right")
            print(f"Player {user_id} moved right.")
        else:
            print(f"Unknown message received from player {user_id}: {message}")

async def main():
    async with websockets.serve(message, "0.0.0.0", port):
        await asyncio.Future()  # run forever

CLIENTS = set()
CONNECTIONS = {}
port = 8080
print(f"Gun2 Server Started @ {port}")
asyncio.run(main())


import sys
import json
import socket
import time
import argparse
import logging
import threading

from PyQt5.QtWidgets import QApplication

from home_work_13.jim.config import *
from home_work_13.jim.utils import send_message, get_message
from errors import IncorrectDataRecivedError, ReqFieldMissingError, ServerError

from home_work_13.decorator import log

from metaclasses import ClientMaker

logger = logging.getLogger('clients')

@log
def arg_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('addr', default=DEFAULT_IP_ADDRESS, nargs='?')
    parser.add_argument('port', default=DEFAULT_PORT, type=int, nargs='?')
    parser.add_argument('-n', '--name', default=None, nargs='?')
    namespace = parser.parse_args(sys.argv[1:])
    server_address = namespace.addr
    server_port = namespace.port
    client_name = namespace.name

    if not 1023 < server_port < 65536:
        logger.critical(
            f'Попытка запуска клиента с неподходящим номером порта: {server_port}. Допустимы адреса с 1024 до 65535. Клиент завершается.')
        exit(1)

    return server_address, server_port, client_name

if __name__ == '__main__':
    from home_work_13.clients.start_dialog import UserNameDialog

    from home_work_13.clients.database import ClientDatabase

    from home_work_13.clients.transport import ClientTransport

    from home_work_13.clients.main_window import ClientMainWindow
    server_address, server_port, client_name = arg_parser()

    client_app = QApplication(sys.argv)

    if not client_name:
        start_dialog = UserNameDialog()
        client_app.exec_()
        if start_dialog.ok_pressed:
            client_name = start_dialog.client_name.text()
            del start_dialog
        else:
            exit(0)

    logger.info(
        f'Запущен клиент с парамертами: адрес сервера: {server_address} , порт: {server_port}, имя пользователя: {client_name}')

    database = ClientDatabase(client_name)

    try:
        transport = ClientTransport(server_port, server_address, database, client_name)
    except ServerError as error:
        print(error.text)
        exit(1)
    transport.setDaemon(True)
    transport.start()

    main_window = ClientMainWindow(database, transport)
    main_window.make_connection(transport)
    main_window.setWindowTitle(f'Чат Программа alpha release - {client_name}')
    client_app.exec_()

    transport.transport_shutdown()
    transport.join()


from copy import deepcopy
from typing import Optional, Sequence, Union
from avalanche.benchmarks import CLExperience
from avalanche.training.templates.base import ExpSequence

import torch
from avalanche.training.templates import SupervisedTemplate
from avalanche_addons.utils.dmc_train import StudentTrainer

from avalanche.training.templates import BaseSGDTemplate

def reset_child_params(module):
    for layer in module.children():
        if hasattr(layer, "reset_parameters"):
            layer.reset_parameters()
        reset_child_params(layer)

def freeze_model(model):
    for param in model.parameters():
        param.requires_grad = False
    for layer in model.children():
        if hasattr(layer, "requires_grad"):
            layer.requires_grad = False

def unfreeze_model(model):
    for param in model.parameters():
        param.requires_grad = True
    for layer in model.children():
        if hasattr(layer, "requires_grad"):
            layer.requires_grad = True

class DMC(SupervisedTemplate):
    def __init__(
        self,
        model,
        device,
        aux_trn_loader,
        aux_val_loader,
        lr,
        optimizer,
        classes_per_task,
        plugins=None,
        nepochs=3,
        lr_min=1e-4,
        lr_factor=3,
        lr_patience=5,
        clipgrad=10000,
        momentum=0.9,
        wd=5e-5,
        multi_softmax=False,
        wu_nepochs=0,
        wu_lr_factor=1,
        fix_bn=False,
        eval_on_train=False,
        *args,
        **kwargs
    ):
        super().__init__(model, optimizer)  # type: ignore
        BaseSGDTemplate.__init__(
            self=self,
            model=model,
            optimizer=optimizer,
            device=device,
            *args,
            **kwargs
        )
        self.model_new = None
        self.model_old = None
        self.lr = lr
        self.acc_clases = 0
        self.classes_per_task = classes_per_task
        # second step params
        self.lr_patience = 4
        self.nepochs = nepochs
        self.aux_trn_loader = aux_trn_loader
        self.aux_val_loader = aux_val_loader
        #
        self.clipgrad = clipgrad
        self.lr_min = lr_min
        self.lr_factor = lr_factor
        self.lr_patience = lr_patience
        self.clipgrad = clipgrad
        self.momentum = momentum
        self.wd = wd
        self.multi_softmax = multi_softmax
        self.wu_nepochs = wu_nepochs
        self.wu_lr_factor = wu_lr_factor
        self.fix_bn = fix_bn
        self.eval_on_train = eval_on_train
        self.warmup_epochs = wu_nepochs
        self.warmup_lr = lr * wu_lr_factor

    def train(
        self,
        experiences: CLExperience | ExpSequence,
        eval_streams: Sequence[CLExperience | ExpSequence] | None = None,
        **kwargs
    ):
        t = experiences.current_experience

        # initialize
        self.acc_clases += self.classes_per_task

        # add new classification layer
        reset_child_params(self.model)
        self.linear_in = self.model.fc.in_features
        self.model.fc = torch.nn.Linear(
            self.linear_in, self.classes_per_task, True
        ).to(self.device)

        # train
        super().train(experiences, eval_streams, **kwargs)

        if t > 0:
            # freeze new model
            self.model_new = deepcopy(self.model)
            freeze_model(self.model_new)
            self.model_new.eval()

            # create new model
            self.model = deepcopy(self.model)
            reset_child_params(self.model)

            # update classification layer
            self.model.fc = torch.nn.Linear(
                self.linear_in, self.acc_clases, True
            ).to(self.device)
            self.model.train()
            unfreeze_model(self.model)

            # train student with new loss
            dmc_args = dict(
                nepochs=self.nepochs,
                lr=self.lr,
                lr_min=self.lr_min,
                lr_factor=self.lr_factor,
                lr_patience=self.lr_patience,
                clipgrad=self.clipgrad,
                momentum=self.momentum,
                wd=self.wd,
                multi_softmax=self.multi_softmax,
                wu_nepochs=self.warmup_epochs,
                wu_lr_factor=self.warmup_lr,
                fix_bn=self.fix_bn,
            )
            student_trainer = StudentTrainer(
                self.model,
                self.model_new,
                self.model_old,
                self.device,
                **dmc_args
            )
            student_trainer.train_loop(
                t, self.aux_trn_loader, self.aux_val_loader
            )

        self.model_old = deepcopy(self.model)

        return self.evaluator.get_last_metrics()