# -*- coding: gb18030 -*-
#
# $Id: SkillLoader.py,v 1.12 2008-07-15 04:21:55 kebiao Exp $

"""
技能资源加载部分。
"""

import BigWorld
import Language
import csconst
from bwdebug import *
import Function
import time
from config.skill.Skill.SkillDataMgr import Datas as SKILL_DATAS

class BuffTime:
	"""
	一个只读取所有spellID以及buff是否保存的信息的类。

	"""
	# 全局数据集合; key is BuffTime::_id and value is instance of BuffTime or derive from it.
	_instances = {}
	def __init__( self ):
		"""
		构造函数。
		"""
		self._id = 0						# spell id
		self._name = ""						# spell name
		self._isSave = False				# 下线是否保存
		self._alwayCalc = False				# 如果下线保存，那么下线后是否还继续计算时间？

	@staticmethod
	def instance( id ):
		"""
		通过 action id 获取action实例
		"""
		return BuffTime._instances[id]

	@staticmethod
	def setInstance( datas ):
		"""
		设置全局的数据集合，此通过由skill loader调用

		@param datas: dict
		"""
		BuffTime._instances = datas

	def init( self, dictDat ):
		"""
		virtual method;
		读取技能配置
		@param dictDat: 配置数据
		@type  dictDat: Python dict Data
		"""
		self._id = dictDat["ID"]
		self._name = dictDat[ "Name" ]
		if dictDat.has_key( "isSave" ) and dictDat["isSave"] != 0:	# 下线保存，不计时
			self._isSave = True
			if dictDat[ "alwayCalc" ] != 0:
				self._alwayCalc = True

	def setSource( self, sourceSkillID, sourceIndex ):
		"""
		设置源技能信息
		"""
		self._id = ( sourceSkillID * 100 ) + sourceIndex + 1 #sourceIndex + 1 是因为BUFF程序ID实际是技能ID+BUFF所在的索引 如果不加1 那么skillID+0=skillID

	def getID( self ):
		"""
		"""
		return self._id

	def getName( self ):
		"""
		"""
		return self._name

	def isSave( self ):
		"""
		判断是否需要保存
		"""
		return self._isSave

	def isTimeout( self, cooldownTime ):
		"""
		判断是否时间已过

		@param cooldownTime: 该值必须是经过计算后的使用BigWorld.time() * 修正值以后的时间
		@type  cooldownTime: INT32
		@return: BOOL
		"""
		if cooldownTime == 0: return False		# 无持续时间，永不过期
		return int( time.time() ) >= cooldownTime

	def calculateOnLoad( self, timeVal ):
		"""
		在加载人物数据的时候重新计算延迟值。
		1.获取剩余时间(需要考虑下线后是否计时)
		2.加上现在的服务器运行时间

		@type  timeVal: INT32
		@return: 返回最新的cooldown时间
		@rtype:  INT32
		"""
		if timeVal == 0: return timeVal		# 无持续时间，不处理
		if self._alwayCalc:
			# 下线后计时，所以时间是真实时间，需要减去以后获得剩余时间
			timeVal -= int( time.time() )
		return int( timeVal + time.time() )		# int( (剩余时间 + 当前运行时间) * 修正值 )

	def calculateOnSave( self, timeVal ):
		"""
		在保存人物数据的时候重新计算延迟值。
		1.获取剩余时间(需要考虑下线后是否计时)
		2.返回剩余时间

		@type  timeVal: INT32
		@return: 返回最新的cooldown时间；我们假设所有传过来的值都是从cellData里获得的，因此该值是一个使用BigWorld.time()的整型数。
		@rtype:  INT32
		"""
		if timeVal == 0: return timeVal		# 无持续时间，不处理
		# 取得剩余时间，必须先除于修正值获取真正的剩余时间
		t = int( timeVal - time.time() )
		if self._alwayCalc:
			# 下线后计时，所以需要将值处理成真实时间
			t += int( time.time() )

		# 不是无限期BUFF在保存的时候不能返回0
		# 否则在恢复BUFF的时候会导致有时间限制的BUFF变成无限期的BUFF
		if t <= 0: t = 1
		return t

class SkillLoader:
	_instance = None
	def __init__( self ):
		"""
		构造函数。
		"""
		assert SkillLoader._instance is None		# 不允许有两个以上的实例
		self._datas = {}	# key is BuffTime::_id and value is instance of BuffTime which derive from it.
		BuffTime.setInstance( self._datas )
		SkillLoader._instance = self

	@staticmethod
	def instance():
		"""
		通过 action id 获取action实例
		"""
		if SkillLoader._instance is None:
			SkillLoader._instance = SkillLoader()
		return SkillLoader._instance

	def __getitem__( self, key ):
		"""
		取得Skill实例
		"""
		if key in self._datas:
			return self._datas[ key ]
		return self.loadSkill( str( key ) )

	def loadSkill( self, skillID ):
		"""
		指定加载某技能或者BUFF
		@type     skill: string
		"""
		DEBUG_MSG( "load skill %s." % skillID )
		buffID = 0
		iSkillID = int( skillID )
		if not SKILL_DATAS.has_key( iSkillID ):
			buffID = iSkillID
			iSkillID /= 100
			if not SKILL_DATAS.has_key( iSkillID ):
				ERROR_MSG( "buff config '%s' is not exist!" % iSkillID )
				return

		dictDat = SKILL_DATAS[ iSkillID ]
		instance = BuffTime()
		instance.init( dictDat )
		key = instance.getID()
		assert not self._datas.has_key( key ), "id %i is exist already in %s. reading file %i" % ( key, self._datas[key].getName(), skillID )
		self._datas[key] = instance
		#///////////////////////////////////////////////////////////////////////////////////////////
		if dictDat.has_key( "buff" ):
			index = 0
			for i in xrange( len( dictDat["buff"] ) ):
				buffInstance = BuffTime()
				try:
					buffInstance.init( dictDat["buff"][i] )
				except:
					ERROR_MSG( "Loading Buff", skillID )
					raise	# 再次抛出
				buffInstance.setSource( instance.getID(), index )
				key = buffInstance.getID()
				assert not self._datas.has_key( key ), "buffID %i is exist already in %s. reading file %i" % ( key, self._datas[key].getName(), skillID )
				self._datas[key] = buffInstance
				index = index + 1
		if buffID > 0:
			return self._datas[buffID]
		return self._datas[iSkillID]

def instance():
	return SkillLoader.instance()


"""
Wrap the opencv optical flow

"""

# -- linalg --
import numpy as np
import torch as th
from einops import rearrange,repeat

# -- misc --
from easydict import EasyDict as edict

# -- opencv --
import cv2 as cv

# -- local --
from noisyknn.utils import color

def run(vid_in,sigma):

    # -- init --
    device = vid_in.device
    vid = vid_in.clone() # copy data for no-rounding-error from RGB <-> YUV
    t,c,h,w = vid.shape

    # -- color2gray --
    vid = th.clamp(vid,0,255.).type(th.uint8)
    color.rgb2yuv(vid)
    vid = vid[:,[0],:,:]
    vid = rearrange(vid,'t c h w -> t h w c')

    # -- alloc --
    fflow = th.zeros((t,2,h,w),device=device)
    bflow = th.zeros((t,2,h,w),device=device)

    # -- computing --
    for ti in range(t-1):
        fflow[ti] = pair2flow(vid[ti],vid[ti+1],device)
    for ti in reversed(range(t-1)):
        bflow[ti] = pair2flow(vid[ti+1],vid[ti],device)

    # -- final shaping --
    # fflow = rearrange(fflow,'t h w c -> t c h w')
    # bflow = rearrange(bflow,'t h w c -> t c h w')

    # -- packing --
    flows = edict()
    flows.fflow = fflow
    flows.bflow = bflow

    # -- gray2color --
    color.yuv2rgb(vid)

    return flows

def pair2flow(frame_a,frame_b,device):

    # -- create opencv-gpu frames --
    gpu_frame_a = cv.cuda_GpuMat()
    gpu_frame_b = cv.cuda_GpuMat()
    gpu_frame_a.upload(frame_a.cpu().numpy())
    gpu_frame_b.upload(frame_b.cpu().numpy())

    # -- create flow object --
    gpu_flow = cv.cuda_FarnebackOpticalFlow.create(5, 0.5, False,
                                                   15, 3, 5, 1.2, 0)

    # -- exec flow --
    flow = cv.cuda_FarnebackOpticalFlow.calc(gpu_flow, gpu_frame_a,
                                             gpu_frame_b, None)
    flow = flow.download()
    flow = flow.transpose(2,0,1)
    flow = th.from_numpy(flow).to(device)

    return flow


from __future__ import absolute_import
import pytest
from mopidy.core import Core

@pytest.fixture
def config():
    return {
        'core': {},
        'mqtt': {
            'host': 'localhost',
            'port': 1883,
            'topic': 'mopidy',
        },
    }

@pytest.fixture
def core(config):
    actor = Core.start(
        config=config, backends=[]).proxy()

    yield actor
    actor.stop()


import sys, os
import pygame

from States import template
from State_Code import button

class Menu(template.State):
    """
    the class resposnible for the main menu
    """

    def __init__(self, screen, identifier="menu"):
        super().__init__(screen, identifier)
        """
        ## attributes in super() ##
        self.nextState
        self.quit
        self.screen
        self.screenWidth, self.screenHeight
        self.persistentVar
        self.id
        """
        self.backgroundColour = (75, 75, 75)

        self.titleColour = (23,211,221)
        self.titleFont = pygame.font.Font(None,70)
        self.titleText = self.titleFont.render("First Person Game",
                                               True, self.titleColour)
        self.titlePosition = (int(self.screenWidth/2), int(self.screenHeight/2) - 100)

        buttonTextColour = (23,211,221)
        buttonColour = (24, 100, 221)

        screenMiddle = (int(self.screenWidth/2), int(self.screenHeight/2))
        self.buttonList = [button.Button(self.screen, "gameplay", {"restart":True, "levelNum": 1}, "Quick Play", 40,
                                         buttonTextColour, buttonColour, (screenMiddle[0], screenMiddle[1])),
                           button.Button(self.screen, "level select", {"restart":True}, "Level Select",
                                         40, buttonTextColour, buttonColour, (screenMiddle[0], screenMiddle[1]+50))]
        self.persistentVar = {}

    def startup(self, persistentVar):
        self.nextState = self.id
        self.persistentVar = persistentVar
        self.screen.fill(self.backgroundColour)
        titleRect = self.titleText.get_rect(center=self.titlePosition)
        self.screen.blit(self.titleText, titleRect)
        with open(os.path.relpath("Levels\\last_played_level.txt"), "rb") as f:
            f.seek(0)
            self.buttonList[0].nextStateArgs["levelNum"] = int(f.read())

    def exit(self):
        with open(os.path.relpath("Levels//last_played_level.txt"), "w") as f:
            f.write(str(self.persistentVar["levelNum"]))
        return self.persistentVar

    def draw(self):
        for thing in self.buttonList:
            thing.draw()

    def update(self, dt):
        mousepos = pygame.mouse.get_pos()
        for thing in self.buttonList:
            thing.update(mousepos)

    def getEvent(self, event):
        if event.type == pygame.MOUSEBUTTONUP:
            for thing in self.buttonList:
                if thing.mouseIsOverMe:
                    self.persistentVar = {**self.persistentVar, **thing.nextStateArgs}
                    self.nextState = thing.nextState


