from . import gcd

class NotOddException(Exception):
    def __init__(self, x):
        print(str(x) + " is not odd")

class NotPositiveException(Exception):
    def __init__(self, x):
        print(str(x) + " is not > 0")

class JacobiSymbol:
    """Calculates the JacobiSymbol (a|b)

    Keyword arguments:
    a -- integer
    b -- positive odd integer
    """

    def __init__(self, a, b):
        if b < 0:
            raise NotPositiveException(b)
        if b % 2 == 0:
            raise NotOddException(b)
        self.a = a
        self.b = b
        if gcd(self.a, self.b) != 1:
            self.notCoPrime = True
        else:
            self.notCoPrime = False

    @staticmethod
    def __supplementary2__(x):
        if x % 8 == 1 or x % 8 == 7:
            return 1
        else:
            return -1

    @staticmethod
    def __supplementary1__(x, y):
        if x % 4 == 1 or y % 4 == 1:
            return 1
        else:
            return -1

    def calculate(self):
        if self.notCoPrime:
            return 0
        elif self.a == 1:
            return 1
        elif self.a == 2:
            return self.__supplementary2__(self.b)
        elif self.a % 2 == 0:
            return JacobiSymbol(self.a // 2, self.b).calculate() * JacobiSymbol(2, self.b).calculate()
        else:
            return JacobiSymbol(self.b % self.a, self.a).calculate() * self.__supplementary1__(self.a, self.b)


board = [[0,0,0,2,6,0,7,0,1],
         [6,8,0,0,7,0,0,9,0],
         [1,9,0,0,0,4,5,0,0],
         [8,2,0,1,0,0,0,4,0],
         [0,0,4,6,0,2,9,0,0],
         [0,5,0,0,0,3,0,2,8],
         [0,0,9,3,0,0,0,7,4],
         [0,4,0,0,5,0,0,3,6],
         [7,0,3,0,1,8,0,0,0]]

def solve(bo):

    find = find_empty(bo)
    if not find:
        return True
    else:
        row, col = find

    for i in range(1,10):
        if valid(bo, i, (row,col)):
            bo[row][col] = i

            if solve(bo):
                return True

            bo[row][col] = 0

    return False

def valid(bo, num, pos):

    # check row

    for i in range(len(bo[0])):
        if bo[pos[0]][i] == num and pos[1]!=i:
            return False

    # check coloumn

    for j in range(len(bo)):
        if bo[j][pos[1]] == num and pos[0]!=j:
            return False

    # check box

    box_x = pos[1] // 3
    box_y = pos[0] // 3

    for i in range(box_y*3, box_y*3 + 3):
        for j in range(box_x*3, box_x*3 + 3):
            if bo[i][j] == num and (i,j)!=pos:
                return False

    return True

def print_board(boa):
    for i in range(len(boa)):
        if i % 3 == 0 and i!=0:
            print("- - - - - - - - - - - - - - -")

        for j in range(len(boa[0])):
            if j%3 == 0 and j!=0:
                print("| ", end="")

            if j!=8:
                print(boa[i][j]," ",end="")
            else:
                print(boa[i][j])

def find_empty(boa):
    for i in range(len(boa)):
        for j in range(len(boa[0])):
            if boa[i][j] == 0:
                return(i,j)

print_board(board)
print()
solve(board)
print()
print_board(board)


class Member():
     def __init__(self, full_name=""):
        self.full_name = full_name
class Student():
    def __init__(self, full_name="", sname="", reason=""):
        Member.__init__(self)
        self.full_name = full_name
        self.sname = sname
        self.reason = reason

    def hello(self):
        print(f'Hello my name is {self.full_name}, but you can call me {self.sname}. The reason why i\'m here? {self.reason}')

class Instructor():
    def __init__(self, full_name="", bio="", skills = []):
        Member.__init__(self)
        self.full_name = full_name
        self.bio = bio
        self.skills = skills

    def intro(self):
        print(f'My name is {self.full_name} and i will be your instructor today. My skills include {self.skills}. I\'m here because {self.bio} \n')

    def add_skill(self, new_skill):
        #new_skill=input("Some new skill")
        self.skills.append(new_skill)
        #To add skill Instructor.add_skill("new skill")

class workshop():
    def __init__(self, date ="", subject = ""):
        self.date = date
        self.subject = subject
        self.students = [ ]
        self.instructors = [ ]

    def add_participant(self, participant):
        if type(participant) is Instructor:
            self.instructors.append(participant)
        elif type(participant) is Student:
            self.students.append(participant)

    def print_details(self):
        print(f"Workshop - {self.date} - {self.subject}")
        print("Students:")
        for index in range(len(self.students)):
            print(f"{index + 1}. {self.students[index].full_name} - {self.students[index].reason}")
        print("Instructors:")
        for index, instructor in enumerate(self.instructors):
            print(f"{index + 1}. {instructor.full_name} - {', '.join(instructor.skills)} \n {instructor.bio}")

    #  this returns full obj <>obj at #x#######
    # def desc(self):
    #     print(f'This workshop is for {self.subject} starts on {self.date}. Participants include:\n Students: {self.students} \n Teachers: {self.instructors}\n')

print('#Students')

Matthew = Student('Matthew Derringer', 'Matt', 'For the lulz\n')
Matthew.hello()

Mark = Student("Markedly Seripticious Johnson", "Mark", "To avenge the death of my father\n")
Mark.hello()

Luke = Student('Lukaz Worley', 'Luke', '*Money by Cardi B starts playing in the background*\n')
Luke.hello()

John = Student('Johnathan Nathanial Thibideaux', 'John', '...bored\n')
John.hello()

print('#Instructors')

Natsu = Instructor('Etherios Natsu Dragneel', 'this will be my greatest challange!!', ["Fire: Dragon Slayer Magic", "Inhuman Strength", "Neigh Immortality"])
Natsu.intro()

Grey = Instructor('Grey Fullbuster', "Natsu roped me into this...", ["Ice: Demon Slayer Magic", "Temperture Immunity", "Acrobatics"])
Grey.intro()

Lucy  = Instructor('Lucy Heartfilia', "Somebody has to keep an eye on those two!", ["Celestial Magic", "Archery", "Bullriding"])
Lucy.intro()

print('#Workshops')
WDI = workshop("March - x794", "Battle Magic")
WDI.print_details()


import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime
import datetime as dt
import matplotlib.dates as mdate
import threading
from itertools import accumulate

# 计算每个站点的积累值
def add_accumulate(one_account_data):
    one_account_data['add_sales'] = list(accumulate(one_account_data['sales']))
    one_account_data['add_spend'] = list(accumulate(one_account_data['spend']))
    one_account_data['add_impression'] = list(accumulate(one_account_data['impression']))
    one_account_data['add_clicks'] = list(accumulate(one_account_data['clicks']))
    one_account_data.reset_index(drop=True, inplace=True)
    all_acos = []
    for i in range(len(one_account_data['add_spend'])):
        if one_account_data['add_sales'][i] > 0:
            temp_acos = one_account_data['add_spend'][i]/one_account_data['add_sales'][i]
        else:
            temp_acos = 0
        all_acos.append(temp_acos)
    one_account_data['add_acos'] = all_acos
    return one_account_data

def save_accounts_png(all_accounts_df):
    all_accounts_df.replace('None', 0, inplace=True)
    all_accounts_df['date'] = [datetime.strptime(i, '%Y-%m-%d') for i in all_accounts_df['date'] if isinstance(i, str)]
    # start_date = datetime.now() - dt.timedelta(days=interval_days)
    # all_accounts_df = all_accounts_df[all_accounts_df['date'] > start_date]
    all_accounts_df = all_accounts_df[['account','site','date','acos','cpc','cr','spend','sales','impression','clicks']]
    all_accounts_df[['acos', 'cpc', 'cr', 'spend', 'sales']] = all_accounts_df[['acos', 'cpc', 'cr', 'spend', 'sales']].astype('float')
    all_accounts_df[['impression', 'clicks']] = all_accounts_df[['impression', 'clicks']].astype('int')
    all_accounts_sites = all_accounts_df[['account', 'site']]
    all_accounts_sites.drop_duplicates(inplace=True)
    for account, site in zip(all_accounts_sites['account'], all_accounts_sites['site']):
        try:
            show_info(all_accounts_df, account, site)
        except Exception as e:
            print(e)
            print(account,site)

# 获取redis中的数据进行展示
def show_info(all_accounts_df, account, site, size=(1920, 984), my_dpi=100, interval_days=31):
    one_account_site_info = all_accounts_df[(all_accounts_df['account'] == account) & (all_accounts_df['site'] == site)]
    last_day = one_account_site_info['date'].max()
    start_day = last_day - dt.timedelta(days=interval_days)
    one_account_site_info = one_account_site_info[one_account_site_info['date'] > start_day]
    one_account_site_info.drop_duplicates(inplace=True)
    one_account_site_info = add_accumulate(one_account_site_info)
    bar_width = 0.25
    cc = one_account_site_info
    # 实例化
    fig = plt.figure(figsize=(size[0]/my_dpi, size[1]/my_dpi), dpi=my_dpi)
    x = cc['date']
    # x = [datetime.strptime(i, "%Y-%m-%d") for i in x]
    x1 = [i + dt.timedelta(hours=6) for i in x]
    x2 = [i + dt.timedelta(hours=12) for i in x]
    x3 = [i + dt.timedelta(hours=18) for i in x]
    # 创造子图
    ax1 = fig.add_subplot(211)
    # 绘图
    ax1.plot(x, cc['acos'], color='blue', label='acos')
    # 添加图例acos
    for a, b in zip(x, cc['acos']):
        if b != 0:
            plt.text(a, b + 0.005, '{:0.2f}%'.format(b * 100), ha='center', va='bottom', fontsize=7)

    ax1.bar(x, cc['cpc'], color='lightcoral', label='cpc', width=bar_width)
    # 添加图例cpc
    for a, b in zip(x, cc['cpc']):
        if b != 0:
            plt.text(a, b + 0.005, '{:0.2f}'.format(b), ha='center', va='bottom', fontsize=7)
            # 添加图例cr
    for a, b in zip(x1, cc['cr']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.2f}%'.format(b * 100), ha='center', va='bottom', fontsize=7)
    ax1.bar(x1, cc['cr'], color='moccasin', label='cr', width=bar_width)
    # 设置横纵标签
    ax1.set_ylabel('acos/cpc/cr')
    ax1.set_title("{}_{}".format(account,site))
    # 图例
    plt.legend(loc="upper left")
    ax1.set_xlabel('date')
    # 设置X轴的刻度
    plt.xticks(pd.date_range(min(x), max(x)))  # 设置时间标签显示格式
    ax1.xaxis.set_major_formatter(mdate.DateFormatter('%m-%d'))  # 设置时间标签显示格式

    # 副坐标 绘制总的acos
    ax4 = ax1.twinx()  # this is the important function
    ax4.set_ylabel("ADD acos")
    ax4.plot(x, cc['add_acos'], color='red', label='add_acos')
    for a, b in zip(x, cc['add_acos']):
        if b != 0:
            plt.text(a, b + 0.001, '{:0.2f}%'.format(b * 100), ha='center', va='bottom', fontsize=7)
    plt.legend(loc="upper right")
    # 设置X轴的刻度
    plt.xticks(pd.date_range(min(x), max(x)))  # 设置时间标签显示格式
    ax4.xaxis.set_major_formatter(mdate.DateFormatter('%m-%d'))  # 设置时间标签显示格式

    ax2 = fig.add_subplot(212)

    # 设置横纵标签
    ax2.set_ylabel('spend/sales/(impression/100)/clicks')
    # 绘制spend/sales/ipmression/clicks
    ax2.bar(x, cc['spend'], color='deepskyblue', width=bar_width, label='spend')
    ax2.bar(x1, cc['sales'], color='palegreen', width=bar_width, label='sales')
    ax2.bar(x2, cc['impression'] / 100, color='linen', width=bar_width, label='impression/100')
    ax2.bar(x3, cc['clicks'], color='lightgray', width=bar_width, label='clicks')
    # 图例
    plt.legend(loc="upper left")
    ax2.set_xlabel('date')
    # 设置X轴的刻度
    plt.xticks(pd.date_range(min(x), max(x)))  # 设置时间标签显示格式
    ax2.xaxis.set_major_formatter(mdate.DateFormatter('%m-%d'))  # 设置时间标签显示格式
    # 添加图例spend/sales/ipmression/clicks等图例
    for a, b in zip(x, cc['spend']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)
    for a, b in zip(x1, cc['sales']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)
    for a, b in zip(x2, cc['impression'] / 100):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)
    for a, b in zip(x3, cc['clicks']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)

            # 副坐标
    ax3 = ax2.twinx()  # this is the important function
    ax3.set_ylabel("ADD spend/sales/(impression/100)/clicks")
    # 绘制总 spend/sales/ipmression/clicks等图例
    ax3.plot(x, cc['add_spend'], color='blue', label='add_spend')
    ax3.plot(x, cc['add_sales'], color='green', label='add_sales')
    ax3.plot(x, cc['add_impression'] / 100, color='red', label='add_impression/100')
    ax3.plot(x, cc['add_clicks'], color='black', label='add_clicks')
    # 添加图例总 spend/sales/ipmression/clicks等图例
    for a, b in zip(x, cc['add_spend']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)
    for a, b in zip(x, cc['add_sales']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)
    for a, b in zip(x, cc['add_impression'] / 100):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)
    for a, b in zip(x, cc['add_clicks']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)

    plt.legend(loc="upper right")
    # 设置X轴的刻度
    plt.xticks(pd.date_range(min(x), max(x)))  # 设置时间标签显示格式
    ax3.xaxis.set_major_formatter(mdate.DateFormatter('%m-%d'))  # 设置时间标签显示格式
    # plt.show()
    dir = 'D:/AD-Helper1/show_img/static/img/{}_{}.jpg'.format(account, site)
    fig.savefig(dir, dpi=fig.dpi)
    plt.close()


