#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on May 11 22:42:06 2021
@author: krzysztof_skos
"""

import matplotlib.pyplot as plt
import numpy as np

def data_for_cylinder_along_z(center_x, center_y, radius, height_z):
    """
    Method for creating grid for cylinder drawing. Cylinder will be created along Z axis
    :param center_x: Euclidean 3 dimensional center of drawing on X axis
    :param center_y: Euclidean 3 dimensional center of drawing on Y axis
    :param radius: cylinder radius
    :param height_z: cylinder height
    :return: Three lists with grid coordinates for z, y, x sequentially
    """
    z = np.linspace(0, height_z, 50)
    theta = np.linspace(0, 2 * np.pi, 50)
    theta_grid, z_grid = np.meshgrid(theta, z)
    x_grid = radius * np.cos(theta_grid) + center_x
    y_grid = radius * np.sin(theta_grid) + center_y
    return z_grid, y_grid, x_grid

def drawPlot(rad, ax, nodeList, length):
    """
    Method for drawing plot during simulation
    :param rad: vein radius
    :param ax: instance of figure() with subplot
    :param nodeList: list of nodes to draw
    :param length: cylinder length
    :return:
    """
    ax.clear()
    ax.scatter(length-2, 0, rad, marker="o")  # router
    ax.text(length - 1.9, 0, rad, "router")
    for node in nodeList:
        if node.x <= length:
            if node.inRouterRange:
                if node.isSendingMessage:
                    ax.scatter(node.x, node.coordinateY, node.coordinateZ, marker="d", c="#00ff02")
                else:
                    ax.scatter(node.x, node.coordinateY, node.coordinateZ, marker="x", c="#00ff02")
            else:
                if node.isSendingMessage:
                    ax.scatter(node.x, node.coordinateY, node.coordinateZ, marker="d", c="Red")
                else:
                    ax.scatter(node.x, node.coordinateY, node.coordinateZ, marker="x", c="Red")

    xc, yc, zc = data_for_cylinder_along_z(0, 0, rad, length)
    ax.plot_surface(xc, yc, zc, alpha=0.5)

    ax.set_xlabel("X")
    ax.set_ylabel("Y")
    ax.set_zlabel("Z")
    plt.show()


# coding: utf-8

# In[181]:

import numpy as np
import pandas as pd

path = "F:/for learn/MLiA/Ch05/"

def loadDataSet(path,outtype="mat"):
    df = pd.read_table(path+"testSet.txt",header=None)
    df.columns = ["x1","x2","label"]
    df["x0"] = 1
    if(outtype=="df"):
        return df
    else:
        dataMat = np.mat(df.loc[:,["x0","x1","x2"]])
        # since df.label is only one pd.Series np.mat just generate a row vec
        labelMat = np.mat(df.label).transpose()
        return dataMat,labelMat

def sigmoid(x):
    return 1/(1+np.exp(-x))

# gradient ascending opt in Logistic
def gradAscent(dataMat,labelMat,alpha=0.001,maxcycles=500):
    # create initial weight vec as a tall column vec
    w = np.ones((dataMat.shape[1],1))
    yHat = sigmoid(dataMat*w)
    error = labelMat-yHat
    stepVec = alpha * dataMat.transpose()*error
    #step = np.max(abs(stepVec))
    i = 1
    while i<=maxcycles:
        w = w + stepVec
        yHat = sigmoid(dataMat*w)
        error = labelMat-yHat
        stepVec = alpha * dataMat.transpose()*error
        #step = np.max(abs(stepVec))
        i += 1
    print("opt cycles num is %d"%i)
    return w

# In[237]:

dataMat,labelMat = loadDataSet(path)

df = loadDataSet(path,outtype="df")

w = gradAscend(dataMat,labelMat)

yHat = sigmoid(dataMat*w)

df["pred"] = yHat

df["predLabel"] = (df.pred>=0.5).astype(int)

len(df[df.label==df.predLabel])/len(df)


from collections import deque

import numpy as np
import carla

PID_PARAMS = [
        dict(K_P=0.5,  K_I=4.0, K_D=0.1,  fps=20, n=40),
        dict(K_P=1.5,  K_I=3.0, K_D=0.1,  fps=20, n=40),
        dict(K_P=0.75,  K_I=2.0, K_D=0.2, fps=20, n=30),
        dict(K_P=1.0,  K_I=3.0, K_D=0.05, fps=20, n=80),
        dict(K_P=1.25,  K_I=3.0, K_D=0.05,  fps=20, n=80),
        ]

class PIDController(object):
    def __init__(self, K_P=1.0, K_I=0.0, K_D=0.0, fps=10, n=20, **kwargs):
        print(K_P, K_I, K_D, fps, n, **kwargs)

        self._K_P = K_P
        self._K_I = K_I
        self._K_D = K_D

        self._dt = 1.0 / fps
        self._n = n
        self._window = deque(maxlen=self._n)

    def step(self, error):
        self._window.append(error)

        if len(self._window) >= 2:
            integral = np.mean(self._window) * self._dt
            derivative = (self._window[-1] - self._window[-2]) / self._dt
        else:
            integral = 0.0
            derivative = 0.0

        return self._K_P * error + self._K_I * integral + self._K_D * derivative

class Controller(object):
    def __init__(self, pid):
        self.brake_threshold = 0.5

        self.turn_control = PIDController(**PID_PARAMS[pid])
        self.speed_control = PIDController(K_P=1.0, K_I=1.0, K_D=0.5, fps=20, n=100)

    def postprocess(self, steer, throttle, brake):
        control = carla.VehicleControl()
        control.steer = np.clip(steer, -1.0, 1.0)
        control.throttle = np.clip(throttle, 0.0, 1.0)
        control.brake = np.clip(brake, 0.0, 1.0)
        control.manual_gear_shift = False

        return control

    def run_step(self, target, target_speed, speed, viz=None):
        target_speed = np.clip(target_speed, 0.0, 7.5)
        delta = np.clip(target_speed - speed, 0.0, 1)
        theta = np.radians(90 - np.degrees(np.arctan2(target[1], target[0])))

        steer = self.turn_control.step(theta)
        throttle = self.speed_control.step(delta)
        brake = 0.0

        self.speed = speed
        self.target_speed = target_speed

        # Slow or stop.
        if target_speed < self.brake_threshold:
            steer = 0.0
            throttle = 0.0
            brake = 0.5

        control = self.postprocess(steer, throttle, brake)

        if viz:
            viz.controller_draw(speed, target_speed, control)

        return control


#This program calculates and plots a mean-variance function for a portfolio
#The idea is based upon the work of Markowitz

from matplotlib import pyplot as plt
from matplotlib.pyplot import xlabel, ylabel
from math import *

def calc(m1, s1, m2, s2, r12):
    l = []
    mpf = 0
    spf = 0
    minvar = 0
    omega = 0
    #Caclulates all the mean-variance points ((y, x) points) for each omega += 0.01 starting from 0
    for i in range(100):
        mpf = omega*m1+(1-omega)*m2
        spf = (omega*omega*s1*s1)+(1-omega)*(1-omega)*s2*s2+2*omega*(1-omega)*s1*s2*r12
        spf = sqrt(spf)
        minvar = 2*omega*s1*s1-s2*s2+(2-4*omega)*s1*s2*r12
        l.append((spf, mpf, omega, minvar))
        omega += 0.01

    return l

g = calc(0.04, 0.03, 0.06, 0.05, 0.2)
x_val = [x[0] for x in g]
y_val = [x[1] for x in g]
plt.plot(x_val, y_val)
plt.ylabel("Mean", fontsize = 14, color = "red")
plt.xlabel("Variance", fontsize = 14, color = "red")
plt.show()


# K = int(input())
# # tmp_k = 0
# # start = ['A']
# # while tmp_k < K:
# #     for x in range(len(start)):
# #         if start[x] == 'A':
# #             start[x] = 'B'
# #         elif start[x] == 'B':
# #             start.append('A')
# #     tmp_k += 1
# #
# # cnt_a = 0
# # cnt_b = 0
# # for x in range(len(start)):
# #     if start[x] == 'A':
# #         cnt_a += 1
# #     elif start[x] == 'B':
# #         cnt_b += 1
# # print('{} {}'.format(cnt_a, cnt_b))

K = int(input())
lst_a = [1, 0]
lst_b = [0, 1]
for i in range(2, K+1):
    new_a = lst_a[i-1] + lst_a[i-2]
    lst_a.append(new_a)
    new_b = lst_b[i-1] + lst_b[i-2]
    lst_b.append(new_b)
print('{} {}'.format(lst_a[K], lst_b[K]))


import torch
import math
from torch.utils.data import Dataset,DataLoader
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
dtype = torch.float
device = torch.device('cuda:3')
def sample_z(bs ,m, n):
	return torch.from_numpy(np.random.uniform(-1., 1., size=[bs,1, m, n])).double()#generate a noise 1*1*m*n
class Generator(nn.Module):
    def __init__(self,img_height,img_width):
        super(Generator,self).__init__()
        self.block1 = nn.Sequential(
            nn.Conv2d(4, 64, kernel_size=9, padding=4),#)int(((img_height+1)/1-img_height+9)/2)),
            nn.PReLU()
        )
        self.block2 = ResidualBlock(64,img_height,img_width)
        self.block3 = ResidualBlock(64,img_height,img_width)
        self.block4 = ResidualBlock(64,img_height,img_width)
        self.block5 = ResidualBlock(64,img_height,img_width)
        self.block6 = ResidualBlock(64,img_height,img_width)
        self.block7 = nn.Sequential(
            nn.Conv2d(64, 64, kernel_size=4, stride = 2,padding=1),
            nn.PReLU()
        )#change the size of the image into 1/2
        self.block8 = nn.Sequential(
            nn.Conv2d(64, 64, kernel_size=3, stride = 1,padding=1),
            nn.PReLU()
        )
        self.block9 = nn.Sequential(
            nn.Conv2d(64, 3, kernel_size=3, stride = 1,padding=1),
        )
        self.height=img_height
        self.width=img_width
    def forward(self, x, test):
        if test == True:
            input_noise = sample_z(1,self.height,self.width)
        else:
            input_noise = sample_z(16,self.height,self.width)
        input_noise.to(device,dtype)
        input_noise = input_noise.cuda()
        block1 = self.block1(torch.cat([x.double(),input_noise],dim=1).float())
        block2 = self.block2(block1)
        block3 = self.block3(block2)
        block4 = self.block4(block3)
        block5 = self.block5(block4)
        block6 = self.block6(block5)
        block7 = self.block7(block6)

        block8 = self.block8(block7)
        block9 = self.block9(block8)
        #block8 = self.block8(block1 + block7)

        return (torch.tanh(block9) + 1) / 2

class Discriminator(nn.Module):
    def __init__(self,opt):
        super(Discriminator,self).__init__()
        self.ngpu = opt.ngpu
        self.net = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, padding=1),
            nn.LeakyReLU(0.2),

            nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1),
            nn.BatchNorm2d(64),
            nn.LeakyReLU(0.2),

            nn.Conv2d(64, 128, kernel_size=3, padding=1),
            nn.BatchNorm2d(128),
            nn.LeakyReLU(0.2),

            nn.Conv2d(128, 128, kernel_size=3, stride=2, padding=1),
            nn.BatchNorm2d(128),
            nn.LeakyReLU(0.2),

            nn.Conv2d(128, 256, kernel_size=3, padding=1),
            nn.BatchNorm2d(256),
            nn.LeakyReLU(0.2),

            nn.Conv2d(256, 512, kernel_size=3, padding=1),
            nn.BatchNorm2d(512),
            nn.LeakyReLU(0.2),

            nn.Conv2d(512, 512, kernel_size=3, stride=2, padding=1),
            nn.BatchNorm2d(512),
            nn.LeakyReLU(0.2),

            nn.AdaptiveAvgPool2d(1),
            nn.Conv2d(512, 1024, kernel_size=1),
            nn.LeakyReLU(0.2),
            nn.Conv2d(1024, 1, kernel_size=1),
            nn.Sigmoid()
        )

    def forward(self, x):
        if isinstance(x.data,torch.cuda.FloatTensor) and self.ngpu>1:
            output = nn.parallel.data_parallel(self.net,x,range(self.ngpu))
        else:
            output = self.net(x)
        return output

class ResidualBlock(nn.Module):
    def __init__(self, channels,img_height,img_width):
        super(ResidualBlock, self).__init__()
        self.conv1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)#int(((img_height+1)/1-img_height+3)/2))
        self.bn1 = nn.BatchNorm2d(channels)
        self.prelu = nn.PReLU()
        self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)#int(((img_height+1)/1-img_height+3)/2))
        self.bn2 = nn.BatchNorm2d(channels)

    def forward(self, x):
        residual = self.conv1(x)
        residual = self.bn1(residual)
        residual = self.prelu(residual)
        residual = self.conv2(residual)
        residual = self.bn2(residual)
        return x + residual
def weights_init(m):
    if type(m)==nn.Conv2d:
        m.weight.data.fill_(1)
        m.bias.data.fill_(0)
def weights_init_(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        m.weight.data.normal_(0.0, 0.02)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.normal_(1.0, 0.02)
        m.bias.data.fill_(0)


from __future__ import unicode_literals

import re

from .common import InfoExtractor
from ..utils import (
    ExtractorError,
    clean_html,
    determine_ext,
    int_or_none,
    js_to_json,
    parse_duration,
)

class ViewLiftBaseIE(InfoExtractor):
    _DOMAINS_REGEX = r'(?:snagfilms|snagxtreme|funnyforfree|kiddovid|winnersview|monumentalsportsnetwork|vayafilm)\.com|kesari\.tv'

class ViewLiftEmbedIE(ViewLiftBaseIE):
    _VALID_URL = r'https?://(?:(?:www|embed)\.)?(?:%s)/embed/player\?.*\bfilmId=(?P<id>[\da-f-]{36})' % ViewLiftBaseIE._DOMAINS_REGEX
    _TESTS = [{
        'url': 'http://embed.snagfilms.com/embed/player?filmId=74849a00-85a9-11e1-9660-123139220831&w=500',
        'md5': '2924e9215c6eff7a55ed35b72276bd93',
        'info_dict': {
            'id': '74849a00-85a9-11e1-9660-123139220831',
            'ext': 'mp4',
            'title': '#whilewewatch',
        }
    }, {
        # invalid labels, 360p is better that 480p
        'url': 'http://www.snagfilms.com/embed/player?filmId=17ca0950-a74a-11e0-a92a-0026bb61d036',
        'md5': '882fca19b9eb27ef865efeeaed376a48',
        'info_dict': {
            'id': '17ca0950-a74a-11e0-a92a-0026bb61d036',
            'ext': 'mp4',
            'title': 'Life in Limbo',
        }
    }, {
        'url': 'http://www.snagfilms.com/embed/player?filmId=0000014c-de2f-d5d6-abcf-ffef58af0017',
        'only_matching': True,
    }]

    @staticmethod
    def _extract_url(webpage):
        mobj = re.search(
            r']+?src=(["\'])(?P<url>(?:https?:)?//(?:embed\.)?(?:%s)/embed/player.+?)\1' % ViewLiftBaseIE._DOMAINS_REGEX,
            webpage)
        if mobj:
            return mobj.group('url')

    def _real_extract(self, url):
        video_id = self._match_id(url)

        webpage = self._download_webpage(url, video_id)

        if '>This film is not playable in your area.<' in webpage:
            raise ExtractorError(
                'Film %s is not playable in your area.' % video_id, expected=True)

        formats = []
        has_bitrate = False
        for source in self._parse_json(js_to_json(self._search_regex(
                r'(?s)sources:\s*(\[.+?\]),', webpage, 'json')), video_id):
            file_ = source.get('file')
            if not file_:
                continue
            type_ = source.get('type')
            ext = determine_ext(file_)
            format_id = source.get('label') or ext
            if all(v == 'm3u8' or v == 'hls' for v in (type_, ext)):
                formats.extend(self._extract_m3u8_formats(
                    file_, video_id, 'mp4', m3u8_id='hls'))
            else:
                bitrate = int_or_none(self._search_regex(
                    [r'(\d+)kbps', r'_\d{1,2}x\d{1,2}_(\d{3,})\.%s' % ext],
                    file_, 'bitrate', default=None))
                if not has_bitrate and bitrate:
                    has_bitrate = True
                height = int_or_none(self._search_regex(
                    r'^(\d+)[pP]$', format_id, 'height', default=None))
                formats.append({
                    'url': file_,
                    'format_id': 'http-%s%s' % (format_id, ('-%dk' % bitrate if bitrate else '')),
                    'tbr': bitrate,
                    'height': height,
                })
        field_preference = None if has_bitrate else ('height', 'tbr', 'format_id')
        self._sort_formats(formats, field_preference)

        title = self._search_regex(
            [r"title\s*:\s*'([^']+)'", r'<title>([^<]+)</title>'],
            webpage, 'title')

        return {
            'id': video_id,
            'title': title,
            'formats': formats,
        }

class ViewLiftIE(ViewLiftBaseIE):
    _VALID_URL = r'https?://(?:www\.)?(?P<domain>%s)/(?:films/title|show|(?:news/)?videos?)/(?P<id>[^?#]+)' % ViewLiftBaseIE._DOMAINS_REGEX
    _TESTS = [{
        'url': 'http://www.snagfilms.com/films/title/lost_for_life',
        'md5': '19844f897b35af219773fd63bdec2942',
        'info_dict': {
            'id': '0000014c-de2f-d5d6-abcf-ffef58af0017',
            'display_id': 'lost_for_life',
            'ext': 'mp4',
            'title': 'Lost for Life',
            'description': 'md5:fbdacc8bb6b455e464aaf98bc02e1c82',
            'thumbnail': r're:^https?://.*\.jpg',
            'duration': 4489,
            'categories': ['Documentary', 'Crime', 'Award Winning', 'Festivals']
        }
    }, {
        'url': 'http://www.snagfilms.com/show/the_world_cut_project/india',
        'md5': 'e6292e5b837642bbda82d7f8bf3fbdfd',
        'info_dict': {
            'id': '00000145-d75c-d96e-a9c7-ff5c67b20000',
            'display_id': 'the_world_cut_project/india',
            'ext': 'mp4',
            'title': 'India',
            'description': 'md5:5c168c5a8f4719c146aad2e0dfac6f5f',
            'thumbnail': r're:^https?://.*\.jpg',
            'duration': 979,
            'categories': ['Documentary', 'Sports', 'Politics']
        }
    }, {
        # Film is not playable in your area.
        'url': 'http://www.snagfilms.com/films/title/inside_mecca',
        'only_matching': True,
    }, {
        # Film is not available.
        'url': 'http://www.snagfilms.com/show/augie_alone/flirting',
        'only_matching': True,
    }, {
        'url': 'http://www.winnersview.com/videos/the-good-son',
        'only_matching': True,
    }, {
        'url': 'http://www.kesari.tv/news/video/1461919076414',
        'only_matching': True,
    }, {
        # Was once Kaltura embed
        'url': 'https://www.monumentalsportsnetwork.com/videos/john-carlson-postgame-2-25-15',
        'only_matching': True,
    }]

    def _real_extract(self, url):
        domain, display_id = re.match(self._VALID_URL, url).groups()

        webpage = self._download_webpage(url, display_id)

        if ">Sorry, the Film you're looking for is not available.<" in webpage:
            raise ExtractorError(
                'Film %s is not available.' % display_id, expected=True)

        film_id = self._search_regex(r'filmId=([\da-f-]{36})"', webpage, 'film id')

        snag = self._parse_json(
            self._search_regex(
                r'Snag\.page\.data\s*=\s*(\[.+?\]);', webpage, 'snag'),
            display_id)

        for item in snag:
            if item.get('data', {}).get('film', {}).get('id') == film_id:
                data = item['data']['film']
                title = data['title']
                description = clean_html(data.get('synopsis'))
                thumbnail = data.get('image')
                duration = int_or_none(data.get('duration') or data.get('runtime'))
                categories = [
                    category['title'] for category in data.get('categories', [])
                    if category.get('title')]
                break
        else:
            title = self._search_regex(
                r'itemprop="title">([^<]+)<', webpage, 'title')
            description = self._html_search_regex(
                r'(?s)
(.+?)
',
                webpage, 'description', default=None) or self._og_search_description(webpage)
            thumbnail = self._og_search_thumbnail(webpage)
            duration = parse_duration(self._search_regex(
                r'([^<]+)<',
                webpage, 'duration', fatal=False))
            categories = re.findall(r'([^<]+)', webpage)

        return {
            '_type': 'url_transparent',
            'url': 'http://%s/embed/player?filmId=%s' % (domain, film_id),
            'id': film_id,
            'display_id': display_id,
            'title': title,
            'description': description,
            'thumbnail': thumbnail,
            'duration': duration,
            'categories': categories,
            'ie_key': 'ViewLiftEmbed',
        }


import asyncio
import socket
import sys
import time
from pathlib import Path
import hashlib
from typing import Any, List
from argparse import ArgumentParser

LOG_TIME = 3
TIMEOUT = 5  # in seconds

MAX_FILENAME_SIZE = 4096
UPLOADS_FOLDER_PATH = Path(__file__).parent.joinpath('uploads')

class Client:
    __idx: int
    __sock: socket.socket = None
    __task: Any = None

    __recv_count: int = 0
    __start: float

    __last_seen: float
    __instant_speed: float = 0
    __average_speed: float = 0

    __finished: bool = False

    def __init__(self, idx: int, sock: socket.socket):
        self.__idx = idx
        self.__start = time.time()
        self.__last_seen = time.time()
        self.__sock = sock

    def get_idx(self) -> int:
        return self.__idx

    def update_last_seen(self):
        self.__last_seen = time.time()

    def increase_recv_count(self, value):

        now = time.time()

        # Calculate instant speed
        self.__instant_speed = (value / (now - self.__last_seen))
        self.__last_seen = now

        # Calculate average speed
        self.__recv_count += value
        self.__average_speed = (self.__recv_count / (now - self.__start))

    def get_last_seen(self) -> float:
        return self.__last_seen

    def check_finished(self) -> bool:
        return self.__finished

    def finish(self):
        print(f'Client {self.__idx} finished')
        self.__finished = True
        self.print_speed()

    def print_speed(self):
        client_idx = self.get_idx()
        print(f'Client {client_idx} Average speed: {int(self.__average_speed)} bytes per sec')
        print(f'Client {client_idx} Instant speed: {int(self.__instant_speed)} bytes per sec')

    async def receive_async(self, size, loop):
        try:
            data = await asyncio.wait_for(loop.sock_recv(self.__sock, size), TIMEOUT)
        except asyncio.TimeoutError:
            self.kill_connection()
            return None

        if len(data) == 0:
            self.kill_connection()
            return None

        return data

    async def handle_client_connection(self):
        loop = asyncio.get_event_loop()

        # Receive info about file
        file_info = await self.receive_async(MAX_FILENAME_SIZE + 12, loop)
        if file_info is None:
            return

        # Parse info about file
        file_size = int.from_bytes(file_info[:8], sys.byteorder)
        filename_size = int.from_bytes(file_info[8:12], sys.byteorder)
        filename = file_info[12:12 + filename_size].decode('utf-8')

        # Start receiving file
        received = 0
        md5 = hashlib.md5()
        with open(UPLOADS_FOLDER_PATH.joinpath(filename), 'wb') as f:
            while received < file_size:
                self.update_last_seen()

                # Receive data from socket with timeout
                batch = await self.receive_async(1024, loop)
                if batch is None:
                    return
                batch_len = len(batch)

                received += batch_len
                self.increase_recv_count(batch_len)

                md5.update(batch)
                f.write(batch)

        # Check that file transferred correct
        checksum = bytes(md5.hexdigest(), 'utf-8')
        client_checksum = await self.receive_async(32, loop)
        if client_checksum is None:
            return

        if checksum != client_checksum:
            print(f'Client {self.__idx} checksum invalid!')
        else:
            print(f'Client {self.__idx} checksum correct')

        self.kill_connection()

    def kill_connection(self):
        self.__sock.close()
        self.finish()

async def client_watcher_loop(clients: List[Client]):

    while True:
        await asyncio.sleep(LOG_TIME)

        clients_to_remove = []
        for client in clients:
            if client.check_finished():
                clients_to_remove.append(client)
                continue
            client.print_speed()

        for client in clients_to_remove:
            clients.remove(client)

def print_canceled_clients(canceled_clients):
    print('\nCanceled clients:')
    for client in canceled_clients:
        print(f'- Client {client.get_idx()}')
    print(f'Total: {len(canceled_clients)} clients canceled\n')

async def start_server(host: str, port: int, clients: List[Client]):
    print(f'Start listening on {host}:{port}')

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((host, port))
    sock.listen()
    sock.setblocking(False)

    last_client_idx = 0

    loop = asyncio.get_event_loop()
    loop.create_task(client_watcher_loop(clients))
    while True:
        client_sock, _ = await loop.sock_accept(sock)

        client = Client(last_client_idx, client_sock)
        clients.append(client)
        last_client_idx += 1

        loop.create_task(client.handle_client_connection())

def main():
    parser = ArgumentParser()
    parser.add_argument("-p", "--port", type=int, default=8081, help="port listen to")
    parser.add_argument("--host", default='', help="hostname listen to")

    args_values = parser.parse_args()
    port = args_values.port
    host = args_values.host

    clients = []

    try:
        asyncio.run(start_server(host, port, clients))
    except KeyboardInterrupt:
        print_canceled_clients(clients)
    finally:
        print('Server closed')

if __name__ == '__main__':
    main()


"""Splits the raw data output from mturk into a test and validation set appropriate for the model eval and test sets.

