import enum
import struct
from typing import Dict, Tuple

# Webots specific library
from controller import Emitter, Receiver, Supervisor  # isort:skip

# Updating? Update `Arena.wbt` too
ZONE_COLOURS = ((1, 0, 1), (1, 1, 0))

RECEIVE_TICKS = 1

# Updating? Update radio.py too.
BROADCASTS_PER_SECOND = 10

# Updating? Update radio.py too.
class Claimant(enum.IntEnum):
    UNCLAIMED = -1
    ZONE_0 = 0
    ZONE_1 = 1

# Updating? Update radio.py too.
class StationCode(str, enum.Enum):
    PN = 'PN'
    EY = 'EY'
    BE = 'BE'
    PO = 'PO'
    YL = 'YL'
    BG = 'BG'
    TS = 'TS'
    OX = 'OX'
    VB = 'VB'
    SZ = 'SZ'
    SW = 'SW'
    BN = 'BN'
    HV = 'HV'

class TerritoryController:

    _emitters: Dict[StationCode, Emitter]
    _receivers: Dict[StationCode, Receiver]

    def __init__(self) -> None:
        self._robot = Supervisor()
        self._station_statuses: Dict[StationCode, Claimant] = {
            code: Claimant.UNCLAIMED for code in StationCode
        }
        self._claim_starts: Dict[Tuple[StationCode, Claimant], float] = {}

    def get_claimant(
        self,
        station_code: StationCode,
    ) -> Claimant:
        return self._station_statuses[station_code]

    def setup(self) -> None:
        self._emitters = {station_code: self._robot.getEmitter(station_code + "Emitter")
                          for station_code in StationCode}

        self._receivers = {station_code: self._robot.getReceiver(station_code + "Receiver")
                           for station_code in StationCode}
        territory_controller.enable_receivers()

    def enable_receivers(self) -> None:
        for receiver in self._receivers.values():
            receiver.enable(RECEIVE_TICKS)

    def _log_territory_claim(
        self,
        station_code: StationCode,
        claimed_by: Claimant,
        claim_time: float,
    ) -> None:
        # TODO add better logging so we can score
        print(f"{station_code} CLAIMED BY {claimed_by} AT {claim_time}s")  # noqa:T001

    def begin_claim(
        self,
        station_code: StationCode,
        claimed_by: Claimant,
        claim_time: float,
    ) -> None:
        self._claim_starts[station_code, claimed_by] = claim_time

    def has_begun_claim_in_time_window(
        self,
        station_code: StationCode,
        claimant: Claimant,
        current_time: float,
    ) -> bool:
        try:
            start_time = self._claim_starts[station_code, claimant]
        except KeyError:
            return False
        time_delta = current_time - start_time
        return 1.8 <= time_delta <= 2.1

    def claim_territory(
        self,
        station_code: StationCode,
        claimed_by: Claimant,
        claim_time: float,
    ) -> None:
        if self.get_claimant(station_code) == claimed_by:
            # This territory is already claimed by this claimant.
            return

        new_colour = ZONE_COLOURS[claimed_by]
        self._robot.getFromDef(station_code).getField("zoneColour").setSFColor(
            list(new_colour),
        )

        self._log_territory_claim(station_code, claimed_by, self._robot.getTime())
        self._station_statuses[station_code] = claimed_by

    def process_packet(
        self,
        station_code: StationCode,
        packet: bytes,
        receive_time: float,
    ) -> None:
        try:
            robot_id, is_conclude = struct.unpack("!BB", packet)
            if is_conclude:
                if self.has_begun_claim_in_time_window(
                    station_code,
                    robot_id,
                    receive_time,
                ):
                    self.claim_territory(
                        station_code,
                        robot_id,
                        receive_time,
                    )
            else:
                self.begin_claim(
                    station_code,
                    robot_id,
                    receive_time,
                )
        except ValueError:
            print(  # noqa:T001
                f"Received malformed packet at {receive_time} on {station_code}: {packet!r}",
            )

    def receive_territory(self, station_code: StationCode, receiver: Receiver) -> None:
        simulation_time = self._robot.getTime()

        while receiver.getQueueLength():
            try:
                data = receiver.getData()
                self.process_packet(station_code, data, simulation_time)
            finally:
                # Always advance to the next packet in queue: if there has been an exception,
                # it is safer to advance to the next.
                receiver.nextPacket()

    def receive_robot_captures(self) -> None:
        for station_code, receiver in self._receivers.items():
            self.receive_territory(station_code, receiver)

    def transmit_pulses(self) -> None:
        for station_code, emitter in self._emitters.items():
            emitter.send(struct.pack("!2sb", station_code.encode('ASCII'),
                         int(self.get_claimant(station_code))))

    def main(self) -> None:
        self.setup()
        timestep = self._robot.getBasicTimeStep()
        steps_per_broadcast = (1 / BROADCASTS_PER_SECOND) / (timestep / 1000)
        counter = 0
        while True:
            counter += 1
            self.receive_robot_captures()
            if (counter > steps_per_broadcast):
                self.transmit_pulses()
                counter = 0
            self._robot.step(int(self._robot.getBasicTimeStep()))

if __name__ == "__main__":
    territory_controller = TerritoryController()
    territory_controller.main()


"""A setuptools based setup module.

Created based on https://github.com/pypa/sampleproject
and dependencies ensured via pipenv-setup sync tooling.
"""
import sys

# Always prefer setuptools over distutils
from setuptools import setup, find_namespace_packages
from os import path

here = path.abspath(path.dirname(__file__))
sys.path.append(path.join(here, "src"))

from tools.utils.version import git_version  # noqa: E402

# Get the long description from the README file
with open(path.join(here, "README.md"), encoding="utf-8") as f:
    long_description = f.read()

setup(
    name="tools",  # Required
    version=git_version(),  # Required
    description="Project with CLI tools: setup-opendns, automount-cifs",  # Optional
    long_description=long_description,  # Optional
    long_description_content_type="text/markdown",  # Optional (see note above)
    url="https://github.com/matihost/monorepo",  # Optional
    author="matihost",  # Optional
    classifiers=[  # Optional
        "Development Status :: 3 - Alpha",
        "Intended Audience :: Developers",
        "Topic :: Software Development :: Build Tools",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3.11",
    ],
    keywords="exchange rate nbp",  # Optional
    # When your source code is in a subdirectory under the project root, e.g.
    # `src/`, it is necessary to specify the `package_dir` argument.
    package_dir={"": "src"},  # Optional
    packages=find_namespace_packages(where="src"),  # Required
    # Ensures that non .py files are included in package
    setup_requires=["setuptools_scm"],
    include_package_data=True,
    python_requires=">=3.11, <4",
    install_requires=[
        "jinja2>=3.1.2",
        "markupsafe>=2.1.1; python_version >= '2.7' and python_version >= '3.11'",
    ],
    dependency_links=[],
    entry_points={
        "console_scripts": [
            "automount-cifs=tools.cli.automount_cifs:main",
            "setup-opendns=tools.cli.setup_opendns:main",
        ],
    },
    project_urls={"Source": "https://github.com/matihost/monorepo/", },  # Optional
)


import json
import requests
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def get_character():
    r = requests.get('https://www.breakingbadapi.com/api/character/random')
    characterjson = r.json()
    character = {
        'image': characterjson[0]['img'],
        'name': characterjson[0]['name'],
        'occupation': characterjson[0]['occupation'],
        'status': characterjson[0]['status'],
        'nickname': characterjson[0]['nickname']
    }

    # Display Character
    return(render_template('green/index.html', character=character))

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80, debug=True)  # specify port=80


import speech_recognition as sr
from datetime import datetime
import webbrowser
import time
from gtts import gTTS
import random
import os
from playsound import playsound
import serial.tools.list_ports
import threading
import urllib.request
import re
from googletrans import Translator
import requests
from bs4 import BeautifulSoup

translater = Translator()

ports=serial.tools.list_ports.comports()

serialInst = serial.Serial()

portlist=[]

for oneport in ports:
    portlist.append(str(oneport))
    print(str(oneport))

val = input("Select port: COM")

for x in range(0,len(portlist)):
    if portlist[x].startswith("COM" + str(val)):
        portVar = "COM" + str(val)
        print(portlist[x])

serialInst.baudrate = 9600
serialInst.port = portVar
serialInst.open()

r = sr.Recognizer()
konuşun = r"C:\\Users\Deniz\Documents\\Python\\oda_serial_ardu\\asistan\\crystal.wav"
alarm = r"C:\\Users\Deniz\Documents\\Python\\oda_serial_ardu\\asistan\\alarm.wav"
bitti = r"C:\\Users\Deniz\Documents\\Python\\oda_serial_ardu\\asistan\\bitti.wav"

def get_video_duration(url):
    page = requests.get(url)
    soup = BeautifulSoup(page.content, "html.parser")
    duration_meta = soup.find("meta", attrs={"itemprop": "duration"})
    if duration_meta:
        duration = duration_meta["content"]
        duration = duration[2:]   #7M7S
        duration = duration.replace("S","")   #7M7
        duration = duration.split("M")
        seconds = (int(duration[0]) * 60) + int(duration[1])
        return seconds
    else:
        return None