class Solution(object):
    def shortestPathLength(self, graph):
        n = len(graph)
        if n < 2: return 0
        newgraph = [set() for _ in range(n)]
        for i in range(n):
            for j in graph[i]:
                newgraph[i].add(j)
                newgraph[j].add(i)
        graph = newgraph

        target = 2 ** n - 1
        dp = [set([1 << i]) for i in range(n)]

        for length in range(2 * n - 2):
            newdp = [set(row) for row in dp]
            for i in range(n):
                for j in graph[i]:
                    for mask in dp[i]:
                        if mask | (1 << j) == target:
                            return length + 1
                        newdp[j].add(mask | (1 << j))
            dp = newdp


import random, os
from pydub import AudioSegment
from pydub.playback import play

original_path=os.getcwd()

path = "C:\\Users\\simon\\music"
os.chdir( path )

entire_folder=os.listdir()
ext=['.mp3']
folder=[file for file in entire_folder if file[-4:] in ext]

while True:

    song_str=random.choice(folder)
    song=AudioSegment.from_mp3(song_str)
    start=int(random.random()*len(song))
    cut_song = song[start:start+20*1000]

    os.chdir(original_path)
    files=os.listdir()

    num=0
    name=''
    cond=True
    while cond:
        name=str(num)+'.mp3'
        if name not in files:
            cond=False
        num+=1

    cut_song.export(name, format="mp3")

    os.startfile(name)
    input("Guess ")
    os.remove(name)
    print(song_str)

    os.chdir( path )

    k=input("type \" exit \" to exit")
    if k=='exit':
        break


import base

class Routerbgp(base.BaseV30):

    def create(self, as_number, route_address, remote_as_address_ls):

        group_neighbor_ls = [
            {
                "peer-group": t["remote_address"],
                "peer-group-remote-as": t["remote_as_number"],
                "advertisement-interval": 1
            } for t in remote_as_address_ls]

        params = {
            "bgp": {
                "as-number": as_number,
                "bgp": {
                    "log-neighbor-changes": 1,
                    "router-id": route_address,
                },
                "neighbor": {
                    "peer-group-neighbor-list": group_neighbor_ls
                },
                "timers": {
                    "bgp-holdtime": 3,
                    "bgp-keepalive": 1
                }
            }
        }
        self._post("/router/bgp/", params)

    def add_remote_as(self, as_number, remote_address, remote_as):
        params = {
            "bgp": {
                "as-number": as_number,
                "neighbor": {
                    "peer-group-neighbor-list": [
                        {
                            "peer-group": remote_address,
                            "peer-group-remote-as": remote_as,
                            "advertisement-interval": 1
                        }
                    ],

                }
            }
        }
        self._post("/router/bgp/{0}/".format(as_number), params)

    def add_route_map(self, as_number, remote_address, remote_as, nbr_route_map, nbr_rmap_direction='in'):
        params = {
            "bgp": {
                "as-number": as_number,
                "neighbor": {
                    "ipv4-neighbor-list": [
                        {
                            "nbr-remote-as": remote_as,
                            "neighbor-ipv4": remote_address,
                            "neighbor-route-map-lists": [
                                {
                                    "nbr-rmap-direction": nbr_rmap_direction,
                                    "nbr-route-map": nbr_route_map
                                }
                            ],
                        }
                    ]
                }
            }
        }
        self._post("/router/bgp/{0}/".format(as_number), params)

    def get(self, as_number):
        return self._get("/router/bgp/{0}/".format(as_number))


def isLeapYear(year):
    if year %4 != 0:
        return False
    elif year %100 != 0:
        return True
    elif year % 400 != 0:
        return False
    return True

def daysInMonth(year,month):
    if month in (1,3,5,7,8,10,12):
        return 31
    elif month == 2:
        if isLeapYear(year):
            return 29
        return 28
    return 30
def nextDay(year,month,day):
    if day<daysInMonth(year,month):
        return year,month,day+1
    else:
        if month<12:
            return year,month+1,1
        else:
            return year+1,1,1

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    #assert dateIsBefore(year1, month1, day1, year2, month2, day2)
    days = 0
    while dateIsBefore(year1, month1, day1, year2, month2, day2):
        year1, month1, day1 = nextDay(year1, month1, day1)
        days+=1
    return days

def dateIsBefore(year1, month1, day1, year2, month2, day2):
	if year2>year1:
		return True
	if month2>month1 and year2>=year1:
		return True
	if month2==month1 and year2>=year1:
		if day2>day1:
			return True
	return False

def test():
    assert daysBetweenDates(2000,1,1,2000,1,1)==0
    assert daysBetweenDates(2000,1,1,2000,2,1)==31
    assert nextDay(2000,1,1)==(2000,1,2)
    assert nextDay(2013,2,28)==(2013,3,1)
    assert nextDay(2013,6,30)==(2013,7,1)
    assert daysBetweenDates(2013,1,1,2014,1,1)==365
    assert daysBetweenDates(2016,1,1,2017,1,1)==366
    print('all test completed')

test()


import string

from django.http import JsonResponse
from django.shortcuts import render, redirect,HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords

from aqg.decorators import teacher_only
from question.models import Subject, AllQues, MathQues, PhysicsQues, EnglishQues, ChemistryQues
from django.utils.timezone import now
from django.contrib import messages
import re
from builtins import zip

# Create your views here.

def timeCal(mr, le):
    if int(mr) == 1:
        if int(le) == 3:
            t = 1.5
        elif int(le) == 2:
            t = 1
        else:
            t = 0.5
    elif int(mr) == 2:
        if int(le) == 3:
            t = 3
        elif int(le) == 2:
            t = 2
        else:
            t = 1
    return t

@login_required
@teacher_only
def dashboardTView(request):
    return render(request, 'dashboard/teacher/Dashboard.html')

@login_required
@teacher_only
def selsub(request):
    return render(request, 'dashboard/teacher/TselSub.html')

@login_required
@teacher_only
def selsubforReview(request):
    return render(request, 'dashboard/teacher/TselSubReview.html')

# ------------------------------------ MATH ------------------------------------------

def mathCount():
    allMathQues = MathQues.objects.all()
    count = allMathQues.count()
    if count:
        sno = allMathQues[count - 1].pk
    else:
        sno = -1
    # print(MathQues.objects.get(pk=5))
    return sno + 1

@login_required
@teacher_only
def mathSel(request):
    global intCosData
    intCosData = 0
    if request.method == 'POST':
        question = request.POST.get('questionArea')
        optA = request.POST.get('optA')
        optB = request.POST.get('optB')
        optC = request.POST.get('optC')
        optD = request.POST.get('optD')
        ans = request.POST.get('answer')
        mark = request.POST.get('mark')
        level = request.POST.get('level')

        if ans == 'optA':
            ans = optA
        elif ans == 'optB':
            ans = optB
        elif ans == 'optC':
            ans = optC
        elif ans == 'optD':
            ans = optD

        timeToSolve = timeCal(mark, level)

        teacherName = request.user.first_name + ' ' + request.user.last_name
        teacherID = request.user.id
        mathID = str(teacherID) + 'M' + str(mathCount())
        mathModel = 'M' + 'mk' + str(mark) + 'le' + str(level) + 'v' + str(mathCount())

        into_all = AllQues(subID='M', Question=question, optA=optA, optB=optB, optC=optC, optD=optD, ans=ans, mark=mark,
                           level=level, teacherName=teacherName, subjID=mathID,
                           timeStamp=now(), subjModel=mathModel, timeToSolve=timeToSolve, moreTimeTaken=0, lessTimeTaken=0, modMark = mark, modLevel= level)
        into_all.save()
        intQusId = AllQues.objects.get(pk=into_all.pk)
        add = MathQues(intQuesID= intQusId, Question=question, optA=optA, optB=optB, optC=optC, optD=optD, ans=ans, mark=mark, level=level,
                       teacherName=teacherName, timeStamp=now(), mathID=mathID, mathModel=mathModel,
                       timeToSolve=timeToSolve, moreTimeTaken=0, lessTimeTaken=0, modMark = mark, modLevel= level)
        add.save()

        messages.success(request, 'Question is added success')

    return render(request, 'dashboard/teacher/AddQuestion/addMath.html')

# ------------------------------------ PHYSICS ------------------------------------------

def physicsCount():
    allPhysicsQues = PhysicsQues.objects.all()
    count = allPhysicsQues.count()
    if count:
        sno = allPhysicsQues[count - 1].pk
    else:
        sno = -1
    return sno + 1

@login_required
@teacher_only
def physicsSel(request):
    global intCosData
    intCosData = 0

    if request.method == 'POST':
        question = request.POST.get('questionArea')
        optA = request.POST.get('optA')
        optB = request.POST.get('optB')
        optC = request.POST.get('optC')
        optD = request.POST.get('optD')
        ans = request.POST.get('answer')
        mark = request.POST.get('mark')
        level = request.POST.get('level')

        if ans == 'optA':
            ans = optA
        elif ans == 'optB':
            ans = optB
        elif ans == 'optC':
            ans = optC
        elif ans == 'optD':
            ans = optD

        timeToSolve = timeCal(mark, level)

        teacherName = request.user.first_name + ' ' + request.user.last_name
        teacherID = request.user.id
        physicsID = str(teacherID) + 'P' + str(physicsCount())
        physicsModel = 'P' + 'mk' + str(mark) + 'le' + str(level) + 'v' + str(physicsCount())

        into_all = AllQues(subID='P', Question=question, optA=optA, optB=optB, optC=optC, optD=optD, ans=ans, mark=mark,
                           level=level, teacherName=teacherName,
                           subjID=physicsID, timeStamp=now(), subjModel=physicsModel, timeToSolve=timeToSolve, moreTimeTaken=0, lessTimeTaken=0, modMark = mark, modLevel= level)
        into_all.save()
        intQusId = AllQues.objects.get(pk=into_all.pk)
        add = PhysicsQues(intQuesID= intQusId, Question=question, optA=optA, optB=optB, optC=optC, optD=optD, ans=ans, mark=mark,
                          level=level,
                          teacherName=teacherName, timeStamp=now(), physicsID=physicsID, physicsModel=physicsModel, timeToSolve=timeToSolve, moreTimeTaken=0, lessTimeTaken=0, modMark = mark, modLevel= level)
        add.save()

    messages.success(request, 'Question is added success')
    return render(request, 'dashboard/teacher/AddQuestion/addPhysics.html')

# ------------------------------------ CHEMISTRY ------------------------------------------

def chemistryCount():
    allChemistryQues = ChemistryQues.objects.all()
    count = allChemistryQues.count()
    if count:
        sno = allChemistryQues[count - 1].pk
    else:
        sno = -1
    return sno + 1