from sklearn.feature_extraction.text import CountVectorizer# 类会将文本中的词语转换为词频矩阵
from sklearn.metrics.pairwise  import cosine_similarity#  计余弦相似度
#开始分词
wordslist = []  # 词列表
titlelist = []  # 文章抬头列表
word ={}
from sklearn.metrics.pairwise  import cosine_similarity
for title,neirong in data_html.items():
    stopkey =[line.strip() for line in open('C:\\Users\\\liuxiangdong.ZAONLINE\\\\AppData\\\\\Local\\\\\\Continuum\\\\\\\Anaconda3\\\\\\\\Lib\\\\\\\\\site-packages\\\\\\\\\\jieba\\\\\\\\\\stop_world.txt').readlines()]
    titlelist.append(title)
    jieba.add_word('陈红')
    jieba.add_word('马思纯')
    seg_list = jieba.cut(neirong, cut_all=False)  #  切词，方法接受三个输入参数: 需要分词的字符串；cut_all 参数用来控制是否采用全模式；HMM 参数用来控制是否使用 HMM 模型
    result = '/'.join(list(set(seg_list)-set(stopkey)))  # 输出分词的词组，本身是seg_list是一个生成器，需要for循环输出
    wordslist.append(result)
    #print('文章标题{}'.format(title ))
    # print('拆分词组{}'.format(wordslist))
    vectorizer = CountVectorizer() # 学习词语词典并返回文档矩阵，矩阵中元素为词语出现的次数。
    word_frequence = vectorizer.fit_transform(wordslist)  #one hot 编码
    print('词频矩阵{}'.format(word_frequence))# 输出文本包含词的频数，,即词在词组中位置，以及相应该词在文本中出现的次数
    words = vectorizer.get_feature_names()  # 获取词袋模型中的所有词语
    transformer = TfidfTransformer()  # 将文本频次转为词频矩阵
    print('词矩阵{}'.format(vectorizer.get_feature_names()))#输出词矩阵即分词后文章对应包含的词矩阵
    tfidf = transformer.fit_transform(word_frequence)#onehot编码
    weight = tfidf.toarray()  #将tf-idf矩阵抽取出来，元素a[i][j]表示j词在i类文本中的tf-idf权重 参考http://scikit-learn.org/stable/modules/feature_extraction.html
    print('词的tf-idf{}'.format(weight))# 输出词的tf-idf
    data_last=pd.DataFrame(weight)
    print('type(weight)')
    print(type(weight))
similarity={}# 计算文章相似度
if len (titlelist)>1:
    for title1 in titlelist:
        for title2 in titlelist:
            if title1 == title2:
                continue
            similarity.setdefault(title1,{})
            similarity[title1].setdefault(title2,{})
            similarity[title1][title2]=cosine_similarity(weight[titlelist.index(title1)].reshape(1,-1),weight[titlelist.index(title2)].reshape(1,-1))
print(similarity)# 输出文章相似度
print(similarity[278][279])


import numpy as np
import pandas as pd

import math

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

learning_rate = 0.0001
no_of_iterations =10
k = 0.0001
x = pd.read_csv('Datasets/data_logistic.csv')

print("Running On Dataset-" + "data_logistic.csv")
new = []
for i in zip(x['variance'], x['skewness'], x['curtosis'], x['entropy'], x['c']):
    new.append((i[0], i[1], i[2], i[3], i[4]))

new = np.array(new)

data_size = len(new)

data = []
for i in zip(x['variance'], x['skewness'], x['curtosis'], x['entropy'], x['c']):
    data.append((i[0], i[1], i[2], i[3], 1))

data = np.array(data)

#sepearating the third column into two classes
class0 = np.array([i for i in new if i[4]==0])
class1 = np.array([i for i in new if i[4]==1])

w = np.ndarray((5, 1))
for i in range(0, 5):
	w[i]=0
#Assigning the sign and calculating the error
for iter in range(0, no_of_iterations):
    for row in range(len(data)):
        x = np.ndarray((5, 1), buffer = np.array([data[row][0], data[row][1], data[row][2], data[row][3], data[row][4]]))
        ans = sigmoid(np.matmul(np.transpose(w), x) )
        if( (ans >=0.5 and new[row][4] ==0) or (ans <0.5 and new[row][4] ==1)):
        	w = w + (learning_rate)*((1/data_size)*(new[row][4]-ans)*x 	+k*w)

print(w)

print("Testing on Logistic Test data....")

y = pd.read_csv('Datasets/data_logistic.csv')

new = []
for i in zip(y['variance'], y['skewness'], y['curtosis'], y['entropy'], y['c']):
    new.append((i[0], i[1], i[2], i[3], i[4]))

new = np.array(new)

data_size = len(new)

data = []
for i in zip(y['variance'], y['skewness'], y['curtosis'], y['entropy'], y['c']):
    data.append((i[0], i[1], i[2], i[3], 1))

data = np.array(data)
#print(data)
cnt1=0
cnt2=0
cnt3=0
cnt4=0
for row in range(len(data)):
    x = np.ndarray((5, 1), buffer = np.array([data[row][0], data[row][1], data[row][2], data[row][3], data[row][4]]))
    ans = sigmoid(np.transpose(w).dot(x))
    if(ans >= 0.5 and new[row][4]==1):
    	cnt1 = cnt1+1;
    if(ans >= 0.5 and new[row][4]==0):
    	cnt2 = cnt2+1;
    if(ans < 0.5 and new[row][4]==1):
    	cnt3 = cnt3+1;
    if(ans < 0.5 and new[row][4]==0):
    	cnt4 = cnt4+1;

print(cnt1)
print(cnt2)
print(cnt3)
print(cnt4)

print("Acuracy is - " + str((cnt1+cnt4)/(cnt1+cnt2+cnt4+cnt3) ) )


import tensorflow as tf
from keras import backend as K
from keras.layers import Dense, Input
from keras.models import Model
from keras.optimizers import Adam
from keras import backend as K
#------------------------------------------------------------------
import socket
import threading
from struct import unpack, pack
from numpy import shape
import numpy as np
from time import sleep
from collections import deque
from Step_8.Parameter import PARA
#------------------------------------------------------------------
import os
import shutil
#------------------------------------------------------------------
import logging
import logging.handlers
logging.basicConfig(filename='./test.log', format='%(asctime)s %(levelname)s %(message)s', level=logging.DEBUG)
#------------------------------------------------------------------
import matplotlib.pyplot as plt
#------------------------------------------------------------------
episode = 0
episode_test = 0
Max_score = 0       # if A3C model get Max_score, A3C model will draw the Max_score grape

class MainModel:
    def __init__(self):
        self._make_folder()
        self.worker = []
        self._make_tensorboaed()
        self.input_para = 6
        self.output_para = 3

        self.actor, self.critic = self.build_model()
        self.optimizer = [self.actor_optimizer(), self.critic_optimizer()]

    def _run(self):
        for i in range(0, 20):
            self.worker.append(A3Cagent(Remote_ip='192.168.0.10',
                                        Remote_port=7100 + i,
                                        CNS_ip='192.168.0.9',
                                        CNS_port=7000 + i,
                                        Shared_actor_net=self.actor,
                                        Shared_cric_net=self.critic,
                                        Optimizer=self.optimizer,
                                        Sess=self.sess,
                                        Summary_ops=[self.summary_op, self.summary_placeholders,
                                                     self.update_ops, self.summary_writer],
                                        Test_model=False,
                                        ))
        # CNS2
        for i in range(0, 20):
            self.worker.append(A3Cagent(Remote_ip='192.168.0.10',
                                        Remote_port=7200 + i,
                                        CNS_ip='192.168.0.7',
                                        CNS_port=7000 + i,
                                        Shared_actor_net=self.actor,
                                        Shared_cric_net=self.critic,
                                        Optimizer=self.optimizer,
                                        Sess=self.sess,
                                        Summary_ops=[self.summary_op, self.summary_placeholders,
                                                     self.update_ops, self.summary_writer],
                                        Test_model=False,
                                        ))
        # CNS3
        for i in range(0, 20):
            self.worker.append(A3Cagent(Remote_ip='192.168.0.10',
                                        Remote_port=7300 + i,
                                        CNS_ip='192.168.0.4',
                                        CNS_port=7000 + i,
                                        Shared_actor_net=self.actor,
                                        Shared_cric_net=self.critic,
                                        Optimizer=self.optimizer,
                                        Sess=self.sess,
                                        Summary_ops=[self.summary_op, self.summary_placeholders,
                                                     self.update_ops, self.summary_writer],
                                        Test_model=False,
                                        ))

        for __ in self.worker:
           __.start()
           sleep(1)
        print("All Agent Start")

        while True:
            sleep(60)
            self._save_model()

    def build_model(self):
        state = Input(batch_shape=(None, self.input_para))
        shared = Dense(8, input_dim=self.input_para, activation='relu', kernel_initializer='glorot_uniform')(state)
        # shared = Dense(48, activation='relu', kernel_initializer='glorot_uniform')(shared)

        actor_hidden = Dense(4, activation='relu', kernel_initializer='glorot_uniform')(shared)
        action_prob = Dense(self.output_para, activation='softmax', kernel_initializer='glorot_uniform')(actor_hidden)

        value_hidden = Dense(2, activation='relu', kernel_initializer='he_uniform')(shared)
        state_value = Dense(1, activation='linear', kernel_initializer='he_uniform')(value_hidden)

        actor = Model(inputs=state, outputs=action_prob)
        critic = Model(inputs=state, outputs=state_value)

        actor._make_predict_function()
        critic._make_predict_function()

        actor.summary(print_fn=logging.info)
        critic.summary(print_fn=logging.info)

        return actor, critic

    def actor_optimizer(self):
        action = K.placeholder(shape=(None, self.output_para))
        advantages = K.placeholder(shape=(None, ))

        policy = self.actor.output

        good_prob = K.sum(action * policy, axis=1)
        eligibility = K.log(good_prob + 1e-10) * K.stop_gradient(advantages)
        loss = -K.sum(eligibility)

        entropy = K.sum(policy * K.log(policy + 1e-10), axis=1)

        actor_loss = loss + 0.01*entropy

        optimizer = Adam(lr=0.01)
        # optimizer = RMSprop(lr=2.5e-4, rho=0.99, epsilon=0.01)
        updates = optimizer.get_updates(self.actor.trainable_weights, [], actor_loss)
        train = K.function([self.actor.input, action, advantages], [], updates=updates)
        return train

    # make loss function for Value approximation
    def critic_optimizer(self):
        discounted_reward = K.placeholder(shape=(None, ))

        value = self.critic.output

        loss = K.mean(K.square(discounted_reward - value))

        optimizer = Adam(lr=0.01)
        # optimizer = RMSprop(lr=2.5e-4, rho=0.99, epsilon=0.01)
        updates = optimizer.get_updates(self.critic.trainable_weights, [], loss)
        train = K.function([self.critic.input, discounted_reward], [], updates=updates)
        return train

    def _save_model(self):
        self.actor.save_weights("./Model/A3C_actor")
        self.critic.save_weights("./Model/A3C_cric")

    def _make_tensorboaed(self):
        self.sess = tf.InteractiveSession()
        K.set_session(self.sess)
        self.sess.run(tf.global_variables_initializer())
        self.summary_placeholders, self.update_ops, self.summary_op = self._setup_summary()
        # tensorboard dir change
        self.summary_writer = tf.summary.FileWriter('./a3c', self.sess.graph)

    def _setup_summary(self):
        episode_total_reward = tf.Variable(0.)
        episode_avg_max_q = tf.Variable(0.)
        episode_duration = tf.Variable(0.)

        tf.summary.scalar('Total Reward/Episode', episode_total_reward)
        tf.summary.scalar('Average Max Prob/Episode', episode_avg_max_q)
        tf.summary.scalar('Duration/Episode', episode_duration)

        summary_vars = [episode_total_reward, episode_avg_max_q, episode_duration]
        summary_placeholders = [tf.placeholder(tf.float32) for _ in range(len(summary_vars))]
        updata_ops = [summary_vars[i].assign(summary_placeholders[i]) for i in range(len(summary_vars))]
        summary_op = tf.summary.merge_all()

        return summary_placeholders, updata_ops, summary_op

    def _make_folder(self):
        fold_list = ['./a3c', './log', './model', './img']
        for __ in fold_list:
            if os.path.isdir(__):
                shutil.rmtree(__)
                sleep(1)
                os.mkdir(__)
            else:
                os.mkdir(__)

