import typing as t
from datetime import datetime, timedelta, timezone
from operator import itemgetter

import pytest

from valuable import load
from valuable.utils import compose

def dataclass_or_skip(*args, **kwargs):
    """create a dataclass or skip the test"""
    dataclasses = pytest.importorskip('dataclasses')
    return dataclasses.make_dataclass(*args, **kwargs)

def test_list_loader():
    assert load.list_loader((int, ), [4, '3', '-1']) == [4, 3, -1]

def test_set_loader():
    assert load.set_loader((int, ), [4, '3', '-1']) == {4, 3, -1}

def test_lookup_default():
    getter = load.lookup_defaults(itemgetter('foo'), 'bla')
    assert getter({}) == 'bla'
    assert getter({'foo': 4}) == 4

class TestPrimitiveRegistry:

    def test_found(self):
        registry = load.PrimitiveRegistry({int: round})
        loader = registry(int)
        assert loader(3.4) == 3

    def test_not_found(self):
        registry = load.PrimitiveRegistry({int: round})
        with pytest.raises(load.UnsupportedType):
            registry(str)

class TestGenericRegistry:

    def test_ok(self):

        Tag = t.NamedTuple('Tag', [('name', str)])

        registry = load.GenericRegistry({
            t.List: load.list_loader,
        }) | load.PrimitiveRegistry({
            Tag: compose(Tag, '<{}>'.format),
        })

        # simple case
        loader = registry(t.List[Tag])
        assert loader(['hello', 5, 'there']) == [
            Tag('<hello>'), Tag('<5>'), Tag('<there>')
        ]

        # recursive case
        loader = registry(t.List[t.List[Tag]])
        assert loader([
            ['hello', 9, 'there'],
            [],
            ['another', 'list']
        ]) == [
            [Tag('<hello>'), Tag('<9>'), Tag('<there>')],
            [],
            [Tag('<another>'), Tag('<list>')]
        ]

    def test_unsupported_type(self):

        Tag = t.NamedTuple('Tag', [('name', str)])

        registry = load.GenericRegistry({
            t.List: load.list_loader,
        }) | load.PrimitiveRegistry({
            Tag: compose(Tag, '<{}>'.format),
        })
        with pytest.raises(load.UnsupportedType):
            registry(t.Set[Tag])

        with pytest.raises(load.UnsupportedType):
            registry(t.List[str])

        with pytest.raises(load.UnsupportedType):
            registry(object)

class TestGetOptionalLoader:

    def test_ok(self):

        Tag = t.NamedTuple('Tag', [('name', str)])

        registry = load.PrimitiveRegistry({
            Tag: compose(Tag, '<{}>'.format)
        }) | load.get_optional_loader

        loader = registry(t.Optional[Tag])
        assert loader(None) is None
        assert loader(5) == Tag('<5>')

class TestParseIso8601:

    def test_with_timezone(self):
        parsed = load.parse_iso8601('2012-02-27T13:08:00+0100')
        assert parsed == datetime(
            2012, 2, 27, 13, 8,
            tzinfo=timezone(timedelta(hours=1)))

    def test_no_timezone(self):
        parsed = load.parse_iso8601('2014-06-10T17:25:29Z')
        assert parsed == datetime(2014, 6, 10, 17, 25, 29)

def test_dataclass_registry(registry):

    Post = dataclass_or_skip('Post', [
        ('title', str),
        ('posted_at', datetime),
        ('author_id', int)
    ])

    data = {
        'Title':     'hello',
        'date':      '2017-10-18T14:13:05Z',
        'author_id': 12,
    }

    registry |= load.DataclassRegistry({
        Post: {
            'title':     itemgetter('Title'),
            'posted_at': itemgetter('date'),
            'author_id': itemgetter('author_id'),
        }
    })

    loader = registry(Post)

    assert loader(data) == Post(
        'hello',
        datetime(2017, 10, 18, 14, 13, 5),
        author_id=12)

    Foo = dataclass_or_skip('Foo', [])

    with pytest.raises(load.UnsupportedType):
        registry(Foo)

def test_create_dataclass_loader(registry):
    User = dataclass_or_skip('User', [
        ('id', int),
        ('name', str),
        ('hobbies', t.Optional[t.List[str]]),
        ('nicknames', t.Set[str]),
        ('height', float),
        ('likes_pizza', t.Optional[bool], True),
    ])

    dloader = load.create_dataclass_loader(User, registry, {
        'id':          itemgetter('id'),
        'name':        itemgetter('username'),
        'likes_pizza': itemgetter('pizza'),
        'height':      itemgetter('height'),
        'nicknames':   itemgetter('nicknames'),
        'hobbies':     itemgetter('hobbies'),
    })
    assert dloader({
        'id': 98,
        'username': 'wilma',
        'hobbies': ['tennis', 'diving'],
        'pizza': 'true',
        'height': 1.64,
        'nicknames': []
    }) == User(98, 'wilma', hobbies=['tennis', 'diving'],
               likes_pizza=True, height=1.64, nicknames=set())

class TestAutoDataclassRegistry:

    def test_ok(self, registry):

        Post = dataclass_or_skip('Post', [
            ('title', str),
            ('posted_at', datetime),
        ])

        registry |= load.AutoDataclassRegistry()
        loader = registry(Post)

        data = {
            'title':     'hello',
            'posted_at': '2017-10-18T14:13:05Z'
        }
        assert loader(data) == Post(
            'hello',
            datetime(2017, 10, 18, 14, 13, 5))

    def test_not_supported(self, registry):

        class MyClass():
            pass

        registry |= load.AutoDataclassRegistry()

        with pytest.raises(load.UnsupportedType):
            registry(MyClass)

def test_simple_registry():

    User = dataclass_or_skip('User', [
        ('name', str),
        ('id', int),
        ('nickname', t.Optional[str]),
    ])

    Post = dataclass_or_skip('Post', [
        ('title', str),
        ('user', User),
        ('comments', t.List[str])
    ])

    loader = load.simple_registry(Post)

    loaded = loader({
        'title': 'hello',
        'comments': ['first!', 'another comment', 5],
        'user': {
            'name': 'bob',
            'nickname': 'bobby',
            'id': '543',
            'extra data': '...',
        }
    })
    assert loaded == Post(
        title='hello',
        comments=['first!', 'another comment', '5'],
        user=User(
            name='bob',
            id=543,
            nickname='bobby'
        )
    )


from sys import argv, exit
import pandas as pd
import numpy as np
from sklearn.ensemble import AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from gensim.models.doc2vec import Doc2Vec

class Classificador():

    def salvar_scores(self, scores, label):

        pt = open('d2v_clfs/pvdm_random_'+label+'.txt', 'w')
        for score in scores:
            pt.write(str(score)+'\n')
        pt.close()

    def pre_proc(self, df):

        # Pré processamento do dataset.
        # Definindo quais vão ser as categorias enviadas para classificação.
        categorias_finais = ['tec', 'esporte',
                             'ilustrada', 'mercado', 'poder', 'mundo']

        categorias_diluidas = list(
            set(df['category']) - set(categorias_finais))

        # Agrupando coluna de tecnologia com ciência.
        df["category"] = df["category"].replace("ciencia", "tec")

        # Criando dataset com categorias finais para teste
        docs_classif = df  # .copy(deep=True)#.sample(frac=1)
        for cat in categorias_diluidas:
            docs_classif = docs_classif[docs_classif['category'] != cat]

        docs_sem_classif = df  # .copy(deep=True)#.sample(frac=1)
        for cat in categorias_finais:
            docs_sem_classif = docs_sem_classif[docs_sem_classif['category'] != cat]

        return docs_classif, docs_sem_classif

    def dataset_treino(self, docs_classif, docs_sem_classif, modelo):

        vetores_treino = list()
        classes_treino = list()

        vetores_teste = list()
        classes_teste = list()

        for index, row in docs_classif.iterrows():
            try:
                vetores_treino.append(modelo['DOC_'+str(index)])
                classes_treino.append(row['category'])
            except:
                print("PADRÃO: ", index)

        for index, row in docs_sem_classif.iterrows():
            try:
                vetores_teste.append(modelo['DOC_'+str(index)])
                classes_teste.append(row['category'])
            except:
                print("GENÉRICOS: ", index)

        docs_classif["vetor"] = vetores_treino
        docs_classif["classe"] = classes_treino
        docs_sem_classif["vetor"] = vetores_teste

    def cross_valid(self, clf, vetores, classes):

        scores = cross_val_score(clf, vetores, classes,
                                 cv=5, scoring='f1_macro', n_jobs=25)
        print("F1-Measure: ", scores)

    def avaliar_classificacao(self, treino, alg=1, vezes=1):

        scores = []

        label = {
            1: "LogisticRegression",
            2: "GaussianNB",
            3: "MLPClassifier",
            4: "AdaBoostClassifier",
            5: "LinearSVC",
            6: "KNeighborsClassifier",
            7: "RandomForestClassifier"
        }

        for i in range(0, vezes):

            # Regressão Logistica.
            if alg == 1:
                print("Aplicando: ", label[alg])
                clf = LogisticRegression(
                    random_state=1, max_iter=300, solver='saga')
            # Naive Bayes.
            elif alg == 2:
                print("Aplicando: ", label[alg])
                clf = GaussianNB()
            # Rede Neural.
            elif alg == 3:
                print("Aplicando: ", label[alg])
                clf = MLPClassifier(solver='adam', hidden_layer_sizes=(
                    100), learning_rate_init=0.002, learning_rate='adaptive', max_iter=200)
            elif alg == 4:
                print("Aplicando: ", label[alg])
                clf = clf = AdaBoostClassifier(n_estimators=100)
            elif alg == 5:
                print("Aplicando: ", label[alg])
                clf = LinearSVC(random_state=0, tol=1e-5)
            elif alg == 6:
                print("Aplicando: ", label[alg])
                clf = KNeighborsClassifier(n_neighbors=3)
            elif alg == 7:
                print("Aplicando: ", label[alg])
                clf = RandomForestClassifier(max_depth=2, random_state=0)

            kf = KFold(n_splits=5, shuffle=True, random_state=None)
            scores += list(cross_val_score(clf, list(treino['vetor']), list(treino['classe']),
                                cv=kf, scoring='f1_macro', n_jobs=25))
        print("F1-Measure: ", label[alg], scores)
        self.salvar_scores(scores, label[alg])

    def treinar(self, treino, alg):

        # Regressão Logistica.
        if alg == 1:
            clf=LogisticRegression(
                random_state=0, max_iter=150, solver='sag')  # C=0.8)
        # Naive Bayes.
        elif alg == 2:
            clf=GaussianNB()
        # Rede Neural.
        elif alg == 3:
            clf=MLPClassifier(solver='adam', hidden_layer_sizes=(100), learning_rate_init=0.002,
                                learning_rate='adaptive', max_iter=200)
        else:
            clf=RandomForestClassifier(max_depth=2, random_state=0)

        self.cross_valid(clf, list(treino['vetor']), list(treino['classe']))

    def classificar(self, treino, teste, alg):

        # Regressão Logistica.
        if alg == 1:
            clf=LogisticRegression(
                random_state=0, max_iter=150, solver='sag')  # , C=0.8)
        # Naive Bayes.
        elif alg == 2:
            clf=GaussianNB()
        # Rede Neural.
        elif alg == 3:
            clf=MLPClassifier(solver='adam', alpha=1e-5,
                                hidden_layer_sizes=(100, 2), random_state=1, learning_rate='adaptive', max_iter=300)
        elif alg == 5:
            print("Aplicando: LinearSVC")
            clf=LinearSVC(random_state=0, tol=1e-5)
        else:
            clf=RandomForestClassifier(max_depth=2, random_state=0)

        clf.fit(list(treino['vetor']), list(treino['classe']))

        # Classificando as novas amostras.
        classificados=clf.predict(list(teste['vetor']))
        teste["classe"]=classificados
        ndf_teste=teste.drop(columns=['vetor'])
        ndf_treino=treino.drop(columns=['vetor'])
        ndf=pd.concat([ndf_treino, ndf_teste]).sort_index()
        ndf.to_csv('../dados/classificados.csv', index=False)

    def executar(self, dataset, caminho_modelo, operacao='treinar', alg=1):

        modelo=Doc2Vec.load(caminho_modelo)
        df=pd.read_csv(dataset)
        docs_classif, docs_sem_classif=self.pre_proc(df)
        self.dataset_treino(docs_classif, docs_sem_classif, modelo)
        if operacao == 'treinar':
            self.treinar(docs_classif, alg)
        elif operacao == 'classif':
            self.classificar(docs_classif, docs_sem_classif, alg)
        else:
            vezes = 6
            for algoritimo in range(1, 8):
                self.avaliar_classificacao(docs_classif, algoritimo, vezes)