@login_required
@teacher_only
def chemistrySel(request):
    global intCosData
    intCosData = 0
    if request.method == 'POST':
        question = request.POST.get('questionArea')
        optA = request.POST.get('optA')
        optB = request.POST.get('optB')
        optC = request.POST.get('optC')
        optD = request.POST.get('optD')
        ans = request.POST.get('answer')
        mark = request.POST.get('mark')
        level = request.POST.get('level')

        if ans == 'optA':
            ans = optA
        elif ans == 'optB':
            ans = optB
        elif ans == 'optC':
            ans = optC
        elif ans == 'optD':
            ans = optD

        timeToSolve = timeCal(mark,level)

        teacherName = request.user.first_name + ' ' + request.user.last_name
        teacherID = request.user.id
        chemistryID = str(teacherID) + 'C' + str(chemistryCount())
        chemistryModel = 'C' + 'mk' + str(mark) + 'le' + str(level) + 'v' + str(chemistryCount())

        into_all = AllQues(subID='C', Question=question, optA=optA, optB=optB, optC=optC, optD=optD, ans=ans, mark=mark,
                           level=level, teacherName=teacherName,
                           subjID=chemistryID, timeStamp=now(), subjModel=chemistryModel, timeToSolve=timeToSolve, moreTimeTaken=0, lessTimeTaken=0, modMark = mark, modLevel= level)
        into_all.save()
        intQusId = AllQues.objects.get(pk=into_all.pk)
        add = ChemistryQues(intQuesID=intQusId, Question=question, optA=optA, optB=optB, optC=optC, optD=optD, ans=ans, mark=mark,
                            level=level, timeToSolve=timeToSolve,
                            teacherName=teacherName, timeStamp=now(), chemistryID=chemistryID,
                            chemistryModel=chemistryModel, moreTimeTaken=0, lessTimeTaken=0, modMark = mark, modLevel= level)
        add.save()

    messages.success(request, 'Question is added success')
    return render(request, 'dashboard/teacher/AddQuestion/addChemistry.html')

# ------------------------------------ ENGLISH ------------------------------------------

def englishCount():
    allEnglishQues = EnglishQues.objects.all()
    count = allEnglishQues.count()
    if count:
        sno = allEnglishQues[count - 1].pk
    else:
        sno = -1
    return sno + 1

@login_required
@teacher_only
def englishSel(request):
    global intCosData
    intCosData = 0
    if request.method == 'POST':
        question = request.POST.get('questionArea')
        optA = request.POST.get('optA')
        optB = request.POST.get('optB')
        optC = request.POST.get('optC')
        optD = request.POST.get('optD')
        ans = request.POST.get('answer')
        mark = request.POST.get('mark')
        level = request.POST.get('level')

        if ans == 'optA':
            ans = optA
        elif ans == 'optB':
            ans = optB
        elif ans == 'optC':
            ans = optC
        elif ans == 'optD':
            ans = optD

        timeToSolve = timeCal(mark, level)

        teacherName = request.user.first_name + ' ' + request.user.last_name
        teacherID = request.user.id
        englishID = str(teacherID) + 'E' + str(englishCount())
        englishModel = 'E' + 'mk' + str(mark) + 'le' + str(level) + 'v' + str(englishCount())

        into_all = AllQues(subID='E', Question=question, optA=optA, optB=optB, optC=optC, optD=optD, ans=ans, mark=mark,
                           level=level, teacherName=teacherName, timeToSolve=timeToSolve,
                           subjID=englishID, timeStamp=now(), subjModel=englishModel, moreTimeTaken=0, lessTimeTaken=0, modMark = mark, modLevel= level)
        into_all.save()
        intQusId = AllQues.objects.get(pk=into_all.pk)
        add = EnglishQues(intQuesID=intQusId, Question=question, optA=optA, optB=optB, optC=optC, optD=optD, ans=ans, mark=mark,
                          level=level, timeToSolve=timeToSolve,
                          teacherName=teacherName, timeStamp=now(), englishID=englishID, englishModel=englishModel, moreTimeTaken=0, lessTimeTaken=0, modMark = mark, modLevel= level)
        add.save()

    messages.success(request, 'Question is added success')

    return render(request, 'dashboard/teacher/AddQuestion/addEnglish.html')

# ------------------------------------ SHOW ONLY MINE ------------------------------------------

@login_required
@teacher_only
def allMyPhysics(request):
    new = []
    idd = request.user.id
    pattern = f'^{idd}P[0-9]+$'
    all = PhysicsQues.objects.all()
    print('all:')
    print(all)
    for x in all:
        if re.match(pattern, x.physicsID):
            print('x:')
            print(x)
            new.append(x)
    data = {'all': new}
    print('New:')
    print(new)
    return render(request, 'dashboard/teacher/ReviewQuestion/physics.html', data)

@login_required
@teacher_only
def allMyChemistry(request):
    new = []
    idd = request.user.id
    pattern = f'^{idd}C[0-9]+$'
    all = ChemistryQues.objects.all()
    for x in all:
        if re.match(pattern, x.chemistryID):
            new.append(x)
    data = {'all': new}
    return render(request, 'dashboard/teacher/ReviewQuestion/chemistry.html', data)

@login_required
@teacher_only
def allMyMath(request):
    new = []
    idd = request.user.id
    pattern = f'^{idd}M[0-9]+$'
    all = MathQues.objects.all()
    for x in all:
        if re.match(pattern, x.mathID):
            new.append(x)
    data = {'all': new}
    return render(request, 'dashboard/teacher/ReviewQuestion/math.html', data)

@login_required
@teacher_only
def allMyEnglish(request):
    new = []
    idd = request.user.id
    pattern = f'^{idd}E[0-9]+$'
    all = EnglishQues.objects.all()
    for x in all:
        if re.match(pattern, x.englishID):
            new.append(x)
    data = {'all': new}
    return render(request, 'dashboard/teacher/ReviewQuestion/english.html', data)

@login_required
@teacher_only
def allMyQues(request):
    new = []
    idd = request.user.id
    pattern = f'^{idd}[P, M, C, E][0-9]+$'
    all = AllQues.objects.all()
    for x in all:
        if re.match(pattern, x.subjID):
            new.append(x)
    data = {'all': new}
    return render(request, 'dashboard/teacher/ReviewQuestion/ownQues.html', data)

# ------------------------------------ ALL QUESTIONS ------------------------------------------

@login_required
@teacher_only
def allQues(request):
    all = AllQues.objects.all()
    c = all.count()
    zipping = zip(range(1,c+1), all)
    data = {'all': all, 'count': c, 'zip':zipping}
    return render(request, 'dashboard/teacher/ReviewQuestion/allQuesColl.html', data)

# ------------------------------------ EDIT -------------------------------------------

def editQues(request, id):
    question = AllQues.objects.get(pk=id)
    print(question)
    QuesID = question.subID
    data = {'data': question, 'QuesID':id}

    if request.method == 'POST':
        question = request.POST.get('questionArea')
        optA = request.POST.get('optA')
        optB = request.POST.get('optB')
        optC = request.POST.get('optC')
        optD = request.POST.get('optD')
        ans = request.POST.get('answer')
        mark = request.POST.get('mark')
        level = request.POST.get('level')

        if ans == 'optA':
            ans = optA
        elif ans == 'optB':
            ans = optB
        elif ans == 'optC':
            ans = optC
        elif ans == 'optD':
            ans = optD

        timeToSolve = timeCal(mark, level)

        AllQues.objects.filter(pk=id).update(Question=question, optA=optA, optB=optB, optC=optC, optD=optD, ans=ans, mark=mark,
                           level=level, timeStamp=now(), timeToSolve=timeToSolve, moreTimeTaken=0, lessTimeTaken=0, modMark = mark, modLevel= level)
        if QuesID == 'P':
            PhysicsQues.objects.filter(intQuesID=id).update(Question=question, optA=optA, optB=optB, optC=optC, optD=optD, ans=ans,
                                                 mark=mark,
                                                 level=level, timeStamp=now(), timeToSolve=timeToSolve, moreTimeTaken=0,
                                                 lessTimeTaken=0, modMark=mark, modLevel=level)
        elif QuesID == 'C':
            ChemistryQues.objects.filter(intQuesID=id).update(Question=question, optA=optA, optB=optB, optC=optC,
                                                            optD=optD, ans=ans,
                                                            mark=mark,
                                                            level=level, timeStamp=now(), timeToSolve=timeToSolve,
                                                            moreTimeTaken=0,
                                                            lessTimeTaken=0, modMark=mark, modLevel=level)
        elif QuesID == 'M':
            MathQues.objects.filter(intQuesID=id).update(Question=question, optA=optA, optB=optB, optC=optC,
                                                            optD=optD, ans=ans,
                                                            mark=mark,
                                                            level=level, timeStamp=now(), timeToSolve=timeToSolve,
                                                            moreTimeTaken=0,
                                                            lessTimeTaken=0, modMark=mark, modLevel=level)
        else:
            EnglishQues.objects.filter(intQuesID=id).update(Question=question, optA=optA, optB=optB, optC=optC,
                                                            optD=optD, ans=ans,
                                                            mark=mark,
                                                            level=level, timeStamp=now(), timeToSolve=timeToSolve,
                                                            moreTimeTaken=0,
                                                            lessTimeTaken=0, modMark=mark, modLevel=level)

        messages.success(request, 'Edit Successful')
        return redirect('/teacher/dashboard/selsubReview/')

    return render(request, 'dashboard/teacher/ReviewQuestion/edit/editQues.html', data)

def deleteQues(request, id):
    question = AllQues.objects.get(pk=id)
    print(id)
    question.delete()
    messages.error(request, 'Delete Successful')
    return redirect('/teacher/dashboard/selsubReview/')

# ----------------------- To Get data for cosine similarity ----------------------------

# ----------------------------- 1. To Get data ----------------------------
data1 = ''
@csrf_exempt
def testLoadCache(request):
    global data1
    lol = request.POST.get('ans')
    data1 = lol
    return HttpResponse('Good Job')

# ----------------------- 2. To send Question mark and level -----------------

intCosData = 0

@csrf_exempt
def testWriteCache(request):
    global data1, intCosData
    print(data1)
    mark = 0
    level = 0
    QuesData = AllQues.objects.all()
    for i in QuesData:
        cosData = cosineSim(i.Question, data1)
        if cosData != 0:
            if cosData >= intCosData:
                intCosData = cosData
                mark = i.mark
                print('mark')
                print(mark)
                level = i.level
                print('level')
                print(level)
                print(i.Question)
                print(cosData)

    return JsonResponse({'mark': mark, 'level': level})

def cosineSim(d1, d2):
    # print(d1)
    # print(d2)
    remPunD1 = remove_punct(d1)
    remPunD2 = remove_punct(d2)
    cosineSimulation = similarityMeasure(remPunD1, remPunD2)
    # print('cosineSimulation')
    # print(cosineSimulation)
    return cosineSimulation

def similarityMeasure(d1, d2):
    x = d1.lower()
    y = d2.lower()
    tok_x = word_tokenize(x)
    tok_y = word_tokenize(y)
    sw = stopwords.words('english')
    l1 = []
    l2 = []
    x_set = {w for w in tok_x if not w in sw}
    y_set = {w for w in tok_y if not w in sw}
    rvector = x_set.union(y_set)
    for w in rvector:
        if w in x_set:
            l1.append(1)  # create a vector
        else:
            l1.append(0)
        if w in y_set:
            l2.append(1)
        else:
            l2.append(0)
    c = 0
    for i in range(len(rvector)):
        c += l1[i] * l2[i]
    cosine = c / float((sum(l1) * sum(l2)) ** 0.5)
    return cosine

def remove_punct(txt):
    txt_nopunt="".join([c for c in txt if c not in string.punctuation])
    return txt_nopunt


# -*- coding: cp936 -*-
from math import *
import visual as vs

import random

import numpy as np
import pylab
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib import pyplot as plt

def dist( pos1, pos2 ):
    return sqrt( pow(pos1[0]-pos2[0], 2) + pow(pos1[1]-pos2[1], 2) + pow(pos1[2]-pos2[2], 2))

xRange = 121
yRange = 121
zRange = 1

density = [0 for i in range( xRange*yRange*zRange )]