def yt(string):
    search_keyword = string
    search_keyword = search_keyword.replace(" ","_")
    search_keyword = search_keyword.replace("ı","i")
    search_keyword = search_keyword.replace("ğ","g")
    search_keyword = search_keyword.replace("ç","c")
    search_keyword = search_keyword.replace("ş","s")
    print(search_keyword)
    html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search_keyword)
    video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())
    url = "https://www.youtube.com/watch?v=" + video_ids[0]
    return url

def record():
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source,duration=5)
        print("Konuşun")
        playsound(konuşun)
        audio = r.listen(source)
        print("Bitti")
        playsound(bitti)
        voice = ""
        try:
            voice = r.recognize_google(audio , language = "tr-TR")
        except sr.UnknownValueError:
            speak("Anlayamadım")
            print("Anlayamadım")
        except sr.requestError:
            speak("Sistem çalışmıyor")
        return voice.capitalize()

def record_eng():
    with sr.Microphone() as source:
        print("Konuşun")
        playsound(konuşun)
        audio = r.listen(source)
        print("Bitti")
        playsound(bitti)
        voice = ""
        try:
            voice = r.recognize_google(audio)
        except sr.UnknownValueError:
            speak("Anlayamadım")
            print("Anlayamadım")
        except sr.requestError:
            speak("Sistem çalışmıyor")
        return voice.capitalize()

def response(voice):
    if "Nasılsın" in voice:
        speak("İyiyim Sen Nasılsın?")
        print("İyiyim sen Nasılsın?")
        mood = record()
        print(mood)
        if "İyiyim" or "Süperim "or "Bomba gibiyim" in mood:
            speak("İyi olmana sevindim!")
            print("İyi olmana sevindim!")
        elif "Kötüyüm" or "Berbatım" or "İyi değilim" or "İyi değilim" in mood:
            speak("Kötü olmana üzüldüm!")
            print("Kötü olmana üzüldüm!")
    if "Saat kaç" in voice:
        speak(datetime.now().strftime("%H:%M"))
        print(datetime.now().strftime("%H:%M"))
    if "Arama yap" in voice:
        speak("Ne aramak istiyorsun ?")
        print("Ne aramak istiyorsun?")
        search = record()
        url = "https://google.com/search?q=" + search
        webbrowser.get().open(url)
        speak(search + " İçin bulduklarım :")
    if "Tamamdır" in voice:
        speak("Görüşürüz")
        exit()
    if "Video ara" in voice:
        speak("Ne aramak istiyorsun ?")
        print("Ne aramak istiyorsun?")
        search = record()
        url = "https://www.youtube.com/results?search_query=" + search
        webbrowser.get().open(url)
        speak(search + "İçin YouTube'da bulduklarım")
    if "Arama motorunu aç" in voice:
        webbrowser.open("https://www.google.com.tr")
    if "Instagram'ı aç" in voice:
        webbrowser.open("https://www.instagram.com/?hl=tr")
    if "İngilizce çeviri yap" in voice:
        speak("Neyi türkçeye çevirmemi istiyorsun?")
        print("Neyi türkçeye çevirmemi istiyorsun?")
        search = record_eng()
        print(search)
        out = translater.translate(search,dest="tr",src="en")
        out = out.text
        speak(f"Söylediğiniz kelime {out} anlamına gelir")
    if "Eş anlamlısını bul" in voice:
        speak("Neyin eş anlamlısını bulmamı istiyorsun?")
        print("Neyin eş anlamlısını bulmamı istiyorsun?")
        url = "https://es-anlam.com/kelime/" + record()
        headerss = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"}
        page = requests.get(url,headers=headerss)
        soup = BeautifulSoup(page.content,"html.parser")
        title = soup.find(id="esanlamlar").get_text().strip()
        speak(title)
    if "Zıt anlamlısını bul" in voice:
        speak("Neyin zıt anlamlısını bulmamı istiyorsun?")
        print("Neyin zıt anlamlısını bulmamı istiyorsun?")
        search = record()
        url = "https://www.es-anlam.com/zit-anlam/kelime/" + search
        headerss = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"}
        page = requests.get(url,headers=headerss)
        soup = BeautifulSoup(page.content,"html.parser")
        title = soup.find(id="esanlamlar").get_text().strip()
        speak(title)
    if "Zamanlayıcı kur" in voice:
        speak("Kaç dakika sonrasına kurmamı istiyorsun ?")
        print("Kaç dakika sonrasına kurmamı istiyorsun ?")
        dakika = record()
        print(dakika)
        saniye = int(dakika) * 5
        geçen = 0
        while geçen < saniye:
            time.sleep(1)
            print(geçen)
            geçen += 1
            if geçen % 5 == 0:
                speak(f"{geçen/5} dakika kaldı")
                geçen += 3
        playsound(alarm)
        time.sleep(4)
        speak("Alarm çaldı!!")
    if "Işığı aç" in voice:
        serialInst.write(str.encode("ac\r\n"))
        speak("Işık açıldı!")
    if "Işığı kapat" in voice:
        serialInst.write(str.encode("kapa\r\n"))
        speak("Işık kapatıldı!")
    if "Ders çalışma müziği aç" in voice:
        webbrowser.open("")
    if "Youtube'da türkçe çal" in voice:
        speak("Ne çalayım?")
        wordd = record()
        link = yt(wordd)
        webbrowser.open(link, new=1, autoraise=True)
        sn = get_video_duration(link)
        threading.Thread(target=sure_bekle,args=(sn,)).start()

    if "Youtube'da i̇ngilizce çal" in voice:
        speak("Ne çalayım?")
        wordd = record_eng()
        webbrowser.open(yt(wordd))

def speak(string):
    tts = gTTS(string,lang="tr")
    rand = random.randint(1,10000)
    file = "audio-" + str(rand) + ".mp3"
    tts.save(file)
    time.sleep(1)
    playsound(file)
    time.sleep(6)
    os.remove(file)

def sure_bekle(sure):
    a = 0
    time.sleep(sure+5)
    print("Betteeee!!")
    os.system("TASKKILL /F /IM chrome.exe")

def speak_eng(string):
    tts = gTTS(string,lang="en")
    rand = random.randint(1,10000)
    file = "audio-" + str(rand) + ".mp3"
    tts.save(file)
    time.sleep(1)
    playsound(file)
    time.sleep(6)
    os.remove(file)

while True:
    if serialInst.in_waiting:
        packet = serialInst.readline()
        cardn = packet.decode("utf").rstrip("\n")
        cardr = cardn.rstrip("\r")
        card = cardr.rstrip(" ")
        print(card)
        if card == "basla":
            speak("Nasıl yardımcı olabilirim?")
            voice = record()
            print(voice)
            response(voice)


import datetime
import time
from decimal import Decimal
from unittest.mock import Mock

from django.test import TestCase
from django.utils.timezone import now

from pytz import utc

from api.actions import TrainingConfigurationActionManager
from api.actions import TrainingTaskActionManager
from api.models import TrainingConfiguration
from api.models import TrainingTask

def alter_tz_format(datetime_str):
    return datetime_str.replace("+00:00", "+0000")

def to_timestamp(date_time_instance):
    return time.mktime(date_time_instance.timetuple())

class ActionManagersTestCase(TestCase):

    def test_schedule_training_task(self):
        training_configuration = self.get_training_configuration()
        actions = TrainingConfigurationActionManager(
            training_configuration
        )

        task = actions.run_training()

        self.assertEqual(task.training_configuration, training_configuration)
        self.assertEqual(task.status, TrainingTask.CREATED)
        self.assertEqual(task.started_on, None)
        self.assertEqual(task.terminated_on, None)
        self.assertEqual(task.test_loss, None)
        self.assertEqual(task.test_accuracy, None)
        self.assertAlmostEqual(
            to_timestamp(task.created_on),
            to_timestamp(datetime.datetime.now()),
            places=8
        )

    def get_training_configuration(self):
        return TrainingConfiguration.objects.create(
            algorithm='algo1.py',
            dockerfile='Dockerfile.dms',
        )
    def get_training_task(self, status=TrainingTask.CREATED):
        started_on = now() if status != TrainingTask.CREATED else None
        return TrainingTask.objects.create(
            training_configuration=self.get_training_configuration(),
            status=status,
            started_on=started_on
        )

    def test_build_action_success(self):
        task = self.get_training_task()
        image = Mock()
        mocked_client = Mock()
        mocked_client.images.build.return_value = (image, [])
        actions = TrainingTaskActionManager(task)

        result = actions.build(
            docker_client=mocked_client
        )

        self.assertEqual(actions.model.status, TrainingTask.BUILDING)
        self.assertNotEqual(actions.model.started_on, None)
        self.assertTrue(mocked_client.images.build.called)
        self.assertEqual(result, image)

    def test_build_action_failure(self):
        task = self.get_training_task()
        mocked_client = Mock()
        mocked_client.images.build.side_effect = Exception("Oops")
        actions = TrainingTaskActionManager(task)

        actions.build(
            docker_client=mocked_client
        )

        self.assertEqual(actions.model.status, TrainingTask.FAILURE)
        self.assertEqual(
            actions.model.failure_message,
            "Failed to start image build: Oops"
        )
        self.assertNotEqual(actions.model.started_on, None)
        self.assertTrue(mocked_client.images.build.called)

    def test_build_action_failure(self):
        task = self.get_training_task()
        mocked_client = Mock()
        mocked_client.images.build.side_effect = Exception("Oops")
        actions = TrainingTaskActionManager(task)

        actions.build(
            docker_client=mocked_client
        )

        self.assertEqual(actions.model.status, TrainingTask.FAILURE)
        self.assertEqual(
            actions.model.failure_message,
            "Failed to start image build: Oops"
        )
        self.assertNotEqual(actions.model.started_on, None)
        self.assertTrue(mocked_client.images.build.called)

    def test_run_action_failure(self):
        task = self.get_training_task(status=TrainingTask.BUILDING)
        image = Mock()
        mocked_client = Mock()
        mocked_client.containers.run.side_effect = Exception("Oops")
        actions = TrainingTaskActionManager(task)

        result = actions.run(
            docker_client=mocked_client, docker_image=image
        )

        self.assertEqual(actions.model.status, TrainingTask.FAILURE)
        self.assertEqual(
            actions.model.failure_message,
            "Failed to run docker container : Oops"
        )
        self.assertNotEqual(actions.model.started_on, None)
        self.assertTrue(mocked_client.containers.run.called)
        self.assertEqual(result, None)

    def test_run_action_success(self):
        task = self.get_training_task(status=TrainingTask.BUILDING)
        container = Mock(id=2345)
        image = Mock()
        mocked_client = Mock()
        mocked_client.containers.run.return_value = container
        actions = TrainingTaskActionManager(task)

        result = actions.run(
            docker_client=mocked_client, docker_image=image
        )

        self.assertEqual(actions.model.status, TrainingTask.TRAINING)
        self.assertEqual(actions.model.failure_message, None)
        self.assertTrue(mocked_client.containers.run.called)
        self.assertEqual(result, container)