For the diabetes data, there's a strange character that causes line breaks in the final data, but I can't seem to get
rid of it... After processing the diabetes data, I went through and removed these characters manually...
"""
import argparse
import json

import numpy as np

np.random.seed(0)
parser = argparse.ArgumentParser()
parser.add_argument('--raw_data_location', type=str, required=True)
parser.add_argument('--dataset', type=str, required=True)
parser.add_argument('--acceptance_threshold', type=float, default=3.0)
args = parser.parse_args()

ACCEPTANCE_THRESHOLD = args.acceptance_threshold

with open(args.raw_data_location, 'r') as file:
    data = json.load(file)
    data_dict = json.loads(data)

original_sentence_hit_ids = list(data_dict.keys())
assert len(original_sentence_hit_ids) == 50, f"Original set has len {len(original_sentence_hit_ids)}!"
test_set_keys = original_sentence_hit_ids
assert len(test_set_keys) == 50, f"Test set has len {len(test_set_keys)}!"

def build_test_suite_string(hit_ids):
    return_string = ""
    for hid in hit_ids:
        hit = data_dict[hid]
        parse = hit["question_parse"]
        for revision_hit_id in hit["revisions"]:
            revision_scores = hit["revisions"][revision_hit_id]["scores"]
            revision_text = hit["revisions"][revision_hit_id]["revised_text"]
            scores = np.array(revision_scores)
            if np.mean(scores) >= ACCEPTANCE_THRESHOLD:
                if revision_text in return_string:
                    continue
                revision_text = revision_text.replace("\n", "")
                revision_text = revision_text.replace("\r", "")
                parse = parse.replace("\n", "")
                parse = parse.replace("\r", "")

                # resolve annotation errors
                parse = parse.replace("previous filter", "previousfilter")
                parse = parse.replace("score accuracy test", "score accuracy")
                parse = parse.replace("greater equal to", "greater equal than")

                return_string += revision_text + "\n"
                return_string += parse + "\n\n"
    while return_string.endswith("\n"):
        return_string = return_string[:-len("\n")]
    return return_string

def save(data_to_save, filename):
    with open(filename, 'w') as file_to_write:
        file_to_write.write(data_to_save)

test_string = build_test_suite_string(test_set_keys)
split_test_string = test_string.split('\n\n')
print(f"Test set has {len(split_test_string)} items")

test_file_name = f"{args.dataset}_test_suite.txt"
eval_file_name = f"{args.dataset}_eval_suite.txt"

save(test_string, test_file_name)


"""
Developer: vkyprmr
Filename: tuner.py
Created on: 2020-09-21 at 12:49:26
"""
"""
Modified by: vkyprmr
Last modified on: 2020-09-21 at 13:39:03
"""

# Imports
import os
import pickle
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
#%matplotlib qt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Dropout
from tensorflow.keras.optimizers import SGD, RMSprop, Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing import image
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, ReduceLROnPlateau
from kerastuner.tuners import RandomSearch
from kerastuner.engine.hyperparameters import HyperParameters

# Runtime device and memory
physical_devices = tf.config.experimental.list_physical_devices('GPU')
for physical_device in physical_devices:
        tf.config.experimental.set_memory_growth(physical_device, True)

""" gpus = tf.config.experimental.list_physical_devices('GPU')
config = [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=(1024*6))]
if gpus:
    # Restrict TensorFlow to only allocate 1*X GB of memory on the first GPU
    try:
        tf.config.experimental.set_virtual_device_configuration(gpus[0], config)
        logical_gpus = tf.config.experimental.list_logical_devices('GPU')
        print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
    except RuntimeError as e:
        # Virtual devices must be set before GPUs have been initialized
        print(e) """

# Preparing data
base_dir = 'Data/cats_dogs_pandas/'
train_dir = os.path.join(base_dir, 'train')

### Individual class directories
train_dir_cats = os.path.join(train_dir, 'cats')
train_dir_dogs = os.path.join(train_dir, 'dogs')
train_dir_pandas = os.path.join(train_dir, 'pandas')

### Files
train_fnames_cats = os.listdir(train_dir_cats)
train_fnames_dogs = os.listdir(train_dir_dogs)
train_fnames_pandas = os.listdir(train_dir_pandas)

# Genearting data using ImageDataGenerator
train_datagen = ImageDataGenerator(
                                    rescale=1./255,
                                    rotation_range=40,
                                    width_shift_range=0.2,
                                    height_shift_range=0.2,
                                    shear_range=0.2,
                                    zoom_range=0.2,
                                    horizontal_flip=True,
                                    fill_mode='nearest'
                                    )
train_generator = train_datagen.flow_from_directory(
                                                    'Data/cats_dogs_pandas/train/',
                                                    target_size=(128, 128),
                                                    batch_size=50,
                                                    class_mode='sparse'
                                                    )
val_datagen = ImageDataGenerator(rescale=1./255)
val_generator = val_datagen.flow_from_directory(
                                                    'Data/cats_dogs_pandas/test/',
                                                    target_size=(128, 128),
                                                    batch_size=25,
                                                    class_mode='sparse'
                                                    )

# Model

def build_model(hp):
    model = Sequential()
    model.add(Conv2D(hp.Int('input_units', min_value=25, max_value=250, step=25),
                            (3,3), input_shape=(128,128,3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(2,2))

    for i in range(hp.Int('n_layers', 1, 3)):
        model.add(Conv2D(hp.Int(f'conv_{i}_units',
                                min_value=32, max_value=256, step=32), (3,3)))
        model.add(Activation('relu'))
        model.add(Dropout(hp.Float(f'dropout_{i}', min_value=0, max_value=0.5, step=0.1)))

    model.add(Flatten())
    for j in range(hp.Int('n_layers', 1, 2)):
        model.add(Dense(hp.Int(f'dense_{j}_units',
                                min_value=64, max_value=512, step=64), activation='relu'))
        model.add(Dropout(hp.Float(f'dropout_{j}', min_value=0, max_value=0.5, step=0.1)))

    model.add(Dense(3, activation='softmax'))

    model.compile(loss='sparse_categorical_crossentropy', optimizer=hp.Choice('optimizer', ['adam','sgd','rmsprop']),
                  metrics=['accuracy'])
    return model

### Callback functions
ckpt_dir = 'logs/ktuner/checkpoints/'+datetime.now().strftime('%Y%m%d-%H%M%S')
os.mkdir(ckpt_dir)
path_checkpoint = ckpt_dir+datetime.now().strftime('%Y%m%d-%H%M%S')+'.ckpt'

callback_checkpoint = ModelCheckpoint(filepath=path_checkpoint,
                                      monitor='val_loss',
                                      verbose=1,
                                      save_weights_only=True,
                                      save_best_only=True)

callback_early_stopping = EarlyStopping(monitor='val_loss',
                                        patience=15, verbose=1)

log_dir = 'logs/ktuner/fit/'+datetime.now().strftime('%Y%m%d-%H%M%S')

callback_tensorboard = TensorBoard(log_dir=log_dir,
                                   histogram_freq=1,
                                   write_graph=False)

callback_reduce_lr = ReduceLROnPlateau(monitor='val_loss',
                                       factor=0.1,
                                       min_lr=1e-4,
                                       patience=5,
                                       verbose=1)

callbacks = [callback_tensorboard,
             callback_checkpoint,
             callback_early_stopping,
             callback_reduce_lr]

klogs = f'logs/ktuner/ktuner/{datetime.now().strftime("%Y%m%d-%H%M%S")}'
os.mkdir(klogs)

# RandomSearch
### Training

ktuner = RandomSearch(build_model, objective='val_acc', max_trials=3,
                      directory=klogs)

ktuner.search(
                train_generator,
                steps_per_epoch=100, epochs=100,
                validation_data=val_generator, validation_steps=10,
                verbose=1, callbacks=callbacks
                )

ktuner.results_summary()

with open(f'logs/ktuner/tuner/{datetime.now().strftime("%Y%m%d-%H%M%S")}.pkl', 'wb') as f:
    pickle.dump(ktuner, f)

# Best hyperparameters && best model
best_hp = ktuner.get_best_hyperparameters()[0].values
best_model = ktuner.get_best_models()[0].summary()
ktuner.results_summary()

# Loading the tuner if exited
tuner_file = ''
ktuner = pickle.load(open(tuner_file, 'rb'))
best_hp = ktuner.get_best_hyperparameters()[0].values
best_model = ktuner.get_best_models()[0].summary()
ktuner.results_summary()


from keras.layers import *
from keras.models import *
import keras.backend as K
import keras.activations
import tensorflow as tf

class first_order_term(Layer):
    def __init__(self):
        super(first_order_term, self).__init__()

    def build(self, input_shape):
        self.w = self.add_weight(name='w_1st',
                                 shape=(1, 1,input_shape[2]),
                                 initializer='uniform',
                                 trainable=True)

        self.b = self.add_weight(name='b_1st',
                                 shape=(1,),
                                 initializer='uniform',
                                 trainable=True)
    def call(self, x):
        return Lambda(lambda x: K.sum(x, keepdims=True))(self.b + K.squeeze((Dot(axes=2)([x, self.w])), axis=2))

class Attention_layer(Layer):
    def __init__(self, att_factor):
        self.att_factor = att_factor
        super(Attention_layer, self).__init__()

    def build(self, input_shape):
        self.w = self.add_weight(name='w_att',
                                 shape=(input_shape[2],self.att_factor),
                                 initializer='uniform',
                                 trainable=True)

        self.b = self.add_weight(name='b_att',
                                 shape=(self.att_factor,),
                                 initializer='uniform',
                                 trainable=True)

        self.h = self.add_weight(name='h_att',
                                 shape=(self.att_factor,1),
                                 initializer='uniform',
                                 trainable=True)

    def call(self, e):
        temp = keras.activations.relu(K.squeeze(self.b + Multiply()([e, self.w]), axis=1))
        return Dot(axes=1)([temp, self.h])

class Attention_FM():
    def __init__(self):
        self.cat_vars = ["Cat1", "Cat2", "Cat3", "Cat4", "Cat5"] # List of All Categorical Variables Names
        self.cat_levels =  [2, 5, 6, 3, 50] # List of All Categorical Variables Levels
        self.embd_dim = 8 # Size for Embedding Output
        self.inputs = [Input(shape=(1,), name='Input_'+c) for c in self.cat_vars]
        self.embeddings_1st = [Embedding(c, 1)(self.inputs[i]) for i,c in enumerate(self.cat_levels)]
        self.embeddings_2nd = [Embedding(c, self.embd_dim)(self.inputs[i]) for i,c in enumerate(self.cat_levels)]
        self.att_factor = 11

    def att_scored(self):
        I, J = [], []
        for i in range(len(self.cat_vars)):
            for j in range(i+1, len(self.cat_vars)):
                I.append(i), J.append(j)

        M_IJ = []
        for i, j in zip(I, J):
            M_IJ.append(Multiply()([self.embeddings_2nd[i], self.embeddings_2nd[j]]))

        att_scores = []
        att = Attention_layer(self.att_factor)
        for Z in M_IJ:
            att_scores.append(K.exp(att(Z)))
        att_scores = Lambda(lambda x: x/K.sum(att_scores, keepdims=True))(att_scores)
        att_scores = Reshape((len(self.cat_vars)*(len(self.cat_vars)-1)//2,1))(att_scores)

        res2 = Multiply()([att_scores, Concatenate(axis=1)(M_IJ)])
        res2 = Lambda(lambda x: K.sum(x, axis=1))(res2)
        res2 = Dense(1, activation='linear')(res2)

        return res2

    def combine(self):
        first = first_order_term()
        res1 = first(Concatenate(axis=1)(embeddings_1st))
        res2 = self.att_scored()
        return keras.activations.sigmoid(res1 + res2)


import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score, roc_auc_score, roc_curve, confusion_matrix,f1_score
from numpy.random import seed
seed(111)
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
import xgboost
from xgboost import XGBClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import cross_validate,StratifiedKFold,cross_val_predict
from sklearn.decomposition import PCA
import os
import warnings
from scipy import stats
warnings.filterwarnings('ignore')
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
xgboost.set_config(verbosity=0)
sns.set(style='darkgrid')
plt.rcParams['font.sans-serif']='SimHei'
plt.rcParams['axes.unicode_minus'] = False

if __name__=="__main__":
    df = pd.read_excel("./data/train_data.xls",header=None)
    x = df.values[0:152,0:-1]
    y = df.values[:,-1]
    xgb = XGBClassifier(n_estimators=70,max_depth=4,learning_rate=0.2,use_label_encoder=False)
    xgb.fit(x, y)
    x_xgb = xgb.apply(x)
    encoder_onehot = OneHotEncoder()
    encoder_onehot.fit(x_xgb)
    x_xgb_encoded = np.array(encoder_onehot.transform(x_xgb).toarray())
    pca = PCA(n_components=52)
    data_pca = pca.fit_transform(x_xgb_encoded)
    kfold = StratifiedKFold(n_splits=10, shuffle=True)
    score = ["roc_auc","f1_micro"]

    # DT
    dt_params = {"max_depth":8}
    dt = DecisionTreeClassifier(**dt_params)
    acc_list_dt = cross_validate(estimator=dt,X=data_pca,y=y,cv=kfold,
                              scoring=score,return_train_score=True)
    auc_dt_average = np.mean(acc_list_dt["test_roc_auc"])
    f1_dt_average = np.mean(acc_list_dt["test_f1_micro"])
    print("dt_auc_average：{}".format(auc_dt_average))
    print("dt_f1_average：{}".format(f1_dt_average))

    # KNN
    knn_params = {"n_neighbors":5}
    knn = KNeighborsClassifier(**knn_params)
    acc_list_knn = cross_validate(estimator=knn,X=data_pca,y=y,cv=kfold,
                              scoring=score,return_train_score=True)
    auc_knn_average = np.mean(acc_list_knn["test_roc_auc"])
    f1_knn_average = np.mean(acc_list_knn["test_f1_micro"])
    print("knn_auc_average：{}".format(auc_knn_average))
    print("knn_f1_average：{}".format(f1_knn_average))

    # RF
    rf_params = {"n_estimators":80,"max_depth":5}
    rf = RandomForestClassifier(**rf_params)
    acc_list_rf = cross_validate(estimator=rf,X=data_pca,y=y,cv=kfold,
                              scoring=score,return_train_score=True)
    auc_rf_average = np.mean(acc_list_rf["test_roc_auc"])
    f1_rf_average = np.mean(acc_list_rf["test_f1_micro"])
    print("rf_auc_average：{}".format(auc_rf_average))
    print("rf_f1_average：{}".format(f1_rf_average))

    # svc
    svc_params = {"C":100, "kernel":'linear'}
    svc = SVC(**svc_params)
    acc_list_svc = cross_validate(estimator=svc,X=data_pca,y=y,cv=kfold,
                              scoring=score,return_train_score=True)
    auc_svc_average = np.mean(acc_list_svc["test_roc_auc"])
    f1_svc_average = np.mean(acc_list_svc["test_f1_micro"])
    print("svc_auc_average：{}".format(auc_svc_average))
    print("svc_f1_average：{}".format(f1_svc_average))

    # xgboost
    XGB_params = {'n_estimators':100,'max_depth':5,'learning_rate':0.15,'use_label_encoder':False}
    XGBOOST = XGBClassifier(**XGB_params)
    acc_list_XGB = cross_validate(estimator=XGBOOST, X=data_pca, y=y, cv=kfold,
                                  scoring=score, return_train_score=True)
    auc_xgboost_average = np.mean(acc_list_XGB["test_roc_auc"])
    f1_xgboost_average = np.mean(acc_list_XGB["test_f1_micro"])
    print("xgboost_auc_average：{}".format(auc_xgboost_average))
    print("xgboost_f1_average：{}".format(f1_xgboost_average))

    # lr
    logistic_regression_params = {"penalty": "l1", "solver":"saga","max_iter": 50, "C": 0.5}
    logistic_regression = LogisticRegression(**logistic_regression_params)
    acc_list_lr = cross_validate(estimator=logistic_regression,X=data_pca,y=y,cv=kfold,
                              scoring=score,return_train_score=True)
    auc_lr_average = np.mean(acc_list_lr["test_roc_auc"])
    f1_lr_average = np.mean(acc_list_lr["test_f1_micro"])
    print("lr_auc_average：{}".format(auc_lr_average))
    print("lr_f1_average：{}".format(f1_lr_average))

    # Confusion matrix
    LR = LogisticRegression(**logistic_regression_params)
    y_pred_cv = cross_val_predict(LR, data_pca, y, cv=kfold)
    confusion_mat_train = confusion_matrix(y, y_pred_cv,normalize="true")
    confusion_mat_train_df = pd.DataFrame(np.round(confusion_mat_train, 2),
    index=['Not Red', 'Red'], columns=['Not Red', 'Red'])
    sns.set(font_scale=1.8)
    fig = plt.figure(figsize=(10, 8))
    ax = plt.subplot(111)
    sns.heatmap(confusion_mat_train_df, cmap='Blues', annot=True, fmt='g')
    ax.set_ylabel('True Label', fontsize=18)
    ax.set_xlabel('Predicted Label', fontsize=18)
    ax.tick_params(axis='y', labelsize=18, labelrotation=45)
    ax.tick_params(axis='x', labelsize=18)
    ax.set_title('Confusion Matrix', fontsize=18)
    plt.show()

    # ROC
    y_pred_cv_pro = cross_val_predict(LR, data_pca, y, cv=kfold,method="predict_proba")
    fpr, tpr, _ = roc_curve(y, y_pred_cv_pro[:, 1], pos_label=1)
    auc = roc_auc_score(y, y_pred_cv)
    f1 = f1_score(y,y_pred_cv,average='micro')
    print('auc on cross validation is %0.2f' % auc)
    print('f1 on cross validation is %0.2f' % f1)
    lw = 2
    plt.plot(fpr, tpr, 'k--', color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % auc)
    plt.plot([0, 1], [0, 1], color=(0.6, 0.6, 0.6), lw=lw, linestyle='--', label='random guessing')
    plt.xlim([-0.05, 1.05])
    plt.ylim([-0.05, 1.05])
    plt.xlabel('False Positive Rate', fontsize=18)
    plt.ylabel('True Positive Rate', fontsize=18)
    plt.title('ROC Curve', fontsize=18)
    plt.legend(loc="lower right")
    plt.xticks(fontsize=18)
    plt.yticks(fontsize=18)
    plt.show()

    # Model comparison
    models = ['dt','knn','rf','svc','xgboost','lr']
    auc_hit = [auc_dt_average,auc_knn_average,auc_rf_average,auc_svc_average,auc_xgboost_average,auc_lr_average]
    f1_hit = [f1_dt_average,f1_knn_average,f1_rf_average,f1_svc_average,f1_xgboost_average,f1_lr_average]
    plt.bar(x=np.arange(6),height=f1_hit,width=0.3,label='f1-score')
    plt.bar(x=np.arange(6)+0.3, height=auc_hit, width=0.3,label='auc')
    plt.xticks(np.arange(6)+0.1,models)
    plt.legend()
    plt.show()

    # Data Analysis
    # Correlation analysis
    raw_x = pd.DataFrame(x)
    raw_coor = raw_x.iloc[:,0:5].corr(method='pearson')
    cmap = sns.diverging_palette(220, 10, as_cmap=True)
    sns.heatmap(
        raw_coor,
        cmap=cmap,
        square=True,
        cbar_kws={'shrink': .9},
        annot=True,
        annot_kws={'fontsize': 18})
    plt.show()
    processed_x = pd.concat((pd.DataFrame(data_pca), pd.Series(y)), axis=1)
    processed_x.columns.values[-1] = 52
    processed_coor = processed_x.iloc[:,0:10].corr(method='pearson')
    processed_coor = processed_coor.round(0)
    sns.heatmap(
        processed_coor,
        cmap=cmap,
        square=True,
        cbar_kws={'shrink': .9},
        annot=True,
        annot_kws={'fontsize': 15})
    plt.show()

    # Normality analysis
    fig = plt.figure(figsize=(10, 9))
    for i in range(8):
        f = fig.add_subplot(2, 4, i + 1)
        if (i < 4):
            stats.probplot(raw_x.iloc[:, i], plot=plt)
        else:
            stats.probplot(processed_x.iloc[:, i - 4], plot=plt)
    plt.show()

    # Model validation
    lr = LogisticRegression(**logistic_regression_params)
    lr.fit(X=data_pca, y=y)
    data = pd.read_excel('./data/val_data.xls', header=None)
    X = data.values
    design_ten = data.values[:, :-1]
    realcolor = data.values[:, -1]
    design_xgb = xgb.apply(design_ten)
    data_xgb = xgb.apply(x)
    data_combine = np.concatenate((data_xgb, design_xgb), axis=0)
    data_combine_encode = np.array(encoder_onehot.transform(data_combine).toarray())
    design_xgb_encode_pca = pca.fit_transform(data_combine_encode)
    resulttwo_lr = lr.predict(design_xgb_encode_pca[len(x):,:])
    print("Accuracy on validation set：{0}".format(accuracy_score(resulttwo_lr, realcolor)))


import asyncio
from discord.utils import get
from discord.ext import commands
from app.vars.client import client
from app.helpers import params, Notify
from app.filesystem import cfg

@client.command()
@commands.guild_only()
@commands.has_permissions(manage_channels=True)
async def createChannel(ctx, *, args = ''):
    notify = Notify(ctx=ctx, title='Creating Channel...')
    notify.prepair()
    args = params.split(args)
    if len(args) > 1:
        try:
            channelType = str.lower(args[0])
            if len(args) == 2:
                args.append(None)
            if(channelType == 'text'):
                await ctx.guild.create_text_channel(args[1],category=get(ctx.guild.categories, name=args[2]))
            elif(channelType == 'voice'):
                await ctx.guild.create_voice_channel(args[1],category=get(ctx.guild.categories, name=args[2]))
            elif(channelType == 'category'):
                await ctx.guild.create_category(args[1])
            else:
                notify.error(content=f'The type of channel you provide ({args[1]}) is not supported\n')
                return
        finally:
            notify.success(content=f'The {args[0]} channel \'{args[1]}\' was created successfully')
    else:
        notify.error(content=f'This command requires two parameters:\n {cfg["prefix"]}createChannel type;;name;;*category')

@client.command(aliases=['create_voice_channel'])
@commands.guild_only()
@commands.has_permissions(manage_channels=True)
async def createVoiceChannel(ctx, *, name):
    await createChannel(ctx, args='voice;;'+ name)

@client.command(aliases=['create_text_channel'])
@commands.guild_only()
@commands.has_permissions(manage_channels=True)
async def createTextChannel(ctx, *, name):
    await createChannel(ctx, args='text;;'+ name)

@client.command(aliases=['create_category','create_category_channel','createcategorychannel'])
@commands.guild_only()
@commands.has_permissions(manage_channels=True)
async def createCategory(ctx, *, name):
    await createChannel(ctx, args='category;;'+ name)


from flask import Flask, render_template, flash, request, redirect
app = Flask (__name__)
app.secret_key = 'secret key'

users={
    "mr admin": "admin",
    "ms admin": "admin",
    "mr user": "user",
    "ms user": "user"
}

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == 'POST':
        if users[request.form['username']] != request.form['password']:
            return render_template('invalid.html')
        else:
            return redirect ('/cabinet')
    else:
        return render_template('login.html')

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

if __name__ == "__main__":
    app.run(host='localhost', port=5000, debug=True)


# -*- coding: utf-8 -*-
"""
Created on Tue Dec 22 17:34:54 2020