if __name__ == '__main__':

    c=Classificador()
    c.executar(argv[1], argv[2], argv[3], int(argv[4]))


import sys
import re
import uuid

try:
    file = open('input.txt', 'r')
    string = file.read()
    words = re.split('[ \n]', string)
    unique,li = [],[]
    c_to,c_ing=0,0
    count_dict={}
    word_dict={}
    palindromes=[]
    index=0
    for x in words:
        unique.append(x)
    for x in unique:
        if x.startswith('To'):
            c_to+=1
        if x.endswith('ing'):
            c_ing+=1
        count_dict[x]=unique.count(x)
        word_dict[index]=x
        index+=1
        if x==x[::-1]:
            palindromes.append(x)
    str_max=list(sorted(count_dict.items(),key=lambda x:x[1], reverse=True))[0][0]
    print("count 'To':",c_to,"\ncount 'ing':",c_ing)
    print("repeted string:",str_max)
    print("palindromes:",palindromes)
    print("word dict:",word_dict)
    for i in range(len(words)):
        li.extend(re.split('a|e|i|o|u|A|E|I|O|U', words[i]))
        li=' '.join(li).split()
    for i in range(len(li)):
        if (i+1)%5==0:
            li[i]=li[i].upper()

    filen=str(uuid.uuid4())
    filen+='.txt'
    with open(filen,"x") as f:
        f.write("-".join(li))

except Exception as e:
    print (e)


import argparse
import re
from pathlib import Path

def check(dataset: Path):
    print(f"Start checking tesseract data: {dataset}")

    # Check if all objects has related txt file
    for img_path in dataset.glob('*.png'):
        tesseract_txt_path = dataset / f"{img_path.stem}.gt.txt"

        if not tesseract_txt_path.exists():
            print(
                f"Provide Tesseract {tesseract_txt_path.name} file for object '{img_path.name}'")
            continue

        fixed_img_name = re.sub('[() ]', '_', img_path.name)

        if fixed_img_name != img_path.name:
            print(f"Rename invalid file name {img_path.name} to {fixed_img_name}")
            img_path = img_path.rename(dataset / fixed_img_name)
            tesseract_txt_path = tesseract_txt_path.rename(
                dataset / f"{img_path.stem}.gt.txt")

        # Check how many lines in each tesseract txt file
        with open(tesseract_txt_path, 'r') as txt:
            lines_count = sum(1 for _ in txt)

            if lines_count != 1:
                print(
                    f"'{tesseract_txt_path.name}' file contains wrong line numbers: {lines_count}. Should be 1!")

    print("Tesseract data checked.")

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Check tesseract train data')

    parser.add_argument('--dataset',
                        default='./tesseract/eng_seeneva-ground-truth',
                        help='Tesseract train dataset')

    args = parser.parse_args()

    check(Path(args.dataset))


from fastapi import APIRouter

from city_details.api.api_v1.routes import health_checker_router, ui_router, city_router

__author__ = "Rohit Warke"
__date_created__ = "2021-08-05"
__purpose__ = "The routers are required to add here. Within each router, we add the routes (endpoints)"

router = APIRouter()
router.include_router(city_router.CityRouter.router, tags=["city-details"])
router.include_router(health_checker_router.router, tags=["maintenance"])
router.include_router(ui_router.UIRouter.router, tags=["ui-portal"])


from __future__ import print_function
from flask import Flask
import soco
from threading import Thread

# Page scraping
import requests
from bs4 import BeautifulSoup
from dateutil.parser import parse
import operator

app = Flask(__name__)
print("Server started.")

def get_sonos():
    sonos = soco.discovery.any_soco()
    if not sonos.group:
        return sonos
    return sonos.group.coordinator

def get_latest_playlist():
    base = 'https://www.npr.org/programs/'
    urls = {
        'all_things_considered': 'all-things-considered/',
        'weekend_edition': 'weekend-edition-saturday/',
        'weekend_edition_sunday': 'weekend-edition-sunday/',
        'morning_edition': 'morning-edition/'
    }
    dates = {}
    m3u = {}

    for program, url in urls.items():
        url = base + url
        page = requests.get(url)
        soup = BeautifulSoup(page.text, 'html.parser')
        audioLabels = soup.find_all(class_='audio-tool-label')
        dates[program] = parse(
            soup.find("div", {"class": "current"}).find("time")['datetime'])

        files = []
        for a in audioLabels:
            if (a.text == 'Download'):
                p = a.parent
                href = p.get('href')
                href = href.split('?')[0]
                #story_title = a.find_parent('article', {"class": "rundown-segment"}).find('h3', {"class": "rundown-segment__title"}).find('a').text
                story_title = "Title"
                files.append([href, story_title])

        m3u[program] = files

    # Get latest program
    if m3u["all_things_considered"] == []:
        del dates['all_things_considered']
    if m3u["morning_edition"] == []:
        del dates['morning_edition']
    if m3u["weekend_edition"] == []:
        del dates['weekend_edition']
    if m3u["weekend_edition_sunday"] == []:
        del dates['weekend_edition_sunday']

    if 'morning_edition' in dates and 'all_things_considered' in dates and dates['morning_edition'] == dates['all_things_considered']:
        del dates['morning_edition']
    if 'weekend_edition' in dates and 'all_things_considered' in dates and dates['all_things_considered'] == dates['weekend_edition']:
        del dates['weekend_edition']
    if 'weekend_edition_sunday' in dates and 'all_things_considered' in dates and dates['all_things_considered'] == dates['weekend_edition_sunday']:
        del dates['weekend_edition_sunday']
    latest = max(dates.items(), key=operator.itemgetter(1))[0]

    return m3u[latest]

def start_npr():
    # Grab the Sonos
    s = get_sonos()

    # Create a group with all devices
    s.partymode()

    # Stop and clear queue
    s.stop()
    s.clear_queue()

    # Set volume to 25%
    if not s.group:
        s.volume = 25
    else:
        for g in s.group.members:
            g.volume = 25

    # Send the playlist and start playing
    playlist = get_latest_playlist()
    for mp3 in playlist:
        print("Adding MP3: %s" % mp3)
        s.add_uri_to_queue(mp3[0])
    s.play_from_queue(0)
    return "OK"

@app.route("/listen", methods=['POST','GET'])
def listen():
    print("Starting...")
    Thread(target=start_npr).start()
    return "OK"

@app.route("/pause")
def pause():
    print("Pausing")
    s = get_sonos()
    s.pause()
    return "OK"

@app.route("/resume")
def resume():
    print("Resuming track")
    s = get_sonos()
    s.play()
    return "OK"

@app.route("/skip")
def skip():
    print("Skipping track")
    s = get_sonos()
    s.next()
    return "OK"

@app.route("/volumeup")
def volumeup():
    print("Turning volume up")
    sonos = get_sonos()
    vol = sonos.volume
    sonos.volume = vol+10
    return "OK"

@app.route("/volumedown")
def volumedown():
    print("Turning volume down")
    sonos = get_sonos()
    vol = sonos.volume
    sonos.volume = vol-10
    return "OK"


import json
from Device import *
from enum import IntEnum

class StateRinging(IntEnum):
    # 서브폰의 호출 상태
    IDLE = 0
    FRONT = 1  # 현관문 초인종
    COMMUNAL = 2  # 공동출입문

class StateDoorLock(IntEnum):
    Unsecured = 0
    Secured = 1
    Jammed = 2
    Unknown = 3