def getDensity(pos):
    if (xRange-1)/2>= pos[0] >= -(xRange-1)/2 and (yRange-1)/2 >= pos[1] >= -(yRange-1)/2 and zRange-1 >= pos[2] >= 0:
        return density[int(((pos[0]+(xRange-1)/2)*yRange+(pos[1]+(yRange-1)/2))*zRange+pos[2])]
    else:
        return -1

# Set the environment here
def drawEnv( sourcePos = (-40, 0, 0), step = 5):
    # Set the environmen(density)
    for i in range(-int((xRange-1)/2), int((xRange-1)/2)):
        for j in range(-int((yRange-1)/2), int((yRange-1)/2)):
            for k in range (0, int(zRange)):
                num = int(((i+(xRange-1)/2)*yRange + (j+(yRange-1)/2))*zRange + k)
                p = (i, j, k)
                density[num] = 1 / (dist(sourcePos, p)+0.00001)

def makeHoriVector(theta):
    return vs.vector(cos(theta), sin(theta), 0)

def makeVector(theta, phi):
    return vs.vector(cos(theta)*cos(phi), sin(theta)*cos(phi), sin(phi))

def sigmoid(x, alpha = -4):
    return 1.0 / (1.0+exp(-alpha*x)) if x < 10 else 0

# Implement your strategy for vehicle here
def loopVehicle( vsrcPos = vs.vector(-20, 0, 30), initPos = (40, 40, 0), theta = 3/2*pi, phi = 0, delta = 0.5, W = 4, alpha = -4, thre_den = 0.4 ):
    """ Init & loop vehicle.
    """

    initAxis = (cos(theta)*cos(phi), sin(theta)*cos(phi), sin(phi))

    vPos, vAxis, vVelocity = vs.vector(initPos), vs.vector(initAxis), vs.vector(initAxis)
    deltat = delta
    vscale = 8

    time = 0
    sampleTime = 500
    sampleN = 0
    distance = 0

    while True:
        #vs.rate(3000)

        orthV = makeHoriVector(theta+pi/2)
        orthV2 = makeVector(theta, phi+pi/2)
        lSensorPos = tuple(int(x) for x in (vPos+orthV*W/2).astuple())
        rSensorPos = tuple(int(x) for x in (vPos-orthV*W/2).astuple())
        #print(rSensorPos)

        if (getDensity(lSensorPos) == -1 or getDensity(rSensorPos) == -1) :
            vVelocity = -vVelocity
            vAxis = vVelocity
            vPos = vPos+vVelocity*deltat
            continue

        if (getDensity(lSensorPos) > getDensity(rSensorPos)):
            theta = theta + pi/180
        elif getDensity(lSensorPos) < getDensity(rSensorPos):
            theta = theta - pi/180

        vVelocity = makeVector(theta, phi)
        vPos = vPos+vVelocity*deltat*sigmoid(getDensity(lSensorPos)+getDensity(rSensorPos), alpha)
        vAxis = vVelocity

        if (getDensity(lSensorPos)+getDensity(rSensorPos))/2 <= thre_den:
            time = time + 1
        else:
            distance = distance+vs.mag(vsrcPos-vPos)
            return (time, distance)
        if time >= sampleTime:
            return (time, distance)

drawEnv(sourcePos = (-20, 0, 0))

thre_den = [0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6]

time = [0 for i in range(len(thre_den))]

distance = [0 for i in range(len(thre_den))]

for k in range(len(thre_den)):
    for i in range(1, 4):
        temp = loopVehicle(vsrcPos = vs.vector(-20, 0, 0), theta = i/2*pi, initPos = (20, 20, 0), alpha = 0, delta = 1, thre_den = thre_den[k])
        time[k] = time[k]+temp[0]
        distance[k] = distance[k]+temp[1]

time = [x/4 for x in time]
distance = [x/4 for x in distance]

fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
plotl = ax1.plot(thre_den, time, '-b', label='Time')
ax1.set_xlabel('Threshold of source declaration')
ax1.set_ylabel('Time', color='b')
ax1.set_ylim(115, 120)
for tl in ax1.get_yticklabels():
    tl.set_color('b')
ax1.legend(loc=1)

ax2 = ax1.twinx()
plotr, = ax2.plot(thre_den, distance, '--ro', label='distance')
ax2.set_ylabel('distance', color='r')
for tl in ax2.get_yticklabels():
    tl.set_color('r')
ax2.legend(loc = 2)
plt.grid()
plt.savefig('./ROBIO/2d_t_d.png', bbox_inches='tight')

plt.show()


import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import cross_val_score
# from keras.wrappers

base = pd.read_csv('C:\\Users\\Igori\\Documents\\Projects\\DeepLearningA-ZCursoCompleto\\Base_de_Dados\\autos.csv', encoding = 'ISO-8859-1')
base = base.drop('dateCrawled', axis =1)
base = base.drop('dateCreated', axis =1)
base = base.drop('nrOfPictures', axis =1)
base = base.drop('postalCode', axis =1)
base = base.drop('lastSeen', axis =1)
#print(base['name'].value_counts())
base = base.drop('name', axis =1)

#print(base['seller'].value_counts())
base = base.drop('seller', axis =1)

#print(base['offerType'].value_counts())
base = base.drop('offerType', axis =1)

#Pre-processamento de valores inconsistentes
i1 = base.loc[base.price <= 10]
base = base[base.price > 10]
i2 = base.loc[base.price > 350000]
base = base[base.price < 350000]

#Pre-processamento de valores faltantes
print(base.loc[pd.isnull(base['vehicleType'])])
print(base['vehicleType'].value_counts()) #limousine
print(base.loc[pd.isnull(base['gearbox'])])
print(base['gearbox'].value_counts()) #manuell
print(base.loc[pd.isnull(base['model'])])
print(base['model'].value_counts()) #golf
print(base.loc[pd.isnull(base['fuelType'])])
print(base['fuelType'].value_counts()) #benzin
print(base.loc[pd.isnull(base['notRepairedDamage'])])
print(base['notRepairedDamage'].value_counts()) #nein

valores = {'vehicleType': 'limousine',
            'gearbox': 'manuell',
            'model': 'golf',
            'fuelType': 'benzin',
            'notRepairedDamage': 'nein'
            }

base = base.fillna(value = valores)

#Pre processamento label encoder
previsores = base.iloc[:, 1:13].values
preco_real = base.iloc[:, 0].values

label_encoder_previsores = LabelEncoder()
previsores[:, 0] = label_encoder_previsores.fit_transform(previsores[:,0])
#previsores[0]
previsores[:, 1] = label_encoder_previsores.fit_transform(previsores[:,1])
previsores[:, 3] = label_encoder_previsores.fit_transform(previsores[:,3])
previsores[:, 5] = label_encoder_previsores.fit_transform(previsores[:,5])
previsores[:, 8] = label_encoder_previsores.fit_transform(previsores[:,8])
previsores[:, 9] = label_encoder_previsores.fit_transform(previsores[:,9])
previsores[:, 10] = label_encoder_previsores.fit_transform(previsores[:,10])

oneHotEncoder = ColumnTransformer([('one_hot_encoder', OneHotEncoder(categories='auto'), [0,1,3,5,8,9,10])],remainder='passthrough') #OneHotEncoder(categories = [0, 1, 3, 5, 8, 9, 10])
previsores = oneHotEncoder.fit_transform(previsores).toarray()


import tensorflow as tf
import os
import time
import numpy as np
os.environ["TF_CPP_MIN_LOG_LEVEL"] = '2'
from ut import *
from model_cgan import discriminator,generator

gpu = 0
learning_rate = 0.0004
min_after_dequeue = 10000
capacity = 256
img_width = 64
img_height = 64
depth = 1
z_dim = 100
batch_size = 32
max_epoch = 300
weiht_decay = 0.00002
total_samples = 51223
train_flag = False
train_data_path = '/storage/wanghua/kaggle/data/faces/'
log_path = '/storage/wanghua/kaggle/log/gan_faces___dc/'
restore_checkpoint = '/storage/wanghua/kaggle/filelist/'
output_dir = log_path + 'gengrate_images/'
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

def tr():
    global_step = tf.Variable(0, name="global_step", trainable=False)

    # input
    image_path_list, label_list = gen_pair(train_data_path)
    inputs, _, _ = get_batch(image_path_list, label_list, img_width, img_height, batch_size, capacity,min_after_dequeue)
    z_prior = tf.placeholder(tf.float32, [batch_size, z_dim], name="z_prior")

    d_real, d_real_logits, _ = discriminator(inputs, is_training=True, reuse=False)
    faka_data = generator(z_prior, is_training=True, reuse=False)
    d_fake, d_fake_logits, _ = discriminator(faka_data, is_training=True, reuse=True)

    # divide trainable variables into a group for D and a group for G
    t_vars = tf.trainable_variables()
    d_params = [var for var in t_vars if 'dis' in var.name]
    g_params = [var for var in t_vars if 'gen' in var.name]

    d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_real_logits, labels=tf.ones_like(d_real)))
    d_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_fake_logits, labels=tf.zeros_like(d_fake)))
    d_l2_loss = tf.add_n([weiht_decay * tf.nn.l2_loss(var) for var in tf.trainable_variables()])
    dis_loss = d_loss_real + d_loss_fake + d_l2_loss

    g_l2_loss = tf.add_n([weiht_decay * tf.nn.l2_loss(var) for var in g_params])
    gen_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_fake_logits, labels=tf.ones_like(d_fake))) + g_l2_loss

    # optimizer
    optimizer_g = tf.train.AdamOptimizer(learning_rate)
    optimizer_d = tf.train.AdamOptimizer(learning_rate)
    # trainer
    d_trainer = optimizer_d.minimize(dis_loss, var_list=d_params)
    g_trainer = optimizer_g.minimize(gen_loss, var_list=g_params)

    d_loss_real_sum = tf.summary.scalar("d_loss_real", d_loss_real)
    d_loss_fake_sum = tf.summary.scalar("d_loss_fake", d_loss_fake)
    d_loss_sum = tf.summary.scalar("d_loss", dis_loss)
    g_loss_sum = tf.summary.scalar("g_loss", gen_loss)
    g_sum = tf.summary.merge([d_loss_fake_sum, g_loss_sum])
    d_sum = tf.summary.merge([d_loss_real_sum, d_loss_sum])

    os.environ["CUDA_VISIBLE_DEVICES"] = '%d' % gpu
    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95)
    sess_config = tf.ConfigProto(gpu_options=gpu_options)
    with tf.Session(config=sess_config) as sess:
        count_trainable_params()
        train_writer = tf.summary.FileWriter(log_path, sess.graph)
        saver = tf.train.Saver()
        load_model(sess=sess, saver=saver, restore_checkpoint=restore_checkpoint)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        with tf.device('/gpu:%d' % gpu):
            show_images_path = []
            for epoch in range(max_epoch):
                # data_load = data_iter('train.csv', batch_size)
                setps = int(total_samples / batch_size)
                for step in range(setps):
                    # x, y = data_load.next_batch()
                    z_sample_val = np.random.normal(0, 1, size=(batch_size, z_dim)).astype(np.float32)
                    dl,summary_str, _  = sess.run([dis_loss,d_sum, d_trainer], feed_dict={z_prior:z_sample_val})
                    train_writer.add_summary(summary_str, epoch*setps+step)
                    print('[Epoch: %s]  Step: %s  Dis_loss: %s' % (epoch, step, dl))

                    if step % 10 == 0:
                        for j in range(3):
                            z_sample_val = np.random.normal(0, 1, size=(batch_size, z_dim)).astype(np.float32)
                            gl,summary_str, _ = sess.run([gen_loss,g_sum, g_trainer], feed_dict={z_prior: z_sample_val})
                            train_writer.add_summary(summary_str, epoch * setps + step)
                            print('[Epoch: %s]  Step: %s  -------------Gen_loss-------------: %s' % (epoch, step, gl))
                            # tmp = view_samples(-3, np.squeeze(pl), (4, 8), output_dir)
                z_sample_val = np.random.normal(0, 1, size=(batch_size, z_dim)).astype(np.float32)
                [im] = sess.run([faka_data], feed_dict={z_prior: z_sample_val})
                tmp = view_samples(epoch,np.squeeze(im),(4,8), output_dir)
                show_images_path.append(tmp)
                save_model(saver, sess, log_path, epoch, gl, dl)
            gen_gif(show_images_path, output_dir)