from flask import Flask, request, Response, jsonify
import json

app = Flask(__name__)

hashset = {'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'}

def get_data_from_file():
    file = open('quotes.json')
    data = json.load(file)
    file.close()
    return data

def get_result(day, quotes=None):
    if quotes is None:
        quotes = get_data_from_file()
    if day is not None:
        result = {key: value for key, value in quotes.items()
                  if key == day}
    else:
        return jsonify({
            "error": "Invalid Request - No Day Parameter"
        }), 400
    if result == {}:
        return {}, 204
    return jsonify(result), 200

@app.route("/")
def get_all():
    data = get_data_from_file()
    if data == {}:
        return {}, 204
    return jsonify(data), 200

@app.route("/<day>", methods=['GET'])
def get_by_id(day):
    if day == None:
        return {}, 400
    day = day.lower()
    day = " ".join(day.split())
    if day not in hashset:
        return {}, 400
    return get_result(day)

@app.route("/", methods=['POST'])
def add_quote():
    data = request.get_json()
    if 'day' not in data or 'quote' not in data:
        return {}, 400
    day = data.get('day').lower()
    day = " ".join(day.split())
    if day not in hashset:
        return {}, 400
    quote = data.get('quote')
    quote = " ".join(quote.split())
    quote_data = get_data_from_file()
    if day in quote_data:
        return {}, 400
    quote_data[day] = quote
    with open('quotes.json', 'w') as f:
        json.dump(quote_data, f)
    return jsonify({
        day : quote
    }), 201

@app.route("/<day>", methods=["PUT", "DELETE"])
def update(day):
    statusCode = 400
    if day == None:
        return {}, statusCode
    day = day.lower()
    day = " ".join(day.split())
    if day not in hashset:
            return {}, statusCode
    quote_data = get_data_from_file()
    if request.method == "PUT":
        if day in quote_data:
            statusCode = 200
        else:
            statusCode = 201
        quote = request.get_json().get("quote", "invalid")
        if quote == "invalid":
            return {}, 400
        quote = " ".join(quote.split())
        quote_data[day] = quote
        with open("quotes.json", "w") as f:
            json.dump(quote_data, f)
        return jsonify({
            day : quote
        }), statusCode
    if request.method == "DELETE":
        if day in quote_data:
            statusCode = 200
        else:
            return {}, 404
        del quote_data[day]
        with open("quotes.json", "w") as f:
            json.dump(quote_data, f)
        return {}, statusCode

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5050)


from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense, Dropout
from sklearn.preprocessing import MinMaxScaler
from keras.utils.vis_utils import plot_model
from matplotlib import pyplot as plt
import numpy as np
from sklearn.metrics import classification_report, confusion_matrix
import random
from pickle import dump

n = 132395
n_train = 92677
n_val = 11915

dataSet = loadtxt('AppDDoS.csv', delimiter=',');
random.shuffle(dataSet)
X = dataSet[:, 0:39]
singleY = dataSet[:,43]

i = 0
listY = []
for val in singleY:
	listY.append([0])
	if (val > 0) :
		listY[i][0] = 1
	i += 1

Y = np.array(listY)

trainX, testX = X[:n_train], X[n_train:]
trainY, testY = Y[:n_train], Y[n_train:]

valX = testX[:n_val]
valY = testY[:n_val]
testX = testX[n_val:]
testY = testY[n_val:]

scaler = MinMaxScaler()
scaler.fit(X)

normalizedTrain = scaler.transform(trainX)
normalizedTest = scaler.transform(testX)
normalizedVal = scaler.transform(valX)