class SubPhone(Device):
    state_streaming: int = 0
    state_ringing: StateRinging = StateRinging.IDLE
    state_ringing_prev: StateRinging = StateRinging.IDLE
    state_doorlock: StateDoorLock = StateDoorLock.Secured

    def __init__(self, name: str = 'SubPhone', index: int = 0, room_index: int = 0):
        super().__init__(name, index, room_index)
        self.dev_type = DeviceType.SUBPHONE
        self.unique_id = f'subphone_{self.room_index}_{self.index}'
        self.mqtt_publish_topic = f'home/state/subphone/{self.room_index}/{self.index}'
        self.mqtt_subscribe_topic = f'home/command/subphone/{self.room_index}/{self.index}'
        self.setHomeAssistantConfigTopic()
        self.sig_state_streaming = Callback(int)
        self.streaming_config = {
            'conf_file_path': '',
            'feed_path': '',
            'input_device': '/dev/video0',
            'frame_rate': 24,
            'width': 320,
            'height': 240,
        }

    def setDefaultName(self):
        self.name = 'SubPhone'

    def publishMQTT(self):
        if self.mqtt_client is not None:
            obj = {
                "streaming_state": self.state_streaming,
                "doorlock_state": self.state_doorlock.name,  # 도어락은 상태 조회가 안되고 '열기' 기능만 존재한다
            }
            self.mqtt_client.publish(self.mqtt_publish_topic, json.dumps(obj), 1)

            if self.state_ringing != self.state_ringing_prev:  # 초인종 호출 상태 알림이 반복적으로 뜨는 것 방지
                writeLog(f"Ringing Publish: Prev={bool(self.state_ringing.name)}, Current={self.state_ringing_prev.name}", self)
                if self.state_ringing in [StateRinging.FRONT, StateRinging.COMMUNAL]:
                    # obj = {"doorbell_state": 'ON'}
                    self.mqtt_client.publish(self.mqtt_publish_topic + '/doorbell', 'ON', 1)
                else:
                    # obj = {"doorbell_state": 'OFF'}
                    self.mqtt_client.publish(self.mqtt_publish_topic + '/doorbell', 'OFF', 1)

    def setHomeAssistantConfigTopic(self):
        self.mqtt_config_topic = f'{self.ha_discovery_prefix}/lock/{self.unique_id}/config'

    def configMQTT(self):
        obj = {
            "name": self.name + "_doorlock",
            "object_id": self.unique_id + "_doorlock",
            "unique_id": self.unique_id + "_doorlock",
            "state_topic": self.mqtt_publish_topic,
            "command_topic": self.mqtt_subscribe_topic,
            "value_template": '{{ value_json.state }}',
            "payload_lock": '{ "state": "Secured" }',
            "payload_unlock": '{ "state": "Unsecured" }',
            "state_locked": "Secured",
            "state_unlocked": "Unsecured",
            "icon": "mdi:door-closed-lock"
        }
        if self.mqtt_client is not None:
            self.mqtt_client.publish(self.mqtt_config_topic, json.dumps(obj), 1, True)

    def updateState(self, _: int, **kwargs):
        streaming = kwargs.get('streaming')
        if streaming is not None:
            self.state_streaming = streaming
            self.sig_state_streaming.emit(self.state_streaming)
            self.publishMQTT()
        ringing_front = kwargs.get('ringing_front')
        if ringing_front is not None:
            if ringing_front:
                self.state_ringing = StateRinging.FRONT
            else:
                self.state_ringing = StateRinging.IDLE
            self.publishMQTT()
            self.state_ringing_prev = self.state_ringing
        ringing_communal = kwargs.get('ringing_communal')
        if ringing_communal is not None:
            if ringing_communal:
                self.state_ringing = StateRinging.COMMUNAL
            else:
                self.state_ringing = StateRinging.IDLE
            self.publishMQTT()
            self.state_ringing_prev = self.state_ringing
        doorlock = kwargs.get('doorlock')
        if doorlock is not None:
            self.state_doorlock = StateDoorLock(doorlock)
            self.publishMQTT()
        writeLog(f"Streaming: {bool(self.state_streaming)}, Ringing: {self.state_ringing.name}, DoorLock: {self.state_doorlock.name}", self)

    def makePacketCommon(self, header: int) -> bytearray:
        return bytearray([0x7F, max(0, min(0xFF, header)), 0x00, 0x00, 0xEE])

    def makePacketSetVideoStreamingState(self, state: int) -> bytearray:
        if state:
            if self.state_ringing == StateRinging.FRONT:
                # 현관 초인종 카메라 영상 서브폰 우회
                return self.makePacketCommon(0xB7)
            elif self.state_ringing == StateRinging.COMMUNAL:
                # 공동현관문 영상 우회
                return self.makePacketCommon(0x5F)
            else:
                # 단순 문열기용 (주방 서브폰 활성화)
                return self.makePacketCommon(0xB9)
        else:
            if self.state_ringing == StateRinging.FRONT:
                # 현관 초인종 카메라 영상 서브폰 우회 종료
                return self.makePacketCommon(0xB8)
            elif self.state_ringing == StateRinging.COMMUNAL:
                # 공동현관문 영상 우회 종료
                return self.makePacketCommon(0x60)
            else:
                # 단순 문열기용 (주방 서브폰 활성화)
                return self.makePacketCommon(0xBA)

    def makePacketOpenFrontDoor(self) -> bytearray:
        # 현관 초인종 카메라 영상이 서브폰으로 우회된 상태에서 도어락 해제
        return self.makePacketCommon(0xB4)

    def makePacketOpenCommunalDoor(self) -> bytearray:
        # 공동현관문 호출 후 카메라 영상이 우회된 상태에서 열림 명령
        return self.makePacketCommon(0x61)

    def makePacketSetOuterDoorCamState(self, state: int) -> bytearray:
        if state:
            pass
        else:
            pass


"""
@leofansq
https://github.com/leofansq
"""
import cv2

from rgblgray import rgblgray

def main(filename):
    """
    Main function
    """
    # Read image
    print ("Processing {} ...".format(filename))
    img = cv2.imread(filename)

    # BGR 2 RGB
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # BGR 2 RGB

    # Call function: rgblgray
    img_gray_a = rgblgray(img, 'average')
    img_gray_NTSC = rgblgray(img, 'NTSC')

    # Save image
    cv2.imwrite("{}_average.png".format(filename[:-4]), img_gray_a)
    cv2.imwrite("{}_NTSC.png".format(filename[:-4]), img_gray_NTSC)

if __name__ == "__main__":

    main("lena512color.tiff")
    main("mandril_color.tif")


import numpy as np
import h5py
from astropy.time import Time
import os
from joblib import Parallel, delayed

def gps2dyr(time):
    """ Convert GPS time to decimal years. """
    return Time(time, format='gps').decimalyear

def track_type(time,lat,tmax=1):
    """
    Separate tracks into ascending and descending.

    Defines tracks as segments with time breaks > tmax,
    and tests whether lat increases or decreases w/time.
    """
    tracks = np.zeros(lat.shape)  # generate track segment
    tracks[0:np.argmax(np.abs(lat))] = 1  # set values for segment
    i_asc = np.zeros(tracks.shape,dtype=bool)  # output index array

    # Loop trough individual segments
    for track in np.unique(tracks):

        i_track, = np.where(track == tracks)  # get all pts from seg

        if len(i_track) < 2: continue

        # Test if lat increases (asc) or decreases (des) w/ time
        i_min = time[i_track].argmin()
        i_max = time[i_track].argmax()
        lat_diff = lat[i_track][i_max] - lat[i_track][i_min]

        # Determine track type
        if lat_diff > 0:  i_asc[i_track] = True

    return i_asc,np.invert(i_asc)  # index vectors

def process(fname,bbox=None):
    """
    Read 1 ATL06 file and output 6 reduced files.

    Extract variables of interest and separate the ATL06 file
    into each beam (ground track) and ascending/descending orbits.
    """

    # Each beam is a group
    group = ['/gt1l','/gt1r','/gt2l','/gt2r','/gt3l','/gt3r']

    # Loop trough beams
    for k,g in enumerate(group):  # 6 groups for 6 beams

        # -----------------------------------#
        # 1) Read in data for a single beam #
        # -----------------------------------#

        # Load variables into memory (more can be added!)
        with h5py.File(fname,'r') as fi:
            lat = fi[g + '/land_ice_segments/latitude'][:]
            lon = fi[g + '/land_ice_segments/longitude'][:]
            h_li = fi[g + '/land_ice_segments/h_li'][:]
            h_li_sigma = fi[g + '/land_ice_segments/h_li_sigma'][:]
            t_dt = fi[g + '/land_ice_segments/delta_time'][:]
            q_flag = fi[g + '/land_ice_segments/atl06_quality_summary'][:]
            dem_h = fi[g + '/land_ice_segments/dem/dem_h'][:]
            bsnow_h = fi[g + '/land_ice_segments/geophysical/bsnow_h'][:]
            bsnow_conf = fi[g + '/land_ice_segments/geophysical/bsnow_conf'][:]
            bsnow_od = fi[g + '/land_ice_segments/geophysical/bsnow_od'][:]
            cloud_flg_asr = fi[g + '/land_ice_segments/geophysical/cloud_flg_asr'][:]
            cloud_flg_atm = fi[g + '/land_ice_segments/geophysical/cloud_flg_atm'][:]
            msw_flag = fi[g + '/land_ice_segments/geophysical/msw_flag'][:]
            t_ref = fi['/ancillary_data/atlas_sdp_gps_epoch'][:]
            orb = np.full_like(h_li,k)

        # ---------------------------------------------#
        # 2) Filter data according region and quality #
        # ---------------------------------------------#

        # Select a region of interest
        if bbox:
            lonmin,lonmax,latmin,latmax = bbox
            bbox_mask = (lon >= lonmin) & (lon <= lonmax) & \
                        (lat >= latmin) & (lat <= latmax)
        else:
            bbox_mask = np.ones_like(lat,dtype=bool)  # get all

        # Only keep good data, and data inside bbox
        mask = (q_flag == 0) & (np.abs(h_li) < 10e3) & (bbox_mask == 1)

        # Update variables
        lat,lon,h_li,h_li_sigma,t_dt,q_flag,dem_h,bsnow_conf,bsnow_h,bsnow_od,cloud_flg_asr,cloud_flg_atm,msw_flag = \
            lat[mask],lon[mask],h_li[mask],h_li_sigma[mask],t_dt[mask],q_flag[mask],dem_h[mask], \
            bsnow_conf[mask],bsnow_h[mask],bsnow_od[mask], \
            cloud_flg_asr[mask],cloud_flg_atm[mask],msw_flag[mask]

        # Test for no data
        if len(h_li) == 0:
            print('ERROR from read_atl06(): granule found with zero length <<h_li>>\n')
            continue

        # -------------------------------------#
        # 3) Convert time and separate tracks #
        # -------------------------------------#

        # Time in GPS seconds (secs sinde 1980...)
        t_gps = t_ref + t_dt

        # Time in decimal years
        t_year = gps2dyr(t_gps)

        # Determine orbit type
        i_asc,i_des = track_type(t_year,lat)

        # -----------------------#
        # 4) Save selected data #
        # -----------------------#

        # Define output file name
        ofile = fname.replace('.h5','_') + 'reduced.h5'

        # Save variables
        with h5py.File(ofile,'a') as f:
            f[g[1:] + '/orbit'] = orb
            f[g[1:] + '/lon'] = lon
            f[g[1:] + '/lat'] = lat
            f[g[1:] + '/t_year'] = t_year
            f[g[1:] + '/t_sec'] = t_gps
            f[g[1:] + '/q_flag'] = q_flag
            f[g[1:] + '/h_li'] = h_li
            f[g[1:] + '/h_li_sigma'] = h_li_sigma
            f[g[1:] + '/dem_h'] = dem_h
            f[g[1:] + '/bsnow_conf'] = bsnow_conf
            f[g[1:] + '/bsnow_h'] = bsnow_h
            f[g[1:] + '/bsnow_od'] = bsnow_od
            f[g[1:] + '/cloud_flg_asr'] = cloud_flg_asr
            f[g[1:] + '/cloud_flg_atm'] = cloud_flg_atm
            f[g[1:] + '/msw_flag'] = msw_flag
            f[g[1:] + '/trk_type'] = i_asc

    print('out ->',ofile)

def process_all(dir,use_parallel=True,njobs=7):
    """ Processes all .h5 files in the given directory using process().
    """
    all_files = os.listdir(dir)
    os.chdir(dir)

    if '.DS_Store' in all_files: all_files.remove('.DS_Store')
    remove_these = []
    for fn in all_files:
        if '.h5' not in fn:
            remove_these.append(fn)
    for rfn in remove_these:
        all_files.remove(rfn)

    if not use_parallel:
        for fn in all_files:
            process(fn)
    else:
        Parallel(n_jobs=njobs,verbose=5)(delayed(process)(fn) for fn in all_files)

def read_h5(fname,vnames=[]):
    """ Simple HDF5 reader. """
    with h5py.File(fname,'r') as f:
        beam_keys = f.keys()
        data = dict()
        for bk in beam_keys:
            data[bk] = dict()
            if len(vnames) == 0:
                vnames = f[bk].keys()
            for vn in vnames:
                data[bk][vn] = f[bk][vn][:]
    return data


# Setup and login
import json
import os
import sys
import signal