def te():
    p = 64#多少张图
    z_prior = tf.placeholder(tf.float32, [p, z_dim], name="z_prior")
    faka_data = generator(z_prior,is_training=False, reuse=False)

    os.environ["CUDA_VISIBLE_DEVICES"] = '%d' % gpu
    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.8)
    sess_config = tf.ConfigProto(gpu_options=gpu_options)
    with tf.Session(config=sess_config) as sess:
        count_trainable_params()
        tf.summary.FileWriter(log_path, sess.graph)
        variables_to_restore = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,'gen')
        saver = tf.train.Saver(variables_to_restore)
        load_model(sess=sess, saver=saver, restore_checkpoint=log_path)
        with tf.device('/gpu:%d' % gpu):
            z_sample_val = np.random.normal(0, 1, size=(p, z_dim)).astype(np.float32)
            [im] = sess.run([faka_data], feed_dict={z_prior: z_sample_val})
            _ = view_samples(-1, np.squeeze(im),(8,8), output_dir)

if train_flag:
    tr()
else:
    te()


from copy import deepcopy, copy
from random import shuffle, choice
from string import ascii_uppercase
from timeit import default_timer as timer
from math import inf, floor
from random import random
from collections import Counter

#BOARD_BG_COLOR_1 = 40
BOARD_BG_COLOR_1 = 43
BOARD_BG_COLOR_2 = 0
WHITE_TEXT_COLOR = 0
BLACK_TEXT_COLOR = 31
COMPARISON_BG_COLOR = 46
DEFAULT_COLOR_CODE = '\x1b[0m'

BOARD_BG_FORMATS = [BOARD_BG_COLOR_1 if (i+int(i/8)) % 2 else BOARD_BG_COLOR_2 for i in range(64)]

# Black pieces have values below; white pieces have negatives of those values
EMPTY = None
ROOK = 1
KNIGHT = 2
BISHOP = 3
QUEEN = 4
KING = 5
BLACK_PAWN_MOVED = 6
BLACK_PAWN_UNMOVED = 7
BLACK = 8
WHITE = -BLACK
WHITE_PAWN_MOVED = -BLACK_PAWN_MOVED
WHITE_PAWN_UNMOVED = -BLACK_PAWN_UNMOVED
PAWNS = [BLACK_PAWN_MOVED, BLACK_PAWN_UNMOVED, WHITE_PAWN_MOVED, WHITE_PAWN_UNMOVED]

PIECE_STRINGS = {ROOK: 'R', KNIGHT: 'N', BISHOP: 'B', QUEEN: 'Q', KING: 'K', BLACK_PAWN_MOVED: 'P',
                 BLACK_PAWN_UNMOVED: 'P'}
FORMATTED_PIECE_STRINGS = {}
for key in list(PIECE_STRINGS.keys()):
    PIECE_STRINGS[-key] = PIECE_STRINGS[key]
    FORMATTED_PIECE_STRINGS[key] = '\x1b[1;' + str(BLACK_TEXT_COLOR) + ';{background}m' + PIECE_STRINGS[key]
    FORMATTED_PIECE_STRINGS[-key] = '\x1b[1;' + str(WHITE_TEXT_COLOR) + ';{background}m' + PIECE_STRINGS[-key]
PIECE_STRINGS[EMPTY] = ' '
FORMATTED_PIECE_STRINGS[EMPTY] = '\x1b[1;0;{background}m' + ' '

PIECE_VALUES = {BLACK_PAWN_MOVED: 1, BLACK_PAWN_UNMOVED: 1, WHITE_PAWN_MOVED: -1, WHITE_PAWN_UNMOVED: -1,
                KNIGHT: 3, -KNIGHT: -3, BISHOP: 3, -BISHOP: -3, ROOK: 5, -ROOK: -5, QUEEN: 9, -QUEEN: -9,
                KING: 200, -KING: -200}

state_counter = 0

def color_code(text, background):
    return '\x1b[1;{text};{background}m'.format(text=text, background=background)

def linearize_xy_coord(xy):
    return xy[1] * 8 + xy[0]

def calculate_move_table():
    def spaces_up(xy):
        return [(xy[0], y) for y in range(xy[1] + 1, 8) if y < 8]

    def spaces_down(xy):
        return [(xy[0], y) for y in range(xy[1] - 1, -1, -1) if y >= 0]

    def spaces_right(xy):
        return [(x, xy[1]) for x in range(xy[0] + 1, 8) if x < 8]

    def spaces_left(xy):
        return [(x, xy[1]) for x in range(xy[0] - 1, -1, -1) if x >= 0]

    def spaces_up_right(xy):
        if xy[0] == 7 or xy[1] == 7:
            return []
        return zip(range(xy[0] + 1, 8), range(xy[1] + 1, 8))

    def spaces_down_right(xy):
        if xy[0] == 7 or xy[1] == 0:
            return []
        return zip(range(xy[0] + 1, 8), range(xy[1] - 1, -1, -1))

    def spaces_up_left(xy):
        if xy[0] == 0 or xy[1] == 7:
            return []
        return zip(range(xy[0] - 1, -1, -1), range(xy[1] + 1, 8))

    def spaces_down_left(xy):
        if xy[0] == 0 or xy[1] == 0:
            return []
        return zip(range(xy[0] - 1, -1, -1), range(xy[1] - 1, -1, -1))

    def diagonal_move_set(xy):
        return [spaces_down_left(xy), spaces_down_right(xy), spaces_up_left(xy),
                spaces_up_right(xy)]

    def straight_move_set(xy):
        return [spaces_up(xy), spaces_down(xy), spaces_left(xy),
                spaces_right(xy)]

    def is_space_on_board(xy):
        return xy[0] >= 0 and xy[0] < 8 and xy[1] >= 0 and xy[1] < 8

    def move_set_from_deltas(xy, deltas):
        move_set = []
        for subset in deltas:
            move_set.append([(xy[0] + d[0], xy[1] + d[1]) for d in subset])
            move_set[-1] = [move_space for move_space in move_set[-1] if is_space_on_board(move_space)]
        return move_set

    def linearize_move_set(move_set):
        return [[linearize_xy_coord(xy) for xy in subset] for subset in move_set]

    def piece_move_set(piece, xy):
        if piece == BLACK_PAWN_UNMOVED:
            deltas = [[(0, -1), (0, -2)], [(-1, -1)], [(1, -1)]]
            move_set = move_set_from_deltas(xy, deltas)

        elif piece == BLACK_PAWN_MOVED:
            deltas = [[(0, -1)], [(-1, -1)], [(1, -1)]]
            move_set = move_set_from_deltas(xy, deltas)

        elif piece == WHITE_PAWN_UNMOVED:
            deltas = [[(0, 1), (0, 2)], [(-1, 1)], [(1, 1)]]
            move_set = move_set_from_deltas(xy, deltas)

        elif piece == WHITE_PAWN_MOVED:
            deltas = [[(0, 1)], [(-1, 1)], [(1, 1)]]
            move_set = move_set_from_deltas(xy, deltas)

        elif piece == ROOK:
            move_set = straight_move_set(xy)

        elif piece == KNIGHT:
            move_set = move_set_from_deltas(xy, [[(1, 2)], [(2, 1)], [(2, -1)], [(1, -2)], [(-1, -2)], [(-2, -1)],
                                                        [(-2, 1)], [(-1, 2)]])

        elif piece == BISHOP:
            move_set = diagonal_move_set(xy)

        elif piece == QUEEN:
            move_set = straight_move_set(xy) + diagonal_move_set(xy)

        elif piece == KING:
            move_set = move_set_from_deltas(xy, [[(0, 1)], [(1, 1)], [(1, 0)], [(1, -1)], [(0, -1)], [(-1, -1)],
                                                        [(-1, 0)], [(-1, 1)]])

        return move_set

    all_pieces = [WHITE_PAWN_UNMOVED, WHITE_PAWN_MOVED, BLACK_PAWN_UNMOVED, BLACK_PAWN_MOVED, KNIGHT, BISHOP, QUEEN,
                  KING, ROOK]

    move_table = {}
    for piece in all_pieces:
        move_table[piece] = {}
        for xy in [(x, y) for x in range(8) for y in range(8)]:
            move_table[piece][linearize_xy_coord(xy)] = linearize_move_set(piece_move_set(piece, xy))

    return move_table

move_table = calculate_move_table()

end_row_piece_order = (ROOK, KNIGHT, BISHOP, KING, QUEEN, BISHOP, KNIGHT, ROOK)
starting_state = [-piece for piece in end_row_piece_order] + \
                 [WHITE_PAWN_UNMOVED]*8 + \
                 [EMPTY]*32 + \
                 [BLACK_PAWN_UNMOVED]*8 + \
                 list(end_row_piece_order) + \
                 [BLACK]     # Active player

starting_state = tuple(starting_state)
full_piece_list = [piece for piece in starting_state[:-1] if piece is not None]
full_piece_counter = Counter(full_piece_list)

MATERIAL_INDEX = 0
PAWN_INDEX = 1
MOBILITY_INDEX = 2
EVALUATION_INDEX = 3
SEARCH_VALUE_INDEX = 4
SEARCH_DEPTH_INDEX = 5
TABLE_COL_NUM = 6
state_table = {}

def random_state():
    global starting_state
    board = list(starting_state)[:-1]
    shuffle(board)
    state = board+[WHITE if random()<0.5 else BLACK]

    return tuple(state)

def are_same_player(piece_a, piece_b):
    return (piece_a < 0) == (piece_b < 0)

def are_opponents(piece_a, piece_b):
    return not are_same_player(piece_a, piece_b)

def child_from_move(state, from_index, to_index, add_to_table):
    global state_counter, state_table

    if state[to_index] is not None:
        if (are_same_player(state[from_index], state[to_index]) or
                (state[from_index] in PAWNS and abs(from_index - to_index) % 8 == 0)):
            # Trying to move into a spot occupied by player's own piece, or
            # Pawn trying to capture straight ahead
            return None
    elif state[from_index] in PAWNS and abs(from_index - to_index) % 8 != 0:
        # Pawn is trying to move diagonally without a capture
        return None

    child = list(state)
    state_counter += 1

    if child[from_index] == WHITE_PAWN_UNMOVED:
        child[to_index] = WHITE_PAWN_MOVED
    elif child[from_index] == BLACK_PAWN_UNMOVED:
        child[to_index] = BLACK_PAWN_MOVED
    else:
        child[to_index] = child[from_index]

    child[from_index] = None
    child[-1] = -child[-1]

    child = tuple(child)
    if add_to_table:
        if child not in state_table.keys():
            state_table[child] = [None for _ in range(TABLE_COL_NUM)]

            child_material_value = state_table[state][MATERIAL_INDEX]
            if state[to_index] is not EMPTY:
                child_material_value -= PIECE_VALUES[state[to_index]]

            state_table[child][MATERIAL_INDEX] = child_material_value

    return child

def children_from_piece(state, piece_index, add_to_table):
    move_set = move_table[abs(state[piece_index]) if state[piece_index] not in PAWNS else state[piece_index]][
        piece_index]
    children = []

    for move_direction in move_set:
        for move_to_index in move_direction:

            child = child_from_move(state, piece_index, move_to_index, add_to_table)
            if child is not None:
                children.append(child)
            if state[move_to_index] is not None:
                break
    return children

def get_children(state, add_to_table=True):

    children = []
    for square_index in range(64):
        if state[square_index] is not None and are_same_player(state[square_index], state[-1]):
            children += children_from_piece(state, square_index, add_to_table)

    return children

def get_captures(state, stringify=False):
    current_pieces = []
    for piece in state[:-1]:
        if piece is not None:
            if piece == BLACK_PAWN_MOVED:
                current_pieces.append(BLACK_PAWN_UNMOVED)
            elif piece == WHITE_PAWN_MOVED:
                current_pieces.append(WHITE_PAWN_UNMOVED)
            else:
                current_pieces.append(piece)
    current_pieces = Counter(current_pieces)
    captured_pieces = full_piece_counter - current_pieces

    captures = {WHITE: [], BLACK: []}
    for piece in captured_pieces.elements():
        captures[WHITE if piece < 0 else BLACK].append(piece if not stringify else FORMATTED_PIECE_STRINGS[
            piece].format(background=0))

    return captures

