#!/usr/bin/env python3
# coding = utf-8
import json
import sqlite3
import os

# 处理客队或者主队的数据
def get_team_data(team_type):
    matchup = team_type["matchup"]
    confrank = matchup["confRank"]
    divrank = matchup["divRank"]
    losses = matchup["losses"]
    profile = team_type["profile"]
    abbr = profile["abbr"]
    city = profile["city"]
    cityen = profile["cityEn"]
    code = profile["code"]
    conference = profile["conference"]
    displayabbr = profile["displayAbbr"]
    displayconference = profile["displayConference"]
    division = profile["division"]
    isallstarteam = profile["isAllStarTeam"]
    isleagueteam = profile["isLeagueTeam"]
    name = profile["name"]
    nameen = profile["nameEn"]

    return (confrank, divrank, losses, abbr, city, cityen, code, conference, displayabbr,
            displayconference, division, isallstarteam, isleagueteam, name, nameen)

# 解析每场比赛的公共数据（出场人数,比分等）
def get_match_data(in_data):
    boxscore = in_data["boxscore"]
    attendance = boxscore["attendance"]
    awayscore = boxscore["awayScore"]
    gamelength = boxscore["gameLength"]
    homescore = boxscore["homeScore"]
    match_profile = in_data["profile"]
    arenalocation = match_profile["arenaLocation"]
    arenaname = match_profile["arenaName"]
    awayteamid = match_profile["awayTeamId"]
    gameid = match_profile["gameId"]
    hometeamid = match_profile["homeTeamId"]
    seasontype = match_profile["seasonType"]
    utcmillis = match_profile["utcMillis"]
    awayteam_data = get_team_data(in_data["awayTeam"])
    hometeam_data = get_team_data(in_data["homeTeam"])
    match_data = (gameid, hometeamid, awayteamid, seasontype, arenalocation, arenaname,
                  attendance, homescore, awayscore, gamelength, utcmillis)
    sum_data = match_data+hometeam_data+awayteam_data
    with open(datafile_for_load, "at") as file:
        for i in range(len(sum_data)):
            if i != len(sum_data)-1:
                file.write(str(sum_data[i]))
                file.write("|*|")
            else:
                file.write(str(sum_data[i]))
        file.write("\n")

# 将每场比赛的数据追加写入数据文件,等待向数据库中加载
def extrac_json(json_file):
    with open(json_file, encoding='utf8') as f:
        data = json.load(f)
        all_data = data["payload"]["dates"]
        for smy_data in all_data:
            group_data = smy_data["games"]
            for want_data in group_data:
                get_match_data(want_data)

# 调用sqlite3,传入sql和附带数据,返回执行结果,ddl语句及upd语句正常执行后返回[]
def run_sql(database, sql_str, insert_data=None):
    con = sqlite3.connect(database)
    cur = con.cursor()
    if insert_data is None:
        cur.execute(sql_str)
    else:
        cur.execute(sql_str, insert_data)
    reslut = []
    for l in cur:
        reslut.append(l)
    con.commit()
    con.close()
    return reslut

# 建立流程控制表并插入文件列表,防止数据文件多次被处理
def create_con_table(path):
    create_table_sql = "create table if not exists extrac_json(filename text, isdone text)"
    insert_data = "insert into extrac_json values (?, ?)"
    run_sql(databasefile, create_table_sql)
    filelist = os.listdir(path)
    for filename in filelist:
        run_sql(databasefile, insert_data, (filename, 'N'))

# 更新流程控制表中文件处理的状态为已处理
def upd_isdone(filename):
    upd_sql = "update extrac_json set isdone = ? where filename = ?"
    run_sql(databasefile, upd_sql, ('Y', filename))

# 获取流程控制表中文件处理状态
def get_isdone(filename):
    sel_sql = "select isdone from extrac_json where filename = ? "
    isdone = run_sql(databasefile, sel_sql, (filename,))
    return isdone[0][0]

# 全局变量
session_data_path = "/home/ji/pythonScripts/NBA/session_data/"
data_path = "/home/ji/pythonScripts/NBA/DATA/"
databasefile = data_path + "runcontrol.db"
datafile_for_load = data_path + "gamelist.txt"
if not os.path.exists(data_path):
    os.mkdir(data_path)

# 删除文件,初始化
def begin_again():
    if os.path.exists(databasefile):
        os.remove(databasefile)
    if os.path.exists(datafile_for_load):
        os.remove(datafile_for_load)

def main():
    create_con_table(session_data_path)
    session_files = os.listdir(session_data_path)
    for sessionfile in session_files:
        doneornot = get_isdone(sessionfile)
        if doneornot != 'Y':
            extrac_json(session_data_path+'/'+sessionfile)
            upd_isdone(sessionfile)
        else:
            continue

# 初始化,重新解析
# begin_again()

main()


#main
'''
You are DA MAIN you must be clean
and consise and beautiful (such beautiful)
'''
import math
import random
import sys, pygame
from pygame.locals import*
import copy
import os
import controller
import view
import model
import entities

def main():
	pygame.init()

	displayWidth = 640
	displayHeight = 640

	screen = pygame.display.set_mode((displayWidth, displayHeight))
	grid = model.Grid(40, 40, model.EMPTY, 20, 20)

	view.loadSprites()

	grid.entityList = model.initialEntities(grid)
	'''
	tl = entities.Point(0, 0)
	tr = entities.Point(0, 19)
	bl = entities.Point(19, 0)
	br = entities.Point(19, 19)
	topLeft = entities.MonsterEnergy('me', tl)
	topRight = entities.MonsterEnergy('me', tr)
	bottomLeft = entities.MonsterEnergy('me', bl)
	bottomRight = entities.MonsterEnergy('me', br)
	grid.entityList = [topLeft, topRight, bottomLeft, bottomRight]
	'''
	model.placeEntities(grid)

#must be placed elsewhere

	gatherer = grid.entityList[0]
	gatherer.aim = grid.entityList[2]
	for entity in grid.entityList:
		if isinstance(entity, entities.MonsterEnergy):
			gatherer.aim = entity
			break
	print (gatherer.aim)

	resetCopy = controller.returnCopiesOf(grid.entityList)

	while 1:
		for event in pygame.event.get():
			keys = pygame.key.get_pressed()
			mouse = pygame.mouse.get_pressed()
			x, y = pygame.mouse.get_pos()
			p = controller.clickToPoint(grid, x, y)

			if event.type == QUIT:
				pygame.quit()
				sys.exit()
			if mouse[0]:
				controller.handleLeftClicks(grid, keys, p)
			if mouse[2]:
				controller.handleRightClicks(grid, p)

			if keys[K_0]:
				grid.keyPressed = 0
				print("Key pressed 0")
				grid = model.resetGrid(resetCopy)
				grid.entityList = controller.returnCopiesOf(resetCopy)
				gatherer = grid.entityList[0]
				grid.spacePressed = False
			if keys[K_s]:
				controller.save(grid)
			if keys[K_l]:
				controller.load(grid)

			controller.handleKeys(grid, keys, gatherer)

		#controller.takeAction(grid, grid.spacePressed, grid.keyPressed, gatherer)
		if grid.spacePressed:
			controller.updateGatherers(grid)
		view.draw(screen, grid, grid.screenW, grid.screenH)

		#view.handleSprites(screen, entityList)

		controller.cleanUp(grid.entityList)
		pygame.display.flip()

		model.placeEntities(grid)

if __name__ == '__main__':
	main()

'''
if keys[K_0]:
	grid.keyPressed = 0
	print("Key pressed 0")
	grid = model.resetGrid(resetCopy)
	grid.entityList = controller.returnCopiesOf(resetCopy)
	gatherer = entityList[0]
	grid.spacePressed = False

elif keys[K_1]:
	grid.keyPressed = 1
	print ("Key pressed 1")
	gatherer.aim = controller.determineNearest(entityList, entityList[0])
	grid.spacePressed = False
	print gatherer.aim

elif keys[K_2]:
	grid.keyPressed = 2
	print("Key pressed 2")
	gatherer.aim = controller.determineFarthest(entityList, entityList[0])
	grid.spacePressed = False
	print gatherer.aim

if keys[K_SPACE]:
	print ("Key pressed Space")
	grid.spacePressed = True

if keys[K_RIGHT]:
	print ("Key pressed Right")
	pass
'''


from socket import *
from threading import Thread
from mysite.net import NetFile
from queue import Queue
import json

HOST = '192.168.35.84' # 클라우드 서버 주소
PORT = 6000
STREAM_PORT = 6001

class Proxy(NetFile):
    def __init__(self, id, dtype, c_socket):
        super().__init__(c_socket)
        self.id = id
        self.dtype = dtype

    def ping(self):
        self.send_json({'cmd': 'ping'})
        pong = self.readline()
        print(f'{self.id} ', pong)

    def command(self, cmd, kwargs = {}):
        try:
            self.send_json({'cmd': cmd, 'kwargs': kwargs})
            return True
        except:
            print(f'{cmd} 전송 실패')
            pool.reave(self.id)
            return False