class A3Cagent(threading.Thread):
    def __init__(self, Remote_ip, Remote_port, CNS_ip, CNS_port, Shared_actor_net, Shared_cric_net, Optimizer, Sess, Summary_ops, Test_model):
        threading.Thread.__init__(self)
        self.shared_mem_structure = self._make_shared_mem_structure()
        self._init_socket(Remote_ip, Remote_port, CNS_ip, CNS_port)
        self._init_shared_model_setting(Shared_actor_net, Shared_cric_net, Optimizer)
        self._init_input_window_setting()
        self._init_model_information()
        self._init_tensorboard(Sess, Summary_ops)
        self.Test_model = Test_model

    def _init_socket(self, Remote_ip, Remote_port, CNS_ip, CNS_port):
        '''
        :param Remote_ip: 현재 컴퓨터의 ip를 작성하는 곳
        :param Remote_port: 현재 컴퓨터의 port를 의미
        :param CNS_ip: CNS의 ip
        :param CNS_port: CNS의 port
        :return: UDP 통신을 위한 send, resv 소켓 개방 및 정보 반환
        '''
        self.Remote_ip, self.Remote_port = Remote_ip, Remote_port
        self.CNS_ip, self.CNS_port = CNS_ip, CNS_port

        self.resv_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.resv_sock.bind((self.Remote_ip, self.Remote_port))

        self.send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        logging.debug('[{}] Initial_socket remote {}/{}, cns {}/{}'.format(self.name,
                                                                           self.Remote_ip, self.Remote_port
                                                                           , self.CNS_ip, self.CNS_port))

    def _init_shared_model_setting(self, Shared_actor_net, Shared_cric_net, Optimizer):
        self.shared_actor_net = Shared_actor_net
        self.shared_cric_net = Shared_cric_net
        self.optimizer = Optimizer

    def _init_input_window_setting(self):
        '''
        입력 윈도우의 창을 설정하는 부분
        :return: list형식의 입력 윈도우
        '''
        self.input_window_shape = self.shared_cric_net.get_input_shape_at(0)

        if PARA.Model == 'LSTM':
            # (none, time-length, parameter) -> 중에서 time-length 를 반환
            self.input_window_box = deque(maxlen=self.shared_cric_net.get_input_shape_at(0)[1])
        elif PARA.Model == 'DNN':
            # (none, time-length, parameter) -> 중에서 time-length 를 반환
            self.input_window_box = deque(maxlen=1)

    def _init_model_information(self):
        self.operation_mode = 0.2

        self.avg_q_max = 0
        self.states, self.actions, self.rewards = [], [], []
        self.action_log, self.reward_log, self.input_window_log = [], [], []
        self.score = 0
        self.step = 0

        self.update_t = 0
        self.update_t_limit = 10

        self.input_dim = 1
        self.input_number = 6

        self.fig = plt.figure(constrained_layout=True)
        self.gs = self.fig.add_gridspec(5, 3)
        self.ax = self.fig.add_subplot(self.gs[:-2, :])
        self.ax_ = self.ax.twinx()
        self.ax2 = self.fig.add_subplot(self.gs[-2, :])
        self.ax3 = self.fig.add_subplot(self.gs[-1, :])

    def _init_tensorboard(self, Sess, Summary_ops):
        self.sess = Sess
        [self.summary_op, self.summary_placeholders, self.update_ops, self.summary_writer] = Summary_ops

    def _make_shared_mem_structure(self):
        # 초기 shared_mem의 구조를 선언한다.
        idx = 0
        shared_mem = {}
        with open('./db.txt', 'r') as f:
            while True:
                temp_ = f.readline().split('\t')
                if temp_[0] == '':  # if empty space -> break
                    break
                sig = 0 if temp_[1] == 'INTEGER' else 1
                shared_mem[temp_[0]] = {'Sig': sig, 'Val': 0, 'Num': idx}
                idx += 1
        # 다음과정을 통하여 shared_mem 은 PID : { type. val, num }를 가진다.
        return shared_mem

    def _update_shared_mem(self):
        '''
        조작 필요 없음
        :return:
        '''
        # binary data를 받아서 보기 쉽게 만들어서 업데이트

        data, addr = self.resv_sock.recvfrom(4008)

        for i in range(0, 4000, 20):
            sig = unpack('h', data[24+i: 26+i])[0]
            para = '12sihh' if sig == 0 else '12sfhh'
            pid, val, sig, idx = unpack(para, data[8+i:28+i])
            pid = pid.decode().rstrip('\x00') # remove '\x00'
            if pid != '':
                self.shared_mem_structure[pid]['Val'] = val

    def _send_control_signal(self, para, val):
        '''
        조작 필요없음
        :param para:
        :param val:
        :return:
        '''
        for i in range(shape(para)[0]):
            self.shared_mem_structure[para[i]]['Val'] = val[i]
        UDP_header = b'\x00\x00\x00\x10\xa8\x0f'
        buffer = b'\x00' * 4008
        temp_data = b''

        # make temp_data to send CNS
        for i in range(shape(para)[0]):
            pid_temp = b'\x00' * 12
            pid_temp = bytes(para[i], 'ascii') + pid_temp[len(para[i]):]  # pid + \x00 ..

            para_sw = '12sihh' if self.shared_mem_structure[para[i]]['Sig'] == 0 else '12sfhh'

            temp_data += pack(para_sw,
                              pid_temp,
                              self.shared_mem_structure[para[i]]['Val'],
                              self.shared_mem_structure[para[i]]['Sig'],
                              self.shared_mem_structure[para[i]]['Num'])

        buffer = UDP_header + pack('h', shape(para)[0]) + temp_data + buffer[len(temp_data):]

        self.send_sock.sendto(buffer, (self.CNS_ip, self.CNS_port))

    # ------------------------------------------------------------------
    # 운전 모드 별 계산
    # ------------------------------------------------------------------

    def _calculator_operation_mode(self):
        tick = self.shared_mem_structure['KCNTOMS']['Val']
        if self.operation_mode == 0.2:      # 0.5%/min
            base_condition = tick / 60000
        elif self.operation_mode == 0.4:    # 1.0%/min
            base_condition = tick / 30000
        elif self.operation_mode == 0.6:    # 1.5%/min
            base_condition = tick / 20000
        elif self.operation_mode == 0.8:    # 2.0%/min
            base_condition = tick / 15000
        else:
            print('Error calculator function')

        upper_condition = base_condition + 0.03
        stady_condition = base_condition + 0.02
        low_condition = base_condition + 0.01
        return upper_condition, stady_condition, low_condition

    def _make_input_window(self):
        power = self.shared_mem_structure['QPROREL']['Val']
        upper_condition, stady_condition, low_condition = self._calculator_operation_mode()

        input_window_temp = [
            power,
            power / 2,
            (upper_condition - power)*10,
            (power - low_condition)*10,
            stady_condition,
            self.operation_mode/10,
        ]
        if len(input_window_temp) != self.input_number:
            logging.error('[{}] _make_input_window ERROR'.format(self))
        self.input_window_box.append(input_window_temp)

        # logging.debug('[{}] input_window_box_shape:{} / input_window_shape_model:{}'.format(self.name,
        #                                                                                np.shape(self.input_window_box),
        #                                                                                self.input_window_shape))

        if PARA.Model == 'LSTM':
            return np.array([self.input_window_box])  # list를 np.array로 전환 (2,3) -> (1, 2, 3)
        elif PARA.Model == 'DNN':
            return np.array(self.input_window_box)  # list를 np.array로 전환 (1, 3) -> (1, 3)

    # ------------------------------------------------------------------
    # CNS 원격 제어 관련
    # ------------------------------------------------------------------
    def _run_cns(self):
        return self._send_control_signal(['KFZRUN'], [3])

    def _set_init_cns(self):
        return self._send_control_signal(['KFZRUN'], [5])

    # ------------------------------------------------------------------
    # gym
    # ------------------------------------------------------------------

    def _gym_send_action_append(self, parameter, value):
        for __ in range(len(parameter)):
            self.para.append(parameter[__])
            self.val.append(value[__])

    def _gym_send_action(self, action):
        power = self.shared_mem_structure['QPROREL']['Val']
        self.para = []
        self.val = []
        if self.shared_mem_structure['KLAMPO22']['Val'] == 0 and power >= 0.10:
            logging.debug('[{}] Tripblock ON'.format(self.name))
            self._gym_send_action_append(['KSWO22', 'KSWO21'], [1, 1])

        # Turbine part
        if power >= 0.04 and self.shared_mem_structure['KBCDO17']['Val'] < 1750:
            logging.debug('[{}] Turbin UP {}/{}'.format(self.name, self.shared_mem_structure['KBCDO17']['Val'],
                                                     self.shared_mem_structure['KBCDO19']['Val']))
            self._gym_send_action_append(['KSWO213'], [1])

        if self.shared_mem_structure['KBCDO17']['Val'] >= 1790:
            logging.debug('[{}] Turbin {}/{}'.format(self.name, self.shared_mem_structure['KBCDO17']['Val'],
                                                        self.shared_mem_structure['KBCDO19']['Val']))
            self._gym_send_action_append(['KSWO213'], [0])

        if power >= 0.04 and self.shared_mem_structure['KBCDO18']['Val'] < 180:
            logging.debug('[{}] Turbin ac UP {}'.format(self.name, self.shared_mem_structure['KBCDO18']['Val']))
            self._gym_send_action_append(['KSWO215'], [1])
        elif self.shared_mem_structure['KBCDO18']['Val'] >= 200:
            self._gym_send_action_append(['KSWO215'], [0])

        if power >= 0.06 and self.shared_mem_structure['KBCDO20']['Val'] < 90:
            self._gym_send_action_append(['KSWO225'], [1])
        elif power >= 0.06 and self.shared_mem_structure['KBCDO20']['Val'] >= 100:
            self._gym_send_action_append(['KSWO225'], [0])

        if power >= 0.06 and self.shared_mem_structure['KBCDO21']['Val'] < 50:
            self._gym_send_action_append(['KSWO227'], [1])
        elif power >= 0.06 and self.shared_mem_structure['KBCDO21']['Val'] >= 60:
            self._gym_send_action_append(['KSWO227'], [0])

        if self.shared_mem_structure['KBCDO17']['Val'] >= 1800 and power >= 0.15:
            self._gym_send_action_append(['KSWO244'], [1])

        if action == 0:
            self._gym_send_action_append(['KSWO33', 'KSWO32'], [0, 0])
        elif action == 1:
            self._gym_send_action_append(['KSWO33', 'KSWO32'], [1, 0])
        elif action == 2:
            self._gym_send_action_append(['KSWO33', 'KSWO32'], [0, 1])

        return self._send_control_signal(self.para, self.val)

    def _gym_reward_done(self):
        power = self.shared_mem_structure['QPROREL']['Val']
        upper_condition, stady_condition, low_condition = self._calculator_operation_mode()

        if self.step >= 600:
            reward = 0
            done = True
        else:
            if power >= low_condition and power <= upper_condition:
                reward = 1
                done = False
            else:
                reward = 0
                done = True

        return reward, done

    def _gym_append_sample(self, input_window, policy, action, reward):
        if PARA.Model == 'LSTM':
            self.states.append(input_window[0]) # (1, 2, 3) -> (2, 3) 잡아서 추출
        elif PARA.Model == 'DNN':
            self.states.append(input_window)  # (1, 2, 3) -> (2, 3) 잡아서 추출
        act = np.zeros(np.shape(policy)[0])
        act[action] = 1
        self.actions.append(act)
        self.rewards.append(reward)

    def _gym_predict_action(self, input_window):
        # policy = self.local_actor_model.predict(input_window)[0]
        policy = self.shared_actor_net.predict(np.reshape(input_window, [self.input_dim, self.input_number]))[0]
        if self.Test_model:
            # 검증 네트워크의 경우 결과를 정확하게 뱉음
            action = np.argmax(policy)
        else:
            # 훈련 네트워크의 경우 랜덤을 값을 뱉음.
            action = np.random.choice(np.shape(policy)[0], 1, p=policy)[0]
        self.avg_q_max += np.amax(self.shared_actor_net.predict(np.reshape(input_window, [self.input_dim,
                                                                                self.input_number])))
        return policy, action

    def _gym_draw_img(self, max_score_ep, current_ep):
        self.ax.clear()
        self.ax_.clear()
        self.ax2.clear()
        self.ax3.clear()

        power, low, high, action = [], [], [], []

        for __ in range(len(self.interval_log)):
            power.append((self.input_window_log[__][0]*100))
            high.append((self.input_window_log[__][0] + self.input_window_log[__][2]/10)*100)
            low.append((self.input_window_log[__][0] - self.input_window_log[__][3]/10)*100)
            if self.action_log[__] == 0:
                action.append(0)
            elif self.action_log[__] == 1:
                action.append(1)
            elif self.action_log[__] == 2:
                action.append(-1)

        # self.turbin_log = {'Setpoint': [], 'Real': [], 'Electric': []}

        self.ax.plot(self.interval_log, power, 'g')
        self.ax.plot(self.interval_log, low, 'r')
        self.ax.plot(self.interval_log, high, 'b')

        self.ax_.plot(self.interval_log, self.turbin_log['Electric'], 'black')

        self.ax.set_ylabel('Reactor Power [%]')
        self.ax_.set_ylabel('Electrical Power [MWe]')
        self.ax.set_ylim(bottom=0)
        self.ax_.set_ylim(bottom=0)
        self.ax.grid()

        self.ax2.plot(self.interval_log, action)
        self.ax2.set_yticks((-1, 0, 1))
        self.ax2.set_yticklabels(('Out', 'Stay', 'In'))
        self.ax2.set_ylabel('Rod control')
        self.ax2.grid()

        self.ax3.plot(self.interval_log, self.turbin_log['Setpoint'], 'r')
        self.ax3.plot(self.interval_log, self.turbin_log['Real'], 'b')
        self.ax3.set_yticks((900, 1800))
        self.ax3.grid()
        self.ax3.set_yticklabels(('900', '1800'))
        self.ax3.set_ylabel('Turbine RPM')
        self.ax3.set_xlabel('Time [s]')

        self.fig.savefig(fname='./img/{}_{}_{}.png'.format(current_ep-1, max_score_ep, self.name), dpi=600, facecolor=None)

    def _gym_save_control_logger(self, input_window, action, reward):
        self.interval_log.append(self.interval)
        self.interval += 1
        self.action_log.append(action)
        self.input_window_log.append(input_window)

        self.turbin_log['Setpoint'].append(self.shared_mem_structure['KBCDO17']['Val'])
        self.turbin_log['Real'].append(self.shared_mem_structure['KBCDO19']['Val'])
        self.turbin_log['Electric'].append(self.shared_mem_structure['KBCDO22']['Val'])

        self.reward_log.append(reward)

    def _gym_save_control_history(self):
        if self.Test_model:
            with open('./log/Test_control_history_{}_{}.txt'.format(episode_test, self.name), 'a') as f:
                for __ in range(len(self.action_log)):
                    f.write('{}, {}, {}, {}, '.format(self.name,
                                                      self.interval_log[__],
                                                      self.reward_log[__],
                                                      self.action_log[__]))
                    for _ in self.input_window_log[__]:
                        f.write('{}, '.format(self.input_window_log[__][_]))
                    f.write('\n')
        else:
            with open('./log/Control_history_{}_{}.txt'.format(episode, self.name), 'a') as f:
                for __ in range(len(self.action_log)):
                    f.write('{}, {}, {}, {}, '.format(self.name,
                                                      self.interval_log[__],
                                                      self.reward_log[__],
                                                      self.action_log[__]))
                    for _ in self.input_window_log[__]:
                        f.write('{}, '.format(_))
                    f.write('\n')

    def _gym_save_score_history(self):
        if self.Test_model:
            # 검증 네트워크에서 결과 값을 저장함
            with open('./test_history.txt', 'a') as f:
                f.writelines('{}/{}/{}\n'.format(episode_test, self.name, self.score))
        else:
            # 훈련 네트워크에서 결과 값을 저장함
            with open('./history.txt', 'a') as f:
                f.writelines('{}/{}/{}\n'.format(episode, self.name, self.score))

    # ------------------------------------------------------------------
    # 네트워크 훈련 관련
    # ------------------------------------------------------------------

    def discount_rewards(self, rewards, done=True):
        discounted_rewards = np.zeros_like(rewards)
        running_add = 0
        if not done:
            running_add = self.shared_cric_net.predict(np.reshape(self.states[-1], (self.input_dim,
                                                                                self.input_number)))[0]
        for t in reversed(range(0, len(rewards))):
            running_add = running_add * 0.99 + rewards[t]
            discounted_rewards[t] = running_add
        return discounted_rewards

    # update policy network and value network every episode
    def train_episode(self, done):
        discounted_rewards = self.discount_rewards(self.rewards, done)

        values = self.shared_cric_net.predict(np.array(self.states))
        values = np.reshape(values, len(values))

        advantages = discounted_rewards - values
        print(np.shape(self.states), np.shape(self.actions), np.shape(advantages), )
        self.optimizer[0]([self.states, self.actions, advantages])
        self.optimizer[1]([self.states, discounted_rewards])
        self.states, self.actions, self.rewards = [], [], []
    # ------------------------------------------------------------------
    # 기타 편의 용
    # ------------------------------------------------------------------

    def _add_function_routine(self, input_window, action):
        reward = 1
        self.score += reward
        self.step += 1
        self.update_t += 1
        self._gym_save_control_logger(input_window[0], action, reward)
        input_window = self._make_input_window()
        if PARA.show_input_windows:
            logging.debug('[{}] Input_window {}'.format(self.name, input_window))
        self._gym_send_action(action)
        self._run_cns()
        return input_window

    # ------------------------------------------------------------------
    def run(self):
        if self.Test_model:
            global episode_test
        else:
            global episode

        global Max_score
        self.Max_score = Max_score

        logging.debug('[{}] Start socket'.format(self.name))
        self.action_log, self.reward_log, self.input_window_log, self.interval_log, self.interval= [], [], [], [], 0
        self.turbin_log = {'Setpoint': [], 'Real': [], 'Electric': []}
        #
        # CNS_10_21.tar 기반의 CNS에서 구동됨.
        #
        self._set_init_cns()
        sleep(1)
        mode = 0
        while episode < 10000:
            self._update_shared_mem()
            if mode == 0:
                if self.shared_mem_structure['KCNTOMS']['Val'] < 10:
                    mode += 1
            elif mode == 1: # LSTM의 데이터를 쌓기 위해서 대기 하는 곳
                if self.shared_mem_structure['KFZRUN']['Val'] == 6:
                    self._run_cns()
                if self.shared_mem_structure['KFZRUN']['Val'] == 4:
                    input_window = self._make_input_window()
                    if np.shape(input_window)[1] == self.input_number:
                        mode += 1
                    else:
                        self._run_cns()
            elif mode == 2: # 좀 더 대기하는 곳
                if self.shared_mem_structure['KFZRUN']['Val'] == 4:
                    if self.shared_mem_structure['KCNTOMS']['Val'] > 15:
                        input_window = self._make_input_window()
                        mode += 1
                    else:
                        input_window = self._make_input_window()
                        self._run_cns()
            elif mode == 3: # 초기 액션
                if self.shared_mem_structure['KFZRUN']['Val'] == 4:
                    input_window = self._make_input_window()
                    # 2.1 네트워크 액션 예측
                    policy, action = self._gym_predict_action(input_window[0]) #(4,)
                    # 2.2. 액션 전송
                    self._gym_send_action(action)
                    self._run_cns()
                    mode += 1
            elif mode == 4:
                if self.shared_mem_structure['KFZRUN']['Val'] == 4:
                    # 2.4 t+1초의 상태에 대한 보상 검증
                    reward, done = self._gym_reward_done()
                    if reward == 100:
                        self.score += 1
                    else:
                        self.score += reward

                    self.step += 1
                    self.update_t += 1

                    # 2.5 data box 에 append
                    self._gym_append_sample(input_window[0], policy, action, reward)
                    self._gym_save_control_logger(input_window[0], action, reward)
                    if PARA.save_input_log:
                        logging.debug('[{}] input window\n{}'.format(self.name, input_window[0]))

                    if self.update_t > self.update_t_limit and done != True:
                        self.train_episode(self.step != 351)
                        self.update_t = 0
                    else:
                        pass

                    # 2.5.2 죽으면 정보 호출 및 텐서보드 업데이트
                    if done:
                        # 운전 이력 저장
                        self._gym_save_score_history()

                        if self.Test_model:
                            pass
                            episode_test += 1
                            self._gym_save_control_history()
                            self.action_log, self.reward_log, self.input_window_log, self.interval_log, self.interval = [], [], [], [], 0
                            self.turbin_log = {'Setpoint': [], 'Real': [], 'Electric': []}
                            print("[TEST]{} Test_Episode:{}, Score:{}, Step:{}".format(episode_test, self.name, self.score,
                                                                                self.step))
                            # if episode_test % 10 == 1:
                            #     logging.debug('[{}] [TEST] Shared_net_work update'.format(self.name))
                            #     # test의 네트워크를 업데이트
                            #     # self.local_actor_model.set_weights(self.shared_actor_net.get_weights())
                            #     # self.local_cric_model.set_weights(self.shared_cric_net.get_weights())
                            #     self.local_actor_model.load_weights('./Model/A3C_actor')
                            #     self.local_cric_model.load_weights('./Model/A3C_cric')
                            #     # test의 네트워크를 저장
                            #     self.local_actor_model.save_weights("./Test_Model/{}_A3C_actor".format(episode))
                            #     self.local_cric_model.save_weights("./Test_Model/{}_A3C_cric".format(episode))
                            #     self.states, self.actions, self.rewards = [], [], []

                        else:
                            episode += 1
                            self.train_episode(self.step != 601)
                            self._gym_save_control_history()

                            if self.score >= Max_score:
                                self._gym_draw_img(current_ep=episode, max_score_ep=self.score)
                                Max_score = self.score
                                self.Max_score = Max_score

                            self.action_log, self.reward_log, self.input_window_log, self.interval_log, self.interval = [], [], [], [], 0
                            self.turbin_log = {'Setpoint': [], 'Real': [], 'Electric': []}
                            print("[TRAIN]{} Episode:{}, Score:{}, Step:{}".format(episode, self.name, self.score,
                                                                                self.step))

                            if self.score >= 120:
                                self.score = 120
                            else:
                                pass

                            stats = [self.score, self.avg_q_max/(self.step/4), self.step]
                            for i in range(len(stats)):
                                self.sess.run(self.update_ops[i], feed_dict={self.summary_placeholders[i]:
                                                                                float(stats[i])})
                            summary_str = self.sess.run(self.summary_op)
                            self.summary_writer.add_summary(summary_str, episode + 1)

                        self.avg_q_max, self.score = 0, 0
                        self.step = 0
                        self.update_t = 0

                        mode += 5
                        done = False
                    else:
                        # 2.6 액션의 결과를 토대로 다시 업데이트
                        input_window = self._make_input_window()
                        if PARA.show_input_windows:
                            logging.debug('[{}] Input_window {}'.format(self.name, input_window))
                        # 2.1 네트워크 액션 예측
                        policy, action = self._gym_predict_action(input_window[0])  # (4,)
                        # 2.2. 액션 전송
                        self._gym_send_action(action)
                        self._run_cns()
                        mode += 1

            if mode == 5 or mode == 6 or mode == 7:
                if self.shared_mem_structure['KFZRUN']['Val'] == 4:
                    input_window = self._add_function_routine(input_window, action)
                    mode += 1
            if mode == 8:
                if self.shared_mem_structure['KFZRUN']['Val'] == 4:
                    input_window = self._add_function_routine(input_window, action)
                    mode -= 4
            if mode == 9:
                if self.shared_mem_structure['KFZRUN']['Val'] == 6:
                    self._run_cns()
                    mode = 0
                else:
                    self._set_init_cns()
    # ------------------------------------------------------------------