def get_board_string(state, bg_formats=BOARD_BG_FORMATS):

    captures = get_captures(state, stringify=True)
    board_string = color_code(BLACK_TEXT_COLOR, 0) + '•' if state[-1] == BLACK else ' '
    board_string += ' '.join(captures[WHITE]) + '\n'

    for y in range(7, -1, -1):
        board_string += DEFAULT_COLOR_CODE + str(y + 1) + ' '
        for x in range(0, 8):
            linear_board_index = linearize_xy_coord((x, y))
            board_string += FORMATTED_PIECE_STRINGS[state[linear_board_index]].\
                format(background=bg_formats[linear_board_index]) + ' '
        board_string += DEFAULT_COLOR_CODE + '\n'

    board_string += '  ' + ' '.join([ascii_uppercase[i] for i in range(0, 8)]) + '\n'

    board_string += color_code(WHITE_TEXT_COLOR, 0) + '•' if state[-1] == WHITE else ' '
    board_string += ' '.join(captures[BLACK]) + DEFAULT_COLOR_CODE

    return board_string

def print_board(state):
    print(get_board_string(state))

def print_board_compare(board_a, board_b):
    """ Print board_a, highlighting any differences from board_b """

    board_bg_formats = [COMPARISON_BG_COLOR if board_a[i] != board_b[i] else BOARD_BG_FORMATS[i]
                        for i in range(64)]

    print(get_board_string(board_a, bg_formats=board_bg_formats))

def material_value(state):

    value = 0
    for i in state[:-1]:
        if i is not None:
            value += PIECE_VALUES[i]

    return value

def pawn_score(state):

    def doubled_pawns(pawns_in_file):
        return len([_ for _ in pawns_in_file if _ > 1])

    def isolated_pawns(pawns_in_file):
        num_isolated_pawns = 0
        for file, file_pawns in enumerate(pawns_in_file):
            if not ((file-1 <= 0 or pawns_in_file[file-1] > 0) and (file+1 >= 8 or pawns_in_file[file+1] > 0)):
                num_isolated_pawns += 1
        return num_isolated_pawns

    white_pawns_in_file = [0 for _ in range(8)]
    black_pawns_in_file = [0 for _ in range(8)]
    white_blocked_pawns = 0
    black_blocked_pawns = 0

    for piece_index, piece in enumerate(state):

        if piece == BLACK_PAWN_MOVED or piece == BLACK_PAWN_UNMOVED:
            black_pawns_in_file[piece_index % 8] += 1

            square_below = piece_index - 8
            if square_below >= 0 and state[square_below] is not EMPTY:
                black_blocked_pawns += 1

        elif piece == WHITE_PAWN_MOVED or piece == WHITE_PAWN_UNMOVED:
            white_pawns_in_file[piece_index % 8] += 1

            square_above = piece_index + 8
            if square_above < 64 and state[square_above] is not EMPTY:
                white_blocked_pawns += 1

    score = 0.5 * (white_blocked_pawns - black_blocked_pawns +
           doubled_pawns(white_pawns_in_file) - doubled_pawns(black_pawns_in_file) +
           isolated_pawns(white_pawns_in_file) - isolated_pawns(black_pawns_in_file))

    return score

def mobility_score(state):
    if state[-1] == BLACK:
        black_moving = state
        white_moving = copy(list(state))
        white_moving[-1] = WHITE
        white_moving = tuple(white_moving)

    else:
        white_moving = state
        black_moving = copy(list(state))
        black_moving[-1] = BLACK
        black_moving = tuple(black_moving)
    return 0.1*(len(get_children(black_moving, add_to_table=False)) - len(get_children(white_moving,
                                                                                add_to_table=False)))

def evaluate(state):
    global state_table

    table_entry = state_table[state]

    if table_entry[EVALUATION_INDEX] is not None:
        return table_entry[EVALUATION_INDEX]

    if table_entry[MOBILITY_INDEX] is None:
        table_entry[MOBILITY_INDEX] = mobility_score(state)

    if table_entry[PAWN_INDEX] is None:
        table_entry[PAWN_INDEX] = pawn_score(state)

    table_entry[EVALUATION_INDEX] = table_entry[MATERIAL_INDEX] + table_entry[MOBILITY_INDEX] + table_entry[PAWN_INDEX]

    return table_entry[EVALUATION_INDEX]

def ordering_function(state, state_table):
    table_entry = state_table[state]

    if table_entry[PAWN_INDEX] is None:
        table_entry[PAWN_INDEX] = pawn_score(state)

    score = table_entry[PAWN_INDEX] + table_entry[MATERIAL_INDEX]
    return score if state[-1] == BLACK else -score

def is_in_check(state, children):
    # Checks if the player whose turn is in state has her opponent in check
    opponents_king = KING if state[-1] == WHITE else -KING
    for child in children:
        if opponents_king not in child:
            return True
    return False

def alphabeta(state, value_function, ordering_function=ordering_function, forward_prune_schedule=None, \
                                                                                depth_limit=inf, \
                                                                                time_limit=inf):

    def alphabeta_recursive(state, state_table, alpha, beta, depth_left, value_function,
                            ordering_function=ordering_function,
                            forward_prune_schedule=None, start_time=0,
                                      time_limit=inf):

        if time_limit is not inf and timer() - start_time >= time_limit:
            return None, None
        if depth_left == 0 or KING not in state or -KING not in state:
            return state, value_function(state)

        children = get_children(state)

        if not children:
            return state, value_function(state)

        children.sort(key=lambda x: ordering_function(x, state_table))

        if forward_prune_schedule and depth_left <= len(forward_prune_schedule):
            fraction_to_prune = forward_prune_schedule[0]
            number_to_prune = floor(fraction_to_prune*len(children))
            if number_to_prune != 0:
                children = children[:-number_to_prune]

        # Black wants positive values; white wants negative values
        best_child_value = inf if state[-1] == WHITE else -inf
        best_child = children[0]
        depth = depth_left-1

        for child in children:
            if state_table[child][SEARCH_VALUE_INDEX] is not None and state_table[child][SEARCH_DEPTH_INDEX] >= depth:
                child_value = state_table[child][SEARCH_VALUE_INDEX]
            else:
                _, child_value = alphabeta_recursive(child, state_table, alpha, beta, depth,
                                                               value_function,
                                                     forward_prune_schedule=forward_prune_schedule[1:],
                                                                      start_time=start_time,
                                                                      time_limit=time_limit)

                if child_value is None:  # Time limit reached
                    return None, None

                state_table[child][SEARCH_VALUE_INDEX] = child_value
                state_table[child][SEARCH_DEPTH_INDEX] = depth

            if state[-1] == WHITE:

                if child_value < best_child_value:
                    best_child = child
                    best_child_value = child_value

                if child_value <= alpha:
                    break
                elif child_value < beta:
                    beta = child_value

            elif state[-1] == BLACK:
                if child_value > best_child_value:
                    best_child = child
                    best_child_value = child_value

                if child_value >= beta:
                    break
                elif child_value > alpha:
                    alpha = child_value

        return best_child, best_child_value

    global state_table, child_getting_time, pawn_score_time, state_counter
    child_getting_time = 0
    pawn_score_time = 0
    state_counter = 0

    state_table = {state: [None for _ in range(TABLE_COL_NUM)]}
    state_table[state][MATERIAL_INDEX] = material_value(state)

    if depth_limit < inf:

        for depth in range(1, depth_limit+1):

            best_child, best_child_value = alphabeta_recursive(state, state_table, -inf, inf, depth, value_function,
                        forward_prune_schedule=forward_prune_schedule[:depth] if forward_prune_schedule else
                        None)

    elif time_limit < inf:
        start_time = timer()
        depth = 1
        child = state
        child_value = None

        while child is not None:
            best_child = child
            best_child_value = child_value
            child, child_value = alphabeta_recursive(state, state_table, -inf, inf, depth, value_function,
                                forward_prune_schedule=forward_prune_schedule if forward_prune_schedule else None,
                                start_time=start_time, time_limit=time_limit)
            depth += 1

        print('Depth limit reached: ' + str(depth-2))

    if KING not in best_child or -KING not in best_child:
        return None
    else:
        return best_child

def minimax(state, depth_left, value_function, start_time=0, time_limit=inf):

    def recursive_depth_limited_minimax(state, depth_left, value_function, start_time=0, time_limit=inf):

        if time_limit is not inf and timer()-start_time >= time_limit:
            return None, None
        if depth_left == 0 or KING not in state or -KING not in state:
            return state, value_function(state)

        children = get_children(state)

        if not children:
            return state, value_function(state)

        # Black wants positive values; white wants negative values
        best_child_value = inf if state[-1] == WHITE else -inf
        best_child = children[0]

        for child in children:
            _, child_value = recursive_depth_limited_minimax(child, depth_left-1, value_function, start_time=start_time,
                                                             time_limit=time_limit)

            if child_value is None:     # Time limit reached
                return None, None

            if (state[-1] == WHITE and child_value < best_child_value) or \
               (state[-1] == BLACK and child_value > best_child_value):
                best_child_value = child_value
                best_child = child

        return best_child, best_child_value

    child, child_value = recursive_depth_limited_minimax(state, depth_left, value_function, start_time=0,
                                                         time_limit=inf)

    if child_value == (inf if state[-1] == WHITE else -inf):
        return None
    else:
        return child

def random_move_generator(state):
    children = get_children(state)

    # Make sure the king is not in check; if it is, move intelligently; otherwise, move randomly
    players_king = KING if state[-1] == BLACK else -KING

    shuffle(children)

    while children:

        child = children.pop()

        # Make sure King is not in check in the selected child
        grandchildren = get_children(child)
        not_in_check = True
        for grandchild in grandchildren:
            if players_king not in grandchild:
                not_in_check = False
                break

        if not_in_check:
            return child

    return None

def human_move_generator(state):

    def parse_input_xy(text):
        text = text.upper()
        try:
            xy = (ascii_uppercase.index(text[0]), int(text[1])-1)
        except (IndexError, ValueError):
            return None
        if xy[0] in range(0,8) and xy[1] in range(0,8):
            return xy[1]*8+xy[0]
            #return xy
        return None

    while True:
        move_from = input('Move from: ')
        move_from = parse_input_xy(move_from)
        if move_from and state[move_from] is not None \
                    and are_same_player(state[move_from], state[-1]):
            children = children_from_piece(state, move_from, False)
            if children:
                break

    while True:
        move_to = input('to: ')
        move_to = parse_input_xy(move_to)
        if move_to:
            moved_piece = state[move_from]
            if moved_piece == BLACK_PAWN_UNMOVED:
                moved_piece = BLACK_PAWN_MOVED
            elif moved_piece == WHITE_PAWN_UNMOVED:
                moved_piece = WHITE_PAWN_MOVED
            for child in children:
                if child[move_to] == moved_piece:
                    return child

def play_game(black_move_generator, white_move_generator, show_game_states=False):

    move_generators = {BLACK: black_move_generator, WHITE: white_move_generator}

    state = starting_state
    states = [state]
    if show_game_states:
        print(get_board_string(state))

    while True:
        move_time = timer()
        state = move_generators[state[-1]](state)
        print('Time for move: {:.1f}'.format(timer() - move_time))

        lookups = 0
        if state is None:
            break

        if show_game_states:
            print_board_compare(state, states[-1])

        states.append(state)

    if show_game_states:
        winner_str = 'Black ' if states[-1][-1] == WHITE else 'White'
        print(winner_str + ' won!')

    return states

def computer_move_generator(state):
    print('Computer is moving...')
    return alphabeta(state, evaluate, depth_limit=5, forward_prune_schedule=[0, 0, 0, 0.25, 0.25])

play_game(computer_move_generator, human_move_generator, show_game_states=True)


from django.http import HttpResponse
from django_email import djemail

def send_email_view(request):
    """
    Simple example on how to send an email in a view.
    """
    # djemail.send_email(
    #     to="email@test.com",
    #     template="email/notification", # .txt and/or .html
    #     context={'variable': 'Variable Content'},
    #     subject="My Subject"
    # )

    djemail.send_email(
        to="email@test.com",
        message="This is the message",
        subject="My Subject"
    )

    return HttpResponse('Please check your console')