model = Sequential()
model.add(Dense(32, input_dim=trainX.shape[1], activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(8, activation='relu'))
#model.add(Dense(8, activation='relu'))
#model.add(Dense(10, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

history = model.fit(
	normalizedTrain,
	trainY,
	epochs=100,
	 batch_size=32,
	 validation_data=(normalizedVal, valY))

#print(model.summary())
#plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)
print(history.history.keys())
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()

plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()

_, accuracy = model.evaluate(normalizedTest, testY)
predictions = model.predict(normalizedTest)

print(predictions[0])

y_pred = predictions > 0.5

#matrix = confusion_matrix(testY.argmax(axis=1), y_pred.argmax(axis=1))
matrix = confusion_matrix(testY, y_pred)

print(matrix)
print('Accuracy: %.2f' % (accuracy*100))

model.save('model.h5')
dump(scaler, open('scaler.pkl', 'wb'))


import requests
if __name__ == '__main__':
    header = {
        "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.34"
    }

    url = 'https://www.sogou.com/web'
    search_word = input('enter word: ')
    param = {
        'query': search_word
    }

    response = requests.get(url=url,params=param,headers=header)
    print(response.text)
    file_name = search_word+'.html'
    print(file_name)
    with open(file_name,'w',encoding='utf-8') as f:
        f.write(response.text)

    print(file_name,'game over')


import jwt
from aiohttp import web
from api.models import Persons
import configparser
import app
from api import utils
config = configparser.ConfigParser()
config.read('config.ini')

@web.middleware
async def auth_middleware(request, handler):
    request.user = None
    jwt_token = request.headers.get('Authorization', None)

    if jwt_token:
        if jwt_token.startswith('Bearer '):
            jwt_token = jwt_token[7:]
        try:
            payload = jwt.decode(
                jwt_token, config["DEFAULT"]['JWT_SECRET'], algorithms= [config["DEFAULT"]['JWT_ALGORITHM']])
        except (jwt.DecodeError, jwt.ExpiredSignatureError):
            await utils.service_log(request)
            return web.json_response(
                {'message': 'Token is invalid'}, status=400)
        db_session = app.DBSession()
        request.user = db_session.query(Persons).filter(Persons.id == payload['user_id']).first()
        # Create log with user.id.
        await utils.service_log(request)
    return await handler(request)


# Filename: train.py
# Description: Train a model on a single gpu for image classification task
# Author: Udari Madhushani

import os
import argparse
import torch
import numpy as np
from omegaconf import OmegaConf
import torchinfo

from assets.models import CNNSimple
from assets.utils import get_dataloaders, get_metadata
from assets.trainers import VanillaTrainer

# Usage: CUDA_VISIBLE_DEVICES=0 python train.py --configs ./assets/configs.yml --override_args dataset.name=cifar10

def main():
    parser = argparse.ArgumentParser(description="Robust residual learning")

    parser.add_argument(
        "--configs",
        type=str,
        default="./assets/configs.yml",
        help="path to config file that provides common configs")
    parser.add_argument(
        '--override_args',
        type=str,
        nargs="*",
        help=
        'orverride (or add new ones) specific configs values with cmd line args (dot-list format)'
    )

    args = parser.parse_args()  # parse command line args first
    cfg = OmegaConf.load(args.configs)  # load args from config file
    # override args from config file with command line args
    if args.override_args is not None:
        cfg = OmegaConf.merge(cfg, OmegaConf.from_dotlist(args.override_args))
    cfg = OmegaConf.merge(cfg, OmegaConf.create(vars(args)))  # add args to cfg
    print(cfg)

    # setup logging
    os.makedirs(cfg.core.save_dir, exist_ok=True)

    # set device to "cuda:0" if gpu is available else "cpu". When using multiple
    # gpus in DistributedDataParallel, the device should be set to "cuda:local_rank"
    # so "cuda:0", "cuda:1", etc. where local_rank is the rank of the process.
    device = "cuda:0"

    # set seed for reproducibility
    np.random.seed(cfg.core.seed)
    torch.manual_seed(cfg.core.seed)
    torch.cuda.manual_seed(cfg.core.seed)

    # set up training and validation dataloaders
    metadata = get_metadata(cfg.dataset.name)
    train_loader, val_loader = get_dataloaders(cfg.dataset.name,
                                               cfg.dataset.data_dir, metadata,
                                               cfg.optimization.batch_size,
                                               cfg.dataset.workers)

    # set up model
    model = CNNSimple(
        in_channels=metadata.num_channels,  # type: ignore
        num_classes=metadata.num_classes)  # type: ignore
    model = model.to(device)  # move model to device
    print(
        torchinfo.summary(
            model,
            input_size=(
                1,
                metadata.num_channels,  # type: ignore
                metadata.image_size,  # type: ignore
                metadata.image_size),  # type: ignore
            col_names=("input_size", "output_size", "num_params",
                       "kernel_size", "mult_adds"),
        ))

    # set up optimizers
    optimizer = torch.optim.SGD(model.parameters(),
                                lr=cfg.optimization.lr,
                                momentum=cfg.optimization.momentum,
                                weight_decay=cfg.optimization.weight_decay)
    # set up learning rate scheduler (decay learning rate after each epochs)
    # One can also decay learning rate after each batch, where the total number of steps
    # would be num_epochs * num_batches_per_epoch in the cosine annealing scheduler. There
    # one would call lrs.step() after each batch. We call it only after each epoch for simplicity.
    lrs = torch.optim.lr_scheduler.CosineAnnealingLR(
        optimizer, T_max=cfg.optimization.epochs, eta_min=0.0)
    loss_fxn = torch.nn.CrossEntropyLoss()

    # Let's train the model!!!
    trainer = VanillaTrainer(model,
                             train_loader,
                             val_loader,
                             optimizer,
                             loss_fxn,
                             lrs,
                             device,
                             cfg.core.print_freq,
                             verbose=True)
    trainer.train_all_epochs(cfg.optimization.epochs)

if __name__ == "__main__":
    main()


import tkinter as tk
from tkinter import ttk
from random import randint
import simpleaudio as sa
import os
import simpleaudio as sa

class KidsGame(tk.Tk):

    def __init__(self):
        super().__init__()

        self.num1 = tk.StringVar()
        self.num2 = tk.StringVar()

        self.count = 0

        # Creating window
        self.title('Math game')
        self.resizable(0, 0)
        self.geometry('315x130')
        self['bg'] = 'lightblue'

        # Creating num1 label
        self.labelNum1 = ttk.Label(
            self,
            text=self.get_Num1(),
            font = ('Digital-7', 40))

        self.labelNum1.place(x=15, y=20)

        # Styling labels
        self.styleLabel = ttk.Style(self)
        self.styleLabel.configure(
            'TLabel',
            background = 'lightblue',
            foreground = 'black')

        self.labelPlus = ttk.Label(
            self,
            text='+',
            font=('Digital', 35))

        # Creating num2 label
        self.labelNum2 = ttk.Label(
            self,
            text=self.get_Num2(),
            font = ('Digital-7', 40))

        self.labelNum2.place(x=117, y=20)

        self.labelEquals = ttk.Label(
            self,
            text='=',
            font=('Digital', 35))

        self.entrySum = ttk.Entry(
            self,
            font=('Digital', 40))

        self.entrySum.place(x=235, y=25, width=65, height=50)

        # Creating a button to start timer with
        self.checkAnswer = ttk.Button(
            self,
            text='Check answer',
            command=lambda:self.check_Sum(self.entrySum))

        self.checkAnswer.place(x=175, y=90)

        # Creating button for refreshing numbers
        self.refreshNums = ttk.Button(
            self,
            text='Refresh',
            command=lambda:self.call_Both()) # Calling 2 functions at once

        self.counterLabel = ttk.Label(
            self,
            text=self.count
        )

        self.counterLabel.place(x=5, y=5)

        self.refreshNums.place(x=55, y=90)

        self.get_Places()

    def get_Num1(self):
        self.randomNum1 = randint(1, 50)

        return self.randomNum1

    def get_Num2(self):
        self.randomNum2 = randint(1, 50)

        return self.randomNum2

    def check_Sum(self, entrySum):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        correctSoundFilePath = dir_path + '\\correctSound.wav'
        incorrectSoundFilePath = dir_path + '\\incorrectSound.wav'
        correctSound = sa.WaveObject.from_wave_file(correctSoundFilePath)
        incorrectSound = sa.WaveObject.from_wave_file(incorrectSoundFilePath)

        sum = self.randomNum1 + self.randomNum2

        if entrySum.get() == str(sum):
            print('Correct result')
            self.count += 1
            self.get_Count()
            correctSound.play()
            self.entrySum.delete(0, 'end')
            self.update_Nums()
        else:
            print('Incorrect result')
            incorrectSound.play()
            self.count = 0
            self.entrySum.delete(0, 'end')
            self.get_Count()

    def update_Nums(self):
        self.labelNum1.config(text=self.get_Num1())
        self.labelNum2.config(text=self.get_Num2())

        self.get_Places()

        self.entrySum.delete(0, 'end') # Clearing entry box

    def get_Places(self):
        self.get_current_Nums()

        # Setting conditions for placing '=' sign
        if self.curNum1 > 9 and self.curNum2 < 10:
            self.labelEquals.place(x=188, y=22)
            self.labelNum2.place(x=133, y=20)
        if  self.curNum1 <= 9 and self.curNum2 >= 10:
            self.labelEquals.place(x=192, y=22)
            self.labelNum2.place(x=122, y=20)
        if self.curNum1 > 9 and self.curNum2 >= 10:
            self.labelEquals.place(x=193, y=22)
            self.labelNum2.place(x=118, y=20)
        if self.curNum1 <= 9 and self.curNum2 < 10:
            self.labelEquals.place(x=187, y=22)
            self.labelNum2.place(x=136, y=20)

        # Setting conditions for placing '+' sign
        if self.curNum1 > 9 and self.curNum2 < 10:
            self.labelPlus.place(x=85, y=22)
        if self.curNum1 > 9 and self.curNum2 >= 10:
            self.labelPlus.place(x=84, y=22)
        if self.curNum1 <= 9 and self.curNum2 >= 10:
            self.labelPlus.place(x=72, y=22)
        if self.curNum1 <= 9 and self.curNum2 < 10:
            self.labelPlus.place(x=72, y=22)

    def get_current_Nums(self):
        self.curNum1 = self.randomNum1
        self.curNum2 = self.randomNum2

        return self.curNum1, self.curNum2

    def get_Count(self):
        self.counterLabel.config(text=self.count)

    def minus_One(self):
        if self.count != 0:
            self.count -= 1
        self.update_Nums()
        self.get_Count()

    def call_Both(self):
        self.update_Nums()
        self.minus_One()

if __name__ == "__main__":
    game = KidsGame()
    game.mainloop()


# Item 30: Consider @property instead of refactoring attributes
from datetime import timedelta
import datetime

# The built-in @property decorator makes it easy for simple accesses of an
# instance's attributes to act smarter (see Item 29: "Use plain attributes
# instead of get and set methods"). One advanced but common use of @property
# is transitioning what was once a simple numerical attribute into an
# on-the-fly calculation. This is extremely helpful because it lets you
# migrate all existing usage of a class to have new behaviors without
# rewriting any of the call sites. It also provides an important stopgap for
# improving your interfaces over time.

# For example, say you want to implement a leaky bucket quota using plain
# Python objects. Here, the Bucket class represents how much quota remains
# and the duration for which the quota will be available:

class Bucket(object):
    def __init__(self, period):
        self.period_delta = timedelta(seconds=period)
        self.reset_time = datetime.datetime.now()
        self.quota = 0

    def __repr__(self):
        return 'Bucket(quota=%d)' % self.quota

# The leaky bucket algorithm works by ensuring that, whenever the bucket is
# filled, the amount of quota does not carry over from one period to the next.

def fill(bucket, amount):
    now = datetime.datetime.now()
    if now - bucket.reset_time > bucket.period_delta:
        bucket.quota = 0
        bucket.reset_time = now
    bucket.quota += amount

# Each time a quota consumer wants to do something, it first must ensure that
# it can deduct the amount of quota it needs to use.

def deduct(bucket, amount):
    now = datetime.datetime.now()
    if now - bucket.reset_time > bucket.period_delta:
        return False
    if bucket.quota - amount < 0:
        return False
    bucket.quota -= amount
    return True

# To use this class, first I fill the bucket.

bucket = Bucket(60)
fill(bucket, 100)
print(bucket)
# Bucket(quota=100)

# Then, I deduct the quota that I need.

if deduct(bucket, 99):
    print('Had 99 quota')
else:
    print('Not enough for 99 quota')
print(bucket)
# Had 99 quota
# Bucket(quota=1)

# Eventually, I'm prevented from making progress because I try to deduct more
# quota than is available. In this case, the bucket's quota level remains
# unchanged.

if deduct(bucket, 3):
    print('Had 3 quota')
else:
    print('Not enough for 3 quota')
print(bucket)
# Not enough for 3 quota
# Bucket(quota=1)

# The problem with this implementation is that I never know that quota level
# the bucket started with. The quota is deducted over the course of the period
# until it reaches zero. At that point, deduct will always return False. When
# that happens, it would be useful to know whether callers to deduct are being
# blocked because the Bucket ran out of quota or because the Bucket never had
# quota in the first place.

# To fix this, I can change the class to keep track of the max_quota issued in
# the period and the quota_consumed in the period.

class Bucket(object):
    def __init__(self, period):
        self.period_delta = timedelta(seconds=period)
        self.reset_time = datetime.datetime.now()
        self.max_quota = 0
        self.quota_consumed = 0

    def __repr__(self):
        return ('Bucket(max_quota=%d, quota_consumed=%d)' %
                (self.max_quota, self.quota_consumed))

# I use a @property method to compute the current level of quota on-the-fly
# using these new attributes.
    @property
    def quota(self):
        return self.max_quota - self.quota_consumed

# When the quota attribute is assigned, I take special action matching the
# current interface of the class used by fill and decuct.
    @quota.setter
    def quota(self, amount):
        delta = self.max_quota - amount
        if amount == 0:
            '''quota being reset for a new period'''
            self.quota_consumed = 0
            self.max_quota = 0
        elif delta < 0:
            '''quota being filled for the new period'''
            assert self.quota_consumed == 0
            self.max_quota = amount
        else:
            '''quota being consumed during the period'''
            assert self.max_quota >= self.quota_consumed
            self.quota_consumed += delta

# Rerunning the demo code from above produces the same results.

bucket = Bucket(60)
print('Initial', bucket)
fill(bucket, 100)
print('Filled', bucket)

if deduct(bucket, 99):
    print('Had 99 quota')
else:
    print('Not enough for 99 quota')
print('Now', bucket)

if deduct(bucket, 3):
    print('Had 3 quota')
else:
    print('Not enough for 3 quota')
print('Still', bucket)
# Initial Bucket(max_quota=0, quota_consumed=0)
# Filled Bucket(max_quota=100, quota_consumed=0)
# Had 99 quota
# Now Bucket(max_quota=100, quota_consumed=99)
# Not enough for 3 quota
# Still Bucket(max_quota=100, quota_consumed=99)

# The best part is that the code using Bucket.quota doesn't have to change or
# know that the class has changed. New usage of Bucket can do the right thing
# and access max_quota and quota_consumed directly.

# I especially like @property because it lets you make incremental progress
# toward a better data model over time. Reading the Bucket example above, you
# may have though to yourself, "fill and deduct should have been implemented
# as instance methods in the first place." Although you're probably right (see
# Item 22: "Prefer helper classes over bookkeeping with dictionaries and
# tuples"), in practice there are many situations in which objects start with
# poorly defined interfaces or act as dumb data containers. This happens when
# code grows over time, scope increases, multiple authors contribute without
# any one considering long-term hygiene, etc.

# @property is a tool to help you address problems you'll come across in real-
# world code. Don't overuse it. When you find yourself repeatedly extending
# @property methods, it's probably time to refactor your class instead of
# further paving over your code's poor design.

# Things to remember

# 1. Use @property to give existing instance attributes new functionality.
# 2. Make incremental progress toward better data models by using @property.
# 3. Consider refactoring a class and all call sites when you find yourself
#     using @property too heavily.


#!/usr/bin/env python
#-*- coding: utf-8 -*-
# Florian THIBORD (22/08/17)
########################################################
#                  OptimiR - SamCleaner                #
########################################################
# Filter reads with more than NB_MM mismatches
# BUG in Bowtie2: allow indels in alignment seed while no mismatch is allowed in local mode

import sys

from pysam import AlignmentFile
from Bio import SeqIO

#Retrieve seqs from fastq of failed alignments
#Output: mono mapping deleted alignments
def alignments_to_seqs(reads, fastq_fn):
    fastq_dict = SeqIO.index(fastq_fn, 'fastq') # MUCH FASTER!!!!
    seqs_to_keep = []
    for read in reads:
        seq = fastq_dict[read]
        seqs_to_keep.append(seq)
    return seqs_to_keep

def delete_alignment(alignment, NB_MM):
    nb_mismatchs = alignment.get_tag('NM')
    read_len = alignment.query_length
    delete = False
    if (nb_mismatchs > NB_MM):
        delete = True
    return delete

# Delete alignment if:
#  - mm in alignment
# If deleted alignment read is mono mapping, then put it back in failed alignments .fastq
def clean_sam(sam_fn, clean_sam_fn, orig_fq_fn, NB_MM):
    sam = AlignmentFile(sam_fn, 'r')
    clean_sam = AlignmentFile(clean_sam_fn, 'wb', template=sam)
    reads_kept = set()
    reads_deleted = set()
    for alignment in sam:
        if delete_alignment(alignment, NB_MM):
            reads_deleted.add(alignment.query_name)
        else:
            clean_sam.write(alignment)
            reads_kept.add(alignment.query_name)
    # only add alignment to fastq if read involved hasn't been kept on a cross-mapping loci
    keep_as_failed_list = []
    for read in reads_deleted:
        if not(read in reads_kept):
            keep_as_failed_list.append(read)
    seqs_failed = alignments_to_seqs(keep_as_failed_list, orig_fq_fn)
    ## Print discarded alignments in fastq
    fastq_output_fn = sam_fn[:-7] + ".cl.fq"
    SeqIO.write(seqs_failed, fastq_output_fn, 'fastq')
    ## Print in log file
    log_clean = open("{}.SamCleaner.log".format(sam_fn[:-7]), 'a')
    cpt_treated = len(reads_kept) + len(reads_deleted)
    log_clean.write('Number of alignments treated : {}\nNumber of alignment kept : {}\nNumber of alignments deleted : {}\n'.format(cpt_treated, len(reads_kept), len(reads_deleted)))
    log_clean.close()
    clean_sam.close()

def main(sam_filename, orig_fq_fn, NB_MM):
    sam_fn = sam_filename
    clean_sam_fn = "{}.ok.sam".format(sam_fn[:-7])
    clean_sam(sam_fn, clean_sam_fn, orig_fq_fn, NB_MM)


import logging
import sys
from pathlib import Path
from typing import List

from torch import Tensor, Size
from tqdm import tqdm

from config import ConfigDict
from loader.utils.reader import label_read, gray_read
from pipeline.iqa import IQA
from pipeline.saliency import Saliency

def check_image(root: Path, img_list: List[str]):
    assert (root / 'ir').exists() and (root / 'vi').exists(), f'ir and vi folders are required'
    for img_name in img_list:
        if not (root / 'ir' / img_name).exists() or not (root / 'vi' / img_name).exists():
            logging.fatal(f'empty img {img_name} in {root.name}')
            sys.exit(1)
    logging.info('find all images on list')

def check_iqa(root: Path, img_list: List[str], config: ConfigDict):
    iqa_cache = True
    if (root / 'iqa').exists():
        for img_name in img_list:
            if not (root / 'iqa' / 'ir' / img_name).exists() or not (root / 'iqa' / 'vi' / img_name).exists():
                iqa_cache = False
                break
    else:
        iqa_cache = False
    if iqa_cache:
        logging.info(f'find iqa cache in folder, skip information measurement')
    else:
        logging.info(f'find no iqa cache in folder, start information measurement')
        iqa = IQA(url=config.iqa.url)
        iqa.inference(src=root, dst=root / 'iqa')

def check_labels(root: Path, img_list: List[str]) -> List[Tensor]:
    assert (root / 'labels').exists(), f'labels folder is required'
    labels = []
    for img_name in img_list:
        label_name = Path(img_name).stem + '.txt'
        if not (root / 'labels' / label_name).exists():
            logging.fatal(f'empty label {label_name} in {root.name}')
            sys.exit(1)
        labels.append(label_read(root / 'labels' / label_name))
    logging.info('find all labels on list')
    return labels

def check_mask(root: Path, img_list: List[str], config: ConfigDict):
    mask_cache = True
    if (root / 'mask').exists():
        for img_name in img_list:
            if not (root / 'mask' / img_name).exists():
                mask_cache = False
                break
    else:
        mask_cache = False
    if mask_cache:
        logging.info('find mask cache in folder, skip saliency detection')
    else:
        logging.info('find no mask cache in folder, start saliency detection')
        saliency = Saliency(url=config.saliency.url)
        saliency.inference(src=root / 'ir', dst=root / 'mask')

def get_max_size(root: Path, img_list: List[str]):
    max_h, max_w = -1, -1
    logging.info('find suitable size for prediction')
    img_l = tqdm(img_list)
    for img_name in img_l:
        img_l.set_description('finding suitable size')
        img = gray_read(root / 'ir' / img_name)
        max_h = max(max_h, img.shape[1])
        max_w = max(max_w, img.shape[2])
    logging.info(f'max size in dataset: H:{max_h} x W:{max_w}')
    return Size((max_h, max_w))


import cv2
import numpy
from imutils.contours import sort_contours
from tensorflow.keras.models import load_model
import numpy as np
import imutils
import tensorflow as tf
from tensorflow.compat.v1 import InteractiveSession
import time

def find(contours, count):
	d = {}
	for cnt in contours:
		x, y, w, h = cv2.boundingRect(cnt)
		d[w * h] = cnt
	list_d = list(d.items())
	list_d.sort(key=lambda i: i[0])
	new_cnts = []
	for i in range(len(list_d) - count, len(list_d)):
		new_cnts.append(list_d[i][1])
	return new_cnts

def blob(image):
	(tH, tW) = image.shape
	if tW > tH:
		thresh = imutils.resize(image, width=32)
	else:
		thresh = imutils.resize(image, height=32)
	padded = cv2.copyMakeBorder(image, top=12, bottom=12,
								left=16, right=16, borderType=cv2.BORDER_CONSTANT,
								value=(0, 0, 0))
	padded = cv2.resize(padded, (32, 32), cv2.INTER_CUBIC)
	padded = padded.astype("float32") / 255.0
	padded = np.expand_dims(padded, axis=-1)
	return padded

def getContours(img, count):
	img = cv2.medianBlur(img, 9)
	thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \
								   cv2.THRESH_BINARY, 11, 2)
	edged = cv2.Canny(thresh, 80, 150)

	cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
	new_cnts = []
	for c in cnts:
		x, y, w, h = cv2.boundingRect(c)
		if (w >= 5 and w <= 150) and (h >= 15 and h <= 200):
			new_cnts.append(c)
	cnts = new_cnts
	cnts = find(cnts, count)
	return cnts