class CameraProxy(Proxy, Thread):   # Camera Subject
    def __init__(self, id, dtype, c_socket):
        Thread.__init__(self)
        Proxy.__init__(self, id, dtype, c_socket)

        global STREAM_PORT
        STREAM_PORT += 1

        self.port = STREAM_PORT
        self.setDaemon(True)
        self.queue = Queue()
        self.observers = []
        self.start()

    def regist(self, ob):
        self.observers.append(ob)
        if len(self.observers) == 1:
            self.command("start_stream", kwargs = {"host": HOST, "port": self.port})
            print('연결된 포트 : ', self.port)

    def unregist(self, ob):
        self.observers.remove(ob)
        if not self.observers:
            self.command("stop_stream")

    def notify_all(self, data):
        for ob in self.observers:
            ob.update(data)

    def run(self):
        # STREAM은 UDP 통신으로 처리
        with socket(type= SOCK_DGRAM) as s:
            try:
                s.bind((HOST, self.port))
                while True:
                    # 패킷의 크기 주의
                    data, addr = s.recvfrom(150000)
                    self.notify_all(data)
            except Exception as e:
                print(e)
                print('send stop_stream')
                self.command('stop_stream')

class MjpegObserver:
    def __init__(self, subject):
        self.queue = Queue(1)
        self.subject = subject

    def update(self, data):
        if self.queue.empty():
            self.queue.put(data)

    def mjpeg(self):
        print('regist')
        self.subject.regist(self)
        try:
            while True:
                print('큐의 크기 : ', self.queue.qsize())
                data = self.queue.get()
                print(len(data))
                # yield (b'--frame\r\n'
                #         b'Content-Length: ' + f'{len(data)}'.encode() + b'\r\n'
                #         b'Content-Type: image/jpeg\cr\n\r\n' + data + b'\r\n')

                yield (b'--myboundary\n'
                    b'Content-Type::image/jpeg\n'
                    b'Content-Length: ' + f"{len(data)}".encode() + b'\n'
                    b'\n' + data + b'\n')

        finally :
            print('unregist')
            self.subject.unregist(self)

def create_proxy(c_socket):
    buf = c_socket.recv(1024)
    msg = json.loads(buf)
    device_id = msg.get('id')
    dtype = msg.get('dtype')

    if dtype == 'CAMERA':
        proxy = CameraProxy(device_id, dtype, c_socket)
    else:
        proxy = Proxy(device_id, dtype, c_socket)

    pool.join(msg['id'], proxy)

class ProxyPool(Thread):
    def __init__(self):
        super().__init__()
        self.setDaemon(True)
        self.pool = {}

    def join(self, id, proxy):
        self.pool[id] = proxy
        print('device join', id)

    def leave(self, id):
        self.pool[id] = None
        print('device leave', id)

    def get(self, id):
        proxy = self.pool.get(id)
        if proxy:
            try: # 접속 유지 상태인지 확인
                proxy.ping()
                return proxy
            except:
                self.leave(proxy.id)
        else:
            print('pool에 등록되지 않음', id)
        return None

    def run(self):
        with socket() as s:
            s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            s.settimeout(1)
            s.bind((HOST, PORT))
            s.listen(1)
            while True:
                try:
                    client_socket, _ = s.accept()
                    Thread(target= create_proxy, args=(client_socket,)).start()
                except Exception as e:
                    if e.__class__.__name__ == 'timeout': pass
                    else: print(e)

pool = ProxyPool()
pool.start()


from playground.common.datastructures import HierarchicalDictionary
from playground.common import CustomConstant

class PacketDefinitionRegistration(object):
    class DefinitionPOD(object):

        def __init__(self):
            self.versions = {}
            self.majorMax = 0
            self.minorMax = {0:0}

    MOST_RECENT = CustomConstant(strValue="MOST RECENT")

    def __init__(self):
        self.__definitions = HierarchicalDictionary()

    def getDefinition(self, identifier, version=MOST_RECENT, permitCompatible=False):
        definitionData = self.__definitions.get(identifier, None)
        if not definitionData or not definitionData.versions: return None

        if version == self.MOST_RECENT:
            version = PacketDefinitionVersion(definitionData.majorMax, definitionData.minorMax[definitionData.majorMax])
        if version in definitionData.versions:
            return definitionData.versions[version]

        if findCompatibleVersion:
            if version.major in definitionData.minorMax:
                compatibleVersion = PacketDefinitionVersion(version.major, definitionData.minorMax[version.major])
                return definitionData.versions[compatibleVersion]
        return None

    def hasDefinition(self, identifier, version=MOST_RECENT):
        definition = self.getDefinition(identifier, version)
        return definition != None

    def registerDefinition(self, identifier, version, definition):
        definitionData = self.__definitions.get(identifier, self.DefinitionPOD())
        definitionData.versions[version] = definition
        definitionData.majorMax = max(version.major, definitionData.majorMax)
        definitionData.minorMax[version.major] = max(definitionData.minorMax.get(version.major, 0), version.minor)
        self.__definitions[identifier] = definitionData

    def __iter__(self):
        return self.__definitions.__iter__()

g_DefaultPacketDefinitions = PacketDefinitionRegistration()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from tkinter import filedialog
from tkinter import *
import openpyxl
from openpyxl import load_workbook
import ctypes
from os.path import expanduser
from datetime import date

today = date.today()
d_str = today.strftime(' - %d%m%Y')

root = Tk()
root.withdraw()

home = expanduser('~')

root.filename = filedialog.askopenfilenames(title = 'Select Watchlist Excel Sheet', \
                                           filetypes = [('Excel Files', '.xls .xlsx')], \
                                           initialdir = home)
watchlist_xlsx = root.filename

fs = ''

for watchlist in watchlist_xlsx:
    wb = load_workbook(watchlist)

    terms = []

    first_sheet = wb.sheetnames[0]
    sheet = wb[first_sheet]

    for row in range(2,sheet.max_row+1):
            cell_name = "{}{}".format('A', row)
            terms.append(sheet[cell_name].value)

    out_file = watchlist.rstrip('.xlsx')
    out_file = out_file + d_str + '.txt'
    fs = fs + out_file + '\n'

    with open(out_file, 'w', newline = '') as fhandle:
        for term in terms:
            fhandle.write(term+'\n')

message = 'Keywords written to the following text file(s):\n%s' % (fs)
ctypes.windll.user32.MessageBoxW(0, message, 'Result', 0)


# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from collections import OrderedDict
import functools
import re
from typing import Dict, Sequence, Tuple, Type, Union
import pkg_resources

import google.api_core.client_options as ClientOptions # type: ignore
from google.api_core import exceptions as core_exceptions  # type: ignore
from google.api_core import gapic_v1                   # type: ignore
from google.api_core import retry as retries           # type: ignore
from google.auth import credentials as ga_credentials   # type: ignore
from google.oauth2 import service_account              # type: ignore

from google.home.enterprise.sdm_v1.services.smart_device_management_service import pagers
from google.home.enterprise.sdm_v1.types import device
from google.home.enterprise.sdm_v1.types import site
from google.home.enterprise.sdm_v1.types import smart_device_management_service
from google.protobuf import struct_pb2  # type: ignore
from .transports.base import SmartDeviceManagementServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import SmartDeviceManagementServiceGrpcAsyncIOTransport
from .client import SmartDeviceManagementServiceClient