# Copyright 2019 Katteli Inc.
# TestFlows.com Open-Source Software Testing Framework (http://testflows.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from testflows._core.cli.arg.common import epilog
from testflows._core.cli.arg.common import HelpFormatter
from testflows._core.cli.arg.handlers.report.compare.command import (
    Handler as HandlerBase,
)
from testflows._core.cli.arg.handlers.report.compare.command import (
    Formatter as FormatterBase,
)
from testflows._core.cli.arg.handlers.report.compare.command import template

class Formatter(FormatterBase):
    def format(self, data):
        body = self.format_metadata(data)
        body += self.format_reference(data)
        body += self.format_chart(data)
        body += self.format_table(data)
        return template.strip() % {
            "title": "Results",
            "logo": self.format_logo(data),
            "confidential": self.format_confidential(data),
            "copyright": self.format_copyright(data),
            "body": body,
        }

class Handler(HandlerBase):
    Formatter = Formatter

    @classmethod
    def add_command(cls, commands):
        parser = commands.add_parser(
            "results",
            help="results report",
            epilog=epilog(),
            description="Generate results comparison report.",
            formatter_class=HelpFormatter,
        )
        cls.add_arguments(parser)
        parser.set_defaults(func=cls())


import sys
import udpPeer

portStr = sys.argv[1]
try:
    port = int(portStr)
except:
    print("bad port number")
    sys.exit()
if port < 0 or port > 65535:
    print("bad port number")
    sys.exit()
print("run udpPeer on port", port)

peer = udpPeer.UdpPeer()
peer.OnOpen = lambda addr: print("OnOpen:", addr)
peer.OnData = lambda data, addr: print("OnData:", addr, data)
peer.OnClose = lambda exp: print("OnClose:", exp)

isAlive = True
print("commands: isOpen / open / send <addr> <msg> / close / exit")
while isAlive:
    text = input()
    blocks = text.split(" ")

    if blocks[0] == "isOpen":
        print("socket open" if peer.IsOpen() else "socket closed")
    elif blocks[0] == "open":
        peer.Open(("localhost", int(port)), 512)
    elif blocks[0] == "send":
        if len(blocks) < 3:
            print("usage: send <addr> <msg>")
            continue

        addrBlocks = blocks[1].split(":")
        if not len(addrBlocks) == 2:
            print("bad address")
            continue

        try:
            port = int(addrBlocks[1])
        except:
            print("bad port number")
            continue
        if port < 0 or port > 65535:
            print("bad port number")
            continue

        peer.Send(bytes(text[len(blocks[0]) + len(blocks[1]) + 2:], "utf8"), (addrBlocks[0], port))
    elif blocks[0] == "close":
        peer.Close()
    elif blocks[0] == "exit":
        peer.Close()
        isAlive = False
    else:
        print("commands: isOpen / open / send <msg> <addr> / close / exit")


def convert(S):
    b = "".join(["1" if c == 'M' else "0" for c in S])
    return int(b, 2)

def solve(MEMBERS, FANS):
    MEMbits = convert(MEMBERS)
    FANbits = convert(FANS)
    res = 0
    for i in range(len(FANS) - len(MEMBERS) + 1):
        if MEMbits & (FANbits >> i):
            continue
        else:
            res += 1
    return res

if __name__ == "__main__":
    C = int(input())
    for _ in range(C):
        MEMBERS = input()
        FANS = input()
        print(solve(MEMBERS, FANS))


from restapi.utils import to_int_list, from_csv
from django import forms
from tasks import models

class StatsForm(forms.Form):
    campaign = forms.IntegerField(required=False)
    tasks = forms.CharField(required=False)
    users = forms.CharField(required=False)
    groups = forms.CharField(required=False)
    start = forms.DateField(required=False)
    end = forms.DateField(required=False)
    plen = forms.IntegerField(required=False)

    def parse_campaign(self):
        if self.cleaned_data['campaign']:
            try:
                return models.Campaign.objects.get(pk=self.cleaned_data['campaign'])
            except models.Campaign.DoesNotExist:
                return None
        return None

    def parse_from_csv(self, name, queryset):
        if self.cleaned_data[name] is not None:
            ids = to_int_list(from_csv(self.cleaned_data[name]))
            return list(queryset.filter(pk__in=ids))
        return []

    def parse_users(self):
        return self.parse_from_csv('users', models.User.objects)

    def parse_tasks(self):
        return self.parse_from_csv('tasks', models.Task.objects)


import itertools

def neighbors(pattern, d):
	d = d + 1
	alph = 'ACGT'   # alphabet
	a = list(range(len(pattern)))
	neighbors_words = []

	for i in range(d):
		possitions = list(itertools.combinations(a, i))

		for pos in possitions:
			sub_word = [pattern[x] for x in pos]

			all_combs = list(itertools.product(alph, repeat=len(sub_word)))
			filt_combs = filter(lambda z: all(map(lambda x, y: x != y, z, sub_word)), all_combs)

			for j in filt_combs:
				tmp = pattern
				for k in range(i):
					tmp = tmp[: pos[k]] + j[k] + tmp[pos[k] + 1 :]
				neighbors_words.append(tmp)

	return neighbors_words

def number_to_pattern(pos, k):
    alph = {0: 'A', 1: 'C', 2: 'G', 3: 'T'}
    rem = pos
    pattern = ''
    while rem > 0:
        pos = rem % 4
        pattern = alph[pos] + pattern
        rem = rem // 4
    if len(pattern) < k:
        pattern = 'A' * (k - len(pattern)) + pattern
    return pattern

def pattern_to_number(pattern):
    alph = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
    pos = 0
    for i in range(len(pattern)):
        pos = pos + 4 ** (len(pattern) - i - 1) * alph[pattern[i]]
    return pos

def hamdist(str1, str2):
	return len(list(filter(lambda x : x[0] != x[1], zip(str1, str2))))

def approx_pattern_count(genome, pattern, d):
	count = 0
	for i in range(len(genome) - len(pattern) + 1):
		if hamdist(genome[i : i + len(pattern)], pattern) <= d:
			count += 1

	return count

def approx_frequent_words(genome, k, d):
	close = [0]*4**k
	frequency_array = [0]*4**k
	frequent_patterns = set()

	for i in range(len(genome) - k + 1):
		neighborhood = neighbors(genome[i : i + k], d)
		for pattern in neighborhood:
			index = pattern_to_number(pattern)
			close[index] = 1

	for i in range(4**k):
		if close[i]:
			pattern = number_to_pattern(i, k)
			frequency_array[i] = approx_pattern_count(genome, pattern, d)
	max_count = max(frequency_array)

	for i in range(4**k):
		if frequency_array[i] == max_count:
			pattern = number_to_pattern(i, k)
			frequent_patterns.add(pattern)

	return frequent_patterns

genome = input()
k, d = map(int, input().split())

frequency_words = approx_frequent_words(genome, k, d)

for word in frequency_words:
	print(word),


from __future__ import annotations

import logging

from rich.console import RenderableType
from rich.style import StyleType

from .. import events
from ..message import Message
from ..scrollbar import ScrollBar, ScrollDown, ScrollUp
from ..geometry import clamp
from ..page import Page
from ..view import DockView
from ..reactive import Reactive

log = logging.getLogger("rich")

class ScrollView(DockView):
    def __init__(
        self,
        renderable: RenderableType,
        *,
        name: str | None = None,
        style: StyleType = "",
        fluid: bool = True,
    ) -> None:
        self.fluid = fluid
        self._vertical_scrollbar = ScrollBar(vertical=True)
        self._page = Page(renderable, style=style)
        super().__init__(name="ScrollView")

    x: Reactive[float] = Reactive(0)
    y: Reactive[float] = Reactive(0)

    target_y: Reactive[float] = Reactive(0)

    def validate_y(self, value: float) -> float:
        return clamp(value, 0, self._page.contents_size.height - self.size.height)

    def validate_target_y(self, value: float) -> float:
        return clamp(value, 0, self._page.contents_size.height - self.size.height)

    def watch_y(self, new_value: float) -> None:
        self._page.y = round(new_value)
        self._vertical_scrollbar.position = round(new_value)

    async def on_mount(self, event: events.Mount) -> None:
        await self.dock(self._vertical_scrollbar, edge="right", size=1)
        await self.dock(self._page, edge="top")

    async def on_idle(self, event: events.Idle) -> None:
        self._vertical_scrollbar.virtual_size = self._page.virtual_size.height
        self._vertical_scrollbar.window_size = self.size.height

        await super().on_idle(event)

    async def on_mouse_scroll_up(self, event: events.MouseScrollUp) -> None:
        self.scroll_up()

    async def on_mouse_scroll_down(self, event: events.MouseScrollUp) -> None:
        self.scroll_down()

    def scroll_up(self) -> None:
        self.target_y += 1.5
        self.animate("y", self.target_y, easing="out_cubic", speed=80)

    def scroll_down(self) -> None:
        self.target_y -= 1.5
        self.animate("y", self.target_y, easing="out_cubic", speed=80)

    def page_up(self) -> None:
        self.target_y -= self.size.height
        self.animate("y", self.target_y, easing="out_cubic")

    def page_down(self) -> None:
        self.target_y += self.size.height
        self.animate("y", self.target_y, easing="out_cubic")

    async def on_key(self, event: events.Key) -> None:
        key = event.key
        if key == "down":
            self.target_y += 2
            self.animate("y", self.target_y, easing="linear", speed=100)
        elif key == "up":
            self.target_y -= 2
            self.animate("y", self.target_y, easing="linear", speed=100)
        elif key == "pagedown":
            log.debug("%r", self.size)
            self.target_y += self.size.height
            self.animate("y", self.target_y, easing="out_cubic")
        elif key == "pageup":
            log.debug("%r", self.size)
            self.target_y -= self.size.height
            self.animate("y", self.target_y, easing="out_cubic")

    async def on_resize(self, event: events.Resize) -> None:
        if self.fluid:
            self._page.update()
        await super().on_resize(event)

    async def on_message(self, message: Message) -> None:
        if isinstance(message, ScrollUp):
            self.page_up()
        elif isinstance(message, ScrollDown):
            self.page_down()
        else:
            await super().on_message(message)


#import PIL
import sys
#from Naked.toolshed.shell import muterun_js
#from subprocess import call
import shlex, subprocess
import serial
ser =  serial.Serial('COM11', 56000)
print(ser.name)         # check which port was really used

#response = muterun_js('nodeDMD.js')
#print (response)
var=subprocess.check_output("node nodeDMD.js", shell=True)
var=var[:-1]

print(type(var),var)
ser.write(var)     # write a string
ser.close()


from sections.section import Section

import numpy as np
import xp_loader
import gzip
import tile_types
import os.path
from application_path import get_app_path
from ui.menu_ui import MenuUI

menu_panel_xp_file = get_app_path() + '/images/menuPanel'

class Menu(Section):
    def __init__(self, engine, x, y, width, height):
        super().__init__(engine, x, y, width, height)

        self.animated_tiles = list()
        for i in range(0, 3):
            if os.path.isfile(menu_panel_xp_file + str(i+1) + '.xp'):
                xp_file = gzip.open(menu_panel_xp_file + str(i+1) + '.xp')
                raw_data = xp_file.read()
                xp_file.close()

                xp_data = xp_loader.load_xp_string(raw_data)

                self.animated_tiles.append(
                    np.full((self.width, self.height), fill_value=tile_types.blank, order="F"))

                for h in range(0, self.height):
                    for w in range(0, self.width):
                        self.animated_tiles[i][w,
                                               h]['graphic'] = xp_data['layer_data'][0]['cells'][w][h]

        self.ui = MenuUI(self, x, y, self.animated_tiles[0]["graphic"])
        self.selected_tiles = 0
        self.frame_length = 20
        self.time_on_frame = 0

    def render(self, console):
        if self.time_on_frame > self.frame_length:
            self.selected_tiles += 1
            self.selected_tiles %= 3
            self.time_on_frame = 0

        if len(self.animated_tiles[self.selected_tiles]) > 0:
            if self.invisible == False:
                console.tiles_rgb[self.x: self.x + self.width, self.y: self.y +
                                  self.height] = self.animated_tiles[self.selected_tiles]["graphic"]

            if self.ui is not None:
                self.ui.render(console)

        self.time_on_frame += 0.16