class State:
    BEGIN = 0
    PENDING_URLS = 1
    PENDING_ITEMS = 2
    END = 3
    PENDING_URLS_ITEMS = 4

def get_job_template(job_name):
    return {
            "state": State.BEGIN,
            "name": job_name,
            "urls_queued": [],
            "urls_error": [],
            "execution_time": 0
        }

def save_job(file_job, job):
    with open(file_job, 'w') as f:
        json.dump(job, f, ensure_ascii=False, indent=4)

def load_job(file_job):
    with open(file_job) as f:
        return json.load(f)

def close_job_scrapper(is_completed, df):
    """Close the job. Requires global vars

    Args:
        is_completed (bool): _description_
        df (DataFrame): _description_
    """
    global scrapper_reference
    global file_job, job
    print(f"Stopping scraper...Completed: {is_completed} DF type: {type(df)}")
    scrapper_reference.stop = True
    print("Saving job...")

    pending = []
    if not is_completed:
        index_seen = scrapper_reference.cache.get("index_seen",-1)
        pending = scrapper_reference.cache.get("urls",[])
        if len(pending) > 0:
            pending = pending[index_seen+1:]

        df = scrapper_reference.cache.get("df", None)

    job['urls_queued'] = pending

    job['urls_error'] = scrapper_reference.cache.get("urls_error", [])
    save_job(file_job, job)

    if df is not None:
        folder_shards = os.path.join("shards")
        if not os.path.isdir(folder_shards):
            os.mkdir(folder_shards)

        df.to_csv(f"{folder_shards}/db_job-{job['name']}_items-run-{job['execution_time']}.csv", index=False)

    print(f"Closing with: {len(scrapper_reference.cache.get('urls',[])) -len(job['urls_queued'])} completed, {len(job['urls_queued'])} pending urls and {len(job['urls_error'])} error urls")

def signal_handler(sig, frame):
    close_job_scrapper(False, None)

    try:
        sys.exit()
    except:
        print("Problems with sys.exit!")
        sys.exit()

def process_job_scrapper(scrapper, fj, j, timers: dict):
    """Process_job in every item. The scrapper must be logged in if needed. And instance
    should have been open.

    Args:
        scrapper (_type_): _description_
        job (_type_): _description_
        timers (dict): _description_
    """
    global scrapper_reference
    global file_job, job
    file_job = fj
    job = j

    scrapper_reference = scrapper
    signal.signal(signal.SIGINT, signal_handler)

    state = job["state"]
    if state == State.BEGIN or state == State.PENDING_ITEMS:
        scrapper.stop = False
        urls_items = job["urls_queued"]
        urls_items.extend(job["urls_error"])  # try again the errors
        job["urls_error"] = []
        job["execution_time"] += 1

        print(f"Pending work...{len(urls_items)} urls in queue")

        df, completed = scrapper.scrape_items(timers, urls=urls_items)

        print("scrape_items ended")

        if completed and len(scrapper.cache["urls_error"]) == 0:
            job["state"] = State.END

        close_job_scrapper(completed, df)
    elif state == State.END:
        print("Work already completed!")
    else:
        print(f"Can't handle this state: {state}")


import re
import requests
import time
from pymongo import MongoClient
from bs4 import BeautifulSoup

def init_mongodb():
    #Mongo database and table
    db_client = MongoClient()
    db = db_client['case_test']
    # db = db_client['case_databse']
    coll = db.cases2001
    return db.cases2001
    # coll = db.cases
    # return db.cases

def case_scrape(cfile):
    '''
    need multiple queries, one for the actual text, one for cases ref(note: not all cases have the related case tag, might need to implement some RE to grap the rest), grab case title?
    '''
    r = requests.get(cfile)
    web_data=r.text
    soup = BeautifulSoup(web_data,'html.parser')
    '''
    from http://law.justia.com/cases/federal/appellate-courts/ca10/2000/ grabs all links of listed 2000 court cases
    note: started with 2017 cases but most were listed as pdf files while the 2000 cases were in a text format
    '''
    link_list=[]
    mylinks=soup.findAll('a',{'class':'case-name'})
    for l in mylinks:
        link_list.append(l['href'])
    return link_list

def link_scape(list_of_links, table):
    '''
    links in list_of_links only contain the second half of neede link, need to add base link to query them
    '''
    base_link='http://law.justia.com/'

    for i,v in enumerate(list_of_links):
        list_of_links[i]=base_link+v

    for lnk in list_of_links:
        link_r = requests.get(lnk)
        new_data=link_r.text
        link_soup = BeautifulSoup(new_data,'html.parser')
        #grabs full case text
        link_text=''
        for page in link_soup.findAll('div',{'class':'page'}):
            link_text+=page.get_text()
        title_text=''
        for x in link_soup.findAll('h1',{'class':'heading-1'}):
            title_text+=x.get_text()
        #makes list of case_ref
        #re expression to pull case refs
        re_list = re.findall('(\d+\s\D\.\D*\w+\s\d*)',link_text)
        add_new = [{'case_title':title_text,'case_text':link_text, 'case_ref':re_list}]
        table.insert(add_new)
        time.sleep(9)

        # outdated code, not all case refs had a class
        # case_ref=[]
        # mya = soup.findAll('a',{'class':'related-case'})
        # for a in mya:
        #     case_ref.append(a.text.strip())
if __name__ == '__main__':
    #start db
    # cases = init_mongodb()
    cases2001 = init_mongodb()
    #get links to scrape
    linklist = case_scrape('http://law.justia.com/cases/federal/appellate-courts/ca10/2001/')
    # case_scrape('http://law.justia.com/cases/federal/appellate-courts/ca10/2000/')

    #scrape and add data, just cases for train set
    link_scape(linklist,cases2001)


"""
This is a simple test file for working out how to use PyQt5 for our Schrodinger's Hack project.

This file simply creates a window application with a menu bar with additional submenus.

Author: Kondapuram Aditya Seshadri
Date: October 24, 2020
"""

import sys
from PyQt5.QtWidgets import (QMainWindow, QApplication, QStackedLayout,
                             QWidget, QPalette, QColor)

class Example(QMainWindow):

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

    def initUI(self):
        # Comment
        stacklayout = QStackedLayout()

        stacklayout.addWidget(Color('red'))
        stacklayout.addWidget(Color('green'))
        stacklayout.addWidget(Color('blue'))
        stacklayout.addWidget(Color('yellow'))

        stacklayout.setCurrentIndex(3)

        widget = QWidget()
        widget.setLayout(stacklayout)

        self.setGeometry(0, 0, 1440, 1080)
        self.setWindowTitle('Stack Layout')
        self.show()

class Color(QWidget):

    def __init__(self, color):
        super().__init__()
        self.setAutoFillBackground(True)

        palette = self.palette()
        palette.setColor(QPalette.Window, QColor(color))
        self.setPalette(palette)

def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


from typing import List

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        n = len(nums)
        if n < 3:
            return n
        num = 1
        cur = 1
        p = 1
        while p < n:
            if nums[p] != nums[p-1]:
                nums[cur] = nums[p]
                cur += 1
                p += 1
                num = 1
            elif nums[p] == nums[p-1] and num < 2:
                nums[cur] = nums[p]
                cur += 1
                p += 1
                num += 1
            else:
                p += 1
        return cur

if __name__ == '__main__':
    solu = Solution()
    nums = [0,0,1,1,1,1,2,3,3]
    ans = solu.removeDuplicates(nums)
    print(ans)


'''
from selenium import webdriver as wd

driver = wd.Chrome("./chromedriver.exe")
url = "https://www.naver.com"
driver.get(url)
'''
import time
import os
from selenium import webdriver
from bs4 import BeautifulSoup as soups

def search_selenium(search_name, search_path, search_limit) :
    search_url = "https://www.google.com/search?q=" + str(search_name) + "&hl=ko&tbm=isch"
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument("headless")
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("lang=ko_KR")
    browser = webdriver.Chrome('./chromedriver.exe',chrome_options=chrome_options)
    browser.get(search_url)

    image_count = len(browser.find_elements_by_tag_name("img"))

    print("로드된 이미지 개수 : ", image_count)

    browser.implicitly_wait(2)

    for i in range( search_limit ) :
        image = browser.find_elements_by_tag_name("img")[i]
        time.sleep(0.5)
        image.screenshot(search_path + str(i) + ".png")

    browser.close()

if __name__ == "__main__" :

    search_name = ['너에게 닿기를 아라이 카즈이치','너에게 닿기를 쿠로누마 사와코','너에게 닿기를 쿠루미자와 우메','원피스 나미','원피스 니코 로빈','원피스 비비','원피스 보아 핸콕','나루토 사쿠라','나루토 히나타','나루토 츠나데','나루토 ',' 나루토 텐텐','도라에몽 이슬이','포켓몬스터 꼬북이','포켓몬스터 이슬이','포켓몬스터 간호순','포켓몬스터 여경','코난 미란이','코난 카즈하','코난 하이바라 아이','인사이드 아웃 슬픔이','겨울왕국 안나','겨울왕국 엘사','뽀로로 루피','코코몽 코코몽','뽀로로 뽀로로']
    search_limit = 150
    for i in search_name:
        print(i)
        directory = "E:/AI/crawl/download/여캐/"+i
        search_path = "E:/AI/crawl/download/여캐/"+i+"/"+i
        if not os.path.exists(directory):
            os.makedirs(directory)
    # search_maybe(search_name, search_limit, search_path)
        search_selenium(i, search_path, search_limit)


import logging
import time
from ckip_transformers.nlp import CkipWordSegmenter, CkipPosTagger, CkipNerChunker

# 对input.txt的文件分词输出到output.txt中
# 开20个进程

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

ws_driver = CkipWordSegmenter(level=3,device=-1)

# ------------------test--------------------------#
# text = [
#    "傅達仁今將執行安樂死，卻突然爆出自己20年前遭緯來體育台封殺，他不懂自己哪裡得罪到電視台。",
#    "美國參議院針對今天總統布什所提名的勞工部長趙小蘭展開認可聽證會，預料她將會很順利通過參議院支持，成為該國有史以來第一位的華裔女性內閣成員。",
#    "空白 也是可以的～",
# ]
# ws  = ws_driver(text)
# print(ws)
# ------------------test--------------------------#

#
output = open('ckip.txt', 'w', encoding='utf-8')
with open('chinese.txt', 'r', encoding='utf-8') as content :
    for texts_num, line in enumerate(content):
        line = line.strip('\n')
        # words = jieba.cut(line, cut_all=False)
        line = str(line)
        line = [(line)]
        # print(line)
        words = ws_driver(line)
        # print(words)
        for word in words:
            # print("Here")
            # print(word)
            word = str(word)
            output.write(word + ' ')
        output.write('\n')

        if (texts_num + 1) % 10000 == 0:
            logging.info("已完成前 %d 行的斷詞" % (texts_num + 1))
output.close()


import argparse
import multiprocessing
import os
from importlib import import_module
import numpy as np
import pandas as pd
import torch
from torch.utils.data import DataLoader

from dataset import TestDataset, MaskBaseDataset