class SmartDeviceManagementServiceAsyncClient:
    """A service that allows API consumers to provision and manage
    Google Home structures and devices for enterprise use cases.
    """

    _client: SmartDeviceManagementServiceClient

    DEFAULT_ENDPOINT = SmartDeviceManagementServiceClient.DEFAULT_ENDPOINT
    DEFAULT_MTLS_ENDPOINT = SmartDeviceManagementServiceClient.DEFAULT_MTLS_ENDPOINT

    device_path = staticmethod(SmartDeviceManagementServiceClient.device_path)
    parse_device_path = staticmethod(SmartDeviceManagementServiceClient.parse_device_path)
    room_path = staticmethod(SmartDeviceManagementServiceClient.room_path)
    parse_room_path = staticmethod(SmartDeviceManagementServiceClient.parse_room_path)
    structure_path = staticmethod(SmartDeviceManagementServiceClient.structure_path)
    parse_structure_path = staticmethod(SmartDeviceManagementServiceClient.parse_structure_path)
    common_billing_account_path = staticmethod(SmartDeviceManagementServiceClient.common_billing_account_path)
    parse_common_billing_account_path = staticmethod(SmartDeviceManagementServiceClient.parse_common_billing_account_path)
    common_folder_path = staticmethod(SmartDeviceManagementServiceClient.common_folder_path)
    parse_common_folder_path = staticmethod(SmartDeviceManagementServiceClient.parse_common_folder_path)
    common_organization_path = staticmethod(SmartDeviceManagementServiceClient.common_organization_path)
    parse_common_organization_path = staticmethod(SmartDeviceManagementServiceClient.parse_common_organization_path)
    common_project_path = staticmethod(SmartDeviceManagementServiceClient.common_project_path)
    parse_common_project_path = staticmethod(SmartDeviceManagementServiceClient.parse_common_project_path)
    common_location_path = staticmethod(SmartDeviceManagementServiceClient.common_location_path)
    parse_common_location_path = staticmethod(SmartDeviceManagementServiceClient.parse_common_location_path)

    @classmethod
    def from_service_account_info(cls, info: dict, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
            info.

        Args:
            info (dict): The service account private key info.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            SmartDeviceManagementServiceAsyncClient: The constructed client.
        """
        return SmartDeviceManagementServiceClient.from_service_account_info.__func__(SmartDeviceManagementServiceAsyncClient, info, *args, **kwargs)  # type: ignore

    @classmethod
    def from_service_account_file(cls, filename: str, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
            file.

        Args:
            filename (str): The path to the service account private key json
                file.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            SmartDeviceManagementServiceAsyncClient: The constructed client.
        """
        return SmartDeviceManagementServiceClient.from_service_account_file.__func__(SmartDeviceManagementServiceAsyncClient, filename, *args, **kwargs)  # type: ignore

    from_service_account_json = from_service_account_file

    @property
    def transport(self) -> SmartDeviceManagementServiceTransport:
        """Returns the transport used by the client instance.

        Returns:
            SmartDeviceManagementServiceTransport: The transport used by the client instance.
        """
        return self._client.transport

    get_transport_class = functools.partial(type(SmartDeviceManagementServiceClient).get_transport_class, type(SmartDeviceManagementServiceClient))

    def __init__(self, *,
            credentials: ga_credentials.Credentials = None,
            transport: Union[str, SmartDeviceManagementServiceTransport] = "grpc_asyncio",
            client_options: ClientOptions = None,
            client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
            ) -> None:
        """Instantiates the smart device management service client.

        Args:
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
            transport (Union[str, ~.SmartDeviceManagementServiceTransport]): The
                transport to use. If set to None, a transport is chosen
                automatically.
            client_options (ClientOptions): Custom options for the client. It
                won't take effect if a ``transport`` instance is provided.
                (1) The ``api_endpoint`` property can be used to override the
                default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
                environment variable can also be used to override the endpoint:
                "always" (always use the default mTLS endpoint), "never" (always
                use the default regular endpoint) and "auto" (auto switch to the
                default mTLS endpoint if client certificate is present, this is
                the default value). However, the ``api_endpoint`` property takes
                precedence if provided.
                (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
                is "true", then the ``client_cert_source`` property can be used
                to provide client certificate for mutual TLS transport. If
                not provided, the default SSL client certificate will be used if
                present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
                set, no client certificate will be used.

        Raises:
            google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
                creation failed for any reason.
        """
        self._client = SmartDeviceManagementServiceClient(
            credentials=credentials,
            transport=transport,
            client_options=client_options,
            client_info=client_info,

        )

    async def get_device(self,
            request: smart_device_management_service.GetDeviceRequest = None,
            *,
            retry: retries.Retry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
            ) -> device.Device:
        r"""Gets a device managed by the enterprise.

        Args:
            request (:class:`google.home.enterprise.sdm_v1.types.GetDeviceRequest`):
                The request object. Request message for
                SmartDeviceManagementService.GetDevice
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.home.enterprise.sdm_v1.types.Device:
                Device resource represents an
                instance of enterprise managed device in
                the property.

        """
        # Create or coerce a protobuf request object.
        request = smart_device_management_service.GetDeviceRequest(request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.get_device,
            default_retry=retries.Retry(
initial=1.0,maximum=10.0,multiplier=1.3,                predicate=retries.if_exception_type(
                    core_exceptions.ServiceUnavailable,
                ),
                deadline=60.0,
            ),
            default_timeout=60.0,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((
                ("name", request.name),
            )),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def list_devices(self,
            request: smart_device_management_service.ListDevicesRequest = None,
            *,
            retry: retries.Retry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
            ) -> pagers.ListDevicesAsyncPager:
        r"""Lists devices managed by the enterprise.

        Args:
            request (:class:`google.home.enterprise.sdm_v1.types.ListDevicesRequest`):
                The request object. Request message for
                SmartDeviceManagementService.ListDevices
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.home.enterprise.sdm_v1.services.smart_device_management_service.pagers.ListDevicesAsyncPager:
                Response message for
                SmartDeviceManagementService.ListDevices
                Iterating over this object will yield
                results and resolve additional pages
                automatically.

        """
        # Create or coerce a protobuf request object.
        request = smart_device_management_service.ListDevicesRequest(request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.list_devices,
            default_retry=retries.Retry(
initial=1.0,maximum=10.0,multiplier=1.3,                predicate=retries.if_exception_type(
                    core_exceptions.ServiceUnavailable,
                ),
                deadline=60.0,
            ),
            default_timeout=60.0,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((
                ("parent", request.parent),
            )),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # This method is paged; wrap the response in a pager, which provides
        # an `__aiter__` convenience method.
        response = pagers.ListDevicesAsyncPager(
            method=rpc,
            request=request,
            response=response,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def execute_device_command(self,
            request: smart_device_management_service.ExecuteDeviceCommandRequest = None,
            *,
            retry: retries.Retry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
            ) -> smart_device_management_service.ExecuteDeviceCommandResponse:
        r"""Executes a command to device managed by the
        enterprise.

        Args:
            request (:class:`google.home.enterprise.sdm_v1.types.ExecuteDeviceCommandRequest`):
                The request object. Request message for
                SmartDeviceManagementService.ExecuteDeviceCommand
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.home.enterprise.sdm_v1.types.ExecuteDeviceCommandResponse:
                Response message for
                SmartDeviceManagementService.ExecuteDeviceCommand

        """
        # Create or coerce a protobuf request object.
        request = smart_device_management_service.ExecuteDeviceCommandRequest(request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.execute_device_command,
            default_timeout=60.0,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((
                ("name", request.name),
            )),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def get_structure(self,
            request: smart_device_management_service.GetStructureRequest = None,
            *,
            retry: retries.Retry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
            ) -> site.Structure:
        r"""Gets a structure managed by the enterprise.

        Args:
            request (:class:`google.home.enterprise.sdm_v1.types.GetStructureRequest`):
                The request object. Request message for
                SmartDeviceManagementService.GetStructure
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.home.enterprise.sdm_v1.types.Structure:
                Structure resource represents an
                instance of enterprise managed home or
                hotel room.

        """
        # Create or coerce a protobuf request object.
        request = smart_device_management_service.GetStructureRequest(request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.get_structure,
            default_retry=retries.Retry(
initial=1.0,maximum=10.0,multiplier=1.3,                predicate=retries.if_exception_type(
                    core_exceptions.ServiceUnavailable,
                ),
                deadline=60.0,
            ),
            default_timeout=60.0,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((
                ("name", request.name),
            )),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def list_structures(self,
            request: smart_device_management_service.ListStructuresRequest = None,
            *,
            retry: retries.Retry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
            ) -> pagers.ListStructuresAsyncPager:
        r"""Lists structures managed by the enterprise.

        Args:
            request (:class:`google.home.enterprise.sdm_v1.types.ListStructuresRequest`):
                The request object. Request message for
                SmartDeviceManagementService.ListStructures
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.home.enterprise.sdm_v1.services.smart_device_management_service.pagers.ListStructuresAsyncPager:
                Response message for
                SmartDeviceManagementService.ListStructures
                Iterating over this object will yield
                results and resolve additional pages
                automatically.

        """
        # Create or coerce a protobuf request object.
        request = smart_device_management_service.ListStructuresRequest(request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.list_structures,
            default_retry=retries.Retry(
initial=1.0,maximum=10.0,multiplier=1.3,                predicate=retries.if_exception_type(
                    core_exceptions.ServiceUnavailable,
                ),
                deadline=60.0,
            ),
            default_timeout=60.0,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((
                ("parent", request.parent),
            )),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # This method is paged; wrap the response in a pager, which provides
        # an `__aiter__` convenience method.
        response = pagers.ListStructuresAsyncPager(
            method=rpc,
            request=request,
            response=response,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def get_room(self,
            request: smart_device_management_service.GetRoomRequest = None,
            *,
            retry: retries.Retry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
            ) -> site.Room:
        r"""Gets a room managed by the enterprise.

        Args:
            request (:class:`google.home.enterprise.sdm_v1.types.GetRoomRequest`):
                The request object. Request message for
                SmartDeviceManagementService.GetRoom
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.home.enterprise.sdm_v1.types.Room:
                Room resource represents an instance
                of sub-space within a structure such as
                rooms in a hotel suite or rental
                apartment.

        """
        # Create or coerce a protobuf request object.
        request = smart_device_management_service.GetRoomRequest(request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.get_room,
            default_retry=retries.Retry(
initial=1.0,maximum=10.0,multiplier=1.3,                predicate=retries.if_exception_type(
                    core_exceptions.ServiceUnavailable,
                ),
                deadline=60.0,
            ),
            default_timeout=60.0,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((
                ("name", request.name),
            )),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def list_rooms(self,
            request: smart_device_management_service.ListRoomsRequest = None,
            *,
            retry: retries.Retry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
            ) -> pagers.ListRoomsAsyncPager:
        r"""Lists rooms managed by the enterprise.

        Args:
            request (:class:`google.home.enterprise.sdm_v1.types.ListRoomsRequest`):
                The request object. Request message for
                SmartDeviceManagementService.ListRooms
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.home.enterprise.sdm_v1.services.smart_device_management_service.pagers.ListRoomsAsyncPager:
                Response message for
                SmartDeviceManagementService.ListRooms
                Iterating over this object will yield
                results and resolve additional pages
                automatically.

        """
        # Create or coerce a protobuf request object.
        request = smart_device_management_service.ListRoomsRequest(request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.list_rooms,
            default_retry=retries.Retry(
initial=1.0,maximum=10.0,multiplier=1.3,                predicate=retries.if_exception_type(
                    core_exceptions.ServiceUnavailable,
                ),
                deadline=60.0,
            ),
            default_timeout=60.0,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((
                ("parent", request.parent),
            )),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # This method is paged; wrap the response in a pager, which provides
        # an `__aiter__` convenience method.
        response = pagers.ListRoomsAsyncPager(
            method=rpc,
            request=request,
            response=response,
            metadata=metadata,
        )

        # Done; return the response.
        return response

try:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
        gapic_version=pkg_resources.get_distribution(
            "google-home-enterprise-sdm",
        ).version,
    )
except pkg_resources.DistributionNotFound:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()

__all__ = (
    "SmartDeviceManagementServiceAsyncClient",
)


from wthings_gateway.connectors.converter import Converter, log

class PlcUplinkConverter(Converter):
    def __init__(self, config):
        self.__config = config
        self.result_dict = {
            'deviceName': config.get('deviceName', 'plcDevice'),
            'deviceType': config.get('deviceType', 'default'),
            'attributes': [],
            'telemetry': []
        }

    def convert(self, config, data):
        # keys = ['attributes', 'timeseries']
        information_types = {"attributes": "attributes", "timeseries": "telemetry"}
        for key in information_types:
            self.result_dict[information_types[key]] = []
            if self.__config.get(key) is not None:
                for config_object in self.__config.get(key):
                    value_key = config_object['key']
                    value = data[key].get(value_key, None)
                    if value != None:
                        self.result_dict[information_types[key]].append({value_key: value})
        return self.result_dict

if __name__ == '__main__':
    pass


"""
Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
"""

class Solution(object):
    def dfs(self, curr, remaining):
        if not remaining:
            return [curr]

        permutations = []
        for idx in xrange(len(remaining)):
            num = remaining.pop(idx)
            new_curr = curr + [num]
            permutations.extend(self.dfs(new_curr, remaining))
            remaining.insert(idx, num)
        return permutations

    def permute(self, nums):
        return self.dfs([], nums)


from  selfdrive.conf_kegman import conf_kegman

class ConfAtom():
  def __init__(self, CP=None):
    self.kegman = conf_kegman()

    self.cv_steerRatioV = [[13.85]]
    self.cv_ActuatorDelayV = [[0.1]]
    self.cv_KPH    = [0.]   # Speed  kph
    self.cv_BPV    = [[200, 255]]  # CV
    self.cv_sMaxV  = [[384, 255]]
    self.cv_sdUPV  = [[3,1]]
    self.cv_sdDNV  = [[7,1]]

    self.read_tune()

  def read_tune(self):
    conf = self.kegman.read_config()

    self.cv_KPH  = conf['cv_KPH']
    self.cv_BPV  = conf['cv_BPV']
    self.cv_sMaxV  = conf['cv_sMaxV']
    self.cv_sdUPV  = conf['cv_sdUPV']
    self.cv_sdDNV = conf['cv_sdDNV']
    self.cv_steerRatioV  = conf['cv_steerRatioV']
    self.cv_ActuatorDelayV = conf['cv_ActuatorDelayV']


def main():
    player = init_entity('Введите данные игрока')
    enemy = init_entity('Введите данные врага')
    atack(player,enemy)
    print(enemy)

def init_entity(note):
    print(note)
    entity = {'name':None,'health':None, 'damage':None}
    try:
        entity['name'] = input('Введите имя: ')
        entity['health'] = int(input('Введите величину здоровья (целое, положительное): '))
        entity['damage'] = int(input('Введите величину урона (целое, положительное: '))
        return entity
    except (TypeError, ValueError):
        print('Величины должны быть целыми положительными числами. Попробуйте ещё раз')
        return init_entity(note)

def atack(player,enemy):
    enemy['health'] -= player['damage']

main()


# coding=utf-8
from distutils.core import setup

from setuptools import find_packages

reqs = [
        'GelReportModels==4.3.4',
        'opencga4gel==0.8.1'
]
setup(
        name='cip_dispatch',
        version='0.2.3',
        packages=find_packages(),
        url='',
        license='',
        author=['cboustred'],
        author_email='christopher.boustred@genomicsengland.co.uk',
        description='',
        install_requires=reqs,
)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Name : Sourav Yadav
AID : A20450418

"""

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pandas
import sklearn
import sklearn.neural_network as nn
import sklearn.metrics as metrics
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt

#Import Dataset
dataframe = pd.read_csv('C:\\Users\\soura\\OneDrive\\Desktop\\ML\\ML Spring20_Assignemnt\\HW5\\SpiralWithCluster.csv')

dataframe.head()

#-----------------------------------1.a------------------------------------
no_of_obs = dataframe.shape[0]
no_of_obs_spe_clu_1 = dataframe[dataframe['SpectralCluster'] == 1].shape[0]
per_obs_spe_clu_1 = (no_of_obs_spe_clu_1) / no_of_obs
print('Percentage of Obeserved Spectral Cluster = 1: ', 100 * per_obs_spe_clu_1)

#-----------------------------------1.b------------------------------------
act_funs = ['identity', 'logistic', 'relu', 'tanh']
num_of_layers = range(1, 6, 1)
n_neurons_per_layer = range(1, 11, 1)
result = pd.DataFrame(columns=['Index', 'ActivationFunction', 'nLayers', 'nNeuronsPerLayer', 'nIterations', 'Loss', 'MisclassificationRate'])
index = 0
# looping for all possible networks for given configuration
for act_fun in act_funs:
    min_loss = float("inf")
    min_miss_rate = float("inf")
    n_lyrs = -1
    n_npl = -1
    niter = -1
    for no_lyrs in num_of_layers:
        for no_npl in n_neurons_per_layer:
            # building the neural network
            nn_obj = nn.MLPClassifier(hidden_layer_sizes=(no_npl,) * no_lyrs, activation=act_fun, verbose=False, solver='lbfgs', learning_rate_init=0.1, max_iter=5000, random_state=20200408)
            this_fit = nn_obj.fit(dataframe[['x', 'y']], dataframe[['SpectralCluster']])
            y_pred = nn_obj.predict_proba(dataframe[['x', 'y']])
            n_iter = nn_obj.n_iter_
            loss = nn_obj.loss_

            target_y = dataframe[['SpectralCluster']]
            no_targets = target_y.shape[0]

            # to determine the predicted class
            pred_y = np.empty_like(target_y)
            threshold = per_obs_spe_clu_1
            for i in range(no_targets):
                if y_pred[i][0] >= threshold:
                    pred_y[i] = 0
                else:
                    pred_y[i] = 1

            # calculating accuracy and misclassification rate
            accuracy = metrics.accuracy_score(target_y, pred_y)
            miss_rate = 1 - accuracy

            # finding neural network with minimum loss and misclassification rate
            if loss <= min_loss and miss_rate <= min_miss_rate:
                min_loss = loss
                min_miss_rate = miss_rate
                n_lyrs = no_lyrs
                n_npl = no_npl
                niter = n_iter

    result = result.append(pd.DataFrame([[index, act_fun, n_lyrs, n_npl, niter, min_loss, min_miss_rate]], columns=['Index', 'ActivationFunction', 'nLayers', 'nNeuronsPerLayer', 'nIterations', 'Loss', 'MisclassificationRate']))
    index += 1
result = result.set_index('Index')
pd.set_option('display.max_columns', 10)
print(result)

#-----------------------------------1.c------------------------------------
print('Activation funciton: ', nn_obj.out_activation_)

#-----------------------------------1.d------------------------------------
min_loss = float("inf")
min_miss_rate = float("inf")
index = None
# finding activation function, number of layers, and number of neurons per layer with minimum loss and misclassification rate
for ind, row in result.iterrows():
    if row['Loss'] <= min_loss and row['MisclassificationRate'] <= min_miss_rate:
        index = ind
        min_loss = row['Loss']
        min_miss_rate = row['MisclassificationRate']

print(result.loc[index])

# building neural network with minimum loss and misclassification rate
nn_obj = nn.MLPClassifier(hidden_layer_sizes=(result.loc[index]['nNeuronsPerLayer'],) * result.loc[index]['nLayers'], activation=result.loc[index]['ActivationFunction'], verbose=False, solver='lbfgs', learning_rate_init=0.1, max_iter=5000, random_state=20200408)
this_fit = nn_obj.fit(dataframe[['x', 'y']], dataframe[['SpectralCluster']])
y_pred = nn_obj.predict_proba(dataframe[['x', 'y']])

target_y = dataframe[['SpectralCluster']]
no_targets = target_y.shape[0]

# determining the predicted class
pred_y = np.empty_like(target_y)
threshold = per_obs_spe_clu_1
for i in range(no_targets):
    if y_pred[i][0] >= threshold:
        pred_y[i] = 0
    else:
        pred_y[i] = 1

dataframe['y_pred_0'] = y_pred[:, 0]
dataframe['y_pred_1'] = y_pred[:, 1]
dataframe['class'] = pred_y

target_y = dataframe[['SpectralCluster']]
accuracy = metrics.accuracy_score(target_y, pred_y)
miss_rate = 1 - accuracy

print('\n Accuracy: ', 100 * accuracy)
print('Misclassification rate: ', miss_rate)

#-----------------------------------1.e------------------------------------
color_array = ['red', 'blue']
for i in range(2):
    x_y = dataframe[dataframe['class'] == i]
    plt.scatter(x_y['x'], x_y['y'], c=color_array[i], label=i)
plt.xlabel('x - coordinate')
plt.ylabel('y - coordinate')
plt.title('Scatter Plot of Spiral Cluster Coordinates')
plt.legend(title='Predicted_Cluster', loc='best')
plt.grid(True)
plt.show()

#-----------------------------------1.f------------------------------------
pd.set_option('float_format', '{:.10f}'.format)
print(dataframe[dataframe['class'] == 1]['y_pred_1'].describe())

#-------------------------------------Question 2--------------------------#
import pandas as pd
import numpy as np
import sklearn.metrics as metrics
import sklearn.svm as svm
import matplotlib.pyplot as plt
import warnings

warnings.filterwarnings("ignore")

spiral_with_cluster = dataframe

# building svm classifier
x_train = spiral_with_cluster[['x', 'y']]
y_train = spiral_with_cluster['SpectralCluster']

svm_model = svm.SVC(kernel='linear', decision_function_shape='ovr', random_state=20200408, max_iter=-1)
this_fit = svm_model.fit(x_train, y_train)

#-----------------------------------2.a------------------------------------

print('Intercept is ', this_fit.intercept_)
print('Coefficients are ', np.round(this_fit.coef_, 7))
print(
    'Separating Hyperplane Eq. is  ==> '
    f'({np.round(this_fit.intercept_[0], 7)}) '
    f'+ ({np.round(this_fit.coef_[0][0], 7)}*x_1) '
    f'+ ({np.round(this_fit.coef_[0][1], 7)}*x_2) = 𝟎')

#-----------------------------------2.b------------------------------------
y_predict_class = this_fit.predict(x_train)

# Accuracy and Misclassification rate
accuracy = metrics.accuracy_score(y_train, y_predict_class)
miss_rate = 1 - accuracy
print('Accuracy of the SVM: ', accuracy)
print('Misclassification rate of the SVM : ', miss_rate)

#-----------------------------------2.c------------------------------------

spiral_with_cluster['pred_class'] = y_predict_class

# Getting the hyperplane
xx = np.linspace(-5, 5)
yy = np.zeros((len(xx), 1))
for j in range(1):
    w = this_fit.coef_[j, :]
    a = -w[0] / w[1]
    yy[:, j] = a * xx - (this_fit.intercept_[j]) / w[1]

# Plotting the line, coordinates, and the nearest vectors to the plane
color_array = ['red', 'blue']
for i in range(2):
    x_y = spiral_with_cluster[spiral_with_cluster['pred_class'] == i]
    plt.scatter(x_y['x'], x_y['y'], c=color_array[i], label=i)
plt.plot(xx, yy[:, 0], color='black', linestyle='--')
plt.xlabel('X - coordinate')
plt.ylabel('Y - coordinate')
plt.title('SVM on 2 Segments')
plt.legend(title='Predicted Cluster', loc='best')
plt.grid(True)
plt.show()

#-----------------------------------2.d------------------------------------

def custArcTan(z):
    theta = np.where(z < 0.0, 2.0 * np.pi + z, z)
    return (theta)

# Getting radius and theta coordinates
spiral_with_cluster['radius'] = np.sqrt(spiral_with_cluster['x'] ** 2 + spiral_with_cluster['y'] ** 2)
spiral_with_cluster['theta'] = np.arctan2(spiral_with_cluster['y'], spiral_with_cluster['x']).apply(custArcTan)

# Plotting the polar coordinates
color_array = ['red', 'blue']
for i in range(2):
    x_y = spiral_with_cluster[spiral_with_cluster['SpectralCluster'] == i]
    plt.scatter(x_y['radius'], x_y['theta'], c=color_array[i], label=i)
plt.xlabel('Radius - Coordinate')
plt.ylabel('Theta - Coordinate')
plt.ylim(-1, 7)
plt.title('SVM on Two Segments')
plt.legend(title='Spectral Cluster', loc='best')
plt.grid(True)
plt.show()

#-----------------------------------2.c------------------------------------
group = np.zeros(spiral_with_cluster.shape[0])

# Creating four groups using the location of the coordinates
for index, row in spiral_with_cluster.iterrows():
    if row['radius'] < 1.5 and row['theta'] > 6:
        group[index] = 0
    elif row['radius'] < 2.5 and row['theta'] > 3:
        group[index] = 1
    elif 2.5 < row['radius'] < 3 and row['theta'] > 5.5:
        group[index] = 1
    elif row['radius'] < 2.5 and row['theta'] < 3:
        group[index] = 2
    elif 3 < row['radius'] < 4 and 3.5 < row['theta'] < 6.5:
        group[index] = 2
    elif 2.5 < row['radius'] < 3 and 2 < row['theta'] < 4:
        group[index] = 2
    elif 2.5 < row['radius'] < 3.5 and row['theta'] < 2.25:
        group[index] = 3
    elif 3.55 < row['radius'] and row['theta'] < 3.25:
        group[index] = 3

spiral_with_cluster['group'] = group

# Plotting the divided coordinates
color_array = ['red', 'blue', 'green', 'black']
for i in range(4):
    x_y = spiral_with_cluster[spiral_with_cluster['group'] == i]
    plt.scatter(x=x_y['radius'], y=x_y['theta'], c=color_array[i], label=i)
plt.xlabel('Radius - Coordinates')
plt.ylabel('Theta - Coordinates')
plt.title('SVM on 4 Segments')
plt.legend(title='Group', loc='best')
plt.grid(True)
plt.show()

#-----------------------------------2.f------------------------------------

# build SVM 0: Group 0 versus Group 1
svm_1 = svm.SVC(kernel="linear", random_state=20200408, decision_function_shape='ovr', max_iter=-1)
subset1 = spiral_with_cluster[spiral_with_cluster['group'] == 0]
subset1 = subset1.append(spiral_with_cluster[spiral_with_cluster['group'] == 1])
train_subset1 = subset1[['radius', 'theta']]
svm_1.fit(train_subset1, subset1['SpectralCluster'])

# build SVM 1: Group 1 versus Group 2
svm_2 = svm.SVC(kernel="linear", random_state=20200408, decision_function_shape='ovr', max_iter=-1)
subset2 = spiral_with_cluster[spiral_with_cluster['group'] == 1]
subset2 = subset2.append(spiral_with_cluster[spiral_with_cluster['group'] == 2])
train_subset2 = subset2[['radius', 'theta']]
svm_2.fit(train_subset2, subset2['SpectralCluster'])

# build SVM 2: Group 2 versus Group 3
svm_3 = svm.SVC(kernel="linear", random_state=20200408, decision_function_shape='ovr', max_iter=-1)
subset3 = spiral_with_cluster[spiral_with_cluster['group'] == 2]
subset3 = subset3.append(spiral_with_cluster[spiral_with_cluster['group'] == 3])
train_subset3 = subset3[['radius', 'theta']]
svm_3.fit(train_subset3, subset3['SpectralCluster'])

print(f'Separating Hyperplane Eq. for SVM 0 is   ==> ' f'({np.round(svm_1.intercept_[0] ,7)})' f' + ({np.round(svm_1.coef_[0][0], 7)}*x_1)' f' + ({np.round(svm_1.coef_[0][1], 7)}*x_2) = 𝟎')
print(f'Separating Hyperplane Eq. for SVM 1 is   ==> ' f'({np.round(svm_2.intercept_[0] ,7)})' f' + ({np.round(svm_2.coef_[0][0], 7)}*x_1)' f' + ({np.round(svm_2.coef_[0][1], 7)}*x_2) = 𝟎')
print(f'Separating Hyperplane Eq. for SVM 2 is   ==> ' f'({np.round(svm_3.intercept_[0] ,7)})' f' + ({np.round(svm_3.coef_[0][0], 7)}*x_1)' f' + ({np.round(svm_3.coef_[0][1], 7)}*x_2) = 𝟎')

#-----------------------------------2.g------------------------------------
w = svm_1.coef_[0]
a = -w[0] / w[1]
xx1 = np.linspace(1, 4)
yy1 = a * xx1 - (svm_1.intercept_[0]) / w[1]

w = svm_2.coef_[0]
a = -w[0] / w[1]
xx2 = np.linspace(1, 4)
yy2 = a * xx2 - (svm_2.intercept_[0]) / w[1]

w = svm_3.coef_[0]
a = -w[0] / w[1]
xx3 = np.linspace(1, 4)
yy3 = a * xx3 - (svm_3.intercept_[0]) / w[1]

# Plotting the polar coordinates and hyperplanes
for i in range(4):
    x_y = spiral_with_cluster[spiral_with_cluster['group'] == i]
    plt.scatter(x_y['radius'], x_y['theta'], c=color_array[i], label=i)
plt.plot(xx1, yy1, color='black', linestyle='-')
plt.plot(xx2, yy2, color='black', linestyle='-')
plt.plot(xx3, yy3, color='black', linestyle='-')
plt.xlabel('Radius - Coordinates')
plt.ylabel('Theta - Coordinates')
plt.title('SVM on 4 Segments')
plt.legend(title='Group', loc='best', )
plt.grid(True)
plt.show()

#-----------------------------------2.h------------------------------------
h1_xx1, h1_yy1 = xx1 * np.cos(yy1), xx1 * np.sin(yy1)

h2_xx2, h2_yy2 = xx2 * np.cos(yy2), xx2 * np.sin(yy2)

h3_xx3, h3_yy3 = xx3 * np.cos(yy3), xx3 * np.sin(yy3)

# Plotting the line, coordinates, and the nearest vectors to the plane
color_array = ['red', 'blue']
for i in range(2):
    x_y = spiral_with_cluster[spiral_with_cluster['SpectralCluster'] == i]
    plt.scatter(x_y['x'], x_y['y'], c=color_array[i], label=i)
plt.plot(h1_xx1, h1_yy1, color='green', linestyle='--')
plt.plot(h2_xx2, h2_yy2, color='black', linestyle='--')
plt.plot(h3_xx3, h3_yy3, color='black', linestyle='--')
plt.xlabel('X - coordinates')
plt.ylabel('Y - coordinates')
plt.title('SVM on 2 Segments')
plt.legend(title='Spectral Cluster', loc='best')
plt.grid(True)
plt.show()


import tensorflow as tf
import numpy as np
from time import time
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics import roc_auc_score

class DCN(BaseEstimator, TransformerMixin):
    def __init__(self, cate_feature_size,field_size,numeric_feature_size,embedding_size=8,
                 deep_layers=[32,32],dropout_deep=[0.5,0.5,0.5],
                deep_layers_activation=tf.nn.relu,epoch=10,batch_size=256,
                 learning_rate=0.01,optimizer_type='adam',
                verbose=False,random_seed=2018,loss_type='logloss',
                eval_metric=roc_auc_score,l2_reg=0.0,cross_layer_num=3):
        assert loss_type in ["logloss", "rmse"], \
            "'logloss' for classification or 'rmse' for regression"

        self.cate_feature_size = cate_feature_size
        self.numeric_feature_size = numeric_feature_size
        self.field_size = field_size
        self.embedding_size = embedding_size
        self.total_size = self.field_size * self.embedding_size + self.numeric_feature_size
        self.deep_layers = deep_layers
        self.cross_layer_num = cross_layer_num
        self.dropout_deep = dropout_deep
        self.deep_layers_activation = deep_layers_activation
        self.l2_reg = l2_reg

        self.epoch = epoch
        self.batch_size = batch_size
        self.learning_rate = learning_rate
        self.optimizer_type = optimizer_type

        self.verbose = verbose
        self.random_seed = random_seed
        self.loss_type = loss_type
        self.eval_metric = eval_metric
        self.train_result,self.valid_result = [],[]

        self._init_graph()

    def _init_graph(self):
        self.graph = tf.Graph()
        with self.graph.as_default():
            tf.set_random_seed(self.random_seed)
            self.feat_index = tf.placeholder(tf.int32, shape=[None,None], name='feat_index')
            self.feat_value = tf.placeholder(tf.float32, shape=[None,None], name='feat_value')
            self.numeric_value = tf.placeholder(tf.float32, shape=[None,None],name='num_value')
            self.label = tf.placeholder(tf.float32,shape=[None,1],name='label')
            self.dropout_keep_deep = tf.placeholder(tf.float32,shape=[None],name='dropout_keep_deep')
            self.train_phase = tf.placeholder(tf.bool,name='train_phase')

            self.weights = self._initialize_weights()

            # model
            self.embeddings = tf.nn.embedding_lookup(self.weights['feature_embeddings'],self.feat_index) # N * F * K
            feat_value = tf.reshape(self.feat_value, shape=[-1,self.field_size,1])
            self.embeddings = tf.multiply(self.embeddings,feat_value)

            self.x0 = tf.concat([self.numeric_value,tf.reshape(self.embeddings,shape=[-1,self.field_size * self.embedding_size])], axis=1)

            # deep network
            self.y_deep = tf.nn.dropout(self.x0,self.dropout_keep_deep[0])

            for i in range(len(self.deep_layers)):
                self.y_deep = tf.add(tf.matmul(self.y_deep,self.weights['deep_layer_%d' % i]), self.weights['deep_bias_%d' % i])
                self.y_deep = self.deep_layers_activation(self.y_deep)
                self.y_deep = tf.nn.dropout(self.y_deep,self.dropout_keep_deep[i+1])

            # cross network
            self._x0 = tf.reshape(self.x0,(-1,self.total_size,1))
            x_l = self._x0
            for l in range(self.cross_layer_num):
                x_l = tf.tensordot(tf.matmul(self._x0,x_l, transpose_b=True),
                                       self.weights['cross_layer_%d' % l],1) + self.weights['cross_bias_%d' % l] + x_l
                self.cross_network_out = tf.reshape(x_l,(-1,self.total_size))

            # concat layer
            concat_input = tf.concat([self.cross_network_out, self.y_deep], axis=1)

            self.out = tf.add(tf.matmul(concat_input,self.weights['concat_projection']),self.weights['concat_bias'])

            # loss
            if self.loss_type == 'logloss':
                self.out = tf.nn.sigmoid(self.out)
                self.loss = tf.losses.log_loss(self.label,self.out)
            elif self.loss_type == 'rmse':
                self.loss = tf.sqrt(tf.losses.mean_squared_error(self.label,self.out))

            # l2_reg
            if self.l2_reg > 0:
                self.loss += tf.contrib.layers.l2_regularizer(self.l2_reg)(self.weights['concat_projection'])
                for i in range(len(self.deep_layers)):
                    self.loss += tf.contrib.layers.l2_regularizer(self.l2_reg)(self.weights['deep_layer_%d' % i])
                for i in range(len(self.cross_layer_num)):
                    self.loss += tf.contrib.layers.l2_regularizer(self.l2_reg)(self.weights['cross_layer_%d' % i])

            # optimization
            if self.optimizer_type == 'adam':
                self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate,beta1=0.9,beta2=0.999,epsilon=1e-8).minimize(self.loss)

            elif self.optimizer_type == 'adagrad':
                self.optimizer = tf.train.AdagradOptimizer(learning_rate=self.learning_rate, initial_accumulator_value=1e-8).minimize(self.loss)

            elif self.optimizer_type == 'gd':
                self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate).minimize(self.loss)

            elif self.optimizer_type == 'momentum':
                self.optimizer = tf.train.MomentumOptimizer(learning_rate=self.learning_rate, momentum=0.95).minimize(self.loss)

            # init
            self.saver = tf.train.Saver()
            init = tf.global_variables_initializer()
            self.sess = tf.Session()
            self.sess.run(init)

            # number of params
            total_parameters = 0
            for v in self.weights.values():
                shape = v.get_shape()
                value_params = 1
                for dim in shape:
                    value_params *= dim.value
                total_parameters += value_params

            if self.verbose > 0:
                print('Parames: %d' % total_parameters)

    def _initialize_weights(self):
        weights = dict()

        #embedding
        weights['feature_embeddings'] = tf.Variable(tf.random_normal([self.cate_feature_size,self.embedding_size],0.0,0.01),name='feature_embeddings')
        weights['feature_bias'] = tf.Variable(tf.random_normal([self.cate_feature_size,1],0.0,1.0),name='feature_bias')

        # deep network
        num_layer = len(self.deep_layers)
        glorot = np.sqrt(2.0 / (self.total_size + self.deep_layers[0]))

        weights['deep_layer_0'] = tf.Variable(np.random.normal(loc=0,scale=glorot,size=(self.total_size,self.deep_layers[0])),dtype=np.float32)
        weights['deep_bias_0'] = tf.Variable(np.random.normal(loc=0,scale=glorot,size=(1,self.deep_layers[0])),dtype=np.float32)

        for i in range(1, num_layer):
            glorot = np.sqrt(2.0 / (self.total_size + self.deep_layers[i]))
            # size = layers[i-1] * layers[i]
            weights['deep_layer_%d' % i] = tf.Variable(np.random.normal(loc=0,scale=glorot,size=(self.deep_layers[i-1],self.deep_layers[i])),dtype=np.float32)
            #size = 1 * layers[i]
            weights['deep_bias_%d' % i] = tf.Variable(np.random.normal(loc=0,scale=glorot,size=(1,self.deep_layers[i])),dtype=np.float32)

        # cross network

        for i in range(self.cross_layer_num):
            weights['cross_layer_%d' % i] = tf.Variable(np.random.normal(loc=0,scale=glorot,size=(self.total_size,1)), dtype=np.float32)
            weights['cross_bias_%d' % i] = tf.Variable(np.random.normal(loc=0,scale=glorot,size=(self.total_size,1)), dtype=np.float32)

        # Concat layers
        input_size = self.total_size + self.deep_layers[-1]

        glorot = np.sqrt(2.0 / (input_size + 1))
        weights['concat_projection'] = tf.Variable(np.random.normal(loc=0,scale=glorot,size=(input_size,1)),dtype=np.float32)
        weights['concat_bias'] = tf.Variable(tf.constant(0.01), dtype=np.float32)

        return weights

    def get_batch(self,Xi,Xv,Xv2,y,batch_size, index):
        start = index * batch_size
        end = (index + 1) * batch_size
        end = end if end < len(y) else len(y)
        return Xi[start:end], Xv[start:end],Xv2[start:end],[[y_] for y_ in y[start:end]]

    # shuffle three lists simutaneously
    def shuffle_in_unison_scary(self,a,b,c,d):
        rng_state = np.random.get_state()
        np.random.shuffle(a)
        np.random.set_state(rng_state)
        np.random.shuffle(b)
        np.random.set_state(rng_state)
        np.random.shuffle(c)
        np.random.set_state(rng_state)
        np.random.shuffle(d)

    def predict(self,Xi,Xv,Xv2,y):
        feed_dict = {self.feat_index: Xi,
                     self.feat_value: Xv,
                     self.numeric_value: Xv2,
                     self.label: y,
                     self.dropout_keep_deep: [1.0] * len(self.dropout_deep),
                     self.train_phase: True}

        loss = self.sess.run([self.loss], feed_dict=feed_dict)

        return loss

    def fit_on_batch(self,Xi,Xv,Xv2,y):
        feed_dict = {self.feat_index: Xi,
                     self.feat_value: Xv,
                     self.numeric_value: Xv2,
                     self.label: y,
                     self.dropout_keep_deep: [1.0] * len(self.dropout_deep),
                     self.train_phase: True}

        loss, opt = self.sess.run([self.loss,self.optimizer],feed_dict=feed_dict)

        return loss

    def fit(self,cate_Xi_train,cate_Xv_train,numeric_Xv_train,y_train,
           cate_Xi_valid=None,cate_Xv_valid=None,numeric_Xv_valid=None,y_valid=None,
           early_stopping=False,refit=False):
        """
        :Xi_train: feature index of feature field of sample in the training set
        :Xv_train: feature value of feature field of sample in the training set; can be either binary or float
        :y_train: label of each sample in the training set
        :Xi_valid: feature indices of each sample in the validation set
        :Xv_valid: feature values of each sample in the validation set
        :y_valid: label of each sample in the validation set
        :early_stopping: early stopping or not
        :refit: refit the model on the train+valid dataset or not
        """

        print(len(cate_Xi_train))
        print(len(cate_Xv_train))
        print(len(numeric_Xv_train))
        print(len(y_train))

        has_valid = cate_Xv_valid is not None

        for epoch in range(self.epoch):
            t1 = time()
            self.shuffle_in_unison_scary(cate_Xi_train,cate_Xv_train,numeric_Xv_train,y_train)
            total_batch = int(len(y_train) / self.batch_size)
            for i in range(total_batch):
                cate_Xi_batch, cate_Xv_batch, numeric_Xv_batch, y_batch = self.get_batch(cate_Xi_train,cate_Xv_train,numeric_Xv_train,y_train,self.batch_size,1)

                self.fit_on_batch(cate_Xi_batch,cate_Xv_batch,numeric_Xv_batch,y_batch)

            if has_valid:
                y_valid = np.array(y_valid).reshape((-1,1))
                loss = self.predict(cate_Xi_valid,cate_Xv_valid,numeric_Xv_valid,y_valid)
                print('epoch: ',epoch, 'loss:',loss)


shopping_ist = ["ab","bc","cd"]
found_item = "12"
found_at = None
for i in range(len(shopping_ist)) :
    if shopping_ist[i] == found_item:
        found_at = i
        break;
if found_at!=None:
    print("found the item at index {0}".format(found_at))
else:
    print("not found")


#!/usr/bin/python3

import sys;
import os;
import tempfile;
import shutil;
# https://docs.python.org/3.5/library/subprocess.html
import subprocess;
# https://docs.python.org/3.5/library/resource.html#resource.getrusage
import resource;
import csv;

def getSize(path):
  total_size = 0
  for dirpath, dirnames, filenames in os.walk(path):
    for f in filenames:
      fp = os.path.join(dirpath, f)
      total_size += os.path.getsize(fp)
  return total_size

def convertOutput(output):
  return output.decode("utf-8").replace('\\n','\n').replace('\\t','\t');

def writeError(outputDir, groupName, returnCode, errorMessage):
  with open(os.path.join(outputDir,groupName + ".err"),'w') as file:
    file.write("return code: " + str(returnCode) + "\n")
    file.write(errorMessage);

def writeOutput(outputDir, groupName, output):
  with open(os.path.join(outputDir,groupName + ".out"),'w') as file:
    file.write(output);

def writeResult(outputDir, line):
  resultCSV = os.path.join(outputDir,"results.csv");
  if not os.path.exists(resultCSV):
    with open(resultCSV, 'w', newline='') as csvfile:
      writer = csv.writer(csvfile);
      writer.writerow(['group','hasBuildError','hasExecutionError','hasTimeout','areResultsCorrect','avg. writing time (in msec)','memory consumption (in KBytes)', 'disk space (in Byte)']);
  with open(resultCSV, 'a+', newline='') as csvfile:
    writer = csv.writer(csvfile);
    writer.writerow(line);

def main(groupName, outputDir=os.path.join(tempfile.gettempdir(),"results"), timeout=60):
  # adjust call dir
  callDir = os.path.dirname(os.path.realpath(__file__));
  os.chdir(callDir);

  if not os.path.exists(outputDir):
    os.makedirs(outputDir);
  workingDir = os.path.join(tempfile.gettempdir(),"statistics_"+groupName);
  inputDir = "../chunks";
  #inputDir = "/home/janke/Dokumente/Promotion/conferences/ReasoningWebSummerSchool2018/chunks-500K";
  solutionDir = "../solution";
  #solutionDir = "/home/janke/Dokumente/Promotion/conferences/ReasoningWebSummerSchool2018/test/";

  try:
    writingTimes = list();
    beforeInfo = resource.getrusage(resource.RUSAGE_CHILDREN);
    for repetition in range(0,10):
      if os.path.exists(workingDir):
        shutil.rmtree(workingDir)
      try:
        result = subprocess.run(["java", "-cp", "build/jar/*:lib/*", "rw2018.statisticsEvaluation.EvaluationWrite", "-i" , inputDir, "-w", workingDir], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout);
      except subprocess.TimeoutExpired:
        writeResult(outputDir, [groupName, 'False', 'False', 'True', '', '-1', '-1', '-1']);
        return;
      if result.returncode != 0:
        writeError(outputDir, groupName, result.returncode, convertOutput(result.stderr));
        writeResult(outputDir, [groupName, 'False', 'True', '', '', '-1', '-1', '-1']);
        return;
      output = convertOutput(result.stdout);
      if len(output) > 0:
        writeOutput(outputDir, groupName, output);
      afterInfo = resource.getrusage(resource.RUSAGE_CHILDREN);
      writingTimes.append(float(afterInfo.ru_utime)-float(beforeInfo.ru_utime) + float(afterInfo.ru_stime)-float(beforeInfo.ru_stime));
      beforeInfo = afterInfo;
    # measure writing time in seconds.miliseconds
    writingTimes = sorted(writingTimes[1:len(writingTimes)-1]);
    writingTime = sum(writingTimes)/len(writingTimes);
    # measures memory consumption in KBytes
    selfInfo = resource.getrusage(resource.RUSAGE_SELF);
    memoryConsumption = int(selfInfo.ru_maxrss);
    # measure directory size in Bytes
    dirSize = getSize(workingDir);

    # check correct solution
    result = subprocess.run(["java", "-cp", "build/jar/*:lib/*", "rw2018.statisticsEvaluation.CompareResults", "-s", solutionDir, "-i" , inputDir, "-w", workingDir], stdout=subprocess.PIPE, stderr=subprocess.PIPE);
    areResultsCorrect = True;
    if result.returncode != 0:
      writeError(outputDir, groupName, result.returncode, convertOutput(result.stderr));
      areResultsCorrect = False;

    # write results
    writeResult(outputDir, [groupName, 'False', 'False', 'False', str(areResultsCorrect), str(writingTime), str(memoryConsumption), str(dirSize)]);
  finally:
    # remove data
    if os.path.exists(workingDir):
      shutil.rmtree(workingDir)

if __name__ == "__main__":
  # stuff only to run when not called via 'import' here
  args = sys.argv;
  if len(args) < 1 + 2:
    print("Missing arguments. Usage: python3 evaluation.py <groupName> <outputDir>");
  else:
    main(args[1],args[2],timeout=60);


# uncompyle6 version 3.7.4
# Python bytecode 2.6 (62161)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.linux-x86_64/egg/spamfighter/service.py
# Compiled at: 2009-01-30 08:10:10
"""
Построение сервисов, составляющих ядро сервера.
"""
import sys
from twisted.application import internet, service
from twisted.internet import protocol
from twisted.python import log
from spamfighter.utils import config

def makeService():
    u"""
    Построить главный сервис.
    Дочерними к нему будут основные сервисы СпамоБорца.

    @return: главный сервис
    """
    observer = log.FileLogObserver(sys.stderr)
    log.addObserver(observer.emit)
    from spamfighter import version
    log.msg('SpamFighter starting up (version %s)...' % version)
    s = service.MultiService()
    if config.http.enabled == 'yes' or config.https.enabled == 'yes':
        log.msg('> Starting HTTP services:')
        from twisted.web import server, resource, static
        root = resource.Resource()
        log.msg('>> Static HTTP @ /')
        static.File.contentTypes.update({'.html': 'text/html; charset=utf-8'})
        root.putChild('', static.File('html/index.html'))
        root.putChild('favicon.ico', static.File('html/favicon.ico'))
        if config.manage.interface.enabled == 'yes':
            log.msg('>>> Management interface @ /%s/' % config.manage.interface.location)
            root.putChild(config.manage.interface.location, static.File(config.manage.interface.path))
        if config.manage.js_api.enabled == 'yes':
            log.msg('>>> JavaScript management API doc @ /%s/' % config.manage.js_api.location)
            root.putChild(config.manage.js_api.location, static.File(config.manage.js_api.path))
        if config.manage.debug.enabled == 'yes':
            log.msg('>>> DEBUG: Management interface @ /%s/' % config.manage.debug.location)
            root.putChild(config.manage.debug.location, static.File(config.manage.debug.path))
        if config.docs.manual.enabled == 'yes':
            log.msg('>>> Manual @ /%s/' % config.docs.manual.location)
            root.putChild(config.docs.manual.location, static.File(config.docs.manual.path))
        if config.docs.source.enabled == 'yes':
            log.msg('>>> DEBUG: Source-docs @ /%s/' % config.docs.source.location)
            root.putChild(config.docs.source.location, static.File(config.docs.source.path))
        api = resource.Resource()
        root.putChild('api', api)
        if config.api.xmlrpc.enabled == 'yes':
            log.msg('>> XML-RPC API @ /api/xml/')
            from spamfighter.core.commands.apiglue import XMLRPC_API_Glue
            api.putChild('xml', XMLRPC_API_Glue())
        if config.api.jsonrpc.enabled == 'yes':
            log.msg('>> JSON-RPC API @ /api/json/')
            from spamfighter.core.commands.apiglue import JSONRPC_API_Glue
            api.putChild('json', JSONRPC_API_Glue())
        if config.http.enabled == 'yes':
            log.msg('>> HTTP server (port %d)' % config.http.port)
            h = internet.TCPServer(config.http.port, server.Site(root))
            h.setServiceParent(s)
        if config.https.enabled == 'yes':
            log.msg('>> HTTPS server (port %d)' % config.https.port)
            from twisted.internet import ssl
            h = internet.SSLServer(config.https.port, server.Site(root), ssl.DefaultOpenSSLContextFactory(config.https.cert.private_key_file, config.https.cert.certificate_file))
            h.setServiceParent(s)
    if config.manhole.enabled == 'yes':
        log.msg('> DEBUG: Starting manhole (port %d)' % config.manhole.port)
        log.msg("> DEBUG: Use 'telnet localhost %d' to login" % config.manhole.port)
        from twisted.conch.telnet import TelnetTransport, TelnetBootstrapProtocol
        from twisted.conch.insults import insults
        from twisted.conch.manhole import ColoredManhole
        f = protocol.ServerFactory()
        f.protocol = lambda : TelnetTransport(TelnetBootstrapProtocol, insults.ServerProtocol, ColoredManhole, None)
        h = internet.TCPServer(config.manhole.port, f)
        h.setServiceParent(s)
    log.msg('Loading commands...')
    from spamfighter.api import loadCommands
    loadCommands()
    from spamfighter.core.commands.dispatcher import listAllCommands
    commandsList = listAllCommands()
    commandsList.sort()
    log.msg('Commands loaded: %s.' % (', ').join(commandsList))
    log.msg('Loading rules...')
    from spamfighter.rules import loadRules
    loadRules()
    from spamfighter.core.rules import factory
    rulesList = factory.getRuleNames()
    rulesList.sort()
    log.msg('Rules loaded: %s.' % (', ').join(rulesList))
    from spamfighter.core.domain import getDefaultDomain
    log.msg('Default domain: %r' % getDefaultDomain())
    from spamfighter.core.partner import getPartnerAuthorizer
    log.msg('Partner authorizer: %r' % getPartnerAuthorizer())
    log.msg('SpamFighter startup done.')
    log.removeObserver(observer.emit)
    return s


import torch
import time
import math
import sys
import torch.nn.functional as F
import torch.backends.cudnn as cudnn

from torch.utils import data
from my_classes import Dataset

class Feedforward(torch.nn.Module):
    def __init__(self, input_dim, hidden_size, no_output_classes, class_map_id):
        super(Feedforward, self).__init__()
        self.input_dim = input_dim
        self.hidden_size = hidden_size

        # Layers of Nerual network
        self.fc1 = torch.nn.Linear(self.input_dim, self.hidden_size)
        self.relu = torch.nn.ReLU()
        self.fc2 = torch.nn.Linear(self.hidden_size, no_output_classes)
       # self.softmax = torch.nn.Softmax(dim=1)

       # CUDA for PyTorch
        use_cuda = torch.cuda.is_available()
        self.device = torch.device("cuda:0" if use_cuda else "cpu")
        self.to(self.device)
        self.class_map_id = class_map_id

    def forward(self, x):

        out = self.fc1(x)
        out = self.relu(out)
        out = self.fc2(out)
        return out

    def fit(self, x_train, Y_train):  # , x_test, Y_test):

        device = self.device
        cudnn.benchmark = True

        # Parameters
        params = {
            'batch_size': 512,
            'shuffle': False,
            'num_workers': 0
        }
        max_epochs = 600

        batches_num = math.floor(len(x_train)/64)

        # Generators
        training_set = Dataset(x_train, Y_train)
        training_generator = data.DataLoader(training_set, **params)

        #validation_set = Dataset(x_test, Y_test)
        #validation_generator = data.DataLoader(validation_set, **params)

        # Loss function and optimizer
        criterion = torch.nn.CrossEntropyLoss()  # Hyper-parameter: loss function
        # Hyper-Parameter: learning algorthem and learing rate
        optimizer = torch.optim.SGD(self.parameters(), lr=0.01)

        self.train()  # Change to training mode
        print('Training NN started, to stop press Ctrl + C')

        # Loop over epochs
        try:
            for epoch in range(max_epochs):
                # Training
                start_time = time.time()
                batch_number = 0
                epoch_loss = 0
                acc_count = 0
                for local_batch, local_labels in training_generator:
                    # Transfer to GPU
                    local_batch, local_labels = local_batch.to(
                        device), local_labels.long().to(device)

                    # Model computations
                    y_pred = self(local_batch)
                    loss = criterion(y_pred, local_labels)
                    loss.backward()
                    optimizer.step()
                    batch_number = batch_number + 1
                    acc_count = acc_count + \
                        self.get_accuracy(local_labels, y_pred)
                    #print('batch: {} train loss: {}'.format(batch_number, loss.item()))

                end_time = time.time()
                epoch_loss += loss.item()

                accuracy = acc_count / len(x_train)
                epoch_mins, epoch_secs = self.epoch_time(start_time, end_time)

                print(
                    f'Epoch: {epoch+1:02} | Epoch Time: {epoch_mins}m {epoch_secs}s')
                print(
                    f'\tTrain Loss: {(epoch_loss / batches_num):.3f} | Train Acc: {(accuracy*100):.3f}%')
                #print('epoch: {} train loss: {}'.format(epoch, loss.item()))
                # Validation
                # with torch.set_grad_enabled(False):
                #      for local_batch, local_labels in validation_generator:
                # # Transfer to GPU
                #          local_batch, local_labels = local_batch.to(device), local_labels.to(device)

                # #         # Model computations
                #          y_pred = self(local_batch)
                #          loss = criterion(y_pred, local_labels)
                #          print('batch: {} Valid loss: {}'.format(i, loss.item()))
        except KeyboardInterrupt:
            end_time = time.time()
            epoch_mins, epoch_secs = self.epoch_time(start_time, end_time)
            print('Training has been stopped at Epoch {}'.format(epoch))
            print('Time taken for training: {} Mins'.format(epoch_mins))
            pass

    def epoch_time(self, start_time, end_time):
        elapsed_time = end_time - start_time
        elapsed_mins = int(elapsed_time / 60)
        elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
        return elapsed_mins, elapsed_secs

    def get_accuracy(self, truth, pred):
        assert len(truth) == len(pred)
        right = 0
        for i in range(len(truth)):
            values, indices = torch.max(pred[i], 0)
            if truth[i].item() == indices.item():
                right += 1.0
        return right

    def predict(self, x):
        self.eval()
        y_pred = self(x.to(self.device))
        return y_pred


# 198. 打家劫舍
# https://leetcode-cn.com/problems/house-robber/

""" 思路
    1.简单情况：
        如果只有一个房子， 肯定要偷。
        如果有两个房子，肯定要偷财产多的
        如果有三个房子呢？ A B C三个房子
            此时会有两种选择，一种是偷A和C， 另一种是偷B
            如果A + B greater than B, 要选择偷AC，否则偷B
            也就是说，C位置的时候，考虑是A+C大呢还是B大的问题。 OK？
            即dp[C] = max(dp[A] + nums[c], dp[B])
    假设dp[i]代表到当前位置i的时候做出的最优的选择，
    那么
        dp[i] = max(dp[i-2] + nums[c], dp[i-1]

    2.直接考虑也行：
    dp[i]表示到第i个位置，偷到的最大数量
    在第i个位置，有两种选择：
        1. 偷
        2. 不偷
    dp[i] = max( dp[i-2] + nums[i], 偷了第i个位置, 要想最大话，肯定也要偷之前位置，但是不能是相邻的位置
                 dp[i-1]            没偷第i个位置
                )

"""

class Solution_0:
    def rob(self, nums):
        if not nums or len(nums) == 0:
            return 0
        if len(nums) < 3:
            return max(nums)
        dp = [0 for i in range(len(nums))]
        dp[0] = nums[0]
        for i in range(1, len(nums)):
            dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])
        print(dp)
        return dp[len(nums)-1]

class Solution():
    def rob(self, nums):
        pre, cur = 0, 0
        for num in nums:
            tmp_cur = cur
            cur = max(pre + num, cur)
            pre = tmp_cur
            # cur, pre = max(pre + num, cur), cur
            print(cur)
        return cur

if __name__ == '__main__':
    nums = [2, 3, 2, 2, 3]
    print(nums)
    res = Solution().rob(nums)
    print(res)