# -*- coding: utf-8 -*-
"""
Created on Thu Sep  8 17:32:17 2018

@author: 刘磊
"""
import os,math
import numpy as np
import pandas as pd

#数据的读取，并筛选指定行和列
def data_load():
    global input_file
    input_file=input('请输入文件的绝对路径:(例如：c:\\study\\model.data)\n')
    #os.chdir(input_path)
    data=pd.read_csv(input_file,engine='python',delimiter=' ',skiprows=9,header=None,
                     usecols=[0,1,2,3,4,18,19,20,21,22,23],
                     names=['id','type','x','y','z','c_1[1]','c_1[2]','c_1[3]','c_1[4]','c_1[5]','c_1[6]'])
    return data

#定义函数计算局部应力,参数分别为加载的数据以及截断半径，截断半径默认为10埃，可更改
def cal_stress(data,cutoff_length=10):
    voli=(2*cutoff_length)**3         #微元的体积
    #初始化待计算物理量
    atom_hydro_von=pd.DataFrame(np.zeros((n_atom,2)),columns=['atom_hydro','atom_von'])
    for i in range(n_atom):
        xx,yy,zz,xy,xz,yz=0,0,0,0,0,0
        neigb=0
        for j in range(n_atom):
            if c_x[j]>c_x[i]-cutoff_length and c_x[j]<c_x[i]+cutoff_length and c_y[j]>c_y[i]-cutoff_length and c_y[j]<c_y[i]+cutoff_length and c_z[j]>c_z[i]-cutoff_length and c_z[j]<c_z[i]+cutoff_length:
                xx+=data['c_1[1]'][j]
                yy+=data['c_1[2]'][j]
                zz+=data['c_1[3]'][j]
                xy+=data['c_1[4]'][j]
                xz+=data['c_1[5]'][j]
                yz+=data['c_1[6]'][j]
                neigb+=1
        atom_hydro_von['atom_hydro'][i]=1.0/3.0*0.0001*(xx+yy+zz)/voli                                   #单位GPa
        atom_hydro_von['atom_von'][i] = 0.0001*math.sqrt(3.0*((xy)**2+(yz)**2+(xz)**2)+0.5*((xx-yy)**2+(xx-zz)**2+(zz-yy)**2))/voli   #单位GPa
    return atom_hydro_von

#写入文件
def data_write():
    output_file=input('请输入输出文件的绝对路径:(例如：c:\\study\\model.data)\n')
    with open(input_file,'r') as filereader:
        with open(output_file,'w') as filewriter:
            for i in range(8):
                header=filereader.readline().strip()
                filewriter.write(header+'\n')
            filewriter.write('ITEM: ATOMS id type x y z c_str[1] c_str[2] c_str[3] c_str[4] c_str[5] c_str[6] hydro von'+'\n')
            for row in range(len(stress_data)):
                row_content=stress_data.iloc[row].tolist()
                filewriter.write(' '.join(map(str,row_content))+'\n')
    print('finished!')

if __name__=='__main__':
    data=data_load()
    #特征量的提取
    n_atom=len(data)
    c_x=data['x']
    c_y=data['y']
    c_z=data['z']
    xlo,xhi=min(c_x),max(c_x)
    ylo,yhi=min(c_y),max(c_y)
    zlo,zhi=min(c_z),max(c_z)

    atom_hydro_von=cal_stress(data,10)
    stress_data=pd.merge(data,atom_hydro_von,left_index=True,right_index=True)
    data_write()


import tile
import board as b

SNAKE = -1
WALL_SPACE = 26
OPEN_SPACE = 15
SMALLER_SNAKE_FUTURE_HEAD = 11
OUR_HEAD = 10
LARGER_SNAKE_FUTURE_HEAD = 99
PATHABLE_TAIL = 12

def int_board(converted_data):
    """
    Call list of functions that modify and build the path_board
    Args:
        converted_data (dict): Converted json

    Returns:
        A* friendly version of the game-board
    """
    # make path_board
    path_board = set_edge(converted_data)

    # pass by reference modify it
    set_snake_values(converted_data, path_board)
    bully_pathing(converted_data, path_board)
    coward_pathing(converted_data, path_board)

    # after snakes fully deployed update board with projected tail positions
    if (converted_data["turn"] > 2):
        update_tails(converted_data, path_board)
    return path_board

def update_tails(converted_data, path_board):
    """
    Reads shout object for last turns moves and updates board to reflect if
    any snake heads occupy a tile that was previously occupied by food

    Args:
        converted_data (dict): python readable version of json
        path_board (list): int representation of the board for A*

    Returns:
        Nothing

    """
    food = converted_data["you"]["shout"].split("/")
    food = [str(x) for x in food]
    food.pop()  # kludge removes empty last element caused by parsing

    growers = []
    if len(food) > 0:
        for location in food:
            # get x,y with unicode converted
            xy = location.split(",")
            x = int(xy[0])
            y = int(xy[1])

            # if other snake or our head
            if (int(path_board[y][x]) <= 0) or (int(path_board[y][x]) == 10):
                snake_id = snake_id_from_XY(x, y, converted_data)
                snake_id.encode("utf-8")  # fixes unicode issue with parser
                growers.append(snake_id)
    remove_hungry_tails(path_board, growers, converted_data)

def remove_hungry_tails(path_board, growers, converted_data):
    """
    Edits the path_board to reflect if a snake ate this turn or not

    Args:
        converted_data (dict): python readable version of json
        path_board (list): int representation of the board for A*
        growers (list): string list of snake_ids whos tail will not move next
        turn
    Returns:
        Modifys path_board by reference.
    """
    for snake in converted_data["board"]["snakes"]:
        if snake["id"] not in growers:
            x = snake["body"][-1]["x"]
            y = snake["body"][-1]["y"]
            path_board[y][x] = PATHABLE_TAIL

def snake_id_from_XY(x, y, converted_data):
    """
    Returns snake_id from x, y integers.

    Args:
        x (int): x value of tile
        y (int): y value of tile
        converted_data (dict): python readable version of json

    Returns:
        snake["id"](unicode string): snake id
    """
    for snake in converted_data["board"]["snakes"]:
        if (x == snake["body"][0]["x"]) and (y == snake["body"][0]["y"]):
            return snake["id"]

def set_snake_values(converted_data, board):
    """
    Replaces values on pathable board that correspond with snake locations
    with values for snake bodies
    Args:
        converted_data (dict): Converted JSON data
        board (list): integer representation of the board

    Returns:
        A_Star friendly version of the game-board.

    """

    # pertaining to our own body
    me = converted_data["you"]["id"]

    for segment in converted_data["you"]["body"]:
        if segment == converted_data["you"]["body"][0]:
            x = segment['x']
            y = segment['y']
            board[y][x] = OUR_HEAD
        else:
            x = segment['x']
            y = segment['y']
            board[y][x] = SNAKE

    # other snakes
    for snake in converted_data["board"]["snakes"]:
        name = snake["id"]
        for segment in snake["body"]:
            if name != me:
                if segment == snake["body"][0]:
                    x = segment['x']
                    y = segment['y']
                    board[y][x] = SNAKE
                else:
                    x = segment['x']
                    y = segment['y']
                    board[y][x] = SNAKE

def set_edge(data_dump):
    """
    Creates path-able board and sets edge of game-map to the value 'WALL_SPACE'
    Args:
        data_dump (dict): Converted JSON data

    Returns:
        Game board with the edges initialised to '10'
    """
    board_width = data_dump["board"]["width"]
    board_height = data_dump["board"]["height"]
    board = [[1 for x in range(board_width)] for y in range(board_height)]
    for x in range(board_width):
        for y in range(board_height):
            # Bottom of board
            if y == data_dump["board"]["height"] - 1:
                board[y][x] = WALL_SPACE
            # Top of Board
            elif y == 0:
                board[y][x] = WALL_SPACE
            # Right side of board
            elif x == data_dump["board"]["width"] - 1:
                board[y][x] = WALL_SPACE
            # Left side of board
            elif x == 0:
                board[y][x] = WALL_SPACE
            # Anything Else
            else:
                board[y][x] = OPEN_SPACE
    return board

def bully_pathing(converted_data, path_board):
    """
    Finds Snakes that are smaller than us and assigns the area around their
    head with the SMALLER_SNAKE_FUTURE_HEAD

    May need logical update for snake bodies but it should be fine

    Args:
        path_board (list): Path from A*
        converted_data (dict): python readable version of json
    Return:
        updated board (list) with potentially new values around smaller snakes
        heads
    """
    snake_id = converted_data["you"]["id"]
    # other snakes heads will be assigned xy
    for snake in converted_data["board"]["snakes"]:
        name = snake["id"]
        for segment in snake["body"]:
            if ((str(name) != str(snake_id))
                    and (len(snake["body"]) <
                         len(converted_data["you"]["body"]))):

                if segment == snake["body"][0]:
                    x = segment['x']
                    y = segment['y']
                    if (converted_data['board']['width'] - 1) > x > 0:
                        if path_board[y][x + 1] != -1:
                            path_board[y][x+1] = SMALLER_SNAKE_FUTURE_HEAD
                        if path_board[y][x - 1] != -1:
                            path_board[y][x-1] = SMALLER_SNAKE_FUTURE_HEAD
                    if (converted_data['board']['width'] - 1) > y > 0:
                        if -1 != path_board[y + 1][x]:
                            path_board[y+1][x] = SMALLER_SNAKE_FUTURE_HEAD
                        if path_board[y - 1][x] != -1:
                            path_board[y-1][x] = SMALLER_SNAKE_FUTURE_HEAD

def coward_pathing(converted_data, path_board):
    """
    Finds Snakes that are LARGER than us and assigns
    the area around their head with the LARGER_Snake_Future_Head

    May need logical update for snake bodies but it should be fine

    Args:
        converted_data (dict): python readable version of json
        path_board (list): path from a*

    Return:
        updated board (list) with potentially new values
        around LARGER snakes heads
    """
    me = converted_data["you"]["id"]
    # other snakes heads will be assigned xy
    for snake in converted_data["board"]["snakes"]:
        name = snake["id"]
        for segment in snake["body"]:
            if ((str(name) != str(me)) and
                    (len(snake["body"]) >=
                        len(converted_data["you"]["body"]))):
                if segment == snake["body"][0]:
                    x = segment['x']
                    y = segment['y']
                    if converted_data['board']['width']-1 > x >= 0:
                        if path_board[y][x + 1] != -1:
                            path_board[y][x+1] = LARGER_SNAKE_FUTURE_HEAD
                        if path_board[y][x - 1] != -1:
                            path_board[y][x-1] = LARGER_SNAKE_FUTURE_HEAD
                    if converted_data['board']['height']-1 > y >= 0:
                        if path_board[y + 1][x] != -1:
                            path_board[y+1][x] = LARGER_SNAKE_FUTURE_HEAD
                        if path_board[y - 1][x] != -1:
                            path_board[y-1][x] = LARGER_SNAKE_FUTURE_HEAD

def board_to_array(data_dump):
    """
    Converts converted JSON data from battle-snake engine to a list
    Args:
        data_dump (dict): Converted JSON data

    Returns:
        2D list of game board.
    """
    board_width = data_dump["board"]["width"]
    board_height = data_dump["board"]["height"]
    board = [[0 for x in range(board_width)] for y in range(board_height)]
    # label spaces as food
    for z in data_dump["board"]["food"]:
        x = z['x']
        y = z['y']
        board[y][x] = 'F'
    # finding your body
    me = data_dump["you"]["id"]
    for z in data_dump["you"]["body"]:
        if z == data_dump["you"]["body"][0]:
            x = z['x']
            y = z['y']
            board[y][x] = 'H'
        else:
            x = z['x']
            y = z['y']
            board[y][x] = 'S'
    # to find other snakes
    for z in data_dump["board"]["snakes"]:
        name = z["id"]
        for a in z["body"]:
            if name != me:
                if a == z["body"][0]:
                    x = a['x']
                    y = a['y']
                    board[y][x] = 'E'
                else:
                    x = a['x']
                    y = a['y']
                    board[y][x] = 'S'
    return board

def display(converted_board, integer_board):
    for x in integer_board:
        for y in x:
            print(str(y) + " "),
        print()
    print()
    for x in converted_board:
        for y in x:
            print(str(y) + " "),
        print()