if __name__ == '__main__':
    test = MainModel()
    test._run()


from time import clock
from configparser import ConfigParser
from configparser import RawConfigParser

from configparser import NoOptionError
from configparser import NoSectionError

class Timer(object):
    def __init__(self, verbose=False):
        self.verbose = verbose

    def __enter__(self):
        self.start = clock()
        return self

    def __exit__(self, *args):
        self.end = clock()
        self.secs = self.end - self.start
        self.msecs = self.secs * 1000  # millisecs

try:
    from line_profiler import LineProfiler
    #from functools import wraps
    #raise Exception('cust')
    def func_line_time(f):
        #@wraps(f)
        def decorator(*args, **kwargs):
            lp = LineProfiler()
            lp_wrap = lp(f)
            func_return = lp_wrap(*args, **kwargs)
            #func_return = f(*args, **kwargs)
            lp.print_stats()
            return func_return
        return decorator
except:
    def func_line_time(f):
        def decorator(*args, **kwargs):
            with Timer() as t:
                func_return = f(*args, **kwargs)
            if t.verbose:
                print('function %s running for %d'%(f.__name__, t.msecs))
            return func_return
        return decorator

class MyConf:
    def getConf(self, section, key, default=None):
        value = default
        try:
            value = self.config.get(section, key)
        except NoSectionError:
            pass
        except NoOptionError:
            pass
        return value
    @staticmethod
    def initConf(file, type=None):
        cp = None
        if type == 'raw':
            cp = RawConfigParser()
        else:
            cp = ConfigParser()
        cp.read(file)
        return cp
    def __init__(self, filename, type=None):
        self.config = MyConf.initConf(filename, type)