def getChars(image, cnts):
	image = cv2.threshold(image, 150, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
	chars = []
	for cnt in cnts:
		x, y, w, h = cv2.boundingRect(cnt)
		char = image[y:y + h, x:x + w]
		char = blob(char)
		chars.append(char)
	return chars

def getLabels(model, chars, cnts, labelNames):
	chars = np.array([c for c in chars], dtype="float32")
	preds = model.predict([chars])
	answers = {}
	for i in range(len(cnts)):
		cnt = cnts[i]
		pred = preds[i]
		x, y, w, h = cv2.boundingRect(cnt)
		i = np.argmax(pred)
		prob = pred[i]
		label = labelNames[i]
		answers[y] = label
	sorted_ans = sorted(answers.items())
	labels = []
	for k, v in sorted_ans:
		print(k, " ", v)
		labels.append(v)
	return labels

def detection(image_path, count):
	start = time.time()
	#image - путь к изображению
	#count - количество символов, включая id + ответы на сам тест
	###tf config###
	config = tf.ConfigProto()
	config.gpu_options.allow_growth = True
	session = InteractiveSession(config=config)
	##model and labels###
	model = load_model("model/handwriting.model")
	print(time.time()-start)
	labelNames = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	labelNames = [l for l in labelNames]

	img = cv2.imread(image_path, 0)
	img = cv2.resize(img, (480, 640), cv2.INTER_CUBIC)

	copy = img.copy()

	cnts = getContours(img, count)
	chars = getChars(copy, cnts)

	labels = getLabels(model, chars, cnts, labelNames)
	print(time.time()-start)
	return labels


from kivy.uix.scatter import Scatter
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.app import App
from kivy.uix.scatterlayout import ScatterLayout
from kivy.graphics.transformation import Matrix
from kivy.uix.codeinput import CodeInput
from kivy.uix.checkbox import CheckBox
from pygments.lexers import CythonLexer
from kivy.uix.widget import Widget
from kivy.animation import Animation
from kivy.uix.switch import Switch
from kivy.properties import BooleanProperty, ObjectProperty, NumericProperty
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

class MyCodeInput(CodeInput):

    def __init__(self, size, **kwargs):
        super(MyCodeInput, self).__init__(**kwargs)
        x = size[0]
        y = size[1]
        chunk = x * .30
        self.size_hint = (None,None)
        self.size = (x - chunk,y)
        # self.pos = (10,0)
        self.pos_hint = {'x': .15, 'y': 0}
        self.lexer = CythonLexer()

    def Deactivate(self):
        self.disabled = True

    def Activate(self):
        self.disabled = False

    def update(self, size):
        x = size[0]
        y = size[1]
        print("code")
        print(x)
        chunk = x * .30
        self.size_hint = (None,None)
        self.size = (x - chunk,y)

class MyButton(Button):

    def __init__(self, size, **kwargs):
        super(MyButton, self).__init__(**kwargs)
        x = size[0]
        y = size[1]
        chunk = x * .85
        self.size_hint = (None, None)
        self.size = (x - chunk,y)
        # self.pos = (690,0)
        self.pos_hint = {'x': .85, 'y': 0}
        # self.size_hint = (.15,1)
        self.text = "Move"

    def update(self, size):
        x = size[0]
        y = size[1]
        print("button")
        print(x)
        chunk = x * .85
        self.size_hint = (None, None)
        self.size = (x - chunk,y)

class MyCheckBox(CheckBox):

    def __init__(self, size, **kwargs):
        super(MyCheckBox, self).__init__(**kwargs)
        self.pos_hint = {'x': 0, 'y': 0}
        x = size[0]
        y = size[1]
        chunk = x * .85
        self.size_hint = (None, None)
        self.size = (x - chunk,y)

    def Deactivate(self):
        self.disabled = True

    def Activate(self):
        self.disabled = False

    def update(self, size):
        self.pos_hint = {'x': 0, 'y': 0}
        x = size[0]
        y = size[1]
        chunk = x * .85
        self.size_hint = (None, None)
        self.size = (x - chunk,y)

class MyRunButton(Button):

    def __init__(self, size, **kwargs):
        super(MyRunButton, self).__init__(**kwargs)
        x = size[0]
        y = size[1]
        chunk = x * .85
        self.size_hint = (None, None)
        self.size = (x - chunk,y/2)
        # self.pos = (690,0)
        self.pos_hint = {'x': .85, 'y': 0}
        # self.size_hint = (.15,1)
        self.text = "Run"

    def update(self, size):
        x = size[0]
        y = size[1]
        chunk = x * .85
        self.size_hint = (None, None)
        self.size = (x - chunk,y/2)

class MyScatterLayout(ScatterLayout):
    move_lock = False
    scale_lock_left = False
    scale_lock_right = False
    scale_lock_top = False
    scale_lock_bottom = False
    col = 1,1,1,1
    disp = 1

    def __init__(self, **kwargs):
        super(MyScatterLayout, self).__init__(**kwargs)
        self.size = (800,400)
        self.pos = (400,400)
        self.size_hint = (None, None)
        self.check = MyCheckBox(self.size, id = "check")
        self.code = MyCodeInput(self.size, id = "code")
        self.move = MyButton(self.size, id = "switch")
        self.run = MyRunButton(self.size, id = "run")
        self.move.bind(on_press=self.flip)
        self.add_widget(self.check)
        self.add_widget(self.code)
        self.add_widget(self.move)
        self.add_widget(self.run)

    def flip(self, button):
        if self.disp:
            self.disp = 0
        else:
            self.disp = 1
        self.flipTheSwitch()

    def flipTheSwitch(self):
        if self.disp:
            self.check.Deactivate()
            self.code.Deactivate()

        else:
            self.check.Activate()
            self.code.Activate()

    def on_touch_up(self, touch):
        self.move_lock = False
        self.scale_lock_left = False
        self.scale_lock_right = False
        self.scale_lock_top = False
        self.scale_lock_bottom = False
        if touch.grab_current is self:
            touch.ungrab(self)
            x = self.pos[0] / 10
            x = round(x, 0)
            x = x * 10
            y = self.pos[1] / 10
            y = round(y, 0)
            y = y * 10
            self.pos = x, y
            return super(MyScatterLayout, self).on_touch_up(touch)

    def transform_with_touch(self, touch):
        changed = False
        x = self.bbox[0][0]
        y = self.bbox[0][1]
        width = self.bbox[1][0]
        height = self.bbox[1][1]
        mid_x = x + width / 2
        mid_y = y + height / 2
        inner_width = width * 0.5
        inner_height = height * 0.5
        left = mid_x - (inner_width / 2)
        right = mid_x + (inner_width / 2)
        top = mid_y + (inner_height / 2)
        bottom = mid_y - (inner_height / 2)

            # just do a simple one finger drag
        if len(self._touches) == self.translation_touches:
            # _last_touch_pos has last pos in correct parent space,
            # just like incoming touch
            dx = (touch.x - self._last_touch_pos[touch][0]) \
                 * self.do_translation_x
            dy = (touch.y - self._last_touch_pos[touch][1]) \
                 * self.do_translation_y
            dx = dx / self.translation_touches
            dy = dy / self.translation_touches
            if (touch.x > left and touch.x < right and touch.y < top and touch.y > bottom or self.move_lock) and not self.scale_lock_left and not self.scale_lock_right and not self.scale_lock_top and not self.scale_lock_bottom:
                self.move_lock = True
                self.apply_transform(Matrix().translate(dx, dy, 0))
                changed = True

        change_x = touch.x - self.prev_x
        change_y = touch.y - self.prev_y
        anchor_sign = 1
        sign = 1
        if abs(change_x) >= 9 and not self.move_lock and not self.scale_lock_top and not self.scale_lock_bottom:
            if change_x < 0:
                sign = -1
            if (touch.x < left or self.scale_lock_left) and not self.scale_lock_right:
                self.scale_lock_left = True
                self.pos = (self.pos[0] + (sign * 10), self.pos[1])
                anchor_sign = -1
            elif (touch.x > right or self.scale_lock_right) and not self.scale_lock_left:
                self.scale_lock_right = True
            self.size[0] = self.size[0] + (sign * anchor_sign * 10)
            self.prev_x = touch.x
            changed = True
        if abs(change_y) >= 9 and not self.move_lock and not self.scale_lock_left and not self.scale_lock_right:
            if change_y < 0:
                sign = -1
            if (touch.y > top or self.scale_lock_top) and not self.scale_lock_bottom:
                self.scale_lock_top = True
            elif (touch.y < bottom or self.scale_lock_bottom) and not self.scale_lock_top:
                self.scale_lock_bottom = True
                self.pos = (self.pos[0], self.pos[1] + (sign * 10))
                anchor_sign = -1
            self.size[1] = self.size[1] + (sign * anchor_sign * 10)
            self.prev_y = touch.y
            changed = True
        if changed:
            self.check.update(self.size)
            self.code.update(self.size)
            self.move.update(self.size)
        return changed

    def on_touch_down(self, touch):
        x, y = touch.x, touch.y
        self.prev_x = touch.x
        self.prev_y = touch.y
        # if the touch isnt on the widget we do nothing
        if not self.do_collide_after_children:
            if not self.collide_point(x, y):
                return False

        # let the child widgets handle the event if they want
        touch.push()
        touch.apply_transform_2d(self.to_local)
        if super(Scatter, self).on_touch_down(touch):
            # ensure children don't have to do it themselves
            if 'multitouch_sim' in touch.profile:
                touch.multitouch_sim = True
            touch.pop()
            self._bring_to_front(touch)
            return True
        touch.pop()

        # if our child didn't do anything, and if we don't have any active
        # interaction control, then don't accept the touch.
        if not self.do_translation_x and \
                not self.do_translation_y and \
                not self.do_rotation and \
                not self.do_scale:
            return False

        if self.do_collide_after_children:
            if not self.collide_point(x, y):
                return False

        if 'multitouch_sim' in touch.profile:
            touch.multitouch_sim = True
        # grab the touch so we get all it later move events for sure
        self._bring_to_front(touch)
        touch.grab(self)
        self._touches.append(touch)
        self._last_touch_pos[touch] = touch.pos
        print(self.size)
        return True

class WheatBlock(FloatLayout):

    def __init__(self, **kwargs):
        super(WheatBlock, self).__init__(**kwargs)
        self.s = MyScatterLayout(do_rotation=False)
        self.add_widget(self.s)


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

# Атрибуты дрона / Астероида

# coord - координаты собственного местоположения
# direction - курс корабля
# my_mathership - космобаза приписки
# asteroids - список всех астероидов на поле
# payload - кол-во элериума в трюме
# free_space - свободного места в трюме
# fullness - процент загрузки
# is_empty - трюм пустой
# is_full - трюм полностью забит элериумом

# Методы дрона
# turn_to(obj) - повернуться к объекту/точке
# move_at(obj) - двигаться к объекту/точке
# stop() – остановиться
# load_from(obj) - загрузить элериум от объекта в трюм
# unload_to(obj) - разгрузить элериум из трюма в объект
# distance_to(obj) - рассчет расстояния до объекта/точки
# near(obj) - дрон находится рядом с объектом/точкой
from enum import IntEnum
from math import sin, cos, pi, sqrt
from typing import Optional, List
from astrobox.core import Drone, Asteroid, MotherShip
from astrobox.space_field import SpaceField
from robogame_engine import scene
from robogame_engine.geometry import Vector, Point
from robogame_engine.theme import theme

class Commander:

    _instance = None
    _enemy: Drone = None
    _attack_points: List[Point] = []
    _enemies: List[Drone] = []
    _drones: List[Drone] = []
    _excluded_points: List[Point] = []
    _initial: bool = True
    _scene: SpaceField = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)

        return cls._instance

    def __init__(self, drone: Drone):
        self._drones.append(drone)
        self._scene = drone.scene

    @property
    def initial(self):
        return self._initial

    @initial.setter
    def initial(self, init):
        self._initial = init

    @property
    def enemy(self) -> Drone:
        return self._enemy

    @enemy.setter
    def enemy(self, enemy: Drone):
        self._enemy = enemy

    @property
    def attack_points(self) -> List[Point]:
        return self._attack_points

    @attack_points.setter
    def attack_points(self, points: List[Point]):
        self._attack_points = points

    @property
    def excluded_points(self) -> list:
        return self._excluded_points

    @property
    def enemies(self):
        return self._enemies

    @enemies.setter
    def enemies(self, enemies: List[Drone]):
        self._enemies = enemies

    @property
    def has_enemy(self):
        if self.enemy:
            return True

        return False

    @staticmethod
    def get_attack_points(center: Point, radius: int, size: int) -> list:
        """
            Возвращает точки атаки вокруг обозначенного центра
        """

        angles = int(360 / radius)
        size = size

        points = list()
        x, y = center.x, center.y

        for i in range(angles):
            x1 = x + size * cos(90 + (2 * pi * i) / angles)
            y1 = y + size * sin(90 + (2 * pi * i) / angles)
            points.append(Point(x1, y1))

        points = [point for point in points if int(point.x) in range(1200) and int(point.y) in range(600)]

        return points

    def get_enemies(self, drone):
        self.enemies = [enemy for enemy in drone.scene.drones
                        if enemy not in drone.teammates and enemy != drone and enemy.is_alive]

        self.enemies.extend([mother_ship for mother_ship in drone.scene.motherships
                             if mother_ship != drone.my_mothership and mother_ship.is_alive])

    def get_closest_enemy(self, drone):
        closest_enemy = self.enemies[0]

        for enemy in self.enemies:
            if drone.distance_to(enemy) < drone.distance_to(closest_enemy):
                closest_enemy = enemy

        return closest_enemy

    def get_attack_point(self, drone):
        """
            Выбирает незанятую точку атаки для дрона
        :param drone:
        :return:
        """

        if self.enemy and not self.enemy.is_alive:
            self._excluded_points = []

        self.get_enemies(drone=drone)

        if not self.enemies:
            drone.mode = DroneMode.DRONE_HARVESTER
            return drone.mothership

        self.enemy = self.get_closest_enemy(drone=drone)

        if self.enemy.state.target_point \
                and drone.distance_to(self.enemy) > drone.distance_to(self.enemy.state.target_point):
            target = self.enemy.state.target_point
        else:
            target = self.enemy.coord

        if self.enemy.state.target_point:
            self.attack_points = self.get_attack_points(target,
                                                        drone.radius,
                                                        drone.gun.shot_distance/2)
        elif type(self.enemy) == MotherShip:
            self.attack_points = self.get_attack_points(self.enemy.coord,
                                                        drone.radius/2,
                                                        drone.gun.shot_distance/2)
        else:
            self.attack_points = self.get_attack_points(Point(600, 300), drone.radius, drone.gun.shot_distance/2)

        for attack_point in self.attack_points:
            for excluded_point in self.excluded_points:
                if attack_point.x == excluded_point.x and attack_point.y == excluded_point.y:
                    break
            else:
                point = attack_point
                self.excluded_points.append(point)
                break
        else:
            point = drone.coord

        return point