def load_model(saved_model, num_classes, device):
    model_cls = getattr(import_module("model"), args.model)
    model = model_cls(
        num_classes=num_classes
    )
    model_path = os.path.join(saved_model, 'best.pth')
    model.load_state_dict(torch.load(model_path, map_location=device))

    return model

@torch.no_grad()
def inference(data_dir, model_dir, output_dir, args):
    """
    """
    use_cuda = torch.cuda.is_available()
    device = torch.device("cuda" if use_cuda else "cpu")

    num_classes = MaskBaseDataset.num_classes
    model_dir_list = os.listdir(model_dir)
    oof_pred = None
    for fold_model in model_dir_list:
        fold_model_path = os.path.join(model_dir, fold_model)
        model = load_model(fold_model_path, num_classes, device).to(device)
        model.eval()

        img_root = os.path.join(data_dir, 'images')
        info_path = os.path.join(data_dir, 'info.csv')
        info = pd.read_csv(info_path)

        img_paths = [os.path.join(img_root, img_id) for img_id in info.ImageID]
        dataset = TestDataset(img_paths, args.resize)
        loader = torch.utils.data.DataLoader(
            dataset,
            batch_size=args.batch_size,
            num_workers=multiprocessing.cpu_count() // 2,
            shuffle=False,
            pin_memory=use_cuda,
            drop_last=False,
        )

        print("Calculating inference results..")
        preds = []
        with torch.no_grad():
            for idx, images in enumerate(loader):
                images = images.to(device)
                pred = model(images)
                preds.extend(pred.cpu().numpy())
            fold_pred = np.array(preds)
        n_splits = len(model_dir_list)
        # 확률 값으로 앙상블을 진행하기 때문에 'k'개로 나누어줍니다.
        if oof_pred is None:
            oof_pred = fold_pred / n_splits
        else:
            oof_pred += fold_pred / n_splits

    info['ans'] = np.argmax(oof_pred, axis=1)
    save_path = os.path.join(output_dir, f'output.csv')
    info.to_csv(save_path, index=False)
    print(f"Inference Done! Inference result saved at {save_path}")

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    # Data and model checkpoints directories
    parser.add_argument('--batch_size', type=int, default=1000, help='input batch size for validing (default: 1000)')
    parser.add_argument('--resize', type=int, nargs="+", default=(128, 96), help='resize size for image when you trained (default: (224, 224))')
    parser.add_argument('--model', type=str, default='MyModel', help='model type (default: BaseModel)')

    # Container environment
    parser.add_argument('--data_dir', type=str, default=os.environ.get('SM_CHANNEL_EVAL', '/opt/ml/input/data/eval'))
    parser.add_argument('--model_dir', type=str, default=os.environ.get('SM_CHANNEL_MODEL', './model/exp'))
    # parser.add_argument('--output_dir', type=str, default=os.environ.get('SM_OUTPUT_DATA_DIR', './output'))
    #parser.add_argument('--model_name', type=str, default=os.environ.get('SM_CHANNEL_MODEL', 'exp'))
    args = parser.parse_args()

    data_dir = args.data_dir
    model_dir = args.model_dir #os.path.join('./results', args.model_name)
    output_dir = model_dir

    os.makedirs(output_dir, exist_ok=True)

    inference(data_dir, model_dir, output_dir, args)


from django.shortcuts import render

# Create your views here.
from .models import MyData
from django.http import HttpResponse
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
import numpy as np
import pickle

# Create your views here.
def home(request):
    return render(request,'Hm.html')

def display(request):
    return render(request,'application.html')

def save(request):
    if request.method=="POST":
        s=MyData()
        s.Name=request.POST.get('ht_name')
        s.Last_Name=request.POST.get('ht_Lname')
        s.Mobile=request.POST.get('ht_Mnum')
        s.Email=request.POST.get('ht_Email')
        s.Gender=request.POST.get('ht_Male')
        s.TOFEL=request.POST.get('ht_tofel')
        s.GRE=request.POST.get('ht_gre')
        s.UNI_rating=request.POST.get('ht_Uni_rating')
        s.SOP=request.POST.get('ht_sop')
        s.LOR=request.POST.get('ht_lor')
        s.CGPA=request.POST.get('ht_cgpa')
        s.Research_Ex=request.POST.get('ht_research')
        s.save()

        #read the data in data frame
        data=[[s.GRE,s.TOFEL,s.UNI_rating,s.SOP,s.LOR,s.CGPA,s.Research_Ex]]
        newx=pd.DataFrame(data,columns=["GRE_Score","TOEFL_Score","University_Rating","SOP","LOR","CGPA","Research"])

        #loading model and data using  pickle
        filename = 'C:\\Users\\Vipin Kumar\\Desktop\\admission\\myapp\\data\\admission_model.sav'

        # load the model from disk

        model,x = pickle.load(open(filename, 'rb'))

        #apply minMax scaler for scaling the data
        scalerX = MinMaxScaler(feature_range=(0, 1))
        x[x.columns] = scalerX.fit(x[x.columns])

        newx[newx.columns] = scalerX.transform(newx[newx.columns])

        #here we predict the score on new data
        y_predict = model.predict(newx)

        #return HttpResponse('Record submitted successfully')
        return render(request,'Output.html', {'score':y_predict})


#!/usr/bin/env python3
"""Writing strings to Redis"""
import redis
import uuid
from typing import Union, Callable
from functools import wraps

def count_calls(method: Callable) -> Callable:
    """ Count calls to a method in the database"""
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        key = method.__name__
        count_key = f"{key}_count"
        self._redis.incr(count_key)
        return method(self, *args, **kwargs)
    return wrapper

def call_history(method: Callable) -> Callable:
    """Returns the callable that will be called"""
    key = method.__qualname__
    inputs = key + ":inputs"
    outputs = key + ":outputs"

    @wraps(method)
    def wrapper(self, *args, **kwds):
        """Returns the method wrapped by this method call"""
        self._redis.rpush(inputs, str(args))
        data = method(self, *args, **kwds)
        self._redis.rpush(outputs, str(data))
        return data
    return wrapper

class Cache:
    """Cache implementation for a single cache object"""
    def __init__(self):
        """Construct a new Cache instance with the given arguments"""
        self._redis = redis.Redis()
        self._redis.flushdb()

    @count_calls
    @call_history
    def store(self, data: Union[str, bytes, int, float]) -> str:
        """Store the given data in the given database
        and return it as a string"""
        key = str(uuid.uuid4())
        if isinstance(data, (str, bytes)):
            self._redis.set(key, data)
        elif isinstance(data, (int, float)):
            self._redis.set(key, str(data))
        return key

    def get(self, key: str, fn: Callable = None)\
            -> Union[str, bytes, int, float]:
        """ Get the value of the given key from the given function"""
        data = self._redis.get(key)
        if data is not None:
            if fn is not None:
                return fn(data)
            return data
        return None

    def get_str(self, key: str) -> str:
        """ Returns the string representation
        of the given key in the given format"""
        return self.get(key, fn=lambda x: x.decode("utf-8"))

    def get_int(self, key: str) -> int:
        """ Returns the value of the given key in the given"""
        return self.get(key, fn=int)

def replay(c: Cache):
    """Retrieving lists"""
    r = c._redis
    key = c.store.__qualname__
    inputs_key = f"{key}:inputs"
    outputs_key = f"{key}:outputs"

    inputs = r.lrange(inputs_key, 0, -1)
    outputs = r.lrange(outputs_key, 0, -1)

    call_count = len(inputs)

    print(f"{key} was called {call_count} times:")

    for input_data, output_data in zip(inputs, outputs):
        input_args = eval(input_data.decode("utf-8"))
        output_key = output_data.decode("utf-8")
        print(f"{key}{input_args} -> {output_key}")


import hero_data
import rules
import facts
import time

TEAM =1
ENEMY =-1
RULES_HEAD = ['strong_against']
FACTS_HEAD = ['counter','ability','range','tier','difficulty']
VARIABLE_LIST = ['A','B','C','D','X']
def sortFunc(e):
  return e.tier

heroes = hero_data.generateList()
# heroes.sort(key = sortFunc)
fact_list = facts.generateList(heroes.values())

Enemy = []
Team = []
favorites = []
suggestions = {}
current_team = ENEMY

def query(resolvent,statement,pick):

	# While the resolvent is not emepty do:
	if len(resolvent) >0:
		# choose a goal from the resolvent

		goal = resolvent.pop()
		# choose a clause from rules
		if goal.predicate in RULES_HEAD or goal.predicate in rules.test_head:
			for rule in rules.rule_list:
				if rule.head.predicate == goal.predicate:
					for small_goal in rule.body:
						small_goal.substitude(rule.head.atoms,goal.atoms)

						resolvent.append(small_goal)

					query(resolvent,statement,pick)

		# or choose a clase from facts
		elif goal.predicate in FACTS_HEAD:

			# loop through each fact

			for fact in fact_list[goal.predicate]:

				variables = 0
				unequal_terms = 0
				i = 0
				while i < len(fact.atoms) :
					if goal.atoms[i] in VARIABLE_LIST:
						variables = variables + 1
						if goal.atoms[i] == 'X':
							pick = fact.atoms[i]
					elif goal.atoms[i] != fact.atoms[i]:
						break

					i = i+1

				if i == len(fact.atoms):

					new_resolvent = []
					for sgoal in resolvent:
						new_resolvent.append(sgoal.copy())

					new_statement = statement + ' ' +fact.__repr__()+ '.'
					if variables != 0:
						for j in range(0, len(new_resolvent)):

							new_resolvent[j].substitude(goal.atoms,fact.atoms)

					else:
						# if the resolvent is empty, a solution is found
						if len(resolvent)==0:

							suggestions[pick] = new_statement

					#Whenever we find an substitution, we recursively call the query with new resolvent.
					query(new_resolvent,new_statement,pick)

	else:
		if len(resolvent)==0:

			suggestions[pick] = statement
# for i in range(1,11):
# 	start = time.time()
# 	query([rules.Goal(str(i),['X'])],'explain: ','X')
# 	end = time.time()
# 	print end-start

def deduce():

    for pick in Enemy:
    	query([rules.Clause('strong_against',['X',pick.name])],'explain: ','X')

def strong_against(heroA, heroB):
	return False
def weak_against(heroA, heroB):
	return strong_against(heroB, heroA)

def teamPick(heroname):
	if len(Team)<=5:
		if heroes[heroname] not in Team and heroes[heroname] not in Enemy:
			Team.append(heroes[heroname])

def enemyPick(heroname):
	if len(Enemy)<=5:
		if heroes[heroname] not in Enemy and heroes[heroname] not in Team :
			Enemy.append(heroes[heroname])

def redo():
	removePick()
	suggestions.clear()
def removePick():
	if current_team == ENEMY:
		if len(Enemy) >=1:
			Enemy.pop()
		elif len(Team) >=1:
			Team.pop()
	else:
		if len(Team) >=1:
			Team.pop()
		elif len(Enemy) >=1:
			Enemy.pop()
def redoSuggest():
	suggestions.clear()


from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from elasticsearch import Elasticsearch
from kafka import KafkaConsumer
from kafka import KafkaProducer
from .. import views
import json
import datetime
import random
import arrow