@author: SENJU
"""

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog , QMessageBox
from PyQt5.QtGui import QImage
import cv2
import numpy as np

from fonctions import otsu , griser , egalisationHisto , lisse , etale , luminosite , translation  ,rotation90 , floutter
from fonctions import inversionCouleur , binarisation , erosion , dilatation , conserver, getLigne , getColonne

class Ui_MainWindow(object):
        def setupUi(self, MainWindow):
            MainWindow.setObjectName("MainWindow")
            MainWindow.resize(1242, 698)
            self.size1 = 1200
            self.size2 = 700
            sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
            MainWindow.setSizePolicy(sizePolicy)
            self.centralwidget = QtWidgets.QWidget(MainWindow)
            self.centralwidget.setObjectName("centralwidget")
            self.label = QtWidgets.QLabel(self.centralwidget)
            self.label.setGeometry(QtCore.QRect(9, 9, 1189, 630))
            self.label.setMaximumSize(QtCore.QSize(1250, 720))
            self.label.setText("")
            self.label.setPixmap(QtGui.QPixmap("../../AIVOPr/images/01972_hsbccelebrationoflight_1920x1080.jpg"))
            self.label.setScaledContents(True)
            self.label.setObjectName("label")
            self.horizontalSlider = QtWidgets.QSlider(self.centralwidget)
            self.horizontalSlider.setGeometry(QtCore.QRect(1199, 40, 151, 22))
            self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
            self.horizontalSlider.setObjectName("horizontalSlider")
            self.horizontalSlider_2 = QtWidgets.QSlider(self.centralwidget)
            self.horizontalSlider_2.setGeometry(QtCore.QRect(1200, 90, 160, 22))
            self.horizontalSlider_2.setOrientation(QtCore.Qt.Horizontal)
            self.horizontalSlider_2.setObjectName("horizontalSlider_2")
            self.label_2 = QtWidgets.QLabel(self.centralwidget)
            self.label_2.setGeometry(QtCore.QRect(1200, 20, 61, 16))
            self.label_2.setObjectName("label_2")
            self.label_3 = QtWidgets.QLabel(self.centralwidget)
            self.label_3.setGeometry(QtCore.QRect(1200, 70, 61, 16))
            self.label_3.setObjectName("label_3")
            MainWindow.setCentralWidget(self.centralwidget)
            self.menubar = QtWidgets.QMenuBar(MainWindow)
            self.menubar.setEnabled(True)
            self.menubar.setGeometry(QtCore.QRect(0, 0, 1290, 22))
            self.menubar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
            self.menubar.setDefaultUp(False)
            self.menubar.setNativeMenuBar(True)
            self.menubar.setObjectName("menubar")
            self.menuOuvrir = QtWidgets.QMenu(self.menubar)
            icon = QtGui.QIcon()
            icon.addPixmap(QtGui.QPixmap("icons/16x16/Open_16px_1.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.menuOuvrir.setIcon(icon)
            self.menuOuvrir.setObjectName("menuOuvrir")
            self.menuAmelioration = QtWidgets.QMenu(self.menubar)
            self.menuAmelioration.setObjectName("menuAmelioration")
            self.menuFiltrage = QtWidgets.QMenu(self.menubar)
            self.menuFiltrage.setObjectName("menuFiltrage")
            self.menuBinarisation = QtWidgets.QMenu(self.menubar)
            self.menuBinarisation.setObjectName("menuBinarisation")
            self.menuTransformation = QtWidgets.QMenu(self.menubar)
            self.menuTransformation.setObjectName("menuTransformation")
            self.menuRotation = QtWidgets.QMenu(self.menubar)
            self.menuRotation.setObjectName("menuRotation")
            self.menuTranslation = QtWidgets.QMenu(self.menubar)
            self.menuTranslation.setObjectName("menuTranslation")
            MainWindow.setMenuBar(self.menubar)
            self.statusbar = QtWidgets.QStatusBar(MainWindow)
            self.statusbar.setObjectName("statusbar")
            MainWindow.setStatusBar(self.statusbar)
            self.toolBar = QtWidgets.QToolBar(MainWindow)
            self.toolBar.setObjectName("toolBar")
            MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
            self.toolBar_2 = QtWidgets.QToolBar(MainWindow)
            self.toolBar_2.setObjectName("toolBar_2")
            MainWindow.addToolBar(QtCore.Qt.RightToolBarArea, self.toolBar_2)
            self.actionOuvrir = QtWidgets.QAction(MainWindow)
            icon1 = QtGui.QIcon()
            icon1.addPixmap(QtGui.QPixmap("icons/16x16/Add Image_16px.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.actionOuvrir.setIcon(icon1)
            self.actionOuvrir.setIconVisibleInMenu(False)
            self.actionOuvrir.setObjectName("actionOuvrir")
            self.actionEnregister = QtWidgets.QAction(MainWindow)
            icon2 = QtGui.QIcon()
            icon2.addPixmap(QtGui.QPixmap("icons/16x16/Save_16px.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.actionEnregister.setIcon(icon2)
            self.actionEnregister.setObjectName("actionEnregister")
            self.actionExit = QtWidgets.QAction(MainWindow)
            icon3 = QtGui.QIcon()
            icon3.addPixmap(QtGui.QPixmap("icons/16x16/Exit_16px.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.actionExit.setIcon(icon3)
            self.actionExit.setObjectName("actionExit")
            self.actionEgalisation = QtWidgets.QAction(MainWindow)
            self.actionEgalisation.setObjectName("actionEgalisation")
            self.actionMedian = QtWidgets.QAction(MainWindow)
            self.actionMedian.setObjectName("actionMedian")
            self.actionGaussien = QtWidgets.QAction(MainWindow)
            self.actionGaussien.setObjectName("actionGaussien")
            self.actionMoyenne = QtWidgets.QAction(MainWindow)
            self.actionMoyenne.setObjectName("actionMoyenne")
            self.actionLissage = QtWidgets.QAction(MainWindow)
            self.actionLissage.setObjectName("actionLissage")
            self.actionSeuil = QtWidgets.QAction(MainWindow)
            self.actionSeuil.setObjectName("actionSeuil")
            self.actionErosion = QtWidgets.QAction(MainWindow)
            self.actionErosion.setObjectName("actionErosion")
            self.actionDilatation = QtWidgets.QAction(MainWindow)
            self.actionDilatation.setObjectName("actionDilatation")
            self.actionNiveau_de_gris = QtWidgets.QAction(MainWindow)
            self.actionNiveau_de_gris.setObjectName("actionNiveau_de_gris")
            self.actionNiveau_de_gris_2 = QtWidgets.QAction(MainWindow)
            self.actionNiveau_de_gris_2.setObjectName("actionNiveau_de_gris_2")
            self.actionNiveau_de_Gris = QtWidgets.QAction(MainWindow)
            self.actionNiveau_de_Gris.setIcon(icon)
            self.actionNiveau_de_Gris.setObjectName("actionNiveau_de_Gris")
            self.actionOpen = QtWidgets.QAction(MainWindow)
            self.actionOpen.setIcon(icon1)
            self.actionOpen.setObjectName("actionOpen")
            self.actionInversion = QtWidgets.QAction(MainWindow)
            icon4 = QtGui.QIcon()
            icon4.addPixmap(QtGui.QPixmap("icons/16x16/Sorting Arrows_16px_1.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.actionInversion.setIcon(icon4)
            self.actionInversion.setObjectName("actionInversion")
            self.actionRotation_90 = QtWidgets.QAction(MainWindow)
            self.actionRotation_90.setObjectName("actionRotation_90")
            self.actionRotation_45 = QtWidgets.QAction(MainWindow)
            self.actionRotation_45.setObjectName("actionRotation_45")
            self.actionConservation = QtWidgets.QAction(MainWindow)
            self.actionConservation.setObjectName("actionConservation")
            self.actionSymetrie = QtWidgets.QAction(MainWindow)
            self.actionSymetrie.setObjectName("actionSymetrie")
            self.actionContours = QtWidgets.QAction(MainWindow)
            self.actionContours.setObjectName("actionContours")
            self.actionTranslation_1_0_100_0_1_50 = QtWidgets.QAction(MainWindow)
            self.actionTranslation_1_0_100_0_1_50.setObjectName("actionTranslation_1_0_100_0_1_50")
            self.menuOuvrir.addAction(self.actionOpen)
            self.menuOuvrir.addAction(self.actionEnregister)
            self.menuOuvrir.addAction(self.actionExit)
            self.menuAmelioration.addAction(self.actionEgalisation)
            self.menuAmelioration.addAction(self.actionConservation)
            self.menuFiltrage.addAction(self.actionMoyenne)
            self.menuFiltrage.addAction(self.actionLissage)
            self.menuBinarisation.addAction(self.actionSeuil)
            self.menuBinarisation.addAction(self.actionErosion)
            self.menuBinarisation.addAction(self.actionDilatation)
            self.menuBinarisation.addAction(self.actionContours)
            self.menuTransformation.addAction(self.actionNiveau_de_Gris)
            self.menuTransformation.addAction(self.actionInversion)
            self.menuTransformation.addAction(self.actionSymetrie)
            self.menuRotation.addAction(self.actionRotation_90)
            self.menuTranslation.addAction(self.actionTranslation_1_0_100_0_1_50)
            self.menubar.addAction(self.menuOuvrir.menuAction())
            self.menubar.addAction(self.menuTransformation.menuAction())
            self.menubar.addAction(self.menuAmelioration.menuAction())
            self.menubar.addAction(self.menuFiltrage.menuAction())
            self.menubar.addAction(self.menuBinarisation.menuAction())
            self.menubar.addAction(self.menuRotation.menuAction())
            self.menubar.addAction(self.menuTranslation.menuAction())

            self.retranslateUi(MainWindow)
            QtCore.QMetaObject.connectSlotsByName(MainWindow)
            self.actionOpen.triggered.connect(self.recuperer)
            self.actionEgalisation.triggered.connect(self.egalisationHistogrammeCouleur)
            self.actionNiveau_de_Gris.triggered.connect(self.grise)
            self.actionSeuil.triggered.connect(self.seuil)
            self.actionInversion.triggered.connect(self.inversion)
            self.actionErosion.triggered.connect(self.erosion)
            self.actionDilatation.triggered.connect(self.dilatation)
            self.actionLissage.triggered.connect(self.lissage)
            self.actionMoyenne.triggered.connect(self.etalage)
            self.actionEnregister.triggered.connect(self.enregister)
            self.actionSymetrie.triggered.connect(self.symetrie)
            self.horizontalSlider.valueChanged['int'].connect(self.valueLuminosite)
            self.horizontalSlider_2.valueChanged['int'].connect(self.valueBlur)
            self.actionRotation_90.triggered.connect(self.rotation)
            self.actionTranslation_1_0_100_0_1_50.triggered.connect(self.translation)

            self.filename = None #retenir adresse de l'image

            self.temp = None #affichage temporaire de l'image pour affichage

        def recuperer(self):
            self.filename = QtWidgets.QFileDialog.getOpenFileName(filter="Image (*.*)")[0]
            self.image = cv2.imread(self.filename)
            self.affichage(self.image)

        def enregister(self):
            cv2.imwrite("Image.png",self.temp)
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setText("Enregistrement")
            msg.setInformativeText("Image enregister")
            msg.setWindowTitle("Enregister")
            msg.exec()

        def affichage(self,image):
            self.temp = image
            self.resize()
            frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            image = QImage(frame , frame.shape[1], frame.shape[0] , frame.strides[0],QImage.Format_RGB888)
            window = MainWindow.height()
            self.size1 = getLigne(window)
            self.size2 = getColonne(self.image,window)
            self.label.setMaximumSize(QtCore.QSize(self.size1, self.size2))
            self.label.setPixmap(QtGui.QPixmap.fromImage(image))

        def grise(self):
            image_grise = griser(self.filename)
            self.affichage(image_grise)

        def egalisationHistogramme(self):

            self.image = self.griser()
            equ = cv2.equalizeHist(self.image)
            self.affichage(equ)

        def egalisationHistogrammeCouleur(self):

            image = cv2.imread(self.filename)
            #on divise l'image en 3 bandes R V B
            b,v,r = cv2.split(image)
            #on egalise l'histogramme de chaque bande
            #on fusionne les 3 bandes pour avoir une seule image couleur
            y = cv2.merge((egalisationHisto(b),egalisationHisto(v),egalisationHisto(r)))
            self.affichage(y)

        def seuil(self):
            image_grise = griser(self.filename)
            seuil = otsu(image_grise)
            newimage = image_grise.copy()
            image_binaire = binarisation(image_grise,seuil,newimage)

            self.affichage(image_binaire)

        def resize(self):
            image = cv2.imread(self.filename)
            window = MainWindow.height()
            self.size1 = MainWindow.height() - 100
            self.size2 = ((MainWindow.height() - 100 ) * image.shape[0]) / image.shape[1]
            self.size1 = getLigne(window)
            self.size2 = getColonne(image,window)
            self.label.setMaximumSize(QtCore.QSize(self.size1, self.size2))

        def inversion(self):
            image = cv2.imread(self.filename)
            #on divise l'image en 3 bandes R V B
            b,v,r = cv2.split(image)

            new_imageInverser = cv2.merge((inversionCouleur(r) , inversionCouleur(v) , inversionCouleur(b)))
            self.affichage(new_imageInverser )

        def erosion(self):
            image_grise = griser(self.filename)
            image_erode = image_grise.copy()
            new_imageErode = erosion(image_grise,image_erode)
            self.affichage(new_imageErode)

        def dilatation(self):
            image_grise = griser(self.filename)
            image_dilate = image_grise.copy()
            ligne = image_grise.shape[0]
            colonne = image_grise.shape[1]
            new_imageDilate = dilatation(image_grise,ligne,colonne,image_dilate)

            self.affichage(new_imageDilate)

        def conservateur(self):
            #image_grise = griser(self.filename)
            #image_conserver = image_grise.copy()
            #new_imageConserver = conserver(image_grise,image_conserver)
            image = cv2.imread(self.filename)
            image_conserver = image.copy()
            #on divise l'image en 3 bandes R V B
            b,v,r = cv2.split(image)

            new_imageConserver = cv2.merge((conserver(b,image_conserver),conserver(v,image_conserver),conserver(r,image_conserver)))
            self.affichage(new_imageConserver)

        def lissage(self):
            image = cv2.imread(self.filename)
            image_lisse = image.copy()
            #on divise l'image en 3 bandes R V B
            b,v,r = cv2.split(image)
            image_lisseRVB = cv2.merge((lisse(v,image_lisse),lisse(b,image_lisse),lisse(r,image_lisse)))
            self.affichage(image_lisseRVB)

        def valueLuminosite(self,value):
            image = cv2.imread(self.filename)
            self.luminosite_value_now = value
            new_imageChanger = luminosite(image,value)
            self.affichage(new_imageChanger)

        def valueBlur(self,value):
            image = cv2.imread(self.filename)
            self.blur_value_now = value
            blur_image =  floutter(image,value)
            self.affichage(blur_image)

        def etalage(self):
            image = cv2.imread(self.filename)
            #on divise l'image en 3 bandes R V B et on l'etale un par un puis le mettre en une seule image
            b,v,r = cv2.split(image)
            image_etale = cv2.merge((etale(b),etale(v),etale(r)))
            self.affichage(image_etale)

        def symetrie(self):
            image = cv2.imread(self.filename)
            image_sym = image.copy()
            for i in range(0,image.shape[0]):
                for j in range(0,image.shape[1]):
                  image_sym[i][j] = image[image.shape[0] - 1 - i][j]

            self.affichage(image_sym)

        def rotation(self):
            image = self.temp
            image_rot = rotation90(image)
            self.affichage(image_rot)

        def translation(self):
            image = cv2.imread(self.filename)
            image_translation = translation(image)

            self.affichage(image_translation)

        def retranslateUi(self, MainWindow):
            _translate = QtCore.QCoreApplication.translate
            MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
            self.label_2.setText(_translate("MainWindow", "Lumonisite"))
            self.label_3.setText(_translate("MainWindow", "Floutter"))
            self.menuOuvrir.setTitle(_translate("MainWindow", "Ouvrir"))
            self.menuAmelioration.setTitle(_translate("MainWindow", "Amelioration"))
            self.menuFiltrage.setTitle(_translate("MainWindow", "Filtrage"))
            self.menuBinarisation.setTitle(_translate("MainWindow", "Binarisation"))
            self.menuTransformation.setTitle(_translate("MainWindow", "Transformation"))
            self.menuRotation.setTitle(_translate("MainWindow", "Rotation"))
            self.menuTranslation.setTitle(_translate("MainWindow", "Translation"))
            self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
            self.toolBar_2.setWindowTitle(_translate("MainWindow", "toolBar_2"))
            self.actionOuvrir.setText(_translate("MainWindow", "Ouvrir"))
            self.actionEnregister.setText(_translate("MainWindow", "Enregister"))
            self.actionExit.setText(_translate("MainWindow", "Quitter"))
            self.actionEgalisation.setText(_translate("MainWindow", "Egalisation Histogramme"))
            self.actionMedian.setText(_translate("MainWindow", "Median"))
            self.actionGaussien.setText(_translate("MainWindow", "Gaussien"))
            self.actionMoyenne.setText(_translate("MainWindow", "Etalage"))
            self.actionLissage.setText(_translate("MainWindow", "Lissage"))
            self.actionSeuil.setText(_translate("MainWindow", "Seuillage Otsu"))
            self.actionErosion.setText(_translate("MainWindow", "Erosion"))
            self.actionDilatation.setText(_translate("MainWindow", "Dilatation"))
            self.actionNiveau_de_gris.setText(_translate("MainWindow", "Niveau de gris"))
            self.actionNiveau_de_gris_2.setText(_translate("MainWindow", "Niveau de gris"))
            self.actionNiveau_de_Gris.setText(_translate("MainWindow", "Niveau de Gris"))
            self.actionOpen.setText(_translate("MainWindow", "Ouvrir"))
            self.actionInversion.setText(_translate("MainWindow", "Inversion Couleur"))
            self.actionRotation_90.setText(_translate("MainWindow", "Rotation 90 "))
            self.actionRotation_45.setText(_translate("MainWindow", "Rotation 45"))
            self.actionSymetrie.setText(_translate("MainWindow", "Symetrie"))
            self.actionContours.setText(_translate("MainWindow", "Contours"))
            self.actionTranslation_1_0_100_0_1_50.setText(_translate("MainWindow", "Translation [[1,0,100],[0,1,50]]"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


from random import randint, choice

class BoardException(Exception):
    pass

class BoardOutException(BoardException):
    def __str__(self):
        return "Вы пытаетесь выстрелить за доску!"

class BoardUsedException(BoardException):
    def __str__(self):
        return "Вы уже стреляли в эту клетку"

class BoardWrongShipException(BoardException):
    pass

class Dot:
    """Класс точек на поле"""
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        """Изначально объекты сравниваются по их id (адресу в памяти),
        а мы бы хотели, чтобы сравнивались точки в каждом из объектов.
        Для этого переопределим магический метод __eq__()"""
        return self.x == other.x and self.y == other.y

    def __repr__(self):
        """Магический метод для отображения информации об объекте класса в режиме отладки (для разработчиков)"""
        return f"Dot({self.x}, {self.y})"

class Ship:
    def __init__(self, bow, l, o):
        self.bow = bow                 # Точка, где размещен нос корабля
        self.l = l                     # Длина корабля
        self.o = o                     # Ориентация корабля
        self.lives = l                 # Количество жизней (сколько точек корабля еще не подбито)

    @property
    def dots(self):
        ship_dots = []
        for i in range(self.l):
            cur_x = self.bow.x
            cur_y = self.bow.y

            if self.o == 0:
                cur_x += i

            elif self.o == 1:
                cur_y += i

            ship_dots.append(Dot(cur_x, cur_y))

        return ship_dots

    def shooten(self, shot):
        return shot in self.dots

class Board:
    """Класс доски представляет матрицу точек"""

    def __init__(self, hid=False, size=6):
        self.size = size
        self.hid = hid

        self.counter_kills = 0   # счетчик уничтоженных кораблей

        self.field = [["O"] * size for _ in range(size)]

        self.busy = []
        self.ships = []
        self.last_hit = []  # список точек, раненого корабля

    def __str__(self):
        res = '  | 1 | 2 | 3 | 4 | 5 | 6 |'
        for i, row in enumerate(self.field):
            res += f'\n{i + 1} | ' + ' | '.join(row) + ' |'

        if self.hid:
            res = res.replace("■", "O")
        return res

    def out(self, d):
        return not ((0 <= d.x < self.size) and (0 <= d.y < self.size))

    def contour(self, ship, verb=False):
        near = [(i, j) for i in range(-1, 2) for j in range(-1, 2)]
        for d in ship.dots:
            for dx, dy in near:
                cur = Dot(d.x + dx, d.y + dy)
                if not self.out(cur) and cur not in self.busy:
                    if verb:
                        self.field[cur.x][cur.y] = "."
                    self.busy.append(cur)

    def add_ship(self, ship):
        for d in ship.dots:
            if self.out(d) or d in self.busy:
                raise BoardWrongShipException()
        for d in ship.dots:
            self.field[d.x][d.y] = "■"
            self.busy.append(d)

        self.ships.append(ship)
        self.contour(ship)

    def shot(self, d):
        if self.out(d):
            raise BoardOutException()

        if d in self.busy:
            raise BoardUsedException()

        self.busy.append(d)

        for ship in self.ships:
            if ship.shooten(d):
                ship.lives -= 1
                self.field[d.x][d.y] = "X"
                print('Попал')
                if ship.lives == 0:
                    self.counter_kills += 1
                    self.contour(ship, verb=True)
                    print("Корабль уничтожен!")
                    self.last_hit = []
                    return False
                else:
                    print("Корабль ранен!")
                    self.last_hit.append(d)
                    return True

        self.field[d.x][d.y] = "."
        print("Мимо!")
        return False

    def begin(self):
        self.busy = []

    def defeat(self):
        return self.counter_kills == len(self.ships)

class Player:
    """Описание игрока"""
    def __init__(self, board, enemy):
        self.board = board
        self.enemy = enemy

    def ask(self):
        raise NotImplementedError()

    def move(self):
        while True:
            try:
                target = self.ask()
                repeat = self.enemy.shot(target)
                return repeat
            except BoardException as e:
                print(e)

class AI(Player):
    def ask(self):
        last = self.enemy.last_hit
        while True:
            if last:  # добиваем раненый корабль
                if len(last) == 1:
                    near = ((0, 1), (0, -1), (1, 0), (-1, 0))
                else:
                    if last[0].x == last[-1].x:
                        near = ((0, 1), (0, -1))
                    else:
                        near = ((1, 0), (-1, 0))
                dx, dy = choice(near)
                d = choice((Dot(last[-1].x + dx, last[-1].y + dy), Dot(last[0].x + dx, last[0].y + dy)))
            else:
                d = Dot(randint(0, 5), randint(0, 5))
            if d not in self.enemy.busy and not self.enemy.out(d):
                break
        print(' ' * 33 + f'Ход компьютера: {d.x + 1} {d.y + 1}')
        print(' ' * 33, end='')
        return d

class User(Player):
    def ask(self):
        while True:
            cords = input("Ваш ход: ").split()

            if len(cords) != 2:
                print(" Введите 2 координаты! ")
                continue

            x, y = cords

            if not (x.isdigit()) or not (y.isdigit()):
                print(" Введите числа! ")
                continue

            x, y = int(x), int(y)

            return Dot(x - 1, y - 1)

class Game:
    def __init__(self, size=6):
        self.size = size
        pl = self.random_board()
        co = self.random_board()
        co.hid = True

        self.ai = AI(co, pl)
        self.us = User(pl, co)

    def try_board(self):
        lens = [3, 2, 2, 1, 1, 1, 1]
        board = Board(size=self.size)
        attempts = 0
        for l in lens:
            while True:
                attempts += 1
                if attempts > 2000:
                    return None
                ship = Ship(Dot(randint(0, self.size), randint(0, self.size)), l, randint(0, 1))
                try:
                    board.add_ship(ship)
                    break
                except BoardWrongShipException:
                    pass
        board.begin()
        return board

    def random_board(self):
        board = None
        while board is None:
            board = self.try_board()
        return board

    def greet(self):
        print("-------------------")
        print("  Приветсвуем вас  ")
        print("      в игре       ")
        print("    морской бой    ")
        print("-------------------")
        print(" формат ввода: x y ")
        print(" x - номер строки  ")
        print(" y - номер столбца ")

    def loop(self):
        num = 0
        while True:
            print('-' * self.size * 10)
            print('Ваша доска:' + ' ' * (self.size * 4 - 2) + 'Доска компьютера:')
            for i in range (self.size):
                print((self.us.board.__str__().split('\n')[i] + ' ' * self.size + self.ai.board.__str__().split('\n')[i]))

            if num % 2 == 0:
                print("Ходит пользователь!")
                repeat = self.us.move()
            else:
                print(' ' * 33 + 'Ходит компьютер!')
                repeat = self.ai.move()
            if repeat:
                num -= 1

            if self.ai.board.defeat():
                print("-" * 20)
                print("Вы выиграли!")
                break

            if self.us.board.defeat():
                print("-" * 20)
                print("Компьютер выиграл!")
                break
            num += 1

    def start(self):
        self.greet()
        self.loop()

g = Game()
g.start()


import configparser
import time
import random

cp = configparser.ConfigParser(
    converters={'list': lambda x: [i.strip() for i in x.split(',')]})
cp.read(['config.cfg'])

class Config:

    def __init__(self):
        pass

    name = "DEFAULT"

    iso = cp.getint("CAMERA", "iso")
    brightness = cp.getint("CAMERA", "brightness")
    contrast = cp.getint("CAMERA", "contrast")

    # focus area around the crosshair
    obs_x = cp.getint("PROCESSING", "obs_x")
    obs_y = cp.getint("PROCESSING", "obs_y")

    # performance and analysis
    benchmark = cp.getboolean("DEBUG", "benchmark")
    image_logger = cp.getboolean("DEBUG", "image_logger")

    # sensitivity in percent
    sens_diff = cp.getfloat("PROCESSING", "sens_diff")
    sens_color = cp.getfloat("PROCESSING", "sens_color")

    # color tracking for color mode
    col_hue_low = cp.getint("PROCESSING", "col_hue_low") / 2
    col_hue_high = cp.getint("PROCESSING", "col_hue_high") / 2
    col_sat_low = int(cp.getfloat("PROCESSING", "col_sat_low") * 255.0)
    col_sat_high = int(cp.getfloat("PROCESSING", "col_sat_high") * 255.0)
    col_bri_low = int(cp.getfloat("PROCESSING", "col_bri_low") * 255.0)
    col_bri_high = int(cp.getfloat("PROCESSING", "col_bri_high") * 255.0)

    # marker color (scoped-in marker color)
    col_marker_hue_low = cp.getint("PROCESSING", "col_marker_hue_low") / 2
    col_marker_hue_high = cp.getint("PROCESSING", "col_marker_hue_high") / 2
    col_marker_sat_low = int(cp.getfloat(
        "PROCESSING", "col_marker_sat_low") * 255.0)
    col_marker_sat_high = int(cp.getfloat(
        "PROCESSING", "col_marker_sat_high") * 255.0)
    col_marker_bri_low = int(cp.getfloat(
        "PROCESSING", "col_marker_bri_low") * 255.0)
    col_marker_bri_high = int(cp.getfloat(
        "PROCESSING", "col_marker_bri_high") * 255.0)

    remote_keyboard = cp.getboolean("CONTROL", "remote_keyboard")

    mode = cp.get("GAMEPLAY", "mode")
    delay = cp.getint("GAMEPLAY", "delay")
    tap_mode = cp.get("GAMEPLAY", "tap_mode")
    marker_check = cp.getboolean("GAMEPLAY", "marker_check")
    consecutive = cp.getboolean("GAMEPLAY", "consecutive")

    duration_active = cp.getint("GAMEPLAY", "duration_active") / 1000.0
    duration_break = cp.getint("GAMEPLAY", "duration_break") / 1000.0
    duration_active_tmp = 0
    duration_breake_tmp = 0

    tap = cp.getboolean("GAMEPLAY", "tap")
    activation_delay = cp.getint("GAMEPLAY", "activation_delay")
    tap_led_time_on = cp.getint("GAMEPLAY", "tap_led_time_on")
    tap_led_time_off = cp.getint("GAMEPLAY", "tap_led_time_off")

    # randomize mouse click and pause time
    # mean values can be set in config
    # using uniform distribution
    def randomizer(self):
        if time.time() * 1000 % 1000 < 25:
            self.duration_active_tmp = self.duration_active + \
                random.randint(-20, 20) / 1000
            self.duration_break_tmp = self.duration_break + \
                random.randint(-50, 50) / 1000

def process_configs(configs):

    NUM = [cp.getlist("KEYS", "NUM_0"), cp.getlist("KEYS", "NUM_1"), cp.getlist("KEYS", "NUM_2"),
           cp.getlist("KEYS", "NUM_3"), cp.getlist(
               "KEYS", "NUM_4"), cp.getlist("KEYS", "NUM_5"),
           cp.getlist("KEYS", "NUM_6"), cp.getlist(
               "KEYS", "NUM_7"), cp.getlist("KEYS", "NUM_8"),
           cp.getlist("KEYS", "NUM_9")]

    for idx, N in enumerate(NUM):
        configs[idx].name = N[0]
        i = 1
        while i < len(N):
            if N[i] == 'mode':
                configs[idx].mode = N[i + 1]
            elif N[i] == 'obs_x':
                configs[idx].obs_x = int(N[i + 1])
            elif N[i] == 'obs_y':
                configs[idx].obs_y = int(N[i + 1])
            elif N[i] == 'sens_diff':
                configs[idx].sens_diff = float(N[i + 1])
            elif N[i] == 'sens_color':
                configs[idx].sens_diff = float(N[i + 1])
            elif N[i] == 'duration_active':
                configs[idx].duration_active = int(N[i + 1]) / 1000.0
            elif N[i] == 'duration_break':
                configs[idx].duration_break = int(N[i + 1]) / 1000.0
            elif N[i] == 'activation_delay':
                configs[idx].activation_delay = int(N[i + 1])
            elif N[i] == 'tap':
                configs[idx].tap = bool(int(N[i + 1]))
            elif N[i] == 'tap_mode':
                configs[idx].tap_mode = N[i + 1]
            elif N[i] == 'marker_check':
                configs[idx].marker_check = bool(int(N[i + 1]))
            i += 2


from Queue import Empty
import time
import logging

from pushkin.database import database
from pushkin.sender.nordifier.apns_push_sender import APNsPushSender
from pushkin.sender.nordifier.gcm_push_sender import GCMPushSender
from pushkin.util.pool import ProcessPool
from pushkin import context
from pushkin import config
from pushkin.sender.nordifier import constants

class NotificationSender(ProcessPool):
    def __init__(self, num_workers):
        ProcessPool.__init__(self, self.__class__.__name__, num_workers, config.sender_queue_limit)

    def limit_exceeded(self, notification):
        notification['status'] = constants.NOTIFICATION_SENDER_QUEUE_LIMIT
        self.log_notifications([notification])

    def queue_size(self):
        return self.task_queue.qsize()

    def log_notifications(self, notifications):
        main_logger = logging.getLogger(config.main_logger_name)
        notification_logger = logging.getLogger(config.notifications_logger_name)
        for notification in notifications:
            try:
                notification['content'] = notification['content'].encode('utf-8').replace(',', '\\,')
                keys = ['status', 'login_id', 'content', 'message_id', 'campaign_id', 'sending_id', 'game', 'world_id',
                        'screen', 'time', 'time_to_live_ts_bigint', 'platform', 'receiver_id']
                notification_logger.info(','.join([str(notification[key]) for key in keys]))
            except:
                main_logger.exception("Error while logging notification to csv log!")

class ApnNotificationSender(NotificationSender):
    def __init__(self):
        NotificationSender.__init__(self, config.apn_num_processes)
        self.apn_sender_interval_sec = config.apn_sender_interval_sec
        self.max_batch_size = config.sender_batch_size

    def send_batch(self, sender):
        """Tries to send up to max_batch_size notifications in a single batch.
        If there is < max_batch_size in queue, sender.send_remaining() will send the notifications.
        If there is > max_batch_size in queue, notifications will be sent by ender.send_in_batch in last iteration.
        """
        sent = []
        try:
            for i in xrange(self.max_batch_size):
                notification = self.task_queue.get_nowait()
                sender.send_in_batch(notification)
                sent.append(notification)
        except Empty:
            pass
        sender.send_remaining()
        return sent

    def process(self):
        main_logger = logging.getLogger(config.main_logger_name)
        while True:
            if self.queue_size() > 0:

                sender = None
                sent = []
                try:
                    sender = APNsPushSender(config.config, main_logger)
                    sent = self.send_batch(sender)
                    time.sleep(self.apn_sender_interval_sec)
                except Exception:
                    main_logger.exception("ApnNotificationProcessor failed to send notifications")
                finally:
                    if sender is not None:
                        sender.close_after_sending()
                    self.log_notifications(sent)
            else:
                time.sleep(self.apn_sender_interval_sec)

class GcmNotificationSender(NotificationSender):
    def __init__(self):
        NotificationSender.__init__(self, config.gcm_num_processes)

    def process(self):
        main_logger = logging.getLogger(config.main_logger_name)
        while True:
            notification = self.task_queue.get()
            try:
                sender = GCMPushSender(config.config, main_logger)
                sender.send_in_batch(notification)
                canonical_ids = sender.get_canonical_ids()
                if len(canonical_ids) > 0:
                    database.update_canonicals(canonical_ids)
                unregistered_devices = sender.get_unregistered_devices()
                if len(unregistered_devices) > 0:
                    database.update_unregistered_devices(unregistered_devices)
            except Exception:
                main_logger.exception("GcmNotificationProcessor failed to send notifications")
            finally:
                self.log_notifications([notification])


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

#
# There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
#
#
# The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.
#
#
# Note:
# All costs are positive integers.
#
# Follow up:
# Could you solve it in O(nk) runtime?

class Solution(object):
    def minCostII(self, costs):
        """
        :type costs: List[List[int]]
        :rtype: int
        """

        # red blue green yellow ...
        # 记录上一层 倒数第一小 和倒数第二小

        n = len(costs)
        if n == 0: return 0
        k = len(costs[0])
        if k == 0: return 0

        min1, min2 = -1, -1
        for i in range(0, n):
            last1, last2 = min1, min2
            min1, min2 = -1, -1
            for j in range(0, k):
                if j != last1:
                    costs[i][j] += (0 if last1 == -1 else costs[i-1][last1])
                else:
                    costs[i][j] += (0 if last2 == -1 else costs[i-1][last2])

                if min1 == -1 or costs[i][j] < costs[i][min1]:
                    min2 = min1
                    min1 = j
                elif min2 == -1 or costs[i][j] < costs[i][min2]:
                    min2 = j

        return costs[n-1][min1]


import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtCore import *
import pybithumb
import time

tickers = ["BTC","ETH","EOS","TRX","BCH","ADA"]
form_class = uic.loadUiType("view.ui")[0]

# BTC 조회하는 클래스
class Worker(QThread):
    finished = pyqtSignal(dict)

    def run(self):
        while True:
            data = {}
            # 전체 데이터 불러옴
            all_data = pybithumb.get_current_price("ALL")
            for ticker, infos in all_data.items() :
                if ticker in tickers:
                    data[ticker] = self.get_market_infos(ticker) + (infos['units_traded'],) + (infos['24H_fluctate_rate'],)

            # 작업이 완료됐을때 이벤트 발생(emit)
            # data 변수가 바인딩하고 있는 딕셔너리 객체가 전송됨
            self.finished.emit(data)
            time.sleep(1)

    def get_market_infos(self, ticker):
        try:

            df = pybithumb.get_ohlcv(ticker)
            ma5 = df['close'].rolling(window=5).mean()
            ma20 = df['close'].rolling(window=20).mean()
            # 전일 이동 편균
            last_ma5 = ma5[-2]
            last_ma20 = ma20[-2]
            price = pybithumb.get_current_price(ticker)
            return price, last_ma5, last_ma20
        except:
            None, None, None

class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setWindowTitle('시세 조회기')
        self.worker = Worker()
        self.worker.finished.connect(self.update_table_widget)
        self.worker.start()

        # 5초마다 호출
        timer = QTimer(self)
        timer.start(1000)
        timer.timeout.connect(self.timeout)
        # self.datetime = QDateTime.currentDateTime()
        # self.statusBar().showMessage(self.datetime.toString(Qt.DefaultLocaleLongDate))

    def timeout(self):
        self.datetime = QDateTime.currentDateTime()
        self.statusBar().showMessage(self.datetime.toString(Qt.DefaultLocaleLongDate))

    # finished 라는 시그널이 발생하면 해당 메소드가 호출됨
    # data는 바인딩 된 key와 value를 가져옴.
    @pyqtSlot(dict)
    def update_table_widget(self,data):

        for ticker, infos in data.items():
            i = tickers.index(ticker)
            self.tableWidget.setItem(i, 0, QTableWidgetItem(ticker))
            self.tableWidget.setItem(i, 1, QTableWidgetItem(str(infos[0])))
            self.tableWidget.setItem(i, 2, QTableWidgetItem(str('%.4f' % float(infos[3]))))
            self.tableWidget.setItem(i, 3, QTableWidgetItem(str(infos[4] + '%')))
            self.tableWidget.setItem(i, 4, QTableWidgetItem(str('%.4f' % infos[1])))
            self.tableWidget.setItem(i, 5, QTableWidgetItem(str('%.4f' % infos[2])))

app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()


import numpy as np
import os
import cv2
import signal
import sys
import logging
import threading

import tkinter.ttk as ttk
import tkinter as tk
from tkinter import Frame, RAISED, BOTH, Button, RIGHT, Canvas, Scale, HORIZONTAL
import datetime

from robot_controller import RobotController

class GraphicalInterface():
    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self)
        self.kwargs = kwargs
        self.enable_joysticks = True
        if 'enable_joysticks' in self.kwargs:
            self.enable_joysticks = self.kwargs['enable_joysticks']

        logging.getLogger("requests").setLevel(logging.WARNING)

        self.stop_robot = False
        self.logger = logging.getLogger('GUI')
        self.curr_image = None
        self.joint_states = []
        self.num_empty_commands = 0

        self.robot_ctrl = RobotController.getInstance(*args, **kwargs)
        self.logger.info('initializing robot...')
        self.robot_ctrl.init_robot()
        self.logger.info('robot successfully initilized')

        if 'robot_init_pos' in self.kwargs:
            self.logger.info('Sending robot to center.')
            self.robot_ctrl.send_robot_to_center(goal=kwargs['robot_init_pos'])
            self.logger.info('Robot centered.')

        np.set_printoptions(precision=2)

        self.image_size = (640, 360)
        if 'image_size' in self.kwargs:
            self.image_size = self.kwargs['image_size']

    def callback(self):
        self.parent.quit()

    def run(self):

        self.parent = tk.Tk()

        self.main_frame = Frame(self.parent)
        self.main_frame.pack()
        if self.enable_joysticks:
            self.create_widgets()

        self.robot_controller()

        # def signal_handler(sig, frame):
        #     self.logger.info('You pressed Ctrl+C')
        #     # cap.release()
        #     cv2.destroyAllWindows()
        #     self.logger.info("Stopping Robot...")
        #     self.stop_robot = True
        #     self.robot_ctrl.send_joint_command_to_robot([0, 0, 0, 0, 0, 0], use_thread=False)
        #     sys.exit(0)

        # signal.signal(signal.SIGINT, signal_handler)

        self.parent.mainloop()

    def robot_controller(self):
        self.curr_image = self.robot_ctrl.get_image_cv2()
        if self.curr_image is None:
            self.parent.after(10, self.robot_controller)
            return

        img = cv2.resize(self.curr_image, self.image_size)
        cv2.imshow('frame', img / 255.0)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            return

        if self.stop_robot == True:
            return

        if self.enable_joysticks:
            x = -self.canvas.joystick_x
            y = -self.canvas.joystick_y
            v = (100 - abs(x)) * (y / 100) + y
            w = (100 - abs(y)) * (x / 100) + x
            x = (v - w) // 2
            y = (v + w) // 2
            command_to_send = [x, y, self.scale1.get(), self.scale2.get(), self.scale4.get(), self.scale3.get()]

            self.robot_ctrl.send_joint_command_to_robot(command_to_send)
            # self.robot_ctrl.update_joint_states()

        self.parent.after(10, self.robot_controller)

    def create_widgets(self):
        self.main_frame.style = ttk.Style()
        self.main_frame.winfo_toplevel().title("Nabot Controls")
        self.main_frame.style.theme_use('default')
        self.main_frame.configure(background='black')

        def create_canvas():
            class Joystick(tk.Canvas):
                pass

            self.canvas = Joystick(self.main_frame, width=400, height=400)
            self.canvas.joystick_x = 0
            self.canvas.joystick_y = 0
            self.canvas.is_moving = False

            def paint(event):
                # self.canvas.create_rectangle(0, 0, 200, 200, fill='red')
                reset_canvas()
                self.canvas.create_oval(0, 0, 400, 400, fill='black', outline='gray')
                x1, y1 = event.x - 75, event.y - 75
                x2, y2 = event.x + 75, event.y + 75
                self.canvas.create_oval(x1, y1, x2, y2, fill='blue')

                self.canvas.joystick_x = (event.x - 200) * 7 / 10
                self.canvas.joystick_y = (event.y - 200) * 7 / 10

                self.canvas.joystick_x = min(max(self.canvas.joystick_x, -100), 100)
                self.canvas.joystick_y = min(max(self.canvas.joystick_y, -100), 100)

            def reset(event):
                self.canvas.is_moving = False
                self.canvas.joystick_x = 0
                self.canvas.joystick_y = 0
                reset_canvas()
                logging.debug('move the robot, x:{} y:{}'.format(self.canvas.joystick_x, self.canvas.joystick_y))

            def reset_canvas():
                self.canvas.create_rectangle(0, 0, 400, 400, fill='black')
                self.canvas.create_oval(0, 0, 400, 400, fill='black', outline='gray')
                self.canvas.create_oval(125, 125, 275, 275, fill='gray')

            self.canvas.pack(side='left')

            # self.canvas.bind('<Button-1>', start)
            self.canvas.bind('<B1-Motion>', paint)
            self.canvas.bind('<ButtonRelease-1>', reset)
            reset_canvas()

            def scale1_command(val):
                val = self.scale1.get()

            def scale1_stop(event):
                self.scale1.set(0)

            self.scale1 = Scale(from_=100, to=-100, label='head', command=scale1_command)
            self.scale1.bind('<ButtonRelease-1>', scale1_stop)
            self.scale1.pack(side='left')

            def scale2_command(val):
                val = self.scale2.get()

            def scale2_stop(event):
                self.scale2.set(0)

            self.scale2 = Scale(from_=100, to=-100, label='elbow', command=scale2_command)
            self.scale2.bind('<ButtonRelease-1>', scale2_stop)
            self.scale2.pack(side='left')
            self.scale3 = Scale(from_=0, to=100, orient=HORIZONTAL, label='Gripper')
            self.scale3.pack(side='top')

            def scale4_command(val):
                val = self.scale4.get()

            def scale4_stop(event):
                self.scale4.set(0)

            self.scale4 = Scale(from_=-100, to=100, orient=HORIZONTAL, command=scale4_command, label='wrist')
            self.scale4.bind('<ButtonRelease-1>', scale4_stop)
            self.scale4.pack(side='top')

        create_canvas()


def reverse(n):
    tozp = ''
    afzp = ''
    rdyNumber = ''
    toDot = True
    afterDot = False
    for num in str(n):
        if num != '.':
            if toDot:
                tozp += num
            if afterDot and num != '.':
                afzp += num
        else:
            toDot = False
            afterDot = True
    revNum = tozp[:: -1]
    revDel = afzp[:: -1]
    rdyNumber += revNum +str('.')+ revDel
    return rdyNumber

n = float(input('Введите первое число: '))
k = float(input('Введите второе число: '))

firstNumber = reverse(n)
secondNumber = reverse(k)
summ = float(firstNumber) + float(secondNumber)

print('Сумма уже перевернутых чисел = ', firstNumber , '+', secondNumber, '= ', summ)