class DroneMode(IntEnum):
    DRONE_HARVESTER = 1
    DRONE_INTERCEPTOR = 2

class IshmukhamedovDrone(Drone):

    _mode: DroneMode = DroneMode.DRONE_HARVESTER

    full_travel: int = 0
    empty_travel: int = 0
    underload_travel: int = 0

    _commander: Optional[Commander] = None
    _attack_point: Optional[Point] = None
    _enemy: Optional[Drone] = None

    _target: Optional[Asteroid] = None
    _teammates_targets: list = []
    except_targets: list = []

    @property
    def enemy(self):
        return self._enemy

    @enemy.setter
    def enemy(self, enemy):
        self._enemy = enemy

    @property
    def mode(self) -> DroneMode:
        return self._mode

    @mode.setter
    def mode(self, mode: DroneMode):
        self._mode = mode

    @property
    def target(self):
        """
            Метод-свойство возвращает астероид-цель.
        :return: Asteroid
        """
        return self._target

    @target.setter
    def target(self, target):
        self._target = target

    @property
    def teammates_targets(self) -> List[Asteroid]:
        """
            Возвращает список астероидов к которым летят другие дроиды из команды
        :return:
        """
        self._teammates_targets = []
        for teammate in self.teammates:
            self._teammates_targets.append(teammate.target)

        return self._teammates_targets

    def available_targets(self) -> List[Asteroid]:
        targets = [obj for obj in self.scene.objects
                   if obj.team != self.team and not obj.is_empty and obj not in self.except_targets]

        return targets

    def closest_target(self) -> Optional[Asteroid]:
        """
            Возвращает ближайщий к дрону астероид
        :return: Asteroid
        """
        asteroids = self.available_targets()

        if not asteroids:
            return None

        closest = asteroids[0]

        for asteroid in asteroids:
            if self.distance_to(closest) > self.distance_to(asteroid):
                closest = asteroid

        return closest

    def count_teammates(self, asteroid):
        """
            Считает количество дронов-однокомандников, летящих на один и тот-же астероид
        :param asteroid: Астероид для которого надо провести подсчет
        :return: Количество в виде dict('quantity': int, 'teammates': list, 'free_space': int)
        """
        free_space = 0
        teammates = [teammate for teammate in self.teammates if teammate.target == asteroid]

        for teammate in teammates:
            free_space += teammate.free_space

        return {'quantity': len(teammates), 'teammates': teammates, 'free_space': free_space}

    def get_target(self):
        closest = self.closest_target()

        if not closest:
            return []

        if closest not in self.teammates_targets:
            self.target = closest
        else:
            closest_info = self.count_teammates(closest)
            if closest.payload > closest_info['free_space']:
                self.target = closest
            else:
                if self.target:
                    if self.target in self.except_targets:
                        self.except_targets.remove(self.target)

                self.except_targets.append(closest)
                self.target = self.closest_target()

        return self.target

    @property
    def attack_point(self) -> Point:
        return self._attack_point

    @attack_point.setter
    def attack_point(self, point: Point):
        self._attack_point = point

    def shot(self, enemy):
        vector = Vector.from_points(self.coord, enemy.coord, module=1)
        self.vector = vector
        able_to_shot = True

        if any(self.point_in_circle(self.coord, teammate) for teammate in self.teammates) or \
                any(self.point_in_circle(self.coord, mother_ship.coord) for mother_ship in self.scene.motherships):
            point = self.make_a_step(self.coord, Point(scene.theme.FIELD_WIDTH/2, scene.theme.FIELD_HEIGHT/2))
            self.move_at(point)
            return

        for teammate in self.teammates:
            vector = Vector.from_points(self.coord, teammate.coord, module=1)
            difference = abs(self.vector.direction - vector.direction)
            distance = self.distance_to(teammate)

            if difference < 15 and distance < self.gun.shot_distance:
                able_to_shot = False
                break

        if able_to_shot and self.distance_to(enemy) <= self.gun.shot_distance:
            if enemy.is_moving:
                self.gun.shot(Point(enemy.coord.x+enemy.vector.x**enemy.vector.module,
                                    enemy.coord.y+enemy.vector.y**enemy.vector.module))
            else:
                self.gun.shot(enemy)

    def _calculate_statistics(self, destination):
        if self.is_empty:
            IshmukhamedovDrone.empty_travel += self.distance_to(destination)
        elif self.is_full:
            IshmukhamedovDrone.full_travel += self.distance_to(destination)
        else:
            IshmukhamedovDrone.underload_travel += self.distance_to(destination)

    def get_statistics(self):
        stat = [self.empty_travel, self.full_travel, self.underload_travel]
        return stat

    @property
    def commander(self) -> Commander:
        return self._commander

    @commander.setter
    def commander(self, commander: Commander):
        self._commander = commander

    def teammates_attack_points(self):

        attack_points = []

        for teammate in self.teammates:
            attack_points.append(teammate.attack_point)

        return attack_points

    @staticmethod
    def check_attack_point(point: Point, points: List[Point]):
        """
            Проверяет наличие точки в списке точек
        :param point: Точка для проверки
        :param points: Список точек
        :return: True если точка есть и False если нет
        """
        for attack_point in points:
            if attack_point and attack_point.x == point.x and attack_point.y == point.y:
                return True

        return False

    def on_born(self):
        self.commander = Commander(drone=self)

        distance = theme.MOTHERSHIP_HEALING_DISTANCE

        if self.have_gun:
            self.mode = DroneMode.DRONE_INTERCEPTOR

            attack_points = self.commander.get_attack_points(self.my_mothership.coord, (len(self.teammates)+1)*4,
                                                             distance*1.5)
            for point in attack_points:
                teammates_attack_points = self.teammates_attack_points()
                if not self.check_attack_point(point, teammates_attack_points):
                    self.attack_point = point
                    break
            else:
                self.attack_point = self.commander.get_attack_point(drone=self)

            self.move_at(self.attack_point)
        else:
            self.move_at(self.get_target())

    def make_a_step(self, start: Point, destination: Point, ratio: float = 2/8) -> Point:
        """
            Возвращает точку в направлении от start до destination
        :param start: Начальная точка
        :param destination: Точка назначения
        :param ratio: Отпределяет в каком отношении точка делит отрезок.
        :return: Точку на отрезке start - destination
        """

        x = (start.x+ratio*destination.x)/(1+ratio)
        y = (start.y+ratio*destination.y)/(1+ratio)

        distance = 5*self.radius

        teammates = [teammate for teammate in self.teammates if self.point_in_circle(Point(x, y), teammate.coord)]

        if not teammates:
            return Point(x, y)
        else:
            points = self.commander.get_attack_points(center=Point(x, y), radius=36, size=distance)
            if (points):
                return points[0]
            return Point(x, y)

    def find_closest_enemy(self):

        enemies = [enemy for enemy in self.scene.drones
                   if enemy not in self.teammates and enemy != self and enemy.is_alive]

        if not enemies:
            enemies.extend([mother_ship for mother_ship in self.scene.motherships
                            if mother_ship != self.my_mothership and mother_ship.is_alive])

        if enemies:
            closest_enemy = enemies[0]
        else:
            return

        for enemy in enemies:
            if self.distance_to(enemy) < self.distance_to(closest_enemy):
                closest_enemy = enemy

        return closest_enemy

    def point_in_circle(self, point, center):
        radius = 2*self.radius

        in_circle = sqrt(pow(center.x-point.x, 2)+pow(center.y-point.y, 2))

        if in_circle <= radius:
            return True

        return False

    def get_common_enemy(self):
        closest_enemy = self.find_closest_enemy()
        for teammate in self.teammates:
            if teammate.enemy and teammate.enemy.is_alive:
                if self.distance_to(teammate.enemy) < self.distance_to(closest_enemy):
                    return teammate.enemy

        return closest_enemy

    def action(self):
        if self.health < 75:
            if self.distance_to(self.my_mothership) > theme.MOTHERSHIP_HEALING_DISTANCE:
                point = self.make_a_step(self.coord, self.my_mothership.coord, 5 / 5)
                self.move_at(point)
        else:
            closest_enemy = self.find_closest_enemy()
            if closest_enemy:
                if self.distance_to(closest_enemy) <= self.gun.shot_distance:
                    self.shot(closest_enemy)
                else:
                    point = self.make_a_step(self.coord, closest_enemy.coord)
                    self.move_at(point)
            else:
                self.mode = DroneMode.DRONE_HARVESTER

    def on_stop(self):
        if self.mode == DroneMode.DRONE_INTERCEPTOR:
            self.action()
        else:
            self.move_at(self.my_mothership)

    def on_stop_at_target(self, target):
        for asteroid in self.asteroids:
            if asteroid.near(target):
                self.on_stop_at_asteroid(asteroid)
                return
        else:
            for ship in self.scene.motherships:
                if ship.near(target):
                    if ship == self.my_mothership:
                        self.on_stop_at_mothership(ship)
                    else:
                        self.on_stop_at_enemy_mothership(ship)

                    return

        self.on_stop_at_point(target)

    def on_stop_at_enemy_mothership(self, mothership):
        if not mothership.is_alive:
            self.load_from(mothership)

    def on_stop_at_point(self, target):
        if self.mode == DroneMode.DRONE_HARVESTER:
            enemy_drones = [drone for drone in self.scene.drones if drone not in self.teammates and not drone.is_empty]
            for drone in enemy_drones:
                if drone.near(target):
                    self.on_stop_at_enemy_drone(drone)
                    return

    def on_stop_at_asteroid(self, asteroid):
        if self.mode == DroneMode.DRONE_INTERCEPTOR:
            self.action()
        else:
            self.load_from(asteroid)

    def on_stop_at_enemy_drone(self, drone):
        self.load_from(drone)

    def on_load_complete(self):
        if self.is_full:
            self.move_at(self.my_mothership)
        else:
            target = self.get_target()
            if target:
                self.move_at(target)
            else:
                self.move_at(self.my_mothership)

        self.target = None

    def on_stop_at_mothership(self, mothership):
        if self.mode == DroneMode.DRONE_INTERCEPTOR:
            self.attack_point = self.commander.get_attack_point(drone=self)
            self.move_at(self.attack_point)
        else:
            if self.is_empty:
                target = self.get_target()
                if target:
                    self.move_at(target)
                else:
                    self.move_at(self.my_mothership)
            else:
                if mothership is self.my_mothership:
                    self.unload_to(mothership)
                else:
                    self.load_from(mothership)

    def on_unload_complete(self):
        target = self.get_target()
        if target:
            self.move_at(target)
        else:
            self.stop()

    def on_wake_up(self):
        if self.mode == DroneMode.DRONE_INTERCEPTOR:
            self.action()
        else:
            self.move_at(self.my_mothership)

drone_class = IshmukhamedovDrone