@func_line_time
def testrun(abc):
    for i in range(0, 500000):
        if i == 0:
            print('hello ' + abc)
    return False

if __name__ == '__main__':
    result = testrun('good')
    print(result)


import cv2
import time
import recognize
from time import sleep
import pandas as pd
from datetime import datetime
import pickle
from datetime import datetime
import numpy as np
import face_recogn
import os
#from cvzone.SerialModule import SerialObject
import datetime
import pyttsx3
newVoiceRate = 100
text_speech = pyttsx3.init()
text_speech.setProperty('rate', newVoiceRate)

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)

data = pickle.loads(open("encodings.pickle", "rb").read())

path = 'ImagesAttendance'
images = []
classNames = []
myList = os.listdir(path)
print(myList)
for cl in myList:
    curImg = cv2.imread(f'{path}/{cl}')
    images.append(curImg)
    classNames.append(os.path.splitext(cl)[0])
print(classNames)

#arduino = SerialObject("COM9")

def main():
    def process_frame():
        ret, frame = cap.read()
        gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=4)
        if len(faces) > 0:
            (x, y, w, h) = faces[0]
            cv2.rectangle(frame, (x, y), (w, h), (0, 0, 255), 2)
            face_cropped = frame[y:y + h, x:x + w]

            # Calculate the ratio of the eye region to the face region
            eye_region_height = int(h * 0.2)
            eye_region_width = int(w * 0.4)
            eye_region_x = int(w * 0.3)
            eye_region_y = int(h * 0.4)
            eye_region = face_cropped[eye_region_y:eye_region_y + eye_region_height,
                         eye_region_x:eye_region_x + eye_region_width]

            # Calculate the average intensity of the pixels in the eye region
            eye_intensity = cv2.mean(eye_region)[0]

            # Check if the average intensity is above a threshold
            if eye_intensity > 100:
                cv2.putText(frame, "fake", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), 2)
            else:
                cv2.putText(frame, "real", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2)
                col_names = ['name', 'date', 'time']
                attendance = pd.DataFrame(columns=col_names)
                imgS = cv2.resize(frame, (0, 0), None, 0.25, 0.25)
                imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)

                facesCurFrame = face_recogn.face_locations(imgS)
                encodesCurFrame = face_recogn.face_encodings(imgS, facesCurFrame)

                for encodeFace, faceLoc in zip(encodesCurFrame, facesCurFrame):
                    matches = face_recogn.compare_faces(data["encodings"], encodeFace)
                    faceDis = face_recogn.face_distance(data["encodings"], encodeFace)
                    # print(faceDis)
                    matchIndex = np.argmin(faceDis)

                    if matches[matchIndex]:
                        name = classNames[matchIndex].upper()
                        # print(name)
                        y1, x2, y2, x1 = faceLoc
                        y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
                        cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
                        cv2.rectangle(frame, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
                        cv2.putText(frame, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)

                        ts = time.time()
                        date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
                        timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
                        # aa = ['Name'].values
                        # tt = str(Id)+"-"+aa
                        attendance.loc[len(attendance)] = [name, date, timeStamp]
                        attendance = attendance.drop_duplicates(subset=['name'], keep='first')
                        fileName = "Attendance\Attendance_" + ".csv"
                        attendance.to_csv(fileName, mode='a', header=None, index=False)

                       # arduino.sendData([1])
                        #sleep(4)
                        #arduino.sendData([0])
                        text_speech.say("Attendance successfull" + str(name))
                        text_speech.runAndWait()

        cv2.imshow('frame', frame)

    # Start processing frames
    start_time = time.time()
    while True:
        elapsed_time = time.time() - start_time
        if elapsed_time >= 0.5:
            process_frame()
            start_time = time.time()
        key = cv2.waitKey(1) & 0xFF
        if key == ord('q'):
            break

    # Clean up
    cap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()


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

import Sofa
import SofaTest

def createScene(rootNode):
    rootNode.createChild("CHILD1")
    ASSERT_GT(len(rootNode.getListOfLinks()), 0)

    aField = rootNode.getListOfLinks()[0]
    ASSERT_EQ( aField.value, "@/CHILD1")

    aField.setPersistant(False)
    ASSERT_FALSE(aField.isPersistant())

    aField.setPersistant(True)
    ASSERT_TRUE(aField.isPersistant())


import json
import boto3
import csv
import io
import urllib.request
from botocore.vendored import requests

def lambda_handler(event, context):
    s3 = boto3.client('s3')
    bucket_name = 'extracted-data-data-swan'

    file_name = '2020_general_paymentdata.csv'

    # URL of the CSV file
    csv_url = "https://openpaymentsdata.cms.gov/api/1/datastore/query/a08c4b30-5cf3-4948-ad40-36f404619019/0/download?&format=csv"

    with requests.get(csv_url, stream=True) as response:
        if response.status_code == 200:
            # Open a temporary file for writing
            with open('/tmp/' + file_name, 'wb') as file:
                for chunk in response.iter_content(chunk_size=1024):
                    file.write(chunk)

            # Upload the file to S3 bucket
            s3.upload_file('/tmp/' + file_name, bucket_name, file_name)

            return {
                'statusCode': 200,
                'body': 'CSV file uploaded successfully'
            }
        else:
            return {
                'statusCode': response.status_code,
                'body': 'Failed to download CSV file'
            }


import numpy as np
import pandas as pd
from scipy.integrate import odeint
from pycbc.types import FrequencySeries

class Precession():

    def __init__(self, params=None) -> None:

        self.params = params

        # non-precession/unlensed parameters
        self.theta_S = params['theta_S']
        self.phi_S = params['phi_S']
        self.theta_J = params['theta_J']
        self.phi_J = params['phi_J']
        self.mcz = params['mcz']
        self.dist = params['dist']
        self.eta = params['eta']
        self.tc = params['tc']
        self.phi_c = params['phi_c']

        # precession parameters
        self.theta_tilde = params['theta_tilde']
        self.omega_tilde = params['omega_tilde']
        self.gamma_P = params['gamma_P']

        # some converters/constants

        self.SOLMASS2SEC = 4.92624076 * 1e-6 # solar mass -> seconds
        self.GIGAPC2SEC = 1.02927125 * 1e17 # gigaparsec -> seconds
        self.FMIN = 20 # lower frequency of the detector sensitivity band [Hz]

    def get_total_mass(self):
        """ Total mass from chirp mass [seconds]
        """
        return self.mcz/(self.eta**(3/5))

    def get_f_cut(self):
        """ f_cut
        """
        return 1/(6**(3/2)*np.pi*self.get_total_mass())

    def get_theta_LJ(self, f):
        """ theta_LJ
        """
        return 0.1*self.theta_tilde*(f/self.get_f_cut())**(1/3)

    def get_phi_LJ(self, f):
        """ phi_LJ
        """
        num = 52.083 * self.omega_tilde
        deno = (self.get_total_mass()/self.SOLMASS2SEC) * np.pi**(8/3) * self.mcz**(5/3) * self.get_f_cut()**(5/3)
        phi_LJ_amp = num/deno
        return phi_LJ_amp * (1/self.FMIN - 1/f) + self.gamma_P

    def amp_prefactor(self) -> float:
        """ amplitude prefactor calculated using chirp mass and distance
        """
        amp_prefactor = np.sqrt(5/96)*np.pi**(-2/3)*self.mcz**(5/6)/self.dist
        return amp_prefactor

    def precession_angles(self):
        """ some angles
        """
        Cie = np.cos(self.theta_S) * np.cos(self.theta_J) + np.sin(self.theta_S) * np.sin(self.theta_J) * np.cos(self.phi_S - self.phi_J)
        Sie = np.sqrt(1-Cie**2.)
        if Sie == 0:
            COe = 1
            SOe = 0
        else:
            COe = (np.cos(self.theta_S)*np.sin(self.theta_J)*np.cos(self.phi_J - self.phi_S)-np.sin(self.theta_S)*np.cos(self.theta_J))/(Sie)
            SOe = (np.sin(self.theta_J)*np.sin(self.phi_J - self.phi_S))/(Sie)
        return Cie, Sie, COe, SOe

    def LdotN(self, f):
        Cie, Sie, COe, SOe = self.precession_angles()
        LdotN = Cie*np.cos(self.get_theta_LJ(f))+Sie*np.sin(self.get_theta_LJ(f))*np.sin(self.get_phi_LJ(f))
        return LdotN

    def polarization_angles(self, f):
        Cie, Sie, COe, SOe = self.precession_angles()
        # polarization angle for precession

        # define cospsitest
        term01 = np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * COe * np.sin(self.theta_S)
        term02 = np.cos(self.get_theta_LJ(f)) * np.sin(self.theta_S) * np.sin(self.theta_J) * np.sin(self.phi_J - self.phi_S)
        term03 = np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * SOe * Cie * np.sin(self.theta_S)
        cospsitest0 = term01 + term02 - term03

        # define sinpsitest
        term11 = np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * SOe * np.sin(self.theta_S)
        term12 = np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * COe * np.sin(self.theta_S) * Cie
        term13 = np.cos(self.get_theta_LJ(f)) * np.cos(self.theta_J)
        term14 = np.cos(self.get_theta_LJ(f)) * np.cos(self.theta_S) * Cie
        sinpsitest0 = term11 + term12 + term13 - term14

        #normalizing cospsi and sinpsi
        if Sie == 0:
            cospsitest = cospsitest0
            sinpsitest = sinpsitest0
        else:
            cospsitest = (cospsitest0)/(np.sqrt(cospsitest0**2+sinpsitest0**2))
            sinpsitest = (sinpsitest0)/(np.sqrt(cospsitest0**2+sinpsitest0**2))

        cos2psi = cospsitest**2.-sinpsitest**2.
        sin2psi = 2*cospsitest*sinpsitest
        return cos2psi, sin2psi

    ### get the amplitude
    def amplitude(self, f) -> np.array:
        """ Non-precessin/unlensed amplitude
        """
        LdotN = self.LdotN(f)
        cos2psi, sin2psi = self.polarization_angles(f)

        # beam patterns
        Fp = (1./2.)*(1+np.cos(self.theta_S)**2)*np.cos(2*self.phi_S)*cos2psi - np.cos(self.theta_S)*np.sin(2*self.phi_S)*sin2psi
        Fc = (1./2.)*(1+np.cos(self.theta_S)**2)*np.cos(2*self.phi_S)*sin2psi + np.cos(self.theta_S)*np.sin(2*self.phi_S)*cos2psi

        amp = self.amp_prefactor()*f**(-7/6)*np.sqrt(4*Fc**2*LdotN**2+Fp**2*(1+LdotN**2)**2)
        return amp

    ### get the phase phi_P
    def phase_phi_P(self, f):

        LdotN = self.LdotN(f)
        cos2psi, sin2psi = self.polarization_angles(f)

        #beam patterns
        Fp = (1./2.)*(1+np.cos(self.theta_S)**2)*np.cos(2*self.phi_S)*cos2psi - np.cos(self.theta_S)*np.sin(2*self.phi_S)*sin2psi
        Fc = (1./2.)*(1+np.cos(self.theta_S)**2)*np.cos(2*self.phi_S)*sin2psi + np.cos(self.theta_S)*np.sin(2*self.phi_S)*cos2psi

        phi_p_temp = np.arctan2(2*LdotN*Fc, (1+LdotN**2)*Fp)
        phi_p = np.unwrap(phi_p_temp, discont=np.pi)
        return phi_p

    ### get the delta phi_P

    def Lcomps(self, f) -> np.array:
        """ L components
        """
        Cie, Sie, COe, SOe = self.precession_angles()
        # define Ldots
        Lx1 = np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * COe * np.sin(self.phi_S)
        Lx2 = np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * SOe * np.cos(self.phi_S) * np.cos(self.theta_S)
        Lx3 = np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * SOe * np.sin(self.phi_S) * Cie
        Lx4 = np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * COe * np.cos(self.phi_S) * Cie * np.cos(self.theta_S)
        Lx5 = np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * np.cos(self.phi_S) * Sie * np.sin(self.theta_S)
        Lx6 = np.cos(self.get_theta_LJ(f)) * np.sin(self.theta_J) * np.cos(self.phi_J)
        Lx  = -Lx1 - Lx2 + Lx3 - Lx4 + Lx5 + Lx6

        Ly1 = np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * COe * np.cos(self.phi_S)
        Ly2 = np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * SOe * np.sin(self.phi_S) * np.cos(self.theta_S)
        Ly3 = np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * SOe * np.cos(self.phi_S) * Cie
        Ly4 = np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * COe * np.sin(self.phi_S) * Cie * np.cos(self.theta_S)
        Ly5 = np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * np.sin(self.phi_S) * Sie * np.sin(self.theta_S)
        Ly6 = np.cos(self.get_theta_LJ(f)) * np.sin(self.theta_J) * np.sin(self.phi_J)
        Ly  = Ly1 - Ly2 - Ly3 - Ly4 + Ly5 + Ly6

        Lz1 = np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * SOe * np.sin(self.theta_S)
        Lz2 = np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * COe * np.sin(self.theta_S) * Cie
        Lz3 = np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * Sie * np.cos(self.theta_S)
        Lz4 = np.cos(self.get_theta_LJ(f)) * np.cos(self.theta_J)
        Lz  = Lz1 + Lz2 + Lz3 + Lz4
        return Lx, Ly, Lz

    def N_comps(self) -> float:
        """ N components
        """
        Nx = np.sin(self.theta_S)*np.cos(self.phi_S)
        Ny = np.sin(self.theta_S)*np.sin(self.phi_S)
        Nz = np.cos(self.theta_S)
        return Nx, Ny, Nz

    def f_dot(self, f):
        """ df/dt from Cutler Flanaghan 1994
        """
        prefactor = (96/5)*np.pi**(8/3)*self.mcz**(5/3)*f**(11/3)
        term1 = 1
        term2 = (743/336 + (11/4)*self.eta)*(np.pi*self.get_total_mass()*f)**(2/3)
        term3 = 4*np.pi*(np.pi*self.get_total_mass()*f)
        return prefactor*(term1-term2+term3)

    def integrand_delta_phi(self, y, f):
        """ integrand for delta phi p (equation in Apostolatos 1994)
        """
        Cie, Sie, COe, SOe = self.precession_angles()
        dfdt_inv = self.f_dot(f)**(-1)
        Lx, Ly, Lz = self.Lcomps(f)
        Nx, Ny, Nz = self.N_comps()
        LdotN = self.LdotN(f)

        derivf_omega = (1e3 * self.omega_tilde * (f/self.get_f_cut())**(5/3)) / (self.get_total_mass()/self.SOLMASS2SEC)
        derivf_theta = (0.1/3) * self.theta_tilde * (f**(-2)/self.get_f_cut())**(1/3)

        Lx1_dot = -derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * COe * np.sin(self.phi_S) + derivf_theta * np.cos(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * COe * np.sin(self.phi_S)
        Lx2_dot = -derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * SOe * np.cos(self.phi_S) * np.cos(self.theta_S) + derivf_theta * np.cos(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * SOe * np.cos(self.phi_S) * np.cos(self.theta_S)
        Lx3_dot =  derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * SOe * np.sin(self.phi_S) * Cie + derivf_theta * np.cos(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * SOe * np.sin(self.phi_S) * Cie
        Lx4_dot =  derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * COe * np.cos(self.phi_S) * Cie * np.cos(self.theta_S) + derivf_theta *  np.cos(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * COe * np.cos(self.phi_S) * Cie * np.cos(self.theta_S)
        Lx5_dot =  derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * np.cos(self.phi_S) * Sie * np.sin(self.theta_S) + derivf_theta * np.cos(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * np.cos(self.phi_S) * Sie * np.sin(self.theta_S)
        Lx6_dot = -derivf_theta * np.sin(self.get_theta_LJ(f)) * np.sin(self.theta_J) * np.cos(self.phi_J)
        Lx_dot  = -Lx1_dot - Lx2_dot + Lx3_dot - Lx4_dot + Lx5_dot + Lx6_dot

        Ly1_dot = -derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * COe * np.cos(self.phi_S) + derivf_theta * np.cos(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * COe * np.cos(self.phi_S)
        Ly2_dot = -derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * SOe * np.sin(self.phi_S) * np.cos(self.theta_S) + derivf_theta * np.cos(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * SOe * np.sin(self.phi_S) * np.cos(self.theta_S)
        Ly3_dot =  derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * SOe * np.cos(self.phi_S) * Cie + derivf_theta * np.cos(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * SOe * np.cos(self.phi_S) * Cie
        Ly4_dot =  derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * COe * np.sin(self.phi_S) * Cie * np.cos(self.theta_S) + derivf_theta * np.cos(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * COe * np.sin(self.phi_S) * Cie * np.cos(self.theta_S)
        Ly5_dot =  derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * np.sin(self.phi_S) * Sie * np.sin(self.theta_S) + derivf_theta * np.cos(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * np.sin(self.phi_S) * Sie * np.sin(self.theta_S)
        Ly6_dot = -derivf_theta * np.sin(self.get_theta_LJ(f)) * np.sin(self.theta_J) * np.sin(self.phi_J)
        Ly_dot  = Ly1_dot - Ly2_dot - Ly3_dot - Ly4_dot + Ly5_dot + Ly6_dot

        Lz1_dot = -derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * SOe * np.sin(self.theta_S) + derivf_theta * np.cos(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * SOe * np.sin(self.theta_S)
        Lz2_dot =  derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * COe * np.sin(self.theta_S) * Cie + derivf_theta * np.cos(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * COe * np.sin(self.theta_S) * Cie
        Lz3_dot =  derivf_omega * dfdt_inv * np.sin(self.get_theta_LJ(f)) * np.cos(self.get_phi_LJ(f)) * Sie * np.cos(self.theta_S) + derivf_theta * np.cos(self.get_theta_LJ(f)) * np.sin(self.get_phi_LJ(f)) * Sie * np.cos(self.theta_S)
        Lz4_dot = -derivf_theta * np.sin(self.get_theta_LJ(f)) * np.cos(self.theta_J)
        Lz_dot = Lz1_dot + Lz2_dot + Lz3_dot + Lz4_dot

        deltaphi_x_P = Lx_dot * (Ly*Nz-Lz*Ny)
        deltaphi_y_P = Ly_dot * (-Lx*Nz+Lz*Nx)
        deltaphi_z_P = Lz_dot * (Lx*Ny-Ly*Nx)

        k = 0
        integrand_delta_phi = (deltaphi_z_P+deltaphi_y_P+deltaphi_x_P)*LdotN/(1-LdotN**2) + k*y
        return integrand_delta_phi

    def phase_delta_phi(self, f):
        """ integrate the delta_phi integrand
        """
        integral = odeint(self.integrand_delta_phi, 0, f)
        return np.squeeze(integral)

    def Psi(self, f):
        """ GW phase
        """
        x = (np.pi*self.get_total_mass()*f)**(2/3)
        term1 = 2*np.pi*f*self.tc - self.phi_c - np.pi/4
        prefactor = (3/4)*(8*np.pi*self.mcz*f)**(-5/3)
        term2 = 1 + (20/9)*(743/336 + (11/4)*self.eta)*x - 16*np.pi*x**(3/2)
        Psi = term1 + prefactor * term2
        return Psi

    def precessing_strain(self, f, delta_f=0.25, frequencySeries=True):
        """ precessing GW
        """
        precessing_strain = self.amplitude(f) * np.exp(1j*(self.Psi(f) - self.phase_phi_P(f) + self.phase_delta_phi(f)))
        if frequencySeries:
            return FrequencySeries(precessing_strain, delta_f, delta_f)
        return precessing_strain


import torch
import torch.nn as nn
import datetime
import sys
sys.path.append('../')

from utilities import run
from utilities import Dataset
from utilities import data_loader
from models import MLP

BATCH_SIZE=8184
max_epochs = 5000
number_conv_steps =32
LOOKBACK_DISTANCE=256
PREDICTION_RANGE=1
RUN_TIME=300000
SAVE_FILE_AT='./finished_models/32_layer_resnet.pt'

train_generator, test_generator, NUM_FEATURES = data_loader.load_csv(
     '../Intraday-Stock-Data/a-f/A_2010_2019.txt',
     LOOKBACK_DISTANCE,
     PREDICTION_RANGE,
     BATCH_SIZE,
     torch.float32
)

def init_weights(m):
    if type(m) == nn.Linear or type(m) == nn.Conv1d:
        nn.init.xavier_uniform_(m.weight)
        if (m.bias != None):
            m.bias.data.fill_(0.01)
    elif (isinstance(m, nn.BatchNorm1d)):
        m.weight.data.fill_(1)
        m.bias.data.zero_()

model = MLP.MLP(
    NUM_FEATURES=NUM_FEATURES,
    LOOKBACK_DISTANCE=LOOKBACK_DISTANCE,
    output_dim=1,
    number_conv_steps=number_conv_steps
)

model.cuda().to(torch.float32)
model.apply(init_weights)

loss_fn = torch.nn.MSELoss(size_average=True).cuda()
LEARNING_RATE = 0.000001

optimizer = torch.optim.Adam(model.parameters(), LEARNING_RATE)

run.run(model, optimizer, loss_fn, max_epochs, train_generator, test_generator, writer, RUN_TIME, WILL_CHECK_TIMINGS=True, USE_AUTOCAST=True, SAVE_FILE_AT=SAVE_FILE_AT)


"""The top level of the ASN.1 tools package contains commonly used
functions and classes, and the command line interface.

"""

import sys
import os
import argparse
import binascii
import logging

from prompt_toolkit.contrib.completers import WordCompleter
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.interface import AbortAction
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory

from .compiler import compile_dict
from .compiler import compile_string
from .compiler import compile_files
from .compiler import pre_process_dict
from .parser import parse_string
from .parser import parse_files
from .parser import ParseError
from .errors import EncodeError
from .errors import DecodeError
from .errors import CompileError

__author__ = 'Erik Moqvist'
__version__ = '0.64.0'

class ArgumentParserError(Exception):
    pass

class ArgumentParser(argparse.ArgumentParser):

    def exit(self, status=0, message=None):
        if message:
            self._print_message(message, sys.stdout)

        raise ArgumentParserError(message)

    def error(self, message):
        self.print_usage(sys.stdout)
        message = '{}: error: {}'.format(self.prog, message)
        print(message)

        raise ArgumentParserError(message)

def _convert_hexstring(input_spec,
                       output_spec,
                       output_format,
                       type_name,
                       hexstring):
    try:
        encoded = binascii.unhexlify(hexstring)
    except Exception as e:
        raise TypeError("'{}': {}".format(hexstring, str(e)))

    decoded = input_spec.decode(type_name, encoded)

    if output_format in ['asn1', 'xer', 'jer']:
        decoded = output_spec.encode(type_name, decoded, indent=4).strip()
    else:
        decoded = binascii.hexlify(output_spec.encode(type_name, decoded))

    print(decoded.decode('latin-1'))

def _compile_files(specifications, input_format, output_format):
    parsed = parse_files(specifications)
    input_spec = compile_dict(parsed, input_format)
    output_spec = compile_dict(parsed, output_format)

    return input_spec, output_spec

def _do_convert(args):
    input_spec, output_spec = _compile_files(args.specification,
                                             args.input_format,
                                             args.output_format)

    if args.hexstring == '-':
        for hexstring in sys.stdin:
            hexstring = hexstring.strip('\r\n')

            if hexstring:
                try:
                    _convert_hexstring(input_spec,
                                       output_spec,
                                       args.output_format,
                                       args.type,
                                       hexstring)
                except TypeError:
                    print(hexstring)
                except DecodeError as e:
                    print(hexstring)
                    print(str(e))
            else:
                print(hexstring)
    else:
        _convert_hexstring(input_spec,
                           output_spec,
                           args.output_format,
                           args.type,
                           args.hexstring)

def _handle_command_compile(line):
    parser = ArgumentParser(prog='compile')
    parser.add_argument('-i', '--input-format',
                        choices=('ber', 'der', 'jer', 'per', 'uper', 'xer'),
                        default='ber',
                        help='Input format (default: ber).')
    parser.add_argument('-o', '--output-format',
                        choices=('ber', 'der', 'jer', 'per', 'uper', 'xer', 'asn1'),
                        default='asn1',
                        help='Output format (default: asn1).')
    parser.add_argument('specification',
                        nargs='+',
                        help='ASN.1 specification as one or more .asn files.')

    try:
        args = parser.parse_args(args=line.split()[1:])
    except ArgumentParserError:
        return None, None, None

    try:
        input_spec, output_spec = _compile_files(args.specification,
                                                 args.input_format,
                                                 args.output_format)
        return input_spec, output_spec, args.output_format
    except Exception as e:
        print('error: {}'.format(str(e)))
        return None, None, None

def _handle_command_convert(line, input_spec, output_spec, output_format):
    if not input_spec:
        print("No compiled specification found. Please use the "
              "'compile' command to compile one.")
        return

    parser = ArgumentParser(prog='convert')
    parser.add_argument('type', help='Type to convert.')
    parser.add_argument(
        'hexstring',
        help='Hexstring to convert.')

    try:
        args = parser.parse_args(args=line.split()[1:])
    except ArgumentParserError:
        return

    try:
        _convert_hexstring(input_spec,
                           output_spec,
                           output_format,
                           args.type,
                           args.hexstring)
    except Exception as e:
        print('error: {}'.format(str(e)))

def _handle_command_help():
    print('Commands:')
    print('  compile')
    print('  convert')

def _do_shell(_args):
    commands = ['compile', 'convert', 'help', 'exit']
    completer = WordCompleter(commands, WORD=True)
    user_home = os.path.expanduser('~')
    history = FileHistory(os.path.join(user_home, '.asn1tools-history.txt'))
    input_spec = None
    output_spec = None
    output_format = None

    print("\nWelcome to the asn1tools shell!\n")

    while True:
        try:
            line = prompt(u'$ ',
                          completer=completer,
                          complete_while_typing=True,
                          auto_suggest=AutoSuggestFromHistory(),
                          enable_history_search=True,
                          history=history,
                          on_abort=AbortAction.RETRY)
        except EOFError:
            return

        line = line.strip()

        if line:
            if line.startswith('compile'):
                input_spec, output_spec, output_format = _handle_command_compile(line)
            elif line.startswith('convert'):
                _handle_command_convert(line,
                                        input_spec,
                                        output_spec,
                                        output_format)
            elif line == 'help':
                _handle_command_help()
            elif line == 'exit':
                return
            else:
                print('{}: command not found'.format(line))

def _main():
    parser = argparse.ArgumentParser(
        description='Various ASN.1 utilities.')

    parser.add_argument('-d', '--debug', action='store_true')
    parser.add_argument('-v', '--verbose',
                        choices=(0, 1, 2),
                        type=int,
                        default=1,
                        help=('Control the verbosity; disable(0), warning(1) '
                              'and debug(2). (default: 1).'))
    parser.add_argument('--version',
                        action='version',
                        version=__version__,
                        help='Print version information and exit.')

    # Workaround to make the subparser required in Python 3.
    subparsers = parser.add_subparsers(title='subcommands',
                                       dest='subcommand')
    subparsers.required = True

    # The 'convert' subparser.
    subparser = subparsers.add_parser(
        'convert',
        description='Convert given hextring and print it to standard output.')
    subparser.add_argument('-i', '--input-format',
                           choices=('ber', 'der', 'jer', 'per', 'uper', 'xer'),
                           default='ber',
                           help='Input format (default: ber).')
    subparser.add_argument('-o', '--output-format',
                           choices=('ber', 'der', 'jer', 'per', 'uper', 'xer', 'asn1'),
                           default='asn1',
                           help='Output format (default: asn1).')
    subparser.add_argument('specification',
                           nargs='+',
                           help='ASN.1 specification as one or more .asn files.')
    subparser.add_argument('type', help='Type to convert.')
    subparser.add_argument(
        'hexstring',
        help='Hexstring to convert, or - to read hexstrings from standard input.')
    subparser.set_defaults(func=_do_convert)

    # The 'shell' subparser.
    shell_parser = subparsers.add_parser('shell',
                                         description='An interactive shell.')
    shell_parser.set_defaults(func=_do_shell)

    args = parser.parse_args()

    levels = [logging.CRITICAL, logging.WARNING, logging.DEBUG]
    level = levels[args.verbose]

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

    if args.debug:
        args.func(args)
    else:
        try:
            args.func(args)
        except BaseException as e:
            sys.exit('error: {}'.format(str(e)))


import setuptools

dependencies = [
    'sendgrid==6.4.8',
    'Jinja2==2.11.2'
]

setuptools.setup(
    name='traceback_notify',
    version='0.3',
    author='Ihor Vnukov',
    packages=['traceback_notifier'],
    package_data={"": ["*.html", ]},
    license='MIT',
    install_requires=dependencies,
    python_requires='>=3.6'
)


# vim: set ts=2 expandtab:
from django.shortcuts import render
from django.template import Context, loader
from django.http import HttpResponse
from django.http import HttpResponseNotFound
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from futaba_archive.models import Board

def index(request):
  boards = Board.objects.all()
  t = loader.get_template('futaba_archive/index.html')
  c = Context({
    'boards': boards,
    })
  return HttpResponse(t.render(c))

def board(request, board_name):
  '''
  Display a certain number of threads on a given board
  '''
  board = Board.objects.get(name=board_name)
  if not board:
    return HttpResponseNotFound('
Board not found
')

  threads = board.post_set.filter(parent=None).order_by('-date')
  paginator = Paginator(threads, 15) #15 threads per page
  page = request.GET.get('page')
  try:
    threads = paginator.page(page)
  except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    threads = paginator.page(1)
  except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
    threads = paginator.page(paginator.num_pages)

  for thread in threads:
    thread.responses = list(thread.post_set.order_by('number').all())
    if thread.responses:
      def add_response_index(response, index):
        response.response_index = index+1
        return response
      thread.responses = [ add_response_index(x, i) for i, x in enumerate(thread.responses)][-5:]
  prev_pages = [ x for x in range(threads.number-5, threads.number) if x>0]
  next_pages = [ x for x in range(threads.number+1, threads.number+6) if x<= paginator.num_pages ]

  t = loader.get_template('futaba_archive/board.html')
  c = Context({
    'board': board,
    'threads' : threads,
    'prev_pages' : prev_pages,
    'next_pages' : next_pages,
    })
  return HttpResponse(t.render(c))

def thread(request, board_name, post_number):
  '''
  Display thread and all responses
  '''
  board = Board.objects.get(name=board_name)
  if not board:
    return HttpResponseNotFound('
Board not found
')

  thread = board.post_set.get(number=post_number)
  if not thread:
    return HttpResponseNotFound('
Thread not found
')

  posts = thread.post_set.all()
  t = loader.get_template('futaba_archive/thread.html')
  c = Context({
    'thread':thread,
    'board':board,
    'posts':posts,
    })
  return HttpResponse(t.render(c))


#-*- coding: UTF-8 -*-
from pymatgen import MPRester
from pymatgen.analysis.phase_diagram import PhaseDiagram, PDPlotter
import collections
import sys, os
import time
import string
import re
from functools import reduce
os.system('rm -rf structure; mkdir structure')

ChemicalSymbols = [ 'H',  'He', 'Li', 'Be','B',  'C',  'N',  'O',  'F',
                    'Ne', 'Na', 'Mg', 'Al', 'Si','P',  'S',  'Cl', 'Ar', 'K',
                    'Ca', 'Sc', 'Ti', 'V',  'Cr','Mn', 'Fe', 'Co', 'Ni', 'Cu',
                    'Zn', 'Ga', 'Ge', 'As', 'Se','Br', 'Kr', 'Rb', 'Sr', 'Y',
                    'Zr', 'Nb', 'Mo', 'Tc', 'Ru','Rh', 'Pd', 'Ag', 'Cd', 'In',
                    'Sn', 'Sb', 'Te', 'I',  'Xe','Cs', 'Ba', 'La', 'Ce', 'Pr',
                    'Nd', 'Pm', 'Sm', 'Eu', 'Gd','Tb', 'Dy', 'Ho', 'Er', 'Tm',
                    'Yb', 'Lu', 'Hf', 'Ta', 'W','Re', 'Os', 'Ir', 'Pt', 'Au',
                    'Hg', 'Tl', 'Pb', 'Bi', 'Po','At', 'Rn', 'Fr', 'Ra', 'Ac',
                    'Th', 'Pa', 'U',  'Np', 'Pu','Am', 'Cm', 'Bk', 'Cf', 'Es',
                    'Fm', 'Md', 'No', 'Lr']
M = ['Sc', 'Ti', 'V', 'Cr', 'Mn',
     'Zr', 'Nb', 'Mo',
     'Hf', 'Ta', 'W']
A = ['Al', 'Si', 'P', 'S',
     'Ga', 'Ge', 'As',
     'Cd', 'In', 'Sn',
     'Ti', 'Pb']
X = ['H',
     'B', 'C', 'N', 'O', 'F',
     'Si', 'P', 'S', 'Cl',
     'Br']

def get_formula(x, y, z):
    formula = []
    for ix in x:
        for iy in y:
            for iz in z:
                formula.append([ix, iy, iz])
    return formula

#comps = get_formula(M, A, X)
comps=[['Mg', 'Al', 'O']]
f=open('in.txt','w')
fcsv=open('id_prop.csv','w')
mpr = MPRester("7UnVyVXyetJ5WK3r")
f1=open('name.txt','w')

def numbersss(numbers):
    if len(numbers) == 1:
        return 1

#    elif len(numbers) == 2 :
#        a = int(numbers[0])
#        b = int(numbers[1])
#        if a>b:
#            t = a
#            a = b
#            b = t
#        for n  in range(1,1+(a)):
#            if (a)%n==0 and (b)%n==0:
#                i = [n]
#                i.sort()
#        return i[-1]
#
    else:            #len(numbers) > 2:
        mx = int(reduce(lambda x ,y: max(x,y),numbers))
        while True:
            flag =True
            for number in numbers :
                number=int(number)
                if  (number) % int(mx) !=0 :
                    flag = False
                    break
            if flag ==True:
                return mx

            mx -= 1

for comp in comps:
    print(comp)
    try:
        entries = mpr.get_entries_in_chemsys(comp)
    except:
        continue
    if len(entries) == 0:
        continue
#    pd = PhaseDiagram(entries)
#    data = collections.defaultdict(list)
    for e in entries:
        #print(e)
        #print(type(e))
        #print(e.energy)
#        print(e.entry_id, e.composition, e.energy)
  #      continue
#        ehull = pd.get_e_above_hull(e)
#        if ehull < 0.00000001 :
        com = e.entry_id
        start_time = time.time()
        prop = mpr.query(criteria={"task_id": com}, properties=[\
        "formation_energy_per_atom", \
        "energy_per_atom", \
        "spacegroup", \
        "pretty_formula", \
        "cif"])
        end_time = time.time()
        run_time = end_time - start_time
        #print('run_time', run_time)

        form_energy =  prop[0]['formation_energy_per_atom']
        energy =  prop[0]['energy_per_atom']
        sp =  prop[0]['spacegroup']['symbol']
        name =  prop[0]['pretty_formula']
#        print(name)
        f1.write(name+'\n')
        struct = prop[0]['cif']

        line=(struct.split('\n')[11])
        #line=(ccc[11])
        if '_chemical_formula_sum' in line :
            a=line.split('   ')[1].strip()
            #a=a[1]
            #a=a.strip()
            if a[0] == "'" :
                a=eval(a)
            b=a.split(' ')
            print(b) # 每个元素及数量
            print('-------')
            element1=[]
            numbers=[]
            for i1 in b:
                s=i1.rstrip(string.digits)
                num= (re.findall(r"\d+\.?\d*",i1))
                element1.append(s)
                num=" ".join(num)
                numbers.append(num)
            n=numbersss(numbers)
            print(numbers)
            print(n)
            reduce_for=[]
            total=0
            dic={}
            for i in range(len(b)):
                dic[element1[i]]=(int(int(numbers[i])/int(n)))
                reduce_for.append(element1[i])
                red=(int(int(numbers[i])/int(n)))
                red1=str(red)
                total+= red
                reduce_for.append(red1)
            print(reduce_for)
            reduce_for1=(" ".join(reduce_for))
            print(reduce_for1)
            reduce_for1=reduce_for1.replace(' ','')                  #(" ".join(reduce_for1.split(' ')))
            print(reduce_for1,n,dic,total)
            print('####################')

        fcif = open('./structure/' + com + '_' + name + '.cif','w')
        fcif.write(struct)
        fcif.close()
       # a=open('./structure/' + com + '_' + name + '.cif','r')
       # print(a)
       # while True:
       #     line=a.readline()
       #     if '_chemical_formula_sum' in line :
       #         a=(line.split()[1:])
       #         b=[str(i) for i in a]
       #         c=''.join(b)
       #         f1.write(c+'\n')
        f.write('%s  ' % name)
        f.write('%15.10f       %s\n' % (energy, com))
        fcsv.write(com + '_' + name + ',  ' + str(energy) + '  ' + str(form_energy) + '  ' + str(sp) + '\n')
f.close()
fcsv.close()
f1.close()


# --------------- Events ------------------
from alexa_concierge.concierge_behavior import get_welcome_response, report_current_action, handle_session_end_request
from alexa_concierge.concierge_response_builder import build_speechlet_response, build_response

def on_session_started(session_started_request, session):
    print("on_session_started requestId=" + session_started_request['requestId']
          + ", sessionId=" + session['sessionId'])

def on_launch(launch_request, session):
    print("on_launch requestId=" + launch_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    return get_welcome_response()

def on_intent(intent_request, session):
    print("on_intent requestId=" + intent_request['requestId'] +
          ", sessionId=" + session['sessionId'])

    intent = intent_request['intent']
    intent_name = intent_request['intent']['name']

    if intent_name == "currentAction":
        return report_current_action(intent, session)
    elif intent_name == "AMAZON.HelpIntent":
        return get_welcome_response()
    elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent":
        return handle_session_end_request()
    else:
        raise build_response({},
                             build_speechlet_response(None, "Not sure what you mean.", None, should_end_session=False))

def on_session_ended(session_ended_request, session):
    """ Called when the user ends the session.

    Is not called when the skill returns should_end_session=true
    """
    print("on_session_ended requestId=" + session_ended_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    # add cleanup logic here


import pytorch_lightning as pl
import torch
import torchmetrics
import transformers

from sdg_clf import base

class LitSDG(pl.LightningModule):
    def __init__(self, model: transformers.AutoModelForSequenceClassification, hparams: base.HParams):
        super().__init__()
        self.model = model
        self.HParams = hparams
        self.criterion = torch.nn.BCEWithLogitsLoss()
        self.sigmoid = torch.nn.Sigmoid()
        # Metrics
        self.train_accuracy = torchmetrics.Accuracy(subset_accuracy=True, num_classes=17, multiclass=False)
        self.train_micro_precision = torchmetrics.Precision(num_classes=17, multiclass=False, average="micro")
        self.train_micro_recall = torchmetrics.Recall(num_classes=17, multiclass=False, average="micro")
        self.train_micro_f1 = torchmetrics.F1Score(num_classes=17, multiclass=False, average="micro")
        self.train_macro_precision = torchmetrics.Precision(num_classes=17, multiclass=False, average="macro")
        self.train_macro_recall = torchmetrics.Recall(num_classes=17, multiclass=False, average="macro")
        self.train_macro_f1 = torchmetrics.F1Score(num_classes=17, multiclass=False, average="macro")
        self.val_accuracy = torchmetrics.Accuracy(subset_accuracy=True, num_classes=17, multiclass=False)
        self.val_micro_precision = torchmetrics.Precision(num_classes=17, multiclass=False, average="micro")
        self.val_micro_recall = torchmetrics.Recall(num_classes=17, multiclass=False, average="micro")
        self.val_micro_f1 = torchmetrics.F1Score(num_classes=17, multiclass=False, average="micro")
        self.val_macro_precision = torchmetrics.Precision(num_classes=17, multiclass=False, average="macro")
        self.val_macro_recall = torchmetrics.Recall(num_classes=17, multiclass=False, average="macro")
        self.val_macro_f1 = torchmetrics.F1Score(num_classes=17, multiclass=False, average="macro")

    def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
        return self.model(input_ids, attention_mask=attention_mask).logits

    def training_step(self, batch, batch_idx):
        input_ids = batch["input_ids"]
        attention_mask = batch["attention_mask"]
        labels = batch["label"]
        model_outputs = self(input_ids, attention_mask=attention_mask)
        loss = self.criterion(model_outputs, labels.float())
        preds = self.sigmoid(model_outputs)
        self.train_accuracy(preds, labels)
        self.train_micro_precision(preds, labels)
        self.train_micro_recall(preds, labels)
        self.train_micro_f1(preds, labels)
        self.train_macro_precision(preds, labels)
        self.train_macro_recall(preds, labels)
        self.train_macro_f1(preds, labels)
        metrics_dict = {"train_loss": loss, "train_accuracy": self.train_accuracy,
                        "train_micro_precision": self.train_micro_precision,
                        "train_micro_recall": self.train_micro_recall,
                        "train_micro_f1": self.train_micro_f1, "train_macro_precision": self.train_macro_precision,
                        "train_macro_recall": self.train_macro_recall, "train_macro_f1": self.train_macro_f1}
        self.log_dict(metrics_dict)

        return loss

    def validation_step(self, batch, batch_idx):
        input_ids = batch["input_ids"]
        attention_mask = batch["attention_mask"]
        labels = batch["label"]
        model_outputs = self(input_ids, attention_mask=attention_mask)
        loss = self.criterion(model_outputs, labels.float())
        preds = self.sigmoid(model_outputs)
        self.val_accuracy(preds, labels)
        self.val_micro_precision(preds, labels)
        self.val_micro_recall(preds, labels)
        self.val_micro_f1(preds, labels)
        self.val_macro_precision(preds, labels)
        self.val_macro_recall(preds, labels)
        self.val_macro_f1(preds, labels)
        metrics_dict = {"val_loss": loss, "val_accuracy": self.val_accuracy, "val_micro_precision": self.val_micro_precision,
                        "val_micro_recall": self.val_micro_recall,
                        "val_micro_f1": self.val_micro_f1, "val_macro_precision": self.val_macro_precision,
                        "val_macro_recall": self.val_macro_recall, "val_macro_f1": self.val_macro_f1}
        self.log_dict(metrics_dict)

    def configure_optimizers(self):
        return torch.optim.AdamW(self.parameters(), lr=self.HParams.lr, weight_decay=self.HParams.weight_decay)


from getmyip.common.common import setup_logger, get_url
from getmyip.getmyip import getip
import logging
import argparse

log = logging.getLogger(__name__)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose", help="increase output verbosity",
                        action="store_true")
    args = parser.parse_args()
    if args.verbose:
        level = logging.DEBUG
    else:
        level = logging.INFO
    setup_logger(level)
    url = get_url()
    print(getip(url))

if __name__ == '__main__':
    main()


#!/usr/bin/python3
"""
Module Docstring
"""

class Square:
    """
    Class Docstring
    """

    def __init__(self, size: int = 0, position: tuple = (0, 0)):
        """
        Initialize class Docstring
        """
        self.size = size
        self.position = position

    @property
    def size(self):
        """
        Property method Docstring
        """
        return self.__size

    @size.setter
    def size(self, value: int):
        """
        Setter method Docstring
        """
        if not isinstance(value, int):
            raise TypeError("size must be an integer")
        if value < 0:
            raise ValueError("size must be >= 0")
        self.__size = value

    @property
    def position(self):
        """
        Property method Docstring
        """
        return self.__position

    @position.setter
    def position(self, value: tuple):
        """
        Setter method Docstring
        """
        if (type(value) != tuple) or (len(value) != 2) or \
                not all(isinstance(i, int) and i >= 0 for i in value):
            raise TypeError("position must be a tuple of 2 positive integers")
        self.__position = value

    def __str__(self):
        """
        Public instance method Docstring
        """
        square = ""
        if self.__size == 0:
            return square
        for i in range(self.__position[1]):
            square += "\n"
        for i in range(self.__size):
            square += (" " * self.__position[0])
            square += ("#" * self.__size)
            if i is not (self.__size - 1):
                square += "\n"
        return square

    def area(self):
        """
        Public instance method Docstring
        """
        return self.__size * self.__size

    def my_print(self):
        """
        Public instance method Docstring
        """
        if self.__size == 0:
            print()
            return
        for i in range(self.__position[1]):
            print()
        for i in range(self.__size):
            print(" " * self.__position[0] + "#" * self.__size)

    def __repr__(self):
        """
        Public instance method Docstring
        """
        return self.__str__()