class ListingFormTests(TestCase):
  #fixtures = ['db']  # load from DB

  def setUp(self): # try to indice some fixtures to elasticsearch
    self.client = Client()

    fixtureA = {"listing_id":1,"drone": 2, "owner": 2, "description": "please rent myseediestdrone!", "time_posted": "2016-10-24T04:28:48.932Z", "price_per_day": 10.0}
    fixtureB = {"listing_id":2,"drone": 3, "owner": 3, "description": "please rent myforgeddrone!", "time_posted": "2016-10-24T04:28:48.991Z", "price_per_day": 14.0}

    es = Elasticsearch(['es'])
    es.index(index='listing_index', doc_type='listing', id=fixtureA['listing_id'], body=fixtureA)
    es.index(index='listing_index', doc_type='listing', id=fixtureB['listing_id'], body=fixtureB)
    es.indices.refresh(index='listing_index')
    producer.send('new-listings-topic', json.dumps(some_new_listing).encode('utf-8'))

    response = self.client.post(reverse('create-listing'), fixtureA)
    print("test_create_listing POST " + str(response))

    resp = json.loads(response.content.decode('utf8'))
    self.assertEquals(response.status_code, 200)
    print("listing_atts" + str(resp))

  # append number to test to get python to run defs in correct order
  def est1_DroneForm(self): # not passing
    response = self.client.get(reverse('inspect_drone', kwargs={'drone_id':201}))
    resp = json.loads(response.content.decode('utf8'))

    print("test_drone_attributes GET " + str(resp))
    self.assertEquals(resp["ok"],True)
    self.assertEquals(resp['resp']['model_name'], 'prehistorians_inexpugnably100')

  def est2_Drone_Invalid_id(self):
    response = self.client.get(reverse('inspect_drone', kwargs={'drone_id':300}))
    resp = json.loads(response.content.decode('utf8'))
    self.assertEquals(resp["ok"], False)

  def est4_Drones_Available_For_hire(self):
    available_drones = models.Drone.objects.filter(available_for_hire = True)
    self.assertGreater(len(available_drones),0)

  def tearDown(self):
    del self.client


"""A Space Invader variant.
"""
import pygame
from pygame.constants import (
    QUIT, KEYDOWN, KEYUP, K_LEFT, K_RIGHT, K_ESCAPE, K_SPACE)
import os
from random import randint

class Settings:
    """Project global informations.

    This static class contains informations that
    are used on many places in the project.
    """
    window_width = 1000
    window_height = 650
    window_border = 10
    enemy_bottom_border = window_height - 80
    enemy_nof_cols = 13
    file_path = os.path.dirname(os.path.abspath(__file__))
    image_path = os.path.join(file_path, "images")
    score = (100, 50, 10)
    max_bombs = 6
    max_rockets = 6

class Background(object):
    """Bitmap class to manage the background of the game.
    """

    def __init__(self, filename):
        """Constructor

        Loading and scaling the background image.
        Args:
            filename (string): name (without path) of the background bitmap
        """
        self.image = pygame.image.load(
            os.path.join(Settings.image_path, filename))
        self.image = pygame.transform.scale(
            self.image, (Settings.window_width, Settings.window_height)).convert()
        self.rect = self.image.get_rect()

    def draw(self, screen):
        """Draws the bitmap on a surface (screen).

        Args:
            screen (python.Surface): surface object - usally the screen.
        """
        screen.blit(self.image, self.rect)

class Defender(pygame.sprite.Sprite):
    """Defender sprite class.
    """

    def __init__(self, filename):
        """Constructor

        Loading, converting, and scaling the defender images.
        Args:
            filename (string): name (without path) of the defender alive bitmap
        """
        super().__init__()
        self.image_alive = pygame.image.load(
            os.path.join(Settings.image_path, filename))
        self.image_alive = pygame.transform.scale(
            self.image_alive, (30, 30)).convert_alpha()
        self.rect = self.image_alive.get_rect()
        self.rect.centerx = Settings.window_width // 2
        self.rect.bottom = Settings.window_height - Settings.window_border
        self.direction = 0
        self.speed = 3
        self.image = self.image_alive

        self.images_explosion = []
        self.imageindex_explosion = -1
        for i in range(1, 5):
            bitmap = pygame.image.load(os.path.join(
                Settings.image_path, "explosion0{0}.png".format(i)))
            bitmap = pygame.transform.scale(bitmap, (30, 30)).convert_alpha()
            self.images_explosion.append(bitmap)

        self.fliptime_explosion = 3
        self.flipcounter = self.fliptime_explosion

    def update(self):
        """Implemention of the horizontal movements, status and animation
        """
        if self.imageindex_explosion == -1:
            self.image = self.image_alive
        else:
            if self.imageindex_explosion < len(self.images_explosion):
                self.image = self.images_explosion[self.imageindex_explosion]
                if self.flipcounter <= 0:
                    self.imageindex_explosion += 1
                    self.flipcounter = self.fliptime_explosion
                else:
                    self.flipcounter -= 1
            else:
                self.kill()

        newrect = self.rect.move(self.direction * self.speed, 0)
        if newrect.left <= Settings.window_border:
            self.move_stop()
        if newrect.right >= Settings.window_width - Settings.window_border:
            self.move_stop()
        self.rect.move_ip(self.direction * self.speed, 0)

    def move_left(self):
        """Sets the direction to left.
        """
        self.direction = -1

    def move_right(self):
        """Sets the direction to right.
        """
        self.direction = 1

    def move_stop(self):
        """The defender stops.
        """
        self.direction = 0

    def hit_by_bomb(self):
        """Set status to "I was hit by a bomb".
        """
        self.imageindex_explosion = 0
        self.flipcounter = self.fliptime_explosion

class Brick(pygame.sprite.Sprite):
    """One brick of the wall.
    """

    def __init__(self):
        """Constructor
        """
        super().__init__()
        self.images = []
        for index in range(1, 4):
            bitmap = pygame.image.load(os.path.join(
                Settings.image_path, "brick0{0}.png".format(index)))
            bitmap = pygame.transform.scale(bitmap, (10, 10)).convert_alpha()
            self.images.append(bitmap)
        self.imageindex = 0
        self.image = self.images[self.imageindex]
        self.rect = self.image.get_rect()

    def hit(self):
        """The brick was hit by bomb or rocket.
        """
        self.imageindex += 1
        if self.imageindex >= len(self.images):
            self.kill()
        else:
            self.image = self.images[self.imageindex]

class Rocket(pygame.sprite.Sprite):
    """Rockets fired by the defender.
    """

    def __init__(self, filename, defender):
        """Constructor.

        Loading, converting, and scaling the rocket image.
        Args:
            filename (string): name (without path) of the rocket bitmap
            defender (Defender): the defender who launches the rocket
        """
        super().__init__()
        self.image = pygame.image.load(
            os.path.join(Settings.image_path, filename))
        self.image = pygame.transform.scale(
            self.image, (5, 10)).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.centerx = defender.rect.centerx
        self.rect.bottom = defender.rect.top
        self.direction = -1
        self.speed = 3

    def update(self):
        """Updates the position and the status of the rocket.
        """
        newrect = self.rect.move(0, self.direction * self.speed)
        if newrect.bottom > 0:
            self.rect = newrect
        else:
            self.kill()

class Bomb(pygame.sprite.Sprite):
    """Bombs dropped by the enemies
    """

    def __init__(self, filename, enemy):
        """Constructor.

        Loading, converting, and scaling the bomb image.
        Args:
            filename (string): name (without path) of the bomb bitmap
            enemy (Enemy): the enemy who drops the bomb
        """
        super().__init__()
        self.image = pygame.image.load(
            os.path.join(Settings.image_path, filename))
        self.image = pygame.transform.scale(
            self.image, (10, 10)).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.centerx = enemy.rect.centerx
        self.rect.top = enemy.rect.bottom
        self.direction = 1
        self.speed = 3

    def update(self):
        """Updates the position and the status of the bomb.
        """
        newrect = self.rect.move(0, self.direction * self.speed)
        if newrect.top < Settings.window_height - Settings.window_border:
            self.rect = newrect
        else:
            self.kill()

class Enemy(pygame.sprite.Sprite):
    """Enemy sprite class.

    Direction and speed are organized as static member variables.
    """
    speed_horizontal = 2
    direction_horizontal = 1
    speed_vertical = 0
    direction_vertical = 0

    def __init__(self, filename, aliennumber, colindex, rowindex):
        """Constructor.

        Loading, converting, and scaling the enemy bitmaps.

        Args:
            filename (string): name (without path) of the enemy bitmap
            aliennumber (int): number of the alien (according to the filename)
            colindex (int): number of the column of the sprite
            rowindex (int): number of the row of the sprite
        """
        super().__init__()
        self.images_alive = []
        self.imageindex_alive = -1
        for i in range(1, 3):
            bitmap = pygame.image.load(os.path.join(
                Settings.image_path, filename.format(aliennumber, i)))
            bitmap = pygame.transform.scale(bitmap, (50, 45)).convert_alpha()
            self.images_alive.append(bitmap)
        self.imageindex_alive = 0

        self.images_explosion = []
        self.imageindex_explosion = -1
        for i in range(1, 5):
            bitmap = pygame.image.load(os.path.join(
                Settings.image_path, "explosion0{0}.png".format(i)))
            bitmap = pygame.transform.scale(bitmap, (50, 45)).convert_alpha()
            self.images_explosion.append(bitmap)

        self.image = self.images_alive[self.imageindex_alive]
        self.rect = self.image.get_rect()
        self.distance = 5
        self.score = Settings.score[rowindex//4]
        newx = Settings.window_border + \
            (self.rect.width + self.distance) * colindex
        newy = Settings.window_border + \
            (self.rect.height + self.distance) * rowindex
        self.rect.move_ip(newx, newy)
        Enemy.speed_vertical = self.rect.height // 4
        self.fliptime_alive = 10
        self.flipcounter = self.fliptime_alive
        self.fliptime_explosion = 3

    def update(self):
        """Updates the status an behaviour.

        Implemention of the horizontal and vertical movements and
        if and how the animation runs.
        """
        if self.imageindex_explosion == -1:
            self.image = self.images_alive[self.imageindex_alive]
            if self.imageindex_alive == 1:
                if self.flipcounter <= 0:
                    self.imageindex_alive = 0
                    self.flipcounter = self.fliptime_alive
                else:
                    self.flipcounter -= 1
        else:
            self.imageindex_alive = -1
            if self.imageindex_explosion < len(self.images_explosion):
                self.image = self.images_explosion[self.imageindex_explosion]
                if self.flipcounter <= 0:
                    self.imageindex_explosion += 1
                    self.flipcounter = self.fliptime_explosion
                else:
                    self.flipcounter -= 1
            else:
                self.kill()

        self.rect.move_ip(Enemy.direction_horizontal * Enemy.speed_horizontal,
                          Enemy.direction_vertical * Enemy.speed_vertical)

    @staticmethod
    def switch_horizontal_direction():
        """Switches the horizontal direction from left to right or from right to left.

        It is implemented as a static method because all enemies must switch at the same time.
        """
        Enemy.direction_horizontal *= -1

    @staticmethod
    def switch_vertical_direction():
        """Switches the vertical direction from up to down or from down to up.

        It is implemented as a static method because all enemies must switch at the same time.
        """
        if Enemy.direction_vertical == 0:
            Enemy.direction_vertical = 1
        else:
            Enemy.direction_vertical = 0

    def is_horizontal_border_reached(self):
        """Has the enemy reached left or right borders of the screen.

        Returns:
            bool: True if it has reached the border, otherwise False.
        """
        newrect = self.rect.move(Enemy.direction_horizontal * Enemy.speed_horizontal,
                                 Enemy.direction_vertical * Enemy.speed_vertical)
        if newrect.left <= Settings.window_border:
            return True
        if newrect.right >= Settings.window_width - Settings.window_border:
            return True
        return False

    def is_vertical_border_reached(self):
        """Has the enemy reached upper or lower borders his area.

        Returns:
            bool: True if it has reached the border, otherwise False.
        """
        newrect = self.rect.move(Enemy.direction_horizontal * Enemy.speed_horizontal,
                                 Enemy.direction_vertical * Enemy.speed_vertical)
        if newrect.bottom >= Settings.enemy_bottom_border:
            return True
        return False

    def dropped_bomb(self):
        """Indicates that the enemy has dropped a bomb.
        """
        self.imageindex_alive = 1

    def can_drop(self):
        """Checks if the enemy can drop a bomb.

        Returns:
            bool: True if dropping animation hasn't startet or is finished, otherwise Fals
        """
        return self.flipcounter == self.fliptime_alive

    def hit_by_rocket(self):
        """Indicates that the enemy is hit by a rocket.
        """
        self.imageindex_explosion = 0
        self.flipcounter = self.fliptime_explosion

class Game(object):
    """The game management.

    After creating the game object you start the game with the
    method run().
    """

    def __init__(self):
        """Constructor.
        """
        self.screen = pygame.display.set_mode(
            (Settings.window_width, Settings.window_height))
        self.clock = pygame.time.Clock()
        self.score = 0
        self.font = pygame.font.Font(pygame.font.get_default_font(), 24)
        self.running = False

        self.all_defenders = pygame.sprite.Group()
        self.all_enemies_alive = pygame.sprite.Group()
        self.all_enemies_exploding = pygame.sprite.Group()
        self.all_rockets = pygame.sprite.Group()
        self.all_bombs = pygame.sprite.Group()
        self.all_bricks = pygame.sprite.Group()

        self.background = Background("background03.png")
        self.defender = Defender("defender01.png")
        self.all_defenders.add(self.defender)
        for rowindex in range(0, 8):
            for colindex in range(0, Settings.enemy_nof_cols):
                aliennumber = rowindex // 2
                enemy = Enemy("alienbig0{0}0{1}.png",
                              aliennumber, colindex, rowindex)
                self.all_enemies_alive.add(enemy)

        self.init_bricks()

    def run(self):
        """Starting the game.
        """
        self.running = True
        while self.running:
            self.clock.tick(60)
            self.watch_for_events()
            self.update()
            self.drop_bomb()
            self.collision_rockets()
            self.collision_bombs()
            self.draw()

    def draw(self):
        """Drawing all bitmaps/sprites.

        This method draws all sprites objects and
        blits the text output to the screen.
        After that it flips the doublebuffer.
        """
        self.background.draw(self.screen)
        self.all_defenders.draw(self.screen)
        self.all_enemies_alive.draw(self.screen)
        self.all_enemies_exploding.draw(self.screen)
        self.all_rockets.draw(self.screen)
        self.all_bombs.draw(self.screen)
        self.all_bricks.draw(self.screen)

        text_surface_scrore = self.font.render(
            "Score: {0}".format(self.score), True, (255, 255, 255))
        self.screen.blit(text_surface_scrore,
                         (Settings.window_border, Settings.window_height - 50))
        pygame.display.flip()

    def collision_bombs(self):
        """Game logic: defender and bomb.
        """
        # bomb hits defender
        if pygame.sprite.spritecollide(self.defender, self.all_bombs, True):
            self.defender.hit_by_bomb()

        # bomb hits brick
        for brick in self.all_bricks:
            if pygame.sprite.spritecollide(brick, self.all_bombs, True):
                brick.hit()

    def collision_rockets(self):
        """Game logic: enemies and rockets.
        """
        # Check rockets
        for rocket in self.all_rockets:
            tmp = pygame.sprite.spritecollide(
                rocket, self.all_enemies_alive, False)
            if len(tmp) > 0:
                rocket.kill()
                self.all_enemies_alive.remove(tmp)
                self.all_enemies_exploding.add(tmp)
                for enemy in tmp:
                    enemy.hit_by_rocket()
                    self.score += enemy.score

        # Rocket hits brick
        for brick in self.all_bricks:
            if pygame.sprite.spritecollide(brick, self.all_rockets, True):
                brick.hit()

    def drop_bomb(self):
        """Game logic: when will and how drops a bomb.
        """
        if len(self.all_bombs) < Settings.max_bombs and len(self.all_enemies_alive) > 0:
            enemy_index = randint(0, len(self.all_enemies_alive) - 1)
            enemy = self.all_enemies_alive.sprites()[enemy_index]
            if enemy.can_drop():
                bomb = Bomb("bomb.png", enemy)
                self.all_bombs.add(bomb)
                enemy.dropped_bomb()

    def update(self):
        """Game logic: updates all sprites according to intended behaviour.
        """
        self.defender.update()

        # Update enemies
        has_horizontal_border_reached = False
        for enemy in self.all_enemies_alive:
            if enemy.is_horizontal_border_reached():
                has_horizontal_border_reached = True
                break
        has_vertical_border_reached = False
        for enemy in self.all_enemies_alive:
            if enemy.is_vertical_border_reached():
                has_vertical_border_reached = True
                break

        if has_horizontal_border_reached:
            Enemy.switch_horizontal_direction()
            if not has_vertical_border_reached:
                Enemy.switch_vertical_direction()
        self.all_enemies_alive.update()
        self.all_enemies_exploding.update()
        if has_horizontal_border_reached:
            if not has_vertical_border_reached:
                Enemy.switch_vertical_direction()

        self.all_rockets.update()
        self.all_bombs.update()

    def watch_for_events(self):
        """Listing for key events.

        According of which key went down or up the corresponding
        messages will send to the objects.
        """
        for event in pygame.event.get():
            if event.type == QUIT:
                self.running = False
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    self.running = False
                elif event.key == K_LEFT:
                    self.defender.move_left()
                elif event.key == K_RIGHT:
                    self.defender.move_right()
                elif event.key == K_SPACE:
                    if len(self.all_rockets) < Settings.max_rockets:
                        rocket = Rocket("shoot.png", self.defender)
                        self.all_rockets.add(rocket)
            elif event.type == KEYUP:
                if event.key == K_LEFT or event.key == K_RIGHT:
                    self.defender.move_stop()

    def init_bricks(self):
        """Setup the 4 walls to protect the defender.
        """
        map = []
        map.append("..XXXXXXX..")
        map.append(".XXXX.XXXX.")
        map.append("XXXX...XXXX")
        map.append("XXXX...XXXX")

        startx = 150
        starty = Settings.window_height - 100
        distance = 200
        for wall in range(4):
            for row in range(len(map)):
                for col in range(len(map[row])):
                    if map[row][col] == "X":
                        brick = Brick()
                        brick.rect.left = startx + \
                            (wall * distance) + (col * brick.rect.width)
                        brick.rect.top = starty + (row * brick.rect.height)
                        self.all_bricks.add(brick)

if __name__ == '__main__':
    os.environ['SDL_VIDEO_WINDOW_POS'] = "10, 50"
    #pylint: disable=no-member
    pygame.init()
    #pylint: enable=no-member

    game = Game()
    game.run()

    #pylint: disable=no-member
    pygame.quit()
    #pylint: enable=no-member


import numpy as np
from bounding_box.zonotope_tree import *
from visualization.visualize import *
from pypolycontain.visualization.visualize_2D import visualize_2D_zonotopes as visZ

def test_with_dataset():
    #FIXME: Import issues
    from utils.PWA_Control_utils import polytree_to_zonotope_tree
    import pickle
    with open("zonotope_datasets/inverted_pendulum.pkl", "rb") as f:
        state_tree = pickle.load(f)
    f.close()
    # extract zonotopes
    zonotope_tree = polytree_to_zonotope_tree(state_tree)
    zonotope_count = len(zonotope_tree.zonotopes)

    query_point = np.asarray([(np.random.rand(1) - 0.5) * 0.24,
                              (np.random.rand(1) - 0.5) * 2])
    print(query_point)
    query_point = query_point.reshape(-1, 1)
    closest_zonotope, candidate_boxes, query_box = zonotope_tree.find_closest_polytopes(query_point)
    print(('Query point: ', query_point))
    ax_lim = np.asarray([-zonotope_count, zonotope_count, -zonotope_count, zonotope_count]) * 1.1
    fig, ax = visZ(zonotope_tree.zonotopes, title="", alpha=0.2, axis_limit=ax_lim)
    fig, ax = visZ(closest_zonotope, title="", fig=fig, ax=ax, alpha=1, axis_limit=ax_lim)
    fig, ax = visualize_box_nodes(zonotope_tree.box_nodes, fig=fig, ax=ax, alpha=0.4, linewidth=0.5)
    fig, ax = visualize_boxes(candidate_boxes, fig=fig, ax=ax, alpha=1)
    print(('Evaluating %d zonotopes out of %d' % (len(candidate_boxes), len(zonotope_tree.zonotopes))))
    fig, ax = visualize_boxes([query_box], fig=fig, ax=ax, alpha=0.3, fill=True)
    plt.scatter(query_point[0], query_point[1], s=20, color='k')
    print(('Closest Zonotope: ', closest_zonotope))
    plt.show()

def zonotope_reduction_line_nd(zonotope_count, dim, num_of_queries):
    zonotopes = []
    centroid_range = zonotope_count*5
    generator_range = 10
    for i in range(zonotope_count):
        m = np.random.random_integers(dim, 2*dim)
        G = 2*(np.random.rand(dim, m) - 0.5) * generator_range * 1
        x = 2*(np.random.rand(dim-1,1) - 0.5)
        x = np.vstack([2*(np.random.rand(1,1) - 0.5) * centroid_range,x])
        # print(x)
        zonotopes.append(zonotope(x, G))
    zt = PolytopeTree_Old(zonotopes)

    query_points = (np.random.rand(dim-1,num_of_queries)-0.5)
    query_points = np.vstack([2*(np.random.rand(1, num_of_queries) - 0.5) * centroid_range,query_points])
    # print(query_points)
    reduction_ratios = np.zeros([num_of_queries])
    for i, q in enumerate(query_points.T):
        closest_zonotope, candidate_boxes, query_box = zt.find_closest_polytopes(q)
        reduction_ratios[i] = len(candidate_boxes)/(zonotope_count*1.)

    if dim ==2:
        fig, ax = visZ(zt.polytopes, title="", alpha=0.2)
        ax.scatter(query_points[0,:], query_points[1,:],s=3)
        ax.set_xlim([-centroid_range*1.2,centroid_range*1.2])
        ax.set_ylim([-centroid_range * 1.2, centroid_range * 1.2])
        plt.xlabel('x')
        plt.ylabel('y')
        plt.title('Zonotope and Query Point Distribution')

        plt.show()

    return np.average(reduction_ratios), np.std(reduction_ratios)

def zonotope_reduction_line_over_d(zonotope_count, d_start,d_end, num_of_queries):
    d = np.arange(d_start,d_end)
    reduction_ratios = np.zeros([d.shape[0],2])
    for i, d_i in enumerate(d):
        print(('Evaluating %d-D' %d_i))
        reduction_ratios[i,0],reduction_ratios[i,1] = zonotope_reduction_line_nd(d_i**zonotope_count,d[i],num_of_queries)
    print(reduction_ratios)
    plt.errorbar(d,100*reduction_ratios[:,0],100*reduction_ratios[:,1],marker='.',ecolor='r',elinewidth=0.3,capsize=2,linewidth=0.5,markersize=7)
    plt.xlabel('Dimension')
    plt.ylabel('% of zonotopes evaluated')
    plt.title('Line Distributed Zonotope Set Reduction with Bounding Boxes')
    plt.show()

def zonotope_reduction_box_nd(zonotope_count, dim, num_of_queries):
    zonotopes = []
    centroid_range = zonotope_count*8
    generator_range = zonotope_count
    print(('Centroid range: %d' %centroid_range))
    print(('Generator range: %d' %generator_range))
    for i in range(zonotope_count):
        m = np.random.random_integers(dim, 2*dim)
        G = (np.random.rand(dim, m) - 0.5) * generator_range * 1
        x = 2*(np.random.rand(dim,1) - 0.5)*centroid_range
        # print(x)
        zonotopes.append(zonotope(x, G))
    zt = PolytopeTree_Old(zonotopes)
    #query points in a line
    # query_points = (np.random.rand(dim-1,num_of_queries)-0.5)
    # query_points = np.vstack([query_points, 2*(np.random.rand(1, num_of_queries) - 0.5) * centroid_range*2])
    #query points anywhere in space
    query_points = 2 * (np.random.rand(dim, num_of_queries) - 0.5) * centroid_range * 2
    reduction_ratios = np.zeros([num_of_queries])
    for i, q in enumerate(query_points.T):
        closest_zonotope, candidate_boxes, query_box = zt.find_closest_polytopes(q)
        reduction_ratios[i] = len(candidate_boxes)/(zonotope_count*1.)
    if dim ==2:
        fig, ax = visZ(zt.polytopes, title="", alpha=0.2)
        ax.scatter(query_points[0,:], query_points[1,:],s=3)
        plt.xlabel('x')
        plt.ylabel('y')
        plt.title('Zonotope and Query Point Distribution')

        plt.show()
    return np.average(reduction_ratios), np.std(reduction_ratios)

def zonotope_reduction_box_over_d(zonotope_count, d_start,d_end, num_of_queries):
    d = np.arange(d_start,d_end)
    reduction_ratios = np.zeros([d.shape[0],2])
    for i, d_i in enumerate(d):
        print(('Evaluating %d-D' %d_i))
        reduction_ratios[i,0],reduction_ratios[i,1] = zonotope_reduction_box_nd(d_i**zonotope_count,d[i],num_of_queries)
    print(reduction_ratios)
    plt.errorbar(d,100*reduction_ratios[:,0],100*reduction_ratios[:,1],marker='.',ecolor='r',elinewidth=0.3,capsize=2,linewidth=0.5,markersize=7)
    plt.xlabel('Dimension')
    plt.ylabel('% of zonotopes evaluated')
    plt.title('Box Distributed Zonotope Set Reduction with Bounding Boxes')
    plt.show()

if __name__ == '__main__':
    plt.rcParams["font.family"] = "Times New Roman"
    zonotope_reduction_box_over_d(5,2,5,100)


# -*- coding: utf-8 -*-
import os,sys

# Import Qt modules
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from model import *
from utils import _date_from_str
from datetime import date
# Import the compiled UI module
sys.path.append("ui")
from deliver_form_ui import Ui_deliver_form
from add_drug_form import AddDrugForm
from new_distributor_form import NewDistributorForm
from new_financing_form import NewFinancingForm
from time import strftime

from appy.pod.renderer import Renderer
from os import popen, path
class DeliverWindow(QFrame):

	def initForm(self):
		QFrame.__init__(self)
		self.ui = Ui_deliver_form()
		self.ui.setupUi(self)

		self.ui.distributor_combo.setEditable(False)
		self.drawDistributorCombo()
		self.drawFinancingCombo()
		QObject.connect(self.ui.tableWidget, SIGNAL("cellDoubleClicked(int, int)"), self.showAddDrugForm)
		QObject.connect(self.ui.save_close_btn, SIGNAL("clicked()"), self.saveAcceptDeliver)
		QObject.connect(self.ui.save_btn, SIGNAL("clicked()"), self.saveDeliver)
		QObject.connect(self.ui.print_bill_btn, SIGNAL("clicked()"), self.createReport)
		QObject.connect(self.ui.close_btn, SIGNAL("clicked()"), self.closeme)

	def initNewDeliver(self):
		self.deliver = Deliver()
		self.deliver.create_date = date.today()
		self.ui.bill_number_date.setText(QString.fromUtf8(repr(self.deliver)))
		self.ui.deliver_date.setText(QString.fromUtf8(self.deliver.create_date.strftime("%d.%m.%Y")))
		self.drawTable()

	def __init__(self,deliver=None):
		self.initForm()
		if deliver == None:
			self.initNewDeliver()
		else:
			self.deliver = deliver
			self.ui.bill_number_date.setText(QString.fromUtf8(repr(self.deliver)))
			self.ui.deliver_date.setText(self.deliver.deliver_date.strftime("%d.%m.%Y"))
			self.ui.distributor_combo.setCurrentIndex(self.ui.distributor_combo.findText(self.deliver.distributor.name))
			self.ui.financing_combo.setCurrentIndex(self.ui.financing_combo.findText(self.deliver.financing.name))
			self.drawTable()

			if self.deliver.accepted:
				self.ui.save_btn.setDisabled(True)
				self.ui.save_close_btn.setDisabled(True)
				self.ui.distributor_combo.setDisabled(True)
				self.ui.financing_combo.setDisabled(True)
				self.ui.deliver_date.setDisabled(True)
	def drawTable(self):
		self.ui.tableWidget.clear()
		self.ui.tableWidget.setRowCount(1)
		self.ui.tableWidget.setColumnCount(7)
		self.ui.tableWidget.setHorizontalHeaderLabels([QString.fromUtf8('ИД'), QString.fromUtf8('Название препарата'), QString.fromUtf8('Производитель'), QString.fromUtf8('Серийный номер'), QString.fromUtf8('Годен до'), QString.fromUtf8('Цена'),QString.fromUtf8('Количество')])
		self.summ = 0
		for m in self.deliver.maps:
			if not m.count == 0:
				data = []
				data.append(str(m.drug.id))
				data.append(QString.fromUtf8(m.drug.name()))
				data.append(m.drug.manufacter.name)
				data.append(str(m.drug.serial))
				data.append(m.drug.best_before.strftime("%d.%m.%Y"))
				data.append(str(m.drug.price))
				data.append(str(m.count))

				self.summ = self.summ + m.count*m.drug.price
				for i in range(0,7):
					tableitem = QTableWidgetItem()
					tableitem.setText(data[i])
					tableitem.font = QFont("Arial", 10)
					tableitem.font.setBold(True)
					tableitem.textcolor = QColor("black")
					tableitem.setBackgroundColor(QColor('White'))
					self.ui.tableWidget.setItem(self.ui.tableWidget.rowCount() - 1,i,tableitem)
				self.ui.tableWidget.setRowCount(self.ui.tableWidget.rowCount()+1)
			else:
				self.deliver.maps.remove(m)
		self.ui.label_3.setText(QString.fromUtf8("Всего лс на сумму " + str(self.summ) + "р."))
		self.ui.tableWidget.resizeColumnsToContents()

	def drawDistributorCombo(self):
		distributors = query_session.query(Distributor).all()
		self.ui.distributor_combo.clear()
		for item in distributors:
			self.ui.distributor_combo.addItem(item.name)

		self.ui.distributor_combo.addItem(QString.fromUtf8('Новый поставщик'))
		QObject.connect(self.ui.distributor_combo, SIGNAL("currentIndexChanged(int)"), self.setDistributor)
		self.setDistributor(0)

	def drawFinancingCombo(self):
		fin = query_session.query(Financing).all()
		self.ui.financing_combo.clear()

		for item in fin:
			self.ui.financing_combo.addItem(item.name)

		self.ui.financing_combo.addItem(QString.fromUtf8('Новый источник финансирования'))
		QObject.connect(self.ui.financing_combo, SIGNAL("currentIndexChanged(int)"), self.setFinancing)
		self.setFinancing(0)

	def showAddDrugForm(self, row, col):
		if row == self.ui.tableWidget.rowCount() - 1:
			self.add_drug_form = AddDrugForm(self)
			self.add_drug_form.setWindowModality(2)
			QObject.connect(self.add_drug_form.count_form, SIGNAL("drugAdded()"), self.drawTable)
			self.add_drug_form.showMaximized()

	def saveAcceptDeliver(self):
		self.deliver.accepted = True
		self.saveDeliver()

	def saveDeliver(self):
		self.deliver.deliver_date = _date_from_str(self.ui.deliver_date.text())
		self.deliver.distributor = self.distributor
		self.deliver.financing = self.financing
		s = Session()
		s.add(self.deliver)
		s.commit()
		s.close()

		self.parent().close()

	def setDistributor(self,num):
		if (num < self.ui.distributor_combo.count() - 1):
			distributor = query_session.query(Distributor).filter_by(name=unicode(self.ui.distributor_combo.itemText(num))).one()
			self.distributor = distributor
		else:
			self.new_distributor_form = NewDistributorForm(self)
			self.new_distributor_form.setWindowModality(2)
			QObject.connect(self.new_distributor_form, SIGNAL("distributorAdded()"), self.drawTable)
			QObject.connect(self.new_distributor_form, SIGNAL("distributorAdded()"), self.drawDistributorCombo)
			self.new_distributor_form.show()

	def setFinancing(self,num):
		if (num < self.ui.financing_combo.count() - 1):
			financing = query_session.query(Financing).filter_by(name=unicode(self.ui.financing_combo.itemText(num))).one()
			self.financing = financing
		else:
			self.new_financing_form = NewFinancingForm(self)
			self.new_financing_form.setWindowModality(2)
			QObject.connect(self.new_financing_form, SIGNAL("financingAdded()"), self.drawTable)
			QObject.connect(self.new_financing_form, SIGNAL("financingAdded()"), self.drawFinancingCombo)
			self.new_financing_form.show()

	def createReport(self):
		fileName = '%sdeliver%d.pdf' % ('reports/', self.deliver.id)
		if path.exists(fileName):
			os.popen('evince %s' % fileName)
		else:
			opts = {'deliver': self.deliver}
			renderer = Renderer('appy/templates/deliver.odt', opts, fileName)
			renderer.run()

		os.popen('evince %s' % fileName)

	def closeme(self):
		self.